gt
stringclasses
1 value
context
stringlengths
2.05k
161k
package test.demo.gyniu.v2ex.model; import android.os.Parcel; import android.support.annotation.Nullable; import com.google.common.base.Objects; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import test.demo.gyniu.v2ex.utils.Constant; /** * Created by uiprj on 17-3-22. */ public class Topic extends Entity { private static final Pattern PATTERN = Pattern.compile("/t/(\\d+?)(?:\\W|$)"); private final int mId; private final String mTitle; private final String mContent; private final int mReplyCount; private final int mClickRate; private final Member mMember; private final Node mNode; private final String mTime; private final boolean mHasInfo; @Nullable private final List<Postscript> mPostscripts; public Topic(int mId, String mTitle, String mContent, int mReplyCount, int mClickRate, Member mMember, Node mNode, String mTime, @Nullable List<Postscript> postscripts) { this.mId = mId; this.mTitle = mTitle; this.mContent = mContent; this.mReplyCount = mReplyCount; this.mClickRate = mClickRate; this.mMember = mMember; this.mNode = mNode; this.mTime = mTime; this.mPostscripts = postscripts; mHasInfo = mMember != null; } public int getId() { return mId; } public String getTitle() { return mTitle; } public String getContent() { return mContent; } public int getReplyCount() { return mReplyCount; } public int getClickRate() { return mClickRate; } public Member getMember() { return mMember; } public Node getNode() { return mNode; } public String getTime() { return mTime; } public boolean hasInfo() { return mHasInfo; } public static int getIdFromUrl(String url) { final Matcher matcher = PATTERN.matcher(url); if (!matcher.find()) { throw new RuntimeException("match id for topic failed: " + url); } final String idStr = matcher.group(1); return Integer.parseInt(idStr); } @Nullable public List<Postscript> getPostscripts() { return mPostscripts; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(this.mId); dest.writeByte(mHasInfo ? (byte) 1 : (byte) 0); dest.writeString(this.mTitle); dest.writeString(this.mContent); dest.writeInt(this.mReplyCount); dest.writeInt(this.mClickRate); dest.writeParcelable(this.mMember, 0); dest.writeParcelable(this.mNode, 0); dest.writeString(this.mTime); } @Override public String getUrl() { return buildUrlFromId(mId); } private String buildUrlFromId(int id) { return Constant.BASE_URL + "/t/" + Integer.toString(id); } public Topic(Parcel in) { this.mId = in.readInt(); this.mHasInfo = in.readByte() != 0; this.mTitle = in.readString(); this.mContent = in.readString(); this.mReplyCount = in.readInt(); this.mClickRate = in.readInt(); this.mMember = in.readParcelable(Member.class.getClassLoader()); this.mNode = in.readParcelable(Node.class.getClassLoader()); this.mTime = in.readString(); this.mPostscripts = null; } public static final Creator<Topic> CREATOR = new Creator<Topic>() { public Topic createFromParcel(Parcel source) { return new Topic(source); } public Topic[] newArray(int size) { return new Topic[size]; } }; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Topic topic = (Topic) o; return mId == topic.mId && mReplyCount == topic.mReplyCount && mClickRate == topic.mClickRate && Objects.equal(mTitle, topic.mTitle) && Objects.equal(mContent, topic.mContent) && Objects.equal(mNode, topic.mNode) && Objects.equal(mTime, topic.mTime); } @Override public int hashCode() { return Objects.hashCode(mId, mTitle, mContent, mReplyCount, mClickRate, mNode, mTime); } @Override public String toString() { return "Topic{" + "mId=" + mId + ", mTitle='" + mTitle + '\'' + ", mContent='" + mContent + '\'' + ", mReplyCount=" + mReplyCount + ", mClickRate=" + mClickRate + ", mMember=" + mMember.getUserName() + ", mNode=" + mNode.getName() + ", mTime='" + mTime + '\'' + ", mHasInfo=" + mHasInfo + ", mPostscripts=" + mPostscripts + '}'; } public Builder toBuilder() { return new Builder() .setId(mId) .setTitle(mTitle) .setContent(mContent) .setMember(mMember) .setNode(mNode) .setReplyCount(mReplyCount) .setClickRate(mClickRate) .setTime(mTime); } public static class Builder{ private int mId; private String mTitle; private String mContent; private int mReplyCount; private int mClickRate; private Member mMember; private Node mNode; private String mTime; private List<Postscript> mPostscripts; public Builder setId(int mId) { this.mId = mId; return this; } public Builder setTitle(String mTitle) { this.mTitle = mTitle; return this; } public Builder setContent(String mContent) { this.mContent = mContent; return this; } public Builder setReplyCount(int mReplyCount) { this.mReplyCount = mReplyCount; return this; } public Builder setClickRate(int mClickRate) { this.mClickRate = mClickRate; return this; } public Builder setMember(Member mMember) { this.mMember = mMember; return this; } public Builder setNode(Node mNode) { this.mNode = mNode; return this; } public Builder setTime(String mTime) { this.mTime = mTime; return this; } public Builder setPostscripts(List<Postscript> postscripts) { mPostscripts = postscripts; return this; } public boolean hasInfo() { return mMember != null; } public Topic createTopic() { return new Topic(mId, mTitle, mContent, mReplyCount, mClickRate, mMember, mNode, mTime, mPostscripts); } } }
package fi.helsinki.acmcrawler.domain.support; import fi.helsinki.acmcrawler.Magic; import fi.helsinki.acmcrawler.domain.Node; import fi.helsinki.acmcrawler.storage.CollaborationGraphDB; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; /** * This class represents a node structure taking place in crawling. * * @author Rodion Efremov * @version I */ public class AuthorNode extends Node<AuthorNode> { private String id; private CollaborationGraphDB<AuthorNode> db; /** * Construct a new <tt>AuthorNode</tt>. * * @param id the author id, may not be <tt>null</tt>. */ public AuthorNode(String id) { super(); if (id == null) { throw new IllegalArgumentException("'id' may not be null."); } this.id = id; } @Override public Iterator<AuthorNode> iterator() { return new NeighborIterator(); } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorNode other = (AuthorNode) obj; return this.id.equals(other.id); } @Override public String toString() { return "[Actor node: id=" + id + " name=\"" + this.getName() + "\"]"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public CollaborationGraphDB<AuthorNode> getDb() { return db; } public void setDb(CollaborationGraphDB<AuthorNode> db) { this.db = db; } private String getAuthorPageUrl() { return getAuthorPageUrlSimple() + Magic.URL_GET_ALL_ARGS; } private String getAuthorPageUrlSimple() { return Magic.URL_BASE + "/" + Magic.URL_AUTHOR_PAGE_SCRIPT_NAME + "?id=" + id; } private class NeighborIterator implements Iterator<AuthorNode> { private static final String XPATH_COLLABORATORS_A = "//div[@class='abstract']/table/tbody/" + "tr[@valign='top']/td/div/a"; private static final String TEXT_LINK_COLLEAGUES = "See all colleagues of this author"; private static final String XPATH_PAPER_A = "//a[starts-with(@href,'citation.cfm')]"; private static final String TEXT_LINK_BIBTEX = "BibTeX"; private Iterator<AuthorNode> iter; NeighborIterator() { List<AuthorNode> adj = new ArrayList<AuthorNode>(); populate(adj, Magic.DEFAULT_JAVASCRIPT_WAIT); iter = adj.iterator(); } @Override public boolean hasNext() { return iter.hasNext(); } @Override public AuthorNode next() { return iter.next(); } @Override public void remove() { throw new UnsupportedOperationException( "remove() not implemented." ); } private void populate(List<AuthorNode> list, int timeoutSeconds) { HtmlUnitDriver driver = new HtmlUnitDriver(true); navigateToColleaguesPage(driver, timeoutSeconds); List<WebElement> aElements = driver.findElements( By.xpath(XPATH_COLLABORATORS_A)); processCoauthorList(aElements, list); navigateToPaperListPage(driver, timeoutSeconds); aElements = driver.findElements(By.xpath(XPATH_PAPER_A)); processPaperList(aElements); downloadBibtex(driver, timeoutSeconds); } private void navigateToColleaguesPage(HtmlUnitDriver driver, int timeoutSeconds) { driver.get(AuthorNode.this.getAuthorPageUrlSimple()); WebDriverWait wait = new WebDriverWait(driver, timeoutSeconds); wait.until(ExpectedConditions .presenceOfElementLocated( By.linkText(TEXT_LINK_COLLEAGUES))); WebElement linkElement = driver.findElement( By.linkText(TEXT_LINK_COLLEAGUES) ); linkElement.click(); wait.until(ExpectedConditions .presenceOfElementLocated( By.xpath(XPATH_COLLABORATORS_A))); } private void processCoauthorList(List<WebElement> aElemList, List<AuthorNode> authors) { for (WebElement e : aElemList) { String href = e.getAttribute("href"); if (href == null) { continue; } int i1 = href.indexOf("id="); if (i1 < 0) { continue; } int i2 = href.indexOf("&"); if (i2 < 0 || i2 < i1) { continue; } String id = href.substring(i1 + "id=".length(), i2).trim(); AuthorNode neighbor = new AuthorNode(id); neighbor.setName(e.getText().trim()); neighbor.setDb(db); authors.add(neighbor); if (db != null) { db.addAuthor(neighbor.getId(), neighbor.getName()); } } } private void navigateToPaperListPage(HtmlUnitDriver driver, int timeoutSeconds) { driver.get(AuthorNode.this.getAuthorPageUrl()); WebDriverWait wait = new WebDriverWait(driver, timeoutSeconds); wait.until(ExpectedConditions .presenceOfElementLocated( By.xpath(XPATH_PAPER_A))); } private void processPaperList(List<WebElement> aElements) { if (AuthorNode.this.db == null) { return; } for (WebElement e : aElements) { String href = e.getAttribute("href"); int i1 = href.indexOf("id="); if (i1 < 0) { continue; } int i2 = href.indexOf("&"); if (i2 < 0) { i2 = href.length(); } else if (i2 < i1) { continue; } String id = href.substring(i1 + "id=".length(), i2).trim(); String name = e.getText().trim(); if (AuthorNode.this.db.addPaper(id, name)) { System.out.println("Added paper: " + name + " id=" + id); AuthorNode.this.db.associate(AuthorNode.this.getId(), id); } } } private void downloadBibtex(WebDriver driver, int timeoutSeconds) { System.out.println("In downloadBibtex(): " + driver.getCurrentUrl()); WebElement e = driver.findElement(By.linkText(TEXT_LINK_BIBTEX)); e.click(); List<WebElement> pres = driver.findElements(By.tagName("pre")); processListOfBibtexReferences(pres); } private void processListOfBibtexReferences(List<WebElement> pres) { if (AuthorNode.this.db == null) { return; } for (WebElement e : pres) { AuthorNode.this.db.addBibtexToPaper(e.getAttribute("id").trim(), e.getText().trim()); } } } }
package org.jivesoftware.openfire.admin; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.util.Map; import java.util.HashMap; import org.jivesoftware.admin.LdapUserProfile; import org.jivesoftware.util.BeanUtils; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.ParamUtils; import java.util.HashMap; import java.util.Map; import org.jivesoftware.openfire.ldap.LdapManager; import org.jivesoftware.openfire.user.UserManager; import org.jivesoftware.openfire.ldap.LdapUserProvider; public final class ldap_002duser_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static java.util.List _jspx_dependants; static { _jspx_dependants = new java.util.ArrayList(1); _jspx_dependants.add("/setup/ldap-user.jspf"); } private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_message_key_nobody; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _jspx_tagPool_fmt_message_key_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); } public void _jspDestroy() { _jspx_tagPool_fmt_message_key_nobody.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write('\n'); out.write('\n'); boolean initialSetup = false; String currentPage = "ldap-user.jsp"; String testPage = "setup/setup-ldap-user_test.jsp"; String nextPage = "ldap-group.jsp"; Map<String, String> meta = new HashMap<String, String>(); meta.put("pageID", "profile-settings"); out.write("\n\n<style type=\"text/css\" title=\"setupStyle\" media=\"screen\">\n\t@import \"style/lightbox.css\";\n\t@import \"style/ldap.css\";\n</style>\n\n<script language=\"JavaScript\" type=\"text/javascript\" src=\"js/prototype.js\"></script>\n<script language=\"JavaScript\" type=\"text/javascript\" src=\"js/scriptaculous.js\"></script>\n<script language=\"JavaScript\" type=\"text/javascript\" src=\"js/lightbox.js\"></script>\n<script language=\"javascript\" type=\"text/javascript\" src=\"js/tooltips/domLib.js\"></script>\n<script language=\"javascript\" type=\"text/javascript\" src=\"js/tooltips/domTT.js\"></script>\n<script language=\"javascript\" type=\"text/javascript\" src=\"js/setup.js\"></script>\n\n"); out.write("\n\n\n\n\n\n\n\n\n\n"); org.jivesoftware.admin.LdapUserProfile vcardBean = null; synchronized (session) { vcardBean = (org.jivesoftware.admin.LdapUserProfile) _jspx_page_context.getAttribute("vcardBean", PageContext.SESSION_SCOPE); if (vcardBean == null){ vcardBean = new org.jivesoftware.admin.LdapUserProfile(); _jspx_page_context.setAttribute("vcardBean", vcardBean, PageContext.SESSION_SCOPE); } } out.write('\n'); out.write('\n'); // Get parameters String serverType = ParamUtils.getParameter(request, "serverType"); // Server type should never be null, but if it is, assume "other" if (serverType == null) { serverType = "other"; } LdapManager manager = LdapManager.getInstance(); @SuppressWarnings("unchecked") Map<String,String> xmppSettings = (Map<String,String>)session.getAttribute("xmppSettings"); // Determine the right default values based on the the server type. String defaultUsernameField; String defaultSearchFields; String defaultSearchFilter; // First check if the http session holds data from a previous post of this page if (session.getAttribute("ldapUserSettings") != null && session.getAttribute("ldapVCardBean") != null) { @SuppressWarnings("unchecked") Map<String, String> userSettings = (Map<String, String>) session.getAttribute("ldapUserSettings"); defaultUsernameField = userSettings.get("ldap.usernameField"); defaultSearchFields = userSettings.get("ldap.searchFields"); defaultSearchFilter = userSettings.get("ldap.searchFilter"); vcardBean = (LdapUserProfile) session.getAttribute("ldapVCardBean"); } else { // No info in the session so try stored XML values or default ones defaultUsernameField = JiveGlobals.getProperty("ldap.usernameField"); defaultSearchFields = JiveGlobals.getProperty("ldap.searchFields"); defaultSearchFilter = JiveGlobals.getProperty("ldap.searchFilter"); vcardBean = new LdapUserProfile(); if (vcardBean.loadFromProperties()) { // Loaded from stored settings, no need to do anything else. } else if (serverType.equals("activedirectory")) { if (!vcardBean.loadFromProperties()) { // Initialize vCard mappings vcardBean.initForActiveDirectory(); } if (defaultUsernameField == null) { defaultUsernameField = "sAMAccountName"; // Initialize vCard mappings } if (defaultSearchFilter == null) { defaultSearchFilter = "(objectClass=organizationalPerson)"; } } else { if (!vcardBean.loadFromProperties()) { // Initialize vCard mappings vcardBean.initForOpenLDAP(); } if (defaultUsernameField == null) { defaultUsernameField = "uid"; } } } String usernameField = defaultUsernameField; String searchFields = defaultSearchFields; String searchFilter = defaultSearchFilter; Map<String, String> errors = new HashMap<String, String>(); boolean save = request.getParameter("save") != null; boolean doTest = request.getParameter("test") != null; boolean isTesting = request.getParameter("userIndex") != null; if ((save || doTest) && !isTesting) { usernameField = ParamUtils.getParameter(request, "usernameField"); if (usernameField == null) { errors.put("username", LocaleUtils.getLocalizedString("setup.ldap.user.username_field_error")); } searchFields = ParamUtils.getParameter(request, "searchFields"); searchFilter = ParamUtils.getParameter(request, "searchFilter"); // Set the properties to the vCard bean with the user input BeanUtils.setProperties(vcardBean, request); if (request.getParameter("storeAvatarInDB") != null) { vcardBean.setAvatarStoredInDB(true); } else { vcardBean.setAvatarStoredInDB(false); } // Store the vcard db setting for later saving. if (xmppSettings != null) { xmppSettings.put("ldap.override.avatar", vcardBean.getAvatarStoredInDB().toString()); } // Save settings and redirect. if (errors.isEmpty()) { // Save information in the session so we can use it in testing pages during setup Map<String, String> settings = new HashMap<String, String>(); settings.put("ldap.usernameField", usernameField); settings.put("ldap.searchFields", searchFields); settings.put("ldap.searchFilter", searchFilter); session.setAttribute("ldapUserSettings", settings); session.setAttribute("ldapVCardBean", vcardBean); if (save) { manager.setUsernameField(usernameField); if (searchFields != null) { if ("org.jivesoftware.openfire.ldap.LdapUserProvider" .equals(JiveGlobals.getProperty("provider.user.className"))) { // Update current instance being used ((LdapUserProvider) UserManager.getUserProvider()).setSearchFields(searchFields); } else { // Just update the property. It will be later used by LdapUserProvider JiveGlobals.setProperty("ldap.searchFields", searchFields); // Store in xmppSettings for later saving if we're in setup if (xmppSettings != null) { xmppSettings.put("ldap.searchFields", searchFields); } } } if (searchFilter != null) { manager.setSearchFilter(searchFilter); } // Save vCard mappings vcardBean.saveProperties(); // Enable the LDAP auth and user providers. The group provider will be enabled on the next step. JiveGlobals.setProperty("provider.user.className", "org.jivesoftware.openfire.ldap.LdapUserProvider"); JiveGlobals.setProperty("provider.auth.className", "org.jivesoftware.openfire.ldap.LdapAuthProvider"); // Store in xmppSettings for later saving if we're in setup if (xmppSettings != null) { xmppSettings.put("provider.user.className", "org.jivesoftware.openfire.ldap.LdapUserProvider"); xmppSettings.put("provider.auth.className", "org.jivesoftware.openfire.ldap.LdapAuthProvider"); } // Redirect response.sendRedirect(nextPage + "?serverType=" + serverType); return; } } // Save the settings for later, if we're in setup if (xmppSettings != null) { session.setAttribute("xmppSettings", xmppSettings); } } out.write("\n<html>\n<head>\n <title>"); if (_jspx_meth_fmt_message_0(_jspx_page_context)) return; out.write("</title>\n "); for (Map.Entry<String, String> entry : meta.entrySet()) { out.write("\n <meta name=\""); out.print( entry.getKey()); out.write("\" content=\""); out.print( entry.getValue()); out.write("\"/>\n "); } out.write("\n</head>\n\n<body>\n\n "); if (doTest && errors.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append(testPage); sb.append("?serverType=").append(serverType); sb.append("&currentPage=").append(currentPage); if (isTesting) { sb.append("&userIndex=").append(request.getParameter("userIndex")); } out.write("\n <a href=\""); out.print( sb.toString()); out.write("\" id=\"lbmessage\" title=\""); if (_jspx_meth_fmt_message_1(_jspx_page_context)) return; out.write("\" style=\"display:none;\"></a>\n <script type=\"text/javascript\">\n function loadMsg() {\n var lb = new lightbox(document.getElementById('lbmessage'));\n lb.activate();\n }\n setTimeout('loadMsg()', 250);\n </script>\n\n "); } out.write("\n\n "); if (initialSetup) { out.write("\n\t<h1>"); if (_jspx_meth_fmt_message_2(_jspx_page_context)) return; out.write(": <span>"); if (_jspx_meth_fmt_message_3(_jspx_page_context)) return; out.write("</span></h1>\n "); } out.write("\n\n\t<!-- BEGIN jive-contentBox_stepbar -->\n\t<div id=\"jive-contentBox_stepbar\">\n\t\t<span class=\"jive-stepbar_step\"><em>1. "); if (_jspx_meth_fmt_message_4(_jspx_page_context)) return; out.write("</em></span>\n\t\t<span class=\"jive-stepbar_step\"><strong>2. "); if (_jspx_meth_fmt_message_5(_jspx_page_context)) return; out.write("</strong></span>\n\t\t<span class=\"jive-stepbar_step\"><em>3. "); if (_jspx_meth_fmt_message_6(_jspx_page_context)) return; out.write("</em></span>\n\t</div>\n\t<!-- END jive-contentBox-stepbar -->\n\n\t<!-- BEGIN jive-contentBox -->\n\t<div class=\"jive-contentBox jive-contentBox_for-stepbar\">\n\n\t<h2>"); if (_jspx_meth_fmt_message_7(_jspx_page_context)) return; out.write(": <span>"); if (_jspx_meth_fmt_message_8(_jspx_page_context)) return; out.write("</span></h2>\n\t<p>"); if (_jspx_meth_fmt_message_9(_jspx_page_context)) return; out.write("</p>\n\n "); if (errors.size() > 0) { out.write("\n\n <div class=\"error\">\n "); for (String error:errors.values()) { out.write("\n "); out.print( error); out.write("<br/>\n "); } out.write("\n </div>\n\n "); } out.write("\n\n <form action=\""); out.print( currentPage); out.write("\" method=\"post\">\n\t\t<input type=\"hidden\" name=\"serverType\" value=\""); out.print(serverType); out.write("\"/>\n <!-- BEGIN jive-contentBox_bluebox -->\n\t\t<div class=\"jive-contentBox_bluebox\">\n\n\t\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\">\n\t\t\t<tr>\n\t\t\t<td colspan=\"2\"><strong>"); if (_jspx_meth_fmt_message_10(_jspx_page_context)) return; out.write("</strong></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t<td align=\"right\">"); if (_jspx_meth_fmt_message_11(_jspx_page_context)) return; out.write(":</td>\n\t\t\t<td><input type=\"text\" name=\"usernameField\" id=\"jiveLDAPusername\" size=\"22\" maxlength=\"50\" value=\""); out.print( usernameField!=null?usernameField:""); out.write("\"><span class=\"jive-setup-helpicon\" onmouseover=\"domTT_activate(this, event, 'content', '"); if (_jspx_meth_fmt_message_12(_jspx_page_context)) return; out.write("', 'styleClass', 'jiveTooltip', 'trail', true, 'delay', 300, 'lifetime', -1);\"/></td>\n\t\t\t</tr>\n\t\t\t</table>\n\n\t\t\t<!-- BEGIN jiveAdvancedButton -->\n\t\t\t<div class=\"jiveAdvancedButton jiveAdvancedButtonTopPad\">\n\t\t\t\t<a href=\"#\" onclick=\"togglePanel(jiveAdvanced); return false;\" id=\"jiveAdvancedLink\">"); if (_jspx_meth_fmt_message_13(_jspx_page_context)) return; out.write("</a>\n\t\t\t</div>\n\t\t\t<!-- END jiveAdvancedButton -->\n\n\t\t\t<!-- BEGIN jiveAdvancedPanelu (advanced user mapping settings) -->\n\t\t\t\t<div class=\"jiveadvancedPanelu\" id=\"jiveAdvanced\" style=\"display: none;\">\n\t\t\t\t\t<div>\n\t\t\t\t\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td align=\"right\">"); if (_jspx_meth_fmt_message_14(_jspx_page_context)) return; out.write(":</td>\n\t\t\t\t\t\t<td><input type=\"text\" name=\"searchFields\" value=\""); out.print( searchFields!=null?searchFields:""); out.write("\" id=\"jiveLDAPsearchfields\" size=\"40\" maxlength=\"250\"><span class=\"jive-setup-helpicon\" onmouseover=\"domTT_activate(this, event, 'content', '"); if (_jspx_meth_fmt_message_15(_jspx_page_context)) return; out.write("', 'styleClass', 'jiveTooltip', 'trail', true, 'delay', 300, 'lifetime', -1);\"/></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td align=\"right\">"); if (_jspx_meth_fmt_message_16(_jspx_page_context)) return; out.write(":</td>\n\t\t\t\t\t\t<td><input type=\"text\" name=\"searchFilter\" value=\""); out.print( searchFilter!=null?searchFilter:""); out.write("\" id=\"jiveLDAPsearchfilter\" size=\"40\" maxlength=\"250\"><span class=\"jive-setup-helpicon\" onmouseover=\"domTT_activate(this, event, 'content', '"); if (_jspx_meth_fmt_message_17(_jspx_page_context)) return; out.write("', 'styleClass', 'jiveTooltip', 'trail', true, 'delay', 300, 'lifetime', -1);\"/></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t<!-- END jiveAdvancedPanelu (advanced user mapping settings) -->\n\n\t\t</div>\n\t\t<!-- END jive-contentBox_bluebox -->\n\n\n\t\t<script type=\"text/javascript\" language=\"JavaScript\">\n\t\t\tfunction jiveRowHighlight(theInput) {\n\n\t\t\t\tvar e = $(jivevCardTable).getElementsByTagName('tr');\n\t\t\t\t\tfor (var i = 0; i < e.length; i++) {\n\t\t\t\t\t\t\te[i].style.backgroundColor = \"#fff\";\n\t\t\t\t\t}\n\n\t\t\t\ttheInput.parentNode.parentNode.style.backgroundColor = \"#eaeff4\";\n\t\t\t}\n\n\t\t</script>\n\t\t<!-- BEGIN jive-contentBox_greybox -->\n\t\t<div class=\"jive-contentBox_greybox\">\n\t\t\t<strong>"); if (_jspx_meth_fmt_message_18(_jspx_page_context)) return; out.write("</strong>\n\t\t\t<p>"); if (_jspx_meth_fmt_message_19(_jspx_page_context)) return; out.write("<br/>\n <input type=\"checkbox\" value=\"enabled\" name=\"storeAvatarInDB\""); out.print( vcardBean.getAvatarStoredInDB() ? " checked" : ""); out.write('/'); out.write('>'); out.write(' '); if (_jspx_meth_fmt_message_20(_jspx_page_context)) return; out.write("</p>\n\n\t\t\t<!-- BEGIN vcard table -->\n\t\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"1\" class=\"jive-vcardTable\" id=\"jivevCardTable\">\n\t\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th width=\"40%\">"); if (_jspx_meth_fmt_message_21(_jspx_page_context)) return; out.write("</th>\n\t\t\t\t\t<th width=\"60%\">"); if (_jspx_meth_fmt_message_22(_jspx_page_context)) return; out.write("</th>\n\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_23(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"name\" value=\""); out.print( vcardBean.getName() ); out.write("\" id=\"name\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_24(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"email\" value=\""); out.print( vcardBean.getEmail() ); out.write("\" id=\"email\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t&nbsp;\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t&nbsp;\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_25(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"fullName\" value=\""); out.print( vcardBean.getFullName() ); out.write("\" id=\"fullName\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_26(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"nickname\" value=\""); out.print( vcardBean.getNickname() ); out.write("\" id=\"nickname\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_27(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"birthday\" value=\""); out.print( vcardBean.getBirthday() ); out.write("\" id=\"birthday\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_28(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"photo\" value=\""); out.print( vcardBean.getPhoto() ); out.write("\" id=\"photo\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_29(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t&nbsp;\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_30(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeStreet\" value=\""); out.print( vcardBean.getHomeStreet() ); out.write("\" id=\"homeStreet\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_31(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeCity\" value=\""); out.print( vcardBean.getHomeCity() ); out.write("\" id=\"homeCity\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_32(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeState\" value=\""); out.print( vcardBean.getHomeState() ); out.write("\" id=\"homeState\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_33(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeZip\" value=\""); out.print( vcardBean.getHomeZip() ); out.write("\" id=\"homeZip\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_34(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeCountry\" value=\""); out.print( vcardBean.getHomeCountry() ); out.write("\" id=\"homeCountry\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_35(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homePhone\" value=\""); out.print( vcardBean.getHomePhone() ); out.write("\" id=\"homePhone\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_36(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeMobile\" value=\""); out.print( vcardBean.getHomeMobile() ); out.write("\" id=\"homeMobile\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_37(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homeFax\" value=\""); out.print( vcardBean.getHomeFax() ); out.write("\" id=\"homeFax\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_38(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"homePager\" value=\""); out.print( vcardBean.getHomePager() ); out.write("\" id=\"homePager\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t<strong>"); if (_jspx_meth_fmt_message_39(_jspx_page_context)) return; out.write("</strong>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t&nbsp;\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_40(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessStreet\" value=\""); out.print( vcardBean.getBusinessStreet() ); out.write("\" id=\"businessStreet\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_41(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessCity\" value=\""); out.print( vcardBean.getBusinessCity() ); out.write("\" id=\"businessCity\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_42(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessState\" value=\""); out.print( vcardBean.getBusinessState() ); out.write("\" id=\"businessState\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_43(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessZip\" value=\""); out.print( vcardBean.getBusinessZip() ); out.write("\" id=\"businessZip\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_44(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessCountry\" value=\""); out.print( vcardBean.getBusinessCountry() ); out.write("\" id=\"businessCountry\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_45(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessJobTitle\" value=\""); out.print( vcardBean.getBusinessJobTitle() ); out.write("\" id=\"businessJobTitle\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_46(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessDepartment\" value=\""); out.print( vcardBean.getBusinessDepartment() ); out.write("\" id=\"businessDepartment\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_47(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessPhone\" value=\""); out.print( vcardBean.getBusinessPhone() ); out.write("\" id=\"businessPhone\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_48(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessMobile\" value=\""); out.print( vcardBean.getBusinessMobile() ); out.write("\" id=\"businessMobile\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_49(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessFax\" value=\""); out.print( vcardBean.getBusinessFax() ); out.write("\" id=\"businessFax\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"jive-vcardTable-label jive-vardBorderBottom jive-vardBorderRight\" nowrap>\n\t\t\t\t\t\t- "); if (_jspx_meth_fmt_message_50(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class=\"jive-vcardTable-value jive-vardBorderBottom\">\n\t\t\t\t\t\t<input type=\"text\" name=\"businessPager\" value=\""); out.print( vcardBean.getBusinessPager() ); out.write("\" id=\"businessPager\" size=\"22\" maxlength=\"50\" onFocus=\"jiveRowHighlight(this);\">\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<!-- END vcard table -->\n\n\t\t</div>\n\t\t<!-- END jive-contentBox_greybox -->\n\n\t\t<!-- BEGIN jive-buttons -->\n\t\t<div class=\"jive-buttons\">\n\n\t\t\t<!-- BEGIN right-aligned buttons -->\n\t\t\t<div align=\"right\">\n <input type=\"Submit\" name=\"test\" value=\""); if (_jspx_meth_fmt_message_51(_jspx_page_context)) return; out.write("\" id=\"jive-setup-test\" border=\"0\">\n\n\t\t\t\t<input type=\"Submit\" name=\"save\" value=\""); if (_jspx_meth_fmt_message_52(_jspx_page_context)) return; out.write("\" id=\"jive-setup-save\" border=\"0\">\n\t\t\t</div>\n\t\t\t<!-- END right-aligned buttons -->\n\n\t\t</div>\n\t\t<!-- END jive-buttons -->\n\n\t</form>\n\n\t</div>\n\t<!-- END jive-contentBox -->\n\n\n\n</body>\n</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_fmt_message_0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_0.setPageContext(_jspx_page_context); _jspx_th_fmt_message_0.setParent(null); _jspx_th_fmt_message_0.setKey("setup.ldap.title"); int _jspx_eval_fmt_message_0 = _jspx_th_fmt_message_0.doStartTag(); if (_jspx_th_fmt_message_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_0); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_0); return false; } private boolean _jspx_meth_fmt_message_1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_1.setPageContext(_jspx_page_context); _jspx_th_fmt_message_1.setParent(null); _jspx_th_fmt_message_1.setKey("global.test"); int _jspx_eval_fmt_message_1 = _jspx_th_fmt_message_1.doStartTag(); if (_jspx_th_fmt_message_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_1); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_1); return false; } private boolean _jspx_meth_fmt_message_2(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_2 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_2.setPageContext(_jspx_page_context); _jspx_th_fmt_message_2.setParent(null); _jspx_th_fmt_message_2.setKey("setup.ldap.profile"); int _jspx_eval_fmt_message_2 = _jspx_th_fmt_message_2.doStartTag(); if (_jspx_th_fmt_message_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_2); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_2); return false; } private boolean _jspx_meth_fmt_message_3(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_3 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_3.setPageContext(_jspx_page_context); _jspx_th_fmt_message_3.setParent(null); _jspx_th_fmt_message_3.setKey("setup.ldap.user_mapping"); int _jspx_eval_fmt_message_3 = _jspx_th_fmt_message_3.doStartTag(); if (_jspx_th_fmt_message_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_3); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_3); return false; } private boolean _jspx_meth_fmt_message_4(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_4 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_4.setPageContext(_jspx_page_context); _jspx_th_fmt_message_4.setParent(null); _jspx_th_fmt_message_4.setKey("setup.ldap.connection_settings"); int _jspx_eval_fmt_message_4 = _jspx_th_fmt_message_4.doStartTag(); if (_jspx_th_fmt_message_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_4); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_4); return false; } private boolean _jspx_meth_fmt_message_5(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_5 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_5.setPageContext(_jspx_page_context); _jspx_th_fmt_message_5.setParent(null); _jspx_th_fmt_message_5.setKey("setup.ldap.user_mapping"); int _jspx_eval_fmt_message_5 = _jspx_th_fmt_message_5.doStartTag(); if (_jspx_th_fmt_message_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_5); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_5); return false; } private boolean _jspx_meth_fmt_message_6(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_6 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_6.setPageContext(_jspx_page_context); _jspx_th_fmt_message_6.setParent(null); _jspx_th_fmt_message_6.setKey("setup.ldap.group_mapping"); int _jspx_eval_fmt_message_6 = _jspx_th_fmt_message_6.doStartTag(); if (_jspx_th_fmt_message_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_6); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_6); return false; } private boolean _jspx_meth_fmt_message_7(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_7 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_7.setPageContext(_jspx_page_context); _jspx_th_fmt_message_7.setParent(null); _jspx_th_fmt_message_7.setKey("setup.ldap.step_two"); int _jspx_eval_fmt_message_7 = _jspx_th_fmt_message_7.doStartTag(); if (_jspx_th_fmt_message_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_7); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_7); return false; } private boolean _jspx_meth_fmt_message_8(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_8 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_8.setPageContext(_jspx_page_context); _jspx_th_fmt_message_8.setParent(null); _jspx_th_fmt_message_8.setKey("setup.ldap.user_mapping"); int _jspx_eval_fmt_message_8 = _jspx_th_fmt_message_8.doStartTag(); if (_jspx_th_fmt_message_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_8); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_8); return false; } private boolean _jspx_meth_fmt_message_9(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_9 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_9.setPageContext(_jspx_page_context); _jspx_th_fmt_message_9.setParent(null); _jspx_th_fmt_message_9.setKey("setup.ldap.user.description"); int _jspx_eval_fmt_message_9 = _jspx_th_fmt_message_9.doStartTag(); if (_jspx_th_fmt_message_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_9); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_9); return false; } private boolean _jspx_meth_fmt_message_10(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_10 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_10.setPageContext(_jspx_page_context); _jspx_th_fmt_message_10.setParent(null); _jspx_th_fmt_message_10.setKey("setup.ldap.user_mapping"); int _jspx_eval_fmt_message_10 = _jspx_th_fmt_message_10.doStartTag(); if (_jspx_th_fmt_message_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_10); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_10); return false; } private boolean _jspx_meth_fmt_message_11(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_11 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_11.setPageContext(_jspx_page_context); _jspx_th_fmt_message_11.setParent(null); _jspx_th_fmt_message_11.setKey("setup.ldap.user.username_field"); int _jspx_eval_fmt_message_11 = _jspx_th_fmt_message_11.doStartTag(); if (_jspx_th_fmt_message_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_11); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_11); return false; } private boolean _jspx_meth_fmt_message_12(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_12 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_12.setPageContext(_jspx_page_context); _jspx_th_fmt_message_12.setParent(null); _jspx_th_fmt_message_12.setKey("setup.ldap.user.username_field_description"); int _jspx_eval_fmt_message_12 = _jspx_th_fmt_message_12.doStartTag(); if (_jspx_th_fmt_message_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_12); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_12); return false; } private boolean _jspx_meth_fmt_message_13(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_13 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_13.setPageContext(_jspx_page_context); _jspx_th_fmt_message_13.setParent(null); _jspx_th_fmt_message_13.setKey("setup.ldap.advanced"); int _jspx_eval_fmt_message_13 = _jspx_th_fmt_message_13.doStartTag(); if (_jspx_th_fmt_message_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_13); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_13); return false; } private boolean _jspx_meth_fmt_message_14(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_14 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_14.setPageContext(_jspx_page_context); _jspx_th_fmt_message_14.setParent(null); _jspx_th_fmt_message_14.setKey("setup.ldap.user.search_fields"); int _jspx_eval_fmt_message_14 = _jspx_th_fmt_message_14.doStartTag(); if (_jspx_th_fmt_message_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_14); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_14); return false; } private boolean _jspx_meth_fmt_message_15(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_15 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_15.setPageContext(_jspx_page_context); _jspx_th_fmt_message_15.setParent(null); _jspx_th_fmt_message_15.setKey("setup.ldap.user.search_fields_description"); int _jspx_eval_fmt_message_15 = _jspx_th_fmt_message_15.doStartTag(); if (_jspx_th_fmt_message_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_15); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_15); return false; } private boolean _jspx_meth_fmt_message_16(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_16 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_16.setPageContext(_jspx_page_context); _jspx_th_fmt_message_16.setParent(null); _jspx_th_fmt_message_16.setKey("setup.ldap.user.user_filter"); int _jspx_eval_fmt_message_16 = _jspx_th_fmt_message_16.doStartTag(); if (_jspx_th_fmt_message_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_16); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_16); return false; } private boolean _jspx_meth_fmt_message_17(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_17 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_17.setPageContext(_jspx_page_context); _jspx_th_fmt_message_17.setParent(null); _jspx_th_fmt_message_17.setKey("setup.ldap.user.user_filter_description"); int _jspx_eval_fmt_message_17 = _jspx_th_fmt_message_17.doStartTag(); if (_jspx_th_fmt_message_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_17); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_17); return false; } private boolean _jspx_meth_fmt_message_18(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_18 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_18.setPageContext(_jspx_page_context); _jspx_th_fmt_message_18.setParent(null); _jspx_th_fmt_message_18.setKey("setup.ldap.user.vcard.mapping"); int _jspx_eval_fmt_message_18 = _jspx_th_fmt_message_18.doStartTag(); if (_jspx_th_fmt_message_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_18); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_18); return false; } private boolean _jspx_meth_fmt_message_19(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_19 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_19.setPageContext(_jspx_page_context); _jspx_th_fmt_message_19.setParent(null); _jspx_th_fmt_message_19.setKey("setup.ldap.user.vcard.description"); int _jspx_eval_fmt_message_19 = _jspx_th_fmt_message_19.doStartTag(); if (_jspx_th_fmt_message_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_19); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_19); return false; } private boolean _jspx_meth_fmt_message_20(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_20 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_20.setPageContext(_jspx_page_context); _jspx_th_fmt_message_20.setParent(null); _jspx_th_fmt_message_20.setKey("setup.ldap.user.vcard.avatardb"); int _jspx_eval_fmt_message_20 = _jspx_th_fmt_message_20.doStartTag(); if (_jspx_th_fmt_message_20.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_20); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_20); return false; } private boolean _jspx_meth_fmt_message_21(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_21 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_21.setPageContext(_jspx_page_context); _jspx_th_fmt_message_21.setParent(null); _jspx_th_fmt_message_21.setKey("setup.ldap.user.vcard.label1"); int _jspx_eval_fmt_message_21 = _jspx_th_fmt_message_21.doStartTag(); if (_jspx_th_fmt_message_21.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_21); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_21); return false; } private boolean _jspx_meth_fmt_message_22(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_22 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_22.setPageContext(_jspx_page_context); _jspx_th_fmt_message_22.setParent(null); _jspx_th_fmt_message_22.setKey("setup.ldap.user.vcard.label2"); int _jspx_eval_fmt_message_22 = _jspx_th_fmt_message_22.doStartTag(); if (_jspx_th_fmt_message_22.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_22); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_22); return false; } private boolean _jspx_meth_fmt_message_23(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_23 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_23.setPageContext(_jspx_page_context); _jspx_th_fmt_message_23.setParent(null); _jspx_th_fmt_message_23.setKey("setup.ldap.user.vcard.name"); int _jspx_eval_fmt_message_23 = _jspx_th_fmt_message_23.doStartTag(); if (_jspx_th_fmt_message_23.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_23); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_23); return false; } private boolean _jspx_meth_fmt_message_24(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_24 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_24.setPageContext(_jspx_page_context); _jspx_th_fmt_message_24.setParent(null); _jspx_th_fmt_message_24.setKey("setup.ldap.user.vcard.email"); int _jspx_eval_fmt_message_24 = _jspx_th_fmt_message_24.doStartTag(); if (_jspx_th_fmt_message_24.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_24); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_24); return false; } private boolean _jspx_meth_fmt_message_25(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_25 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_25.setPageContext(_jspx_page_context); _jspx_th_fmt_message_25.setParent(null); _jspx_th_fmt_message_25.setKey("setup.ldap.user.vcard.fullname"); int _jspx_eval_fmt_message_25 = _jspx_th_fmt_message_25.doStartTag(); if (_jspx_th_fmt_message_25.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_25); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_25); return false; } private boolean _jspx_meth_fmt_message_26(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_26 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_26.setPageContext(_jspx_page_context); _jspx_th_fmt_message_26.setParent(null); _jspx_th_fmt_message_26.setKey("setup.ldap.user.vcard.nickname"); int _jspx_eval_fmt_message_26 = _jspx_th_fmt_message_26.doStartTag(); if (_jspx_th_fmt_message_26.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_26); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_26); return false; } private boolean _jspx_meth_fmt_message_27(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_27 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_27.setPageContext(_jspx_page_context); _jspx_th_fmt_message_27.setParent(null); _jspx_th_fmt_message_27.setKey("setup.ldap.user.vcard.birthday"); int _jspx_eval_fmt_message_27 = _jspx_th_fmt_message_27.doStartTag(); if (_jspx_th_fmt_message_27.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_27); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_27); return false; } private boolean _jspx_meth_fmt_message_28(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_28 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_28.setPageContext(_jspx_page_context); _jspx_th_fmt_message_28.setParent(null); _jspx_th_fmt_message_28.setKey("setup.ldap.user.vcard.photo"); int _jspx_eval_fmt_message_28 = _jspx_th_fmt_message_28.doStartTag(); if (_jspx_th_fmt_message_28.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_28); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_28); return false; } private boolean _jspx_meth_fmt_message_29(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_29 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_29.setPageContext(_jspx_page_context); _jspx_th_fmt_message_29.setParent(null); _jspx_th_fmt_message_29.setKey("setup.ldap.user.vcard.home"); int _jspx_eval_fmt_message_29 = _jspx_th_fmt_message_29.doStartTag(); if (_jspx_th_fmt_message_29.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_29); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_29); return false; } private boolean _jspx_meth_fmt_message_30(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_30 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_30.setPageContext(_jspx_page_context); _jspx_th_fmt_message_30.setParent(null); _jspx_th_fmt_message_30.setKey("setup.ldap.user.vcard.street"); int _jspx_eval_fmt_message_30 = _jspx_th_fmt_message_30.doStartTag(); if (_jspx_th_fmt_message_30.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_30); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_30); return false; } private boolean _jspx_meth_fmt_message_31(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_31 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_31.setPageContext(_jspx_page_context); _jspx_th_fmt_message_31.setParent(null); _jspx_th_fmt_message_31.setKey("setup.ldap.user.vcard.city"); int _jspx_eval_fmt_message_31 = _jspx_th_fmt_message_31.doStartTag(); if (_jspx_th_fmt_message_31.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_31); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_31); return false; } private boolean _jspx_meth_fmt_message_32(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_32 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_32.setPageContext(_jspx_page_context); _jspx_th_fmt_message_32.setParent(null); _jspx_th_fmt_message_32.setKey("setup.ldap.user.vcard.state"); int _jspx_eval_fmt_message_32 = _jspx_th_fmt_message_32.doStartTag(); if (_jspx_th_fmt_message_32.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_32); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_32); return false; } private boolean _jspx_meth_fmt_message_33(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_33 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_33.setPageContext(_jspx_page_context); _jspx_th_fmt_message_33.setParent(null); _jspx_th_fmt_message_33.setKey("setup.ldap.user.vcard.pcode"); int _jspx_eval_fmt_message_33 = _jspx_th_fmt_message_33.doStartTag(); if (_jspx_th_fmt_message_33.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_33); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_33); return false; } private boolean _jspx_meth_fmt_message_34(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_34 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_34.setPageContext(_jspx_page_context); _jspx_th_fmt_message_34.setParent(null); _jspx_th_fmt_message_34.setKey("setup.ldap.user.vcard.country"); int _jspx_eval_fmt_message_34 = _jspx_th_fmt_message_34.doStartTag(); if (_jspx_th_fmt_message_34.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_34); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_34); return false; } private boolean _jspx_meth_fmt_message_35(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_35 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_35.setPageContext(_jspx_page_context); _jspx_th_fmt_message_35.setParent(null); _jspx_th_fmt_message_35.setKey("setup.ldap.user.vcard.phone"); int _jspx_eval_fmt_message_35 = _jspx_th_fmt_message_35.doStartTag(); if (_jspx_th_fmt_message_35.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_35); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_35); return false; } private boolean _jspx_meth_fmt_message_36(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_36 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_36.setPageContext(_jspx_page_context); _jspx_th_fmt_message_36.setParent(null); _jspx_th_fmt_message_36.setKey("setup.ldap.user.vcard.mobile"); int _jspx_eval_fmt_message_36 = _jspx_th_fmt_message_36.doStartTag(); if (_jspx_th_fmt_message_36.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_36); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_36); return false; } private boolean _jspx_meth_fmt_message_37(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_37 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_37.setPageContext(_jspx_page_context); _jspx_th_fmt_message_37.setParent(null); _jspx_th_fmt_message_37.setKey("setup.ldap.user.vcard.fax"); int _jspx_eval_fmt_message_37 = _jspx_th_fmt_message_37.doStartTag(); if (_jspx_th_fmt_message_37.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_37); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_37); return false; } private boolean _jspx_meth_fmt_message_38(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_38 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_38.setPageContext(_jspx_page_context); _jspx_th_fmt_message_38.setParent(null); _jspx_th_fmt_message_38.setKey("setup.ldap.user.vcard.pager"); int _jspx_eval_fmt_message_38 = _jspx_th_fmt_message_38.doStartTag(); if (_jspx_th_fmt_message_38.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_38); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_38); return false; } private boolean _jspx_meth_fmt_message_39(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_39 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_39.setPageContext(_jspx_page_context); _jspx_th_fmt_message_39.setParent(null); _jspx_th_fmt_message_39.setKey("setup.ldap.user.vcard.business"); int _jspx_eval_fmt_message_39 = _jspx_th_fmt_message_39.doStartTag(); if (_jspx_th_fmt_message_39.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_39); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_39); return false; } private boolean _jspx_meth_fmt_message_40(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_40 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_40.setPageContext(_jspx_page_context); _jspx_th_fmt_message_40.setParent(null); _jspx_th_fmt_message_40.setKey("setup.ldap.user.vcard.street"); int _jspx_eval_fmt_message_40 = _jspx_th_fmt_message_40.doStartTag(); if (_jspx_th_fmt_message_40.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_40); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_40); return false; } private boolean _jspx_meth_fmt_message_41(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_41 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_41.setPageContext(_jspx_page_context); _jspx_th_fmt_message_41.setParent(null); _jspx_th_fmt_message_41.setKey("setup.ldap.user.vcard.city"); int _jspx_eval_fmt_message_41 = _jspx_th_fmt_message_41.doStartTag(); if (_jspx_th_fmt_message_41.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_41); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_41); return false; } private boolean _jspx_meth_fmt_message_42(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_42 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_42.setPageContext(_jspx_page_context); _jspx_th_fmt_message_42.setParent(null); _jspx_th_fmt_message_42.setKey("setup.ldap.user.vcard.state"); int _jspx_eval_fmt_message_42 = _jspx_th_fmt_message_42.doStartTag(); if (_jspx_th_fmt_message_42.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_42); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_42); return false; } private boolean _jspx_meth_fmt_message_43(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_43 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_43.setPageContext(_jspx_page_context); _jspx_th_fmt_message_43.setParent(null); _jspx_th_fmt_message_43.setKey("setup.ldap.user.vcard.pcode"); int _jspx_eval_fmt_message_43 = _jspx_th_fmt_message_43.doStartTag(); if (_jspx_th_fmt_message_43.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_43); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_43); return false; } private boolean _jspx_meth_fmt_message_44(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_44 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_44.setPageContext(_jspx_page_context); _jspx_th_fmt_message_44.setParent(null); _jspx_th_fmt_message_44.setKey("setup.ldap.user.vcard.country"); int _jspx_eval_fmt_message_44 = _jspx_th_fmt_message_44.doStartTag(); if (_jspx_th_fmt_message_44.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_44); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_44); return false; } private boolean _jspx_meth_fmt_message_45(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_45 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_45.setPageContext(_jspx_page_context); _jspx_th_fmt_message_45.setParent(null); _jspx_th_fmt_message_45.setKey("setup.ldap.user.vcard.title"); int _jspx_eval_fmt_message_45 = _jspx_th_fmt_message_45.doStartTag(); if (_jspx_th_fmt_message_45.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_45); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_45); return false; } private boolean _jspx_meth_fmt_message_46(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_46 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_46.setPageContext(_jspx_page_context); _jspx_th_fmt_message_46.setParent(null); _jspx_th_fmt_message_46.setKey("setup.ldap.user.vcard.department"); int _jspx_eval_fmt_message_46 = _jspx_th_fmt_message_46.doStartTag(); if (_jspx_th_fmt_message_46.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_46); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_46); return false; } private boolean _jspx_meth_fmt_message_47(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_47 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_47.setPageContext(_jspx_page_context); _jspx_th_fmt_message_47.setParent(null); _jspx_th_fmt_message_47.setKey("setup.ldap.user.vcard.phone"); int _jspx_eval_fmt_message_47 = _jspx_th_fmt_message_47.doStartTag(); if (_jspx_th_fmt_message_47.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_47); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_47); return false; } private boolean _jspx_meth_fmt_message_48(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_48 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_48.setPageContext(_jspx_page_context); _jspx_th_fmt_message_48.setParent(null); _jspx_th_fmt_message_48.setKey("setup.ldap.user.vcard.mobile"); int _jspx_eval_fmt_message_48 = _jspx_th_fmt_message_48.doStartTag(); if (_jspx_th_fmt_message_48.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_48); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_48); return false; } private boolean _jspx_meth_fmt_message_49(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_49 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_49.setPageContext(_jspx_page_context); _jspx_th_fmt_message_49.setParent(null); _jspx_th_fmt_message_49.setKey("setup.ldap.user.vcard.fax"); int _jspx_eval_fmt_message_49 = _jspx_th_fmt_message_49.doStartTag(); if (_jspx_th_fmt_message_49.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_49); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_49); return false; } private boolean _jspx_meth_fmt_message_50(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_50 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_50.setPageContext(_jspx_page_context); _jspx_th_fmt_message_50.setParent(null); _jspx_th_fmt_message_50.setKey("setup.ldap.user.vcard.pager"); int _jspx_eval_fmt_message_50 = _jspx_th_fmt_message_50.doStartTag(); if (_jspx_th_fmt_message_50.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_50); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_50); return false; } private boolean _jspx_meth_fmt_message_51(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_51 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_51.setPageContext(_jspx_page_context); _jspx_th_fmt_message_51.setParent(null); _jspx_th_fmt_message_51.setKey("setup.ldap.test"); int _jspx_eval_fmt_message_51 = _jspx_th_fmt_message_51.doStartTag(); if (_jspx_th_fmt_message_51.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_51); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_51); return false; } private boolean _jspx_meth_fmt_message_52(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_52 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_message_52.setPageContext(_jspx_page_context); _jspx_th_fmt_message_52.setParent(null); _jspx_th_fmt_message_52.setKey("setup.ldap.continue"); int _jspx_eval_fmt_message_52 = _jspx_th_fmt_message_52.doStartTag(); if (_jspx_th_fmt_message_52.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_52); return true; } _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_52); return false; } }
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * Specify parameters of a name to give to an object. * * <h5>Description</h5> * * <p>Applications <b>may</b> change the name associated with an object simply by calling {@code vkSetDebugUtilsObjectNameEXT} again with a new string. If {@code pObjectName} is either {@code NULL} or an empty string, then any previously set name is removed.</p> * * <h5>Valid Usage</h5> * * <ul> * <li>If {@code objectType} is {@link VK10#VK_OBJECT_TYPE_UNKNOWN OBJECT_TYPE_UNKNOWN}, {@code objectHandle} <b>must</b> not be {@link VK10#VK_NULL_HANDLE NULL_HANDLE}</li> * <li>If {@code objectType} is not {@link VK10#VK_OBJECT_TYPE_UNKNOWN OBJECT_TYPE_UNKNOWN}, {@code objectHandle} <b>must</b> be {@link VK10#VK_NULL_HANDLE NULL_HANDLE} or a valid Vulkan handle of the type associated with {@code objectType} as defined in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#debugging-object-types">{@code VkObjectType} and Vulkan Handle Relationship</a> table</li> * </ul> * * <h5>Valid Usage (Implicit)</h5> * * <ul> * <li>{@code sType} <b>must</b> be {@link EXTDebugUtils#VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT}</li> * <li>{@code pNext} <b>must</b> be {@code NULL}</li> * <li>{@code objectType} <b>must</b> be a valid {@code VkObjectType} value</li> * <li>If {@code pObjectName} is not {@code NULL}, {@code pObjectName} <b>must</b> be a null-terminated UTF-8 string</li> * </ul> * * <h5>See Also</h5> * * <p>{@link VkDebugUtilsMessengerCallbackDataEXT}, {@link EXTDebugUtils#vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT}</p> * * <h3>Layout</h3> * * <pre><code> * struct VkDebugUtilsObjectNameInfoEXT { * VkStructureType {@link #sType}; * void const * {@link #pNext}; * VkObjectType {@link #objectType}; * uint64_t {@link #objectHandle}; * char const * {@link #pObjectName}; * }</code></pre> */ public class VkDebugUtilsObjectNameInfoEXT extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int STYPE, PNEXT, OBJECTTYPE, OBJECTHANDLE, POBJECTNAME; static { Layout layout = __struct( __member(4), __member(POINTER_SIZE), __member(4), __member(8), __member(POINTER_SIZE) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); STYPE = layout.offsetof(0); PNEXT = layout.offsetof(1); OBJECTTYPE = layout.offsetof(2); OBJECTHANDLE = layout.offsetof(3); POBJECTNAME = layout.offsetof(4); } /** * Creates a {@code VkDebugUtilsObjectNameInfoEXT} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkDebugUtilsObjectNameInfoEXT(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** the type of this structure. */ @NativeType("VkStructureType") public int sType() { return nsType(address()); } /** {@code NULL} or a pointer to a structure extending this structure. */ @NativeType("void const *") public long pNext() { return npNext(address()); } /** a {@code VkObjectType} specifying the type of the object to be named. */ @NativeType("VkObjectType") public int objectType() { return nobjectType(address()); } /** the object to be named. */ @NativeType("uint64_t") public long objectHandle() { return nobjectHandle(address()); } /** either {@code NULL} or a null-terminated UTF-8 string specifying the name to apply to {@code objectHandle}. */ @Nullable @NativeType("char const *") public ByteBuffer pObjectName() { return npObjectName(address()); } /** either {@code NULL} or a null-terminated UTF-8 string specifying the name to apply to {@code objectHandle}. */ @Nullable @NativeType("char const *") public String pObjectNameString() { return npObjectNameString(address()); } /** Sets the specified value to the {@link #sType} field. */ public VkDebugUtilsObjectNameInfoEXT sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; } /** Sets the {@link EXTDebugUtils#VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT} value to the {@link #sType} field. */ public VkDebugUtilsObjectNameInfoEXT sType$Default() { return sType(EXTDebugUtils.VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT); } /** Sets the specified value to the {@link #pNext} field. */ public VkDebugUtilsObjectNameInfoEXT pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; } /** Sets the specified value to the {@link #objectType} field. */ public VkDebugUtilsObjectNameInfoEXT objectType(@NativeType("VkObjectType") int value) { nobjectType(address(), value); return this; } /** Sets the specified value to the {@link #objectHandle} field. */ public VkDebugUtilsObjectNameInfoEXT objectHandle(@NativeType("uint64_t") long value) { nobjectHandle(address(), value); return this; } /** Sets the address of the specified encoded string to the {@link #pObjectName} field. */ public VkDebugUtilsObjectNameInfoEXT pObjectName(@Nullable @NativeType("char const *") ByteBuffer value) { npObjectName(address(), value); return this; } /** Initializes this struct with the specified values. */ public VkDebugUtilsObjectNameInfoEXT set( int sType, long pNext, int objectType, long objectHandle, @Nullable ByteBuffer pObjectName ) { sType(sType); pNext(pNext); objectType(objectType); objectHandle(objectHandle); pObjectName(pObjectName); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkDebugUtilsObjectNameInfoEXT set(VkDebugUtilsObjectNameInfoEXT src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code VkDebugUtilsObjectNameInfoEXT} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkDebugUtilsObjectNameInfoEXT malloc() { return wrap(VkDebugUtilsObjectNameInfoEXT.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VkDebugUtilsObjectNameInfoEXT} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkDebugUtilsObjectNameInfoEXT calloc() { return wrap(VkDebugUtilsObjectNameInfoEXT.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VkDebugUtilsObjectNameInfoEXT} instance allocated with {@link BufferUtils}. */ public static VkDebugUtilsObjectNameInfoEXT create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VkDebugUtilsObjectNameInfoEXT.class, memAddress(container), container); } /** Returns a new {@code VkDebugUtilsObjectNameInfoEXT} instance for the specified memory address. */ public static VkDebugUtilsObjectNameInfoEXT create(long address) { return wrap(VkDebugUtilsObjectNameInfoEXT.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkDebugUtilsObjectNameInfoEXT createSafe(long address) { return address == NULL ? null : wrap(VkDebugUtilsObjectNameInfoEXT.class, address); } /** * Returns a new {@link VkDebugUtilsObjectNameInfoEXT.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkDebugUtilsObjectNameInfoEXT.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VkDebugUtilsObjectNameInfoEXT.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkDebugUtilsObjectNameInfoEXT.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkDebugUtilsObjectNameInfoEXT.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VkDebugUtilsObjectNameInfoEXT.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VkDebugUtilsObjectNameInfoEXT.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VkDebugUtilsObjectNameInfoEXT.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkDebugUtilsObjectNameInfoEXT.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkDebugUtilsObjectNameInfoEXT.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VkDebugUtilsObjectNameInfoEXT} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkDebugUtilsObjectNameInfoEXT malloc(MemoryStack stack) { return wrap(VkDebugUtilsObjectNameInfoEXT.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VkDebugUtilsObjectNameInfoEXT} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkDebugUtilsObjectNameInfoEXT calloc(MemoryStack stack) { return wrap(VkDebugUtilsObjectNameInfoEXT.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkDebugUtilsObjectNameInfoEXT.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkDebugUtilsObjectNameInfoEXT.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkDebugUtilsObjectNameInfoEXT.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkDebugUtilsObjectNameInfoEXT.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #sType}. */ public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkDebugUtilsObjectNameInfoEXT.STYPE); } /** Unsafe version of {@link #pNext}. */ public static long npNext(long struct) { return memGetAddress(struct + VkDebugUtilsObjectNameInfoEXT.PNEXT); } /** Unsafe version of {@link #objectType}. */ public static int nobjectType(long struct) { return UNSAFE.getInt(null, struct + VkDebugUtilsObjectNameInfoEXT.OBJECTTYPE); } /** Unsafe version of {@link #objectHandle}. */ public static long nobjectHandle(long struct) { return UNSAFE.getLong(null, struct + VkDebugUtilsObjectNameInfoEXT.OBJECTHANDLE); } /** Unsafe version of {@link #pObjectName}. */ @Nullable public static ByteBuffer npObjectName(long struct) { return memByteBufferNT1Safe(memGetAddress(struct + VkDebugUtilsObjectNameInfoEXT.POBJECTNAME)); } /** Unsafe version of {@link #pObjectNameString}. */ @Nullable public static String npObjectNameString(long struct) { return memUTF8Safe(memGetAddress(struct + VkDebugUtilsObjectNameInfoEXT.POBJECTNAME)); } /** Unsafe version of {@link #sType(int) sType}. */ public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkDebugUtilsObjectNameInfoEXT.STYPE, value); } /** Unsafe version of {@link #pNext(long) pNext}. */ public static void npNext(long struct, long value) { memPutAddress(struct + VkDebugUtilsObjectNameInfoEXT.PNEXT, value); } /** Unsafe version of {@link #objectType(int) objectType}. */ public static void nobjectType(long struct, int value) { UNSAFE.putInt(null, struct + VkDebugUtilsObjectNameInfoEXT.OBJECTTYPE, value); } /** Unsafe version of {@link #objectHandle(long) objectHandle}. */ public static void nobjectHandle(long struct, long value) { UNSAFE.putLong(null, struct + VkDebugUtilsObjectNameInfoEXT.OBJECTHANDLE, value); } /** Unsafe version of {@link #pObjectName(ByteBuffer) pObjectName}. */ public static void npObjectName(long struct, @Nullable ByteBuffer value) { if (CHECKS) { checkNT1Safe(value); } memPutAddress(struct + VkDebugUtilsObjectNameInfoEXT.POBJECTNAME, memAddressSafe(value)); } // ----------------------------------- /** An array of {@link VkDebugUtilsObjectNameInfoEXT} structs. */ public static class Buffer extends StructBuffer<VkDebugUtilsObjectNameInfoEXT, Buffer> implements NativeResource { private static final VkDebugUtilsObjectNameInfoEXT ELEMENT_FACTORY = VkDebugUtilsObjectNameInfoEXT.create(-1L); /** * Creates a new {@code VkDebugUtilsObjectNameInfoEXT.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkDebugUtilsObjectNameInfoEXT#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VkDebugUtilsObjectNameInfoEXT getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@link VkDebugUtilsObjectNameInfoEXT#sType} field. */ @NativeType("VkStructureType") public int sType() { return VkDebugUtilsObjectNameInfoEXT.nsType(address()); } /** @return the value of the {@link VkDebugUtilsObjectNameInfoEXT#pNext} field. */ @NativeType("void const *") public long pNext() { return VkDebugUtilsObjectNameInfoEXT.npNext(address()); } /** @return the value of the {@link VkDebugUtilsObjectNameInfoEXT#objectType} field. */ @NativeType("VkObjectType") public int objectType() { return VkDebugUtilsObjectNameInfoEXT.nobjectType(address()); } /** @return the value of the {@link VkDebugUtilsObjectNameInfoEXT#objectHandle} field. */ @NativeType("uint64_t") public long objectHandle() { return VkDebugUtilsObjectNameInfoEXT.nobjectHandle(address()); } /** @return a {@link ByteBuffer} view of the null-terminated string pointed to by the {@link VkDebugUtilsObjectNameInfoEXT#pObjectName} field. */ @Nullable @NativeType("char const *") public ByteBuffer pObjectName() { return VkDebugUtilsObjectNameInfoEXT.npObjectName(address()); } /** @return the null-terminated string pointed to by the {@link VkDebugUtilsObjectNameInfoEXT#pObjectName} field. */ @Nullable @NativeType("char const *") public String pObjectNameString() { return VkDebugUtilsObjectNameInfoEXT.npObjectNameString(address()); } /** Sets the specified value to the {@link VkDebugUtilsObjectNameInfoEXT#sType} field. */ public VkDebugUtilsObjectNameInfoEXT.Buffer sType(@NativeType("VkStructureType") int value) { VkDebugUtilsObjectNameInfoEXT.nsType(address(), value); return this; } /** Sets the {@link EXTDebugUtils#VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT} value to the {@link VkDebugUtilsObjectNameInfoEXT#sType} field. */ public VkDebugUtilsObjectNameInfoEXT.Buffer sType$Default() { return sType(EXTDebugUtils.VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT); } /** Sets the specified value to the {@link VkDebugUtilsObjectNameInfoEXT#pNext} field. */ public VkDebugUtilsObjectNameInfoEXT.Buffer pNext(@NativeType("void const *") long value) { VkDebugUtilsObjectNameInfoEXT.npNext(address(), value); return this; } /** Sets the specified value to the {@link VkDebugUtilsObjectNameInfoEXT#objectType} field. */ public VkDebugUtilsObjectNameInfoEXT.Buffer objectType(@NativeType("VkObjectType") int value) { VkDebugUtilsObjectNameInfoEXT.nobjectType(address(), value); return this; } /** Sets the specified value to the {@link VkDebugUtilsObjectNameInfoEXT#objectHandle} field. */ public VkDebugUtilsObjectNameInfoEXT.Buffer objectHandle(@NativeType("uint64_t") long value) { VkDebugUtilsObjectNameInfoEXT.nobjectHandle(address(), value); return this; } /** Sets the address of the specified encoded string to the {@link VkDebugUtilsObjectNameInfoEXT#pObjectName} field. */ public VkDebugUtilsObjectNameInfoEXT.Buffer pObjectName(@Nullable @NativeType("char const *") ByteBuffer value) { VkDebugUtilsObjectNameInfoEXT.npObjectName(address(), value); return this; } } }
package com.cratorsoft.android.aamain; import android.os.Bundle; import android.support.v4.app.Fragment; import com.earthflare.android.ircradio.R; public class Fargs { public Bundle bundle; public static Fargs create(){ return new Fargs(); } public static Fargs create(Fragment frag){ Fargs farg = new Fargs(); farg.bundle = frag.getArguments(); return farg; } public Fargs(){ bundle = new Bundle(); } public Fargs(Bundle bundle){ this.bundle = bundle; } //Action public Fargs setAction(int action){ bundle.putInt("action",action); return this; } public int getAction(){ return bundle.getInt("action"); } //Uid public Fargs setUid(long uid){ bundle.putLong("uid",uid); return this; } public long getUid(){ if (bundle.containsKey("uid")){ return bundle.getLong("uid",-1); }else{ return -1; } } //AccountId public Fargs setAccount(Long accountid){ if (accountid != null) { bundle.putLong("accountid",accountid); } return this; } public Long getAccount(){ if (bundle.containsKey("accountid")) { return bundle.getLong("accountid"); }else{ return null; } } //ChannelId public Fargs setChannel(Long channelid){ if (channelid != null) { bundle.putLong("channelid",channelid); } return this; } public Long getChannel(){ if (bundle.containsKey("channelid")) { return bundle.getLong("channelid"); }else{ return null; } } //Network public Fargs setNetwork(Long network){ if (network != null) { bundle.putLong("network",network); } return this; } public Long getNetwork(){ if (bundle.containsKey("network")) { return bundle.getLong("network"); }else{ return null; } } //Title public Fargs setTitle(String title){ if (title != null) { bundle.putString("title",title); } return this; } public String getTitle(){ if (bundle.containsKey("title")) { return bundle.getString("title"); }else{ return ""; } } //Message public Fargs setMessage(String message){ if (message != null) { bundle.putString("message",message); } return this; } public String getMessage(){ if (bundle.containsKey("message")) { return bundle.getString("message"); }else{ return ""; } } //ChannelName public Fargs setChannelName(String channelName){ if (channelName != null) { bundle.putString("channelname",channelName); } return this; } public String getChannelName(){ if (bundle.containsKey("channelname")) { return bundle.getString("channelname"); }else{ return ""; } } //AccountName public Fargs setAccountName(String accountName){ if (accountName != null) { bundle.putString("accountname",accountName); } return this; } public String getAccountName(){ if (bundle.containsKey("accountname")) { return bundle.getString("accountname"); }else{ return ""; } } //Acttype public Fargs setActtype(String acttype){ if (acttype != null) { bundle.putString("acttype",acttype); } return this; } public String getActtype(){ if (bundle.containsKey("acttype")) { return bundle.getString("acttype"); }else{ return null; } } //TargetFragment public Fargs setTargetFrag(String targetFrag){ if (targetFrag != null) { bundle.putString("targetfrag",targetFrag); } return this; } public String getTargetFrag(){ if (bundle.containsKey("targetfrag")) { return bundle.getString("targetfrag"); }else{ return ""; } } //String public Fargs setManualResource(String str){ if (str != null) { bundle.putString("manualitem",str); } return this; } public String getManualResource(){ if (bundle.containsKey("manualitem")) { return bundle.getString("manualitem"); }else{ return null; } } //notificationlink public Fargs setNotificationLink(boolean notificationlink){ bundle.putBoolean("notificationlink",notificationlink); return this; } public boolean getNotificationLink(){ return bundle.getBoolean("targetfrag",false); } //preference resoure public Fargs setPreferencesResource(int preferencesresource){ bundle.putInt("preferencesresource", preferencesresource); return this; } public int getPreferencesResource(){ return bundle.getInt("preferencesresource", R.xml.preferences); } }
/** * Copyright 2013 Diego Ceccarelli * * 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 it.cnr.isti.hpc.wikipedia.parser; import it.cnr.isti.hpc.wikipedia.article.Article; import it.cnr.isti.hpc.wikipedia.article.Article.Type; import it.cnr.isti.hpc.wikipedia.article.Language; import it.cnr.isti.hpc.wikipedia.article.Link; import it.cnr.isti.hpc.wikipedia.article.Table; import it.cnr.isti.hpc.wikipedia.article.Template; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.tudarmstadt.ukp.wikipedia.parser.Content; import de.tudarmstadt.ukp.wikipedia.parser.ContentElement; import de.tudarmstadt.ukp.wikipedia.parser.DefinitionList; import de.tudarmstadt.ukp.wikipedia.parser.NestedList; import de.tudarmstadt.ukp.wikipedia.parser.NestedListContainer; import de.tudarmstadt.ukp.wikipedia.parser.Paragraph; import de.tudarmstadt.ukp.wikipedia.parser.ParsedPage; import de.tudarmstadt.ukp.wikipedia.parser.Section; import de.tudarmstadt.ukp.wikipedia.parser.Span; import de.tudarmstadt.ukp.wikipedia.parser.mediawiki.MediaWikiParser; /** * Generates a Mediawiki parser given a language, (it will expect to find a * locale file in <tt>src/main/resources/</tt>). * * @see Locale * * @author Diego Ceccarelli <diego.ceccarelli@isti.cnr.it> * * Created on Feb 14, 2013 */ public class ArticleParser { static MediaWikiParserFactory parserFactory = new MediaWikiParserFactory(); private static final Logger logger = LoggerFactory .getLogger(ArticleParser.class); /** the language (used for the locale) default is English **/ private String lang = Language.EN; static int shortDescriptionLength = 500; private List<String> redirects; private MediaWikiParser parser; private Locale locale; public ArticleParser(String lang) { this.lang = lang; parser = parserFactory.getParser(lang); locale = new Locale(lang); redirects = locale.getRedirectIdentifiers(); } public ArticleParser() { parser = parserFactory.getParser(lang); locale = new Locale(lang); redirects = locale.getRedirectIdentifiers(); } public void parse(Article article, String mediawiki) { ParsedPage page = parser.parse(mediawiki); setRedirect(article, mediawiki); parse(article, page); } private void parse(Article article, ParsedPage page) { article.setLang(lang); setWikiTitle(article); if (page == null) { logger.warn("page is null for article {}", article.getTitle()); } else { setParagraphs(article, page); // setShortDescription(article); setTemplates(article, page); setLinks(article, page); setCategories(article, page); setHighlights(article, page); setSections(article, page); setTables(article, page); setEnWikiTitle(article, page); setLists(article, page); } setRedirect(article); setDisambiguation(article); setIsList(article); } // /** // * @param article // */ // private void setShortDescription(Article article) { // StringBuilder sb = new StringBuilder(); // for (String paragraph : article.getParagraphs()) { // paragraph = removeTemplates(paragraph); // sb.append(paragraph); // if (sb.length() > shortDescriptionLength) { // break; // } // } // if (sb.length() > shortDescriptionLength) { // sb.setLength(shortDescriptionLength); // int pos = sb.lastIndexOf(" "); // sb.setLength(pos); // } // article.setShortDescription(sb.toString()); // // } // private final static String templatePattern = "TEMPLATE\\[[^]]+\\]"; // // private static String removeTemplates(String paragraph) { // paragraph = paragraph.replaceAll(templatePattern, " "); // // return paragraph; // } /** * @param article */ private void setWikiTitle(Article article) { article.setWikiTitle(Article.getTitleInWikistyle(article.getTitle())); } /** * @param article */ private void setIsList(Article article) { for (String list : locale.getListIdentifiers()) { if (StringUtils.startsWithIgnoreCase(article.getTitle(), list)) { article.setType(Type.LIST); } } } private void setRedirect(Article article) { if (!article.getRedirect().isEmpty()) return; List<List<String>> lists = article.getLists(); if ((!lists.isEmpty()) && (! lists.get(0).isEmpty())) { // checking only first item in first list String line = lists.get(0).get(0); for (String redirect : redirects) { if (StringUtils.startsWithIgnoreCase(line, redirect)) { int pos = line.indexOf(' '); if (pos < 0) return; String red = line.substring(pos).trim(); red = Article.getTitleInWikistyle(red); article.setRedirect(red); article.setType(Type.REDIRECT); return; } } } } // for (List<String> lists : article.getLists()) { // for (String line : lists) { // for (String redirect : redirects) { // if (StringUtils.startsWithIgnoreCase(line, redirect)) { // int pos = line.indexOf(' '); // if (pos < 0) // return; // String red = line.substring(pos).trim(); // red = Article.getTitleInWikistyle(red); // article.setRedirect(red); // article.setType(Type.REDIRECT); // return; // // } // } // } // } /** * @param article * @param page */ private void setRedirect(Article article, String mediawiki) { for (String redirect : redirects) if (StringUtils.startsWithIgnoreCase(mediawiki, redirect)) { int start = mediawiki.indexOf("[[") + 2; int end = mediawiki.indexOf("]]"); if (start < 0 || end < 0) { logger.warn("cannot find the redirect {}\n mediawiki: {}", article.getTitle(), mediawiki); continue; } String r = Article.getTitleInWikistyle(mediawiki.substring( start, end)); article.setRedirect(r); article.setType(Type.REDIRECT); } } /** * @param page */ private void setTables(Article article, ParsedPage page) { List<Table> tables = new ArrayList<Table>(); for (de.tudarmstadt.ukp.wikipedia.parser.Table t : page.getTables()) { // System.out.println(t); int i = 0; String title = ""; if (t.getTitleElement() != null) { title = t.getTitleElement().getText(); if (title == null) title = ""; } Table table = new Table(title); List<String> currentRow = new ArrayList<String>(); List<Content> contentList = t.getContentList(); for (@SuppressWarnings("unused") Content c : contentList) { int row, col; String elem = ""; try { col = t.getTableElement(i).getCol(); row = t.getTableElement(i).getRow(); elem = t.getTableElement(i).getText(); } catch (IndexOutOfBoundsException e) { // logger.( // "Error creating table {}, Index out of bound - content = {}", // table.getName(), c.getText()); break; } if (row > 0 && col == 0) { if ((currentRow.size() == 1) && (currentRow.get(0).equals(table.getName()))) { currentRow = new ArrayList<String>(); } else { if (!currentRow.isEmpty()) table.addRow(currentRow); currentRow = new ArrayList<String>(); } } currentRow.add(elem); i++; } table.addRow(currentRow); tables.add(table); } article.setTables(tables); } protected void setEnWikiTitle(Article article, ParsedPage page) { if (article.isLang(Language.EN)) { return; } try { if (page.getLanguages() == null) { article.setEnWikiTitle(""); return; } } catch (NullPointerException e) { // FIXME title is always null! logger.warn("no languages for page {} ", article.getTitle()); return; } for (de.tudarmstadt.ukp.wikipedia.parser.Link l : page.getLanguages()) if (l.getText().startsWith("en:")) { article.setEnWikiTitle(l.getTarget().substring(3)); break; } } /** * @param page */ private void setSections(Article article, ParsedPage page) { List<String> sections = new ArrayList<String>(10); for (Section s : page.getSections()) { if (s == null || s.getTitle() == null) continue; sections.add(s.getTitle()); } article.setSections(sections); } private void setLinks(Article article, ParsedPage page) { List<Link> links = new ArrayList<Link>(10); List<Link> elinks = new ArrayList<Link>(10); for (de.tudarmstadt.ukp.wikipedia.parser.Link t : page.getLinks()) { if (t.getType() == de.tudarmstadt.ukp.wikipedia.parser.Link.type.INTERNAL) { links.add(new Link(t.getTarget(), t.getText())); } if (t.getType() == de.tudarmstadt.ukp.wikipedia.parser.Link.type.EXTERNAL) { elinks.add(new Link(t.getTarget(), t.getText())); } } article.setLinks(links); article.setExternalLinks(elinks); } private void setTemplates(Article article, ParsedPage page) { List<Template> templates = new ArrayList<Template>(10); for (de.tudarmstadt.ukp.wikipedia.parser.Template t : page .getTemplates()) { List<String> templateParameters = t.getParameters(); parseTemplatesSchema(article, templateParameters); if (t.getName().toLowerCase().startsWith("infobox")) { article.setInfobox(new Template(t.getName(), templateParameters)); } else { templates.add(new Template(t.getName(), templateParameters)); } } article.setTemplates(templates); } /** * * @param templateParameters */ private void parseTemplatesSchema(Article article, List<String> templateParameters) { List<String> schema = new ArrayList<String>(10); for (String s : templateParameters) { try { if (s.contains("=")) { String attributeName = s.split("=")[0].trim().toLowerCase(); schema.add(attributeName); } } catch (Exception e) { continue; } } article.addTemplatesSchema(schema); } private void setCategories(Article article, ParsedPage page) { ArrayList<Link> categories = new ArrayList<Link>(10); for (de.tudarmstadt.ukp.wikipedia.parser.Link c : page.getCategories()) { categories.add(new Link(c.getTarget(), c.getText())); } article.setCategories(categories); } private void setHighlights(Article article, ParsedPage page) { List<String> highlights = new ArrayList<String>(20); for (Paragraph p : page.getParagraphs()) { for (Span t : p.getFormatSpans(Content.FormatType.BOLD)) { highlights.add(t.getText(p.getText())); } for (Span t : p.getFormatSpans(Content.FormatType.ITALIC)) { highlights.add(t.getText(p.getText())); } } article.setHighlights(highlights); } private void setParagraphs(Article article, ParsedPage page) { List<String> paragraphs = new ArrayList<String>(page.nrOfParagraphs()); for (Paragraph p : page.getParagraphs()) { String text = p.getText(); // text = removeTemplates(text); text = text.replace("\n", " ").trim(); if (!text.isEmpty()) paragraphs.add(text); } article.setParagraphs(paragraphs); } private void setLists(Article article, ParsedPage page) { List<List<String>> lists = new LinkedList<List<String>>(); for (DefinitionList dl : page.getDefinitionLists()) { List<String> l = new ArrayList<String>(); for (ContentElement c : dl.getDefinitions()) { l.add(c.getText()); } lists.add(l); } for (NestedListContainer dl : page.getNestedLists()) { List<String> l = new ArrayList<String>(); for (NestedList nl : dl.getNestedLists()) l.add(nl.getText()); lists.add(l); } article.setLists(lists); } private void setDisambiguation(Article a) { for (String disambiguation : locale.getDisambigutionIdentifiers()) { if (StringUtils.containsIgnoreCase(a.getTitle(), disambiguation)) { a.setType(Type.DISAMBIGUATION); return; } for (Template t : a.getTemplates()) { if (StringUtils.equalsIgnoreCase(t.getName(), disambiguation)) { a.setType(Type.DISAMBIGUATION); return; } } } } }
/* * Copyright 2006-2014 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 com.consol.citrus.http.message; import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; import com.consol.citrus.exceptions.CitrusRuntimeException; import com.consol.citrus.message.DefaultMessage; import com.consol.citrus.message.Message; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import java.util.Map; /** * @author Christoph Deppisch * @since 2.0 */ public class HttpMessage extends DefaultMessage { /** * Empty constructor initializing with empty message payload. */ public HttpMessage() { super(); } /** * Constructs copy of given message. * @param message */ public HttpMessage(Message message) { super(message); } /** * Default message using message payload. * @param payload */ public HttpMessage(Object payload) { super(payload); } /** * Default message using message payload and headers. * @param payload * @param headers */ public HttpMessage(Object payload, Map<String, Object> headers) { super(payload, headers); } /** * Sets the Http request method. * @param method */ public HttpMessage method(HttpMethod method) { setHeader(HttpMessageHeaders.HTTP_REQUEST_METHOD, method.name()); return this; } /** * Sets the Http version. * @param version */ public HttpMessage version(String version) { setHeader(HttpMessageHeaders.HTTP_VERSION, version); return this; } /** * Sets the Http response status code. * @param statusCode */ public HttpMessage status(HttpStatus statusCode) { statusCode(Integer.valueOf(statusCode.value())); reasonPhrase(statusCode.name()); return this; } /** * Sets the Http response status code. * @param statusCode */ public HttpMessage statusCode(Integer statusCode) { setHeader(HttpMessageHeaders.HTTP_STATUS_CODE, statusCode); return this; } /** * Sets the Http response reason phrase. * @param reasonPhrase */ public HttpMessage reasonPhrase(String reasonPhrase) { setHeader(HttpMessageHeaders.HTTP_REASON_PHRASE, reasonPhrase); return this; } /** * Sets the Http request request uri. * @param requestUri */ public HttpMessage uri(String requestUri) { setHeader(DynamicEndpointUriResolver.ENDPOINT_URI_HEADER_NAME, requestUri); setHeader(HttpMessageHeaders.HTTP_REQUEST_URI, requestUri); return this; } /** * Sets the Http request content type. * @param contentType */ public HttpMessage contentType(String contentType) { setHeader("Content-Type", contentType); return this; } /** * Sets the Http accepted content type for response. * @param accept */ public HttpMessage accept(String accept) { setHeader("Accept", accept); return this; } /** * Sets the Http request context path. * @param contextPath */ public HttpMessage contextPath(String contextPath) { setHeader(HttpMessageHeaders.HTTP_CONTEXT_PATH, contextPath); return this; } /** * Sets the Http request query params. * @param queryParamString */ public HttpMessage queryParams(String queryParamString) { header(HttpMessageHeaders.HTTP_QUERY_PARAMS, queryParamString); header(DynamicEndpointUriResolver.QUERY_PARAM_HEADER_NAME, queryParamString); return this; } /** * Sets a new Http request query param. * @param name * @param value */ public HttpMessage queryParam(String name, String value) { if (!StringUtils.hasText(name)) { throw new CitrusRuntimeException("Invalid query param name - must not be empty!"); } String queryParams; if (getHeader(HttpMessageHeaders.HTTP_QUERY_PARAMS) != null) { queryParams = getHeader(HttpMessageHeaders.HTTP_QUERY_PARAMS).toString(); queryParams += "," + name + "=" + value; } else { queryParams = name + "=" + value; } header(HttpMessageHeaders.HTTP_QUERY_PARAMS, queryParams); header(DynamicEndpointUriResolver.QUERY_PARAM_HEADER_NAME, queryParams); return this; } /** * Sets request path that is dynamically added to base uri. * @param path * @return */ public HttpMessage path(String path) { header(HttpMessageHeaders.HTTP_REQUEST_URI, path); header(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, path); return this; } /** * Sets new header name value pair. * @param headerName * @param headerValue */ public HttpMessage header(String headerName, Object headerValue) { return (HttpMessage) super.setHeader(headerName, headerValue); } @Override public HttpMessage setHeader(String headerName, Object headerValue) { return (HttpMessage) super.setHeader(headerName, headerValue); } /** * Gets the Http request method. * @return */ public HttpMethod getRequestMethod() { Object method = getHeader(HttpMessageHeaders.HTTP_REQUEST_METHOD); if (method != null) { return HttpMethod.valueOf(method.toString()); } return null; } /** * Gets the Http request request uri. * @return */ public String getUri() { Object requestUri = getHeader(HttpMessageHeaders.HTTP_REQUEST_URI); if (requestUri != null) { return requestUri.toString(); } return null; } /** * Gets the Http request context path. * @return */ public String getContextPath() { Object contextPath = getHeader(HttpMessageHeaders.HTTP_CONTEXT_PATH); if (contextPath != null) { return contextPath.toString(); } return null; } /** * Gets the Http request query params. * @return */ public String getQueryParams() { Object queryParams = getHeader(HttpMessageHeaders.HTTP_QUERY_PARAMS); if (queryParams != null) { return queryParams.toString(); } return null; } /** * Gets the Http response status code. * @return */ public HttpStatus getStatusCode() { Object statusCode = getHeader(HttpMessageHeaders.HTTP_STATUS_CODE); if (statusCode != null) { if (statusCode instanceof HttpStatus) { return (HttpStatus) statusCode; } else if (statusCode instanceof Integer) { return HttpStatus.valueOf((Integer) statusCode); } else { return HttpStatus.valueOf(Integer.valueOf(statusCode.toString())); } } return null; } /** * Gets the Http response reason phrase. * @return */ public String getReasonPhrase() { Object reasonPhrase = getHeader(HttpMessageHeaders.HTTP_REASON_PHRASE); if (reasonPhrase != null) { return reasonPhrase.toString(); } return null; } /** * Gets the Http version. * @return */ public String getVersion() { Object version = getHeader(HttpMessageHeaders.HTTP_VERSION); if (version != null) { return version.toString(); } return null; } /** * Gets the request path after the context path. * @return */ public String getPath() { Object path = getHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME); if (path != null) { return path.toString(); } return null; } }
/* * Copyright (C) 2015 Synchronoss Technologies * * 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.synchronoss.cloud.nio.multipart.io.buffer; import org.synchronoss.cloud.nio.multipart.testutil.TestUtils; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import static org.junit.Assert.*; /** * <p> Unit tests for {@link CircularBuffer} * * @author Silvano Riz. */ public class CircularBufferTest { private static final Logger log = LoggerFactory.getLogger(CircularBuffer.class); @Test public void testCreate_invalidSize() throws Exception { Exception expected = null; try{ CircularBuffer buffer = new CircularBuffer(0); }catch (Exception e){ expected = e; } assertNotNull(expected); assertTrue(expected instanceof IllegalArgumentException); expected = null; try{ CircularBuffer buffer = new CircularBuffer(-1); }catch (Exception e){ expected = e; } assertNotNull(expected); assertTrue(expected instanceof IllegalArgumentException); } @Test public void testWrite_bufferSize_1() throws Exception { final CircularBuffer buffer = new CircularBuffer(1); assertEquals(0, buffer.startValidDataIndex); assertEquals(0, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); for(int i=0; i<10; i++){ buffer.write((byte)i); assertEquals(0, buffer.startValidDataIndex); assertEquals(0, buffer.nextAvailablePosition); assertEquals(1, buffer.availableReadLength); assertEquals((byte)i,buffer.buffer[0]); } } @Test public void testWrite() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); log.info("Buffer initial status:\n" + circularBufferToString(buffer) + "\n"); assertEquals(0, buffer.startValidDataIndex); assertEquals(0, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); byte[] chunk1 = {0x01}; writeDataToCircularBuffer(buffer, chunk1); log.info("Buffer after writing 1 byte:\n" + circularBufferToString(buffer) + "\n"); assertEquals(0, buffer.startValidDataIndex); assertEquals(1, buffer.nextAvailablePosition); assertEquals(1, buffer.availableReadLength); byte[] chunk2 = {0x02, 0x03, 0x04, 0x05}; writeDataToCircularBuffer(buffer, chunk2); log.info("Buffer after writing 5 bytes:\n" + circularBufferToString(buffer) + "\n"); assertEquals(0, buffer.startValidDataIndex); assertEquals(5, buffer.nextAvailablePosition); assertEquals(5, buffer.availableReadLength); byte[] chunk3 = {0x06, 0x07, 0x08, 0x09}; writeDataToCircularBuffer(buffer, chunk3); log.info("Buffer after writing 9 bytes:\n" + circularBufferToString(buffer) + "\n"); assertEquals(0, buffer.startValidDataIndex); assertEquals(9, buffer.nextAvailablePosition); assertEquals(9, buffer.availableReadLength); byte[] chunk4 = {0x10}; writeDataToCircularBuffer(buffer, chunk4); log.info("Buffer after writing 10 bytes:\n" + circularBufferToString(buffer) + "\n"); assertEquals(0, buffer.startValidDataIndex); assertEquals(0, buffer.nextAvailablePosition); assertEquals(10, buffer.availableReadLength); byte[] chunk5 = {0x11}; writeDataToCircularBuffer(buffer, chunk5); log.info("Buffer after writing 11 bytes:\n" + circularBufferToString(buffer) + "\n"); assertEquals(1, buffer.startValidDataIndex); assertEquals(1, buffer.nextAvailablePosition); assertEquals(10, buffer.availableReadLength); byte[] chunk6 = {0x12}; writeDataToCircularBuffer(buffer, chunk6); log.info("Buffer after writing 12 bytes:\n" + circularBufferToString(buffer) + "\n"); assertEquals(2, buffer.startValidDataIndex); assertEquals(2, buffer.nextAvailablePosition); assertEquals(10, buffer.availableReadLength); } @Test public void testReadAll() throws Exception { ByteArrayOutputStream readBaos = new ByteArrayOutputStream(); byte[] readBytes; final CircularBuffer buffer = new CircularBuffer(10); log.info("Buffer initial status:\n" + circularBufferToString(buffer) + "\n"); // Read all when buffer is empty buffer.readAll(readBaos); readBytes = readBaos.toByteArray(); log.info("Buffer after reading all:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(new byte[]{}, readBaos.toByteArray()); assertEquals(0, buffer.startValidDataIndex); assertEquals(0, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); buffer.reset(); readBaos.reset(); log.info("Buffer after recycle:\n" + circularBufferToString(buffer) + "\n"); byte[] chunk1 = {0x01}; writeDataToCircularBuffer(buffer, chunk1); log.info("Buffer after writing 1 byte:\n" + circularBufferToString(buffer) + "\n"); buffer.readAll(readBaos); readBytes = readBaos.toByteArray(); log.info("Buffer after reading all:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(chunk1, readBaos.toByteArray()); assertEquals(1, buffer.startValidDataIndex); assertEquals(1, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); buffer.reset(); readBaos.reset(); log.info("Buffer after recycle:\n" + circularBufferToString(buffer) + "\n"); byte[] chunk2 = {0x01, 0x02, 0x03, 0x04, 0x05}; writeDataToCircularBuffer(buffer, chunk2); log.info("Buffer after writing 5 byte:\n" + circularBufferToString(buffer) + "\n"); buffer.readAll(readBaos); readBytes = readBaos.toByteArray(); log.info("Buffer after reading all:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(chunk2, readBytes); assertEquals(5, buffer.startValidDataIndex); assertEquals(5, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); readBaos.reset(); byte[] chunk3 = {0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12}; writeDataToCircularBuffer(buffer, chunk3); log.info("Buffer after writing 7 byte more:\n" + circularBufferToString(buffer) + "\n"); buffer.readAll(readBaos); readBytes = readBaos.toByteArray(); log.info("Buffer after reading all:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(chunk3, readBytes); assertEquals(2, buffer.startValidDataIndex); assertEquals(2, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); } @Test public void testReadChunk() throws Exception { ByteArrayOutputStream readBaos = new ByteArrayOutputStream(); byte[] readBytes; final CircularBuffer buffer = new CircularBuffer(10); log.info("Buffer initial status:\n" + circularBufferToString(buffer) + "\n"); buffer.readChunk(readBaos, 0); readBytes = readBaos.toByteArray(); log.info("Buffer after reading a chunk of 0 bytes:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(new byte[]{}, readBytes); assertEquals(0, buffer.startValidDataIndex); assertEquals(0, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); readBaos.reset(); writeDataToCircularBuffer(buffer, new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}); log.info("Buffer after writing 7 byte:\n" + circularBufferToString(buffer) + "\n"); buffer.readChunk(readBaos, 0); readBytes = readBaos.toByteArray(); log.info("Buffer after reading a chunk of 0 bytes:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(new byte[]{}, readBytes); assertEquals(0, buffer.startValidDataIndex); assertEquals(7, buffer.nextAvailablePosition); assertEquals(7, buffer.availableReadLength); readBaos.reset(); buffer.readChunk(readBaos, 3); readBytes = readBaos.toByteArray(); log.info("Buffer after reading a chunk of 3 bytes:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(new byte[]{0x01, 0x02, 0x03}, readBytes); assertEquals(3, buffer.startValidDataIndex); assertEquals(7, buffer.nextAvailablePosition); assertEquals(4, buffer.availableReadLength); readBaos.reset(); buffer.readChunk(readBaos, 4); readBytes = readBaos.toByteArray(); log.info("Buffer after reading a chunk of 4 bytes:\n" + circularBufferToString(buffer)); log.info("Read bytes: " + TestUtils.printBytesHexEncoded(readBytes) + "\n"); assertArrayEquals(new byte[]{0x04, 0x05, 0x06, 0x07}, readBytes); assertEquals(7, buffer.startValidDataIndex); assertEquals(7, buffer.nextAvailablePosition); assertEquals(0, buffer.availableReadLength); } @Test public void testReadChunk_chunkTooBig() throws Exception { ByteArrayOutputStream readBaos = new ByteArrayOutputStream(); final CircularBuffer buffer = new CircularBuffer(10); writeDataToCircularBuffer(buffer, new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}); Exception expected = null; try{ buffer.readChunk(readBaos, 8); }catch (Exception e){ expected = e; } assertNotNull(expected); assertTrue(expected instanceof IllegalArgumentException); } @Test public void testForwards() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); assertEquals(1, buffer.forwards(0)); assertEquals(5, buffer.forwards(4)); assertEquals(0, buffer.forwards(9)); } @Test public void testBackwards() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); assertEquals(9, buffer.backwards(0)); assertEquals(3, buffer.backwards(4)); assertEquals(8, buffer.backwards(9)); } @Test public void testForwards_multiplePositions() throws Exception { CircularBuffer buffer = new CircularBuffer(10); assertEquals(1, buffer.forwards(0, 1)); assertEquals(2, buffer.forwards(0, 2)); assertEquals(9, buffer.forwards(0, 9)); assertEquals(0, buffer.forwards(0, 10)); assertEquals(1, buffer.forwards(0, 11)); assertEquals(2, buffer.forwards(0, 12)); assertEquals(0, buffer.forwards(0, 20)); assertEquals(1, buffer.forwards(0, 21)); assertEquals(2, buffer.forwards(0, 22)); } @Test public void testBackwards_multiplePositions() throws Exception { CircularBuffer buffer = new CircularBuffer(10); assertEquals(4, buffer.backwards(5, 1)); assertEquals(3, buffer.backwards(5, 2)); assertEquals(0, buffer.backwards(5, 5)); assertEquals(9, buffer.backwards(5, 6)); assertEquals(8, buffer.backwards(5, 7)); assertEquals(5, buffer.backwards(5, 10)); assertEquals(4, buffer.backwards(5, 11)); assertEquals(5, buffer.backwards(5, 20)); assertEquals(4, buffer.backwards(5, 21)); } @Test public void testIsFull() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); //log.info("Buffer initial status:\n" + TestUtils.printCircularBuffer(buffer) + "\n"); byte[] chunk1 = {0x01, 0x02, 0x03, 0x04, 0x05}; writeDataToCircularBuffer(buffer, chunk1); //log.info("Buffer after writing 5 bytes:\n" + TestUtils.printCircularBuffer(buffer) + "\n"); Assert.assertFalse(buffer.isFull()); byte[] chunk2 = {0x06, 0x07, 0x08, 0x09, 0x10}; writeDataToCircularBuffer(buffer, chunk2); //log.info("Buffer after writing 5 more bytes:\n" + TestUtils.printCircularBuffer(buffer) + "\n"); assertTrue(buffer.isFull()); } @Test public void testIsEmpty() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); assertTrue(buffer.isEmpty()); writeDataToCircularBuffer(buffer, new byte[]{0x01, 0x02, 0x03}); Assert.assertFalse(buffer.isEmpty()); writeDataToCircularBuffer(buffer, new byte[]{0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10}); Assert.assertFalse(buffer.isEmpty()); writeDataToCircularBuffer(buffer, new byte[]{0x11}); Assert.assertFalse(buffer.isEmpty()); } @Test public void testGetAvailableLength() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); assertEquals(0, buffer.getAvailableDataLength()); writeDataToCircularBuffer(buffer, new byte[]{0x01, 0x02, 0x03}); assertEquals(3, buffer.getAvailableDataLength()); writeDataToCircularBuffer(buffer, new byte[]{0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10}); assertEquals(10, buffer.getAvailableDataLength()); writeDataToCircularBuffer(buffer, new byte[]{0x11}); assertEquals(10, buffer.getAvailableDataLength()); } @Test public void testReset() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); assertTrue(buffer.isEmpty()); writeDataToCircularBuffer(buffer, new byte[]{0x01, 0x02, 0x03}); Assert.assertFalse(buffer.isEmpty()); buffer.reset(); assertTrue(buffer.isEmpty()); } @Test public void testGetBufferSize() throws Exception { final CircularBuffer buffer = new CircularBuffer(10); assertEquals(10, buffer.getBufferSize()); } static void writeDataToCircularBuffer(final CircularBuffer circularBuffer, final byte[] data){ for (byte aData : data) { circularBuffer.write(aData); } } static String circularBufferToString(final CircularBuffer circularBuffer){ return "CircularBuffer{" + "size=" + circularBuffer.size + ", buffer=" + TestUtils.printBytesHexEncoded(circularBuffer.buffer) + ", startValidDataIndex=" + circularBuffer.startValidDataIndex + ", nextAvailablePosition=" + circularBuffer.nextAvailablePosition + ", availableReadLength=" + circularBuffer.availableReadLength + '}'; } }
/* * 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.wicket.util.io; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * This class is used to wrap a stream that includes an encoded {@link ByteOrderMark} as its first bytes. * * This class detects these bytes and, if required, can automatically skip them and return the subsequent byte as the * first byte in the stream. * * The {@link ByteOrderMark} implementation has the following pre-defined BOMs: * <ul> * <li>UTF-8 - {@link ByteOrderMark#UTF_8}</li> * <li>UTF-16BE - {@link ByteOrderMark#UTF_16LE}</li> * <li>UTF-16LE - {@link ByteOrderMark#UTF_16BE}</li> * <li>UTF-32BE - {@link ByteOrderMark#UTF_32LE}</li> * <li>UTF-32LE - {@link ByteOrderMark#UTF_32BE}</li> * </ul> * * * <h3>Example 1 - Detect and exclude a UTF-8 BOM</h3> * * <pre> * BOMInputStream bomIn = new BOMInputStream(in); * if (bomIn.hasBOM()) { * // has a UTF-8 BOM * } * </pre> * * <h3>Example 2 - Detect a UTF-8 BOM (but don't exclude it)</h3> * * <pre> * boolean include = true; * BOMInputStream bomIn = new BOMInputStream(in, include); * if (bomIn.hasBOM()) { * // has a UTF-8 BOM * } * </pre> * * <h3>Example 3 - Detect Multiple BOMs</h3> * * <pre> * BOMInputStream bomIn = new BOMInputStream(in, * ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, * ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE * ); * if (bomIn.hasBOM() == false) { * // No BOM found * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) { * // has a UTF-16LE BOM * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) { * // has a UTF-16BE BOM * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32LE)) { * // has a UTF-32LE BOM * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32BE)) { * // has a UTF-32BE BOM * } * </pre> * * @see ByteOrderMark * @see <a href="http://en.wikipedia.org/wiki/Byte_order_mark">Wikipedia - Byte Order Mark</a> * @version $Id$ * @since 2.0 */ public class BOMInputStream extends ProxyInputStream { private final boolean include; /** * BOMs are sorted from longest to shortest. */ private final List<ByteOrderMark> boms; private ByteOrderMark byteOrderMark; private int[] firstBytes; private int fbLength; private int fbIndex; private int markFbIndex; private boolean markedAtStart; /** * Constructs a new BOM InputStream that excludes a {@link ByteOrderMark#UTF_8} BOM. * * @param delegate * the InputStream to delegate to */ public BOMInputStream(final InputStream delegate) { this(delegate, false, ByteOrderMark.UTF_8); } /** * Constructs a new BOM InputStream that detects a a {@link ByteOrderMark#UTF_8} and optionally includes it. * * @param delegate * the InputStream to delegate to * @param include * true to include the UTF-8 BOM or false to exclude it */ public BOMInputStream(final InputStream delegate, final boolean include) { this(delegate, include, ByteOrderMark.UTF_8); } /** * Constructs a new BOM InputStream that excludes the specified BOMs. * * @param delegate * the InputStream to delegate to * @param boms * The BOMs to detect and exclude */ public BOMInputStream(final InputStream delegate, final ByteOrderMark... boms) { this(delegate, false, boms); } /** * Compares ByteOrderMark objects in descending length order. */ private static final Comparator<ByteOrderMark> ByteOrderMarkLengthComparator = new Comparator<ByteOrderMark>() { public int compare(final ByteOrderMark bom1, final ByteOrderMark bom2) { final int len1 = bom1.length(); final int len2 = bom2.length(); if (len1 > len2) { return -1; } if (len2 > len1) { return 1; } return 0; } }; /** * Constructs a new BOM InputStream that detects the specified BOMs and optionally includes them. * * @param delegate * the InputStream to delegate to * @param include * true to include the specified BOMs or false to exclude them * @param boms * The BOMs to detect and optionally exclude */ public BOMInputStream(final InputStream delegate, final boolean include, final ByteOrderMark... boms) { super(delegate); if (boms == null || boms.length == 0) { throw new IllegalArgumentException("No BOMs specified"); } this.include = include; // Sort the BOMs to match the longest BOM first because some BOMs have the same starting two bytes. Arrays.sort(boms, ByteOrderMarkLengthComparator); this.boms = Arrays.asList(boms); } /** * Indicates whether the stream contains one of the specified BOMs. * * @return true if the stream has one of the specified BOMs, otherwise false if it does not * @throws IOException * if an error reading the first bytes of the stream occurs */ public boolean hasBOM() throws IOException { return getBOM() != null; } /** * Indicates whether the stream contains the specified BOM. * * @param bom * The BOM to check for * @return true if the stream has the specified BOM, otherwise false if it does not * @throws IllegalArgumentException * if the BOM is not one the stream is configured to detect * @throws IOException * if an error reading the first bytes of the stream occurs */ public boolean hasBOM(final ByteOrderMark bom) throws IOException { if (!boms.contains(bom)) { throw new IllegalArgumentException("Stream not configure to detect " + bom); } return byteOrderMark != null && getBOM().equals(bom); } /** * Return the BOM (Byte Order Mark). * * @return The BOM or null if none * @throws IOException * if an error reading the first bytes of the stream occurs */ public ByteOrderMark getBOM() throws IOException { if (firstBytes == null) { fbLength = 0; // BOMs are sorted from longest to shortest final int maxBomSize = boms.get(0).length(); firstBytes = new int[maxBomSize]; // Read first maxBomSize bytes for (int i = 0; i < firstBytes.length; i++) { firstBytes[i] = in.read(); fbLength++; if (firstBytes[i] < 0) { break; } } // match BOM in firstBytes byteOrderMark = find(); if (byteOrderMark != null) { if (!include) { if (byteOrderMark.length() < firstBytes.length) { fbIndex = byteOrderMark.length(); } else { fbLength = 0; } } } } return byteOrderMark; } /** * Return the BOM charset Name - {@link ByteOrderMark#getCharsetName()}. * * @return The BOM charset Name or null if no BOM found * @throws IOException * if an error reading the first bytes of the stream occurs * */ public String getBOMCharsetName() throws IOException { getBOM(); return byteOrderMark == null ? null : byteOrderMark.getCharsetName(); } /** * This method reads and either preserves or skips the first bytes in the stream. It behaves like the single-byte * <code>read()</code> method, either returning a valid byte or -1 to indicate that the initial bytes have been * processed already. * * @return the byte read (excluding BOM) or -1 if the end of stream * @throws IOException * if an I/O error occurs */ private int readFirstBytes() throws IOException { getBOM(); return fbIndex < fbLength ? firstBytes[fbIndex++] : -1; } /** * Find a BOM with the specified bytes. * * @return The matched BOM or null if none matched */ private ByteOrderMark find() { for (final ByteOrderMark bom : boms) { if (matches(bom)) { return bom; } } return null; } /** * Check if the bytes match a BOM. * * @param bom * The BOM * @return true if the bytes match the bom, otherwise false */ private boolean matches(final ByteOrderMark bom) { // if (bom.length() != fbLength) { // return false; // } // firstBytes may be bigger than the BOM bytes for (int i = 0; i < bom.length(); i++) { if (bom.get(i) != firstBytes[i]) { return false; } } return true; } // ---------------------------------------------------------------------------- // Implementation of InputStream // ---------------------------------------------------------------------------- /** * Invokes the delegate's <code>read()</code> method, detecting and optionally skipping BOM. * * @return the byte read (excluding BOM) or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public int read() throws IOException { final int b = readFirstBytes(); return b >= 0 ? b : in.read(); } /** * Invokes the delegate's <code>read(byte[], int, int)</code> method, detecting and optionally skipping BOM. * * @param buf * the buffer to read the bytes into * @param off * The start offset * @param len * The number of bytes to read (excluding BOM) * @return the number of bytes read or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public int read(final byte[] buf, int off, int len) throws IOException { int firstCount = 0; int b = 0; while (len > 0 && b >= 0) { b = readFirstBytes(); if (b >= 0) { buf[off++] = (byte) (b & 0xFF); len--; firstCount++; } } final int secondCount = in.read(buf, off, len); return secondCount < 0 ? firstCount > 0 ? firstCount : -1 : firstCount + secondCount; } /** * Invokes the delegate's <code>read(byte[])</code> method, detecting and optionally skipping BOM. * * @param buf * the buffer to read the bytes into * @return the number of bytes read (excluding BOM) or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public int read(final byte[] buf) throws IOException { return read(buf, 0, buf.length); } /** * Invokes the delegate's <code>mark(int)</code> method. * * @param readlimit * read ahead limit */ @Override public synchronized void mark(final int readlimit) { markFbIndex = fbIndex; markedAtStart = firstBytes == null; in.mark(readlimit); } /** * Invokes the delegate's <code>reset()</code> method. * * @throws IOException * if an I/O error occurs */ @Override public synchronized void reset() throws IOException { fbIndex = markFbIndex; if (markedAtStart) { firstBytes = null; } in.reset(); } /** * Invokes the delegate's <code>skip(long)</code> method, detecting and optionallyskipping BOM. * * @param n * the number of bytes to skip * @return the number of bytes to skipped or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public long skip(long n) throws IOException { while (n > 0 && readFirstBytes() >= 0) { n--; } return in.skip(n); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.EOFException; import java.io.IOException; import org.apache.hadoop.fs.Options.Rename; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.PermissionStatus; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.protocol.LayoutVersion; import org.apache.hadoop.hdfs.protocol.LayoutVersion.Feature; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import static org.apache.hadoop.hdfs.server.common.Util.now; import org.apache.hadoop.hdfs.server.common.GenerationStamp; import org.apache.hadoop.hdfs.server.common.Storage; import org.apache.hadoop.hdfs.server.namenode.FSEditLog.Ops; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableFactories; import org.apache.hadoop.io.WritableFactory; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.hdfs.protocol.CodingMatrix; public class FSEditLogLoader { private final FSNamesystem fsNamesys; public FSEditLogLoader(FSNamesystem fsNamesys) { this.fsNamesys = fsNamesys; } /** * Load an edit log, and apply the changes to the in-memory structure * This is where we apply edits that we've been writing to disk all * along. */ int loadFSEdits(EditLogInputStream edits) throws IOException { DataInputStream in = edits.getDataInputStream(); long startTime = now(); int numEdits = loadFSEdits(in, true); FSImage.LOG.info("Edits file " + edits.getName() + " of size " + edits.length() + " edits # " + numEdits + " loaded in " + (now()-startTime)/1000 + " seconds."); return numEdits; } int loadFSEdits(DataInputStream in, boolean closeOnExit) throws IOException { int numEdits = 0; int logVersion = 0; try { // Read log file version. Could be missing. in.mark(4); // If edits log is greater than 2G, available method will return negative // numbers, so we avoid having to call available boolean available = true; try { logVersion = in.readByte(); } catch (EOFException e) { available = false; } if (available) { in.reset(); logVersion = in.readInt(); if (logVersion < FSConstants.LAYOUT_VERSION) // future version throw new IOException( "Unexpected version of the file system log file: " + logVersion + ". Current version = " + FSConstants.LAYOUT_VERSION + "."); } assert logVersion <= Storage.LAST_UPGRADABLE_LAYOUT_VERSION : "Unsupported version " + logVersion; numEdits = loadEditRecords(logVersion, in, false); } finally { if(closeOnExit) in.close(); } if (logVersion != FSConstants.LAYOUT_VERSION) // other version numEdits++; // save this image asap return numEdits; } /**modified by tony * */ @SuppressWarnings("deprecation") int loadEditRecords(int logVersion, DataInputStream in, boolean closeOnExit) throws IOException { FSNamesystem.LOG.info("logversion: "+logVersion); FSDirectory fsDir = fsNamesys.dir; int numEdits = 0; String clientName = null; String clientMachine = null; String path = null; int numOpAdd = 0, numOpClose = 0, numOpDelete = 0, numOpRenameOld = 0, numOpSetRepl = 0, numOpMkDir = 0, numOpSetPerm = 0, numOpSetOwner = 0, numOpSetGenStamp = 0, numOpTimes = 0, numOpRename = 0, numOpConcatDelete = 0, numOpSymlink = 0, numOpGetDelegationToken = 0, numOpRenewDelegationToken = 0, numOpCancelDelegationToken = 0, numOpUpdateMasterKey = 0, numOpOther = 0; try { while (true) { long timestamp = 0; long mtime = 0; long atime = 0; long blockSize = 0; byte opcode = -1; try { in.mark(1); opcode = in.readByte(); if (opcode == Ops.OP_INVALID) { in.reset(); // reset back to end of file if somebody reads it again break; // no more transactions } } catch (EOFException e) { break; // no more transactions } numEdits++; switch (opcode) { case Ops.OP_ADD: case Ops.OP_CLOSE: { // versions > 0 support per file replication // get name and replication int length = in.readInt(); //modified by tony if (-7 == logVersion && length != 3|| -17 < logVersion && logVersion < -7 && length != 4 || logVersion <= -17 && length != 7) { throw new IOException("Incorrect data format." + " logVersion is " + logVersion + " but writables.length is " + length + ". "); } path = FSImageSerialization.readString(in); short replication = fsNamesys.adjustReplication(readShort(in)); mtime = readLong(in); if (LayoutVersion.supports(Feature.FILE_ACCESS_TIME, logVersion)) { atime = readLong(in); } if (logVersion < -7) { blockSize = readLong(in); } long fileSize = readLong(in); byte type = (byte)readLong(in); // get blocks boolean isFileUnderConstruction = (opcode == Ops.OP_ADD); BlockInfo blocks[] = readBlocks(in, logVersion, isFileUnderConstruction, replication); // Older versions of HDFS does not store the block size in inode. // If the file has more than one block, use the size of the // first block as the blocksize. Otherwise use the default // block size. if (-8 <= logVersion && blockSize == 0) { if (blocks.length > 1) { blockSize = blocks[0].getNumBytes(); } else { long first = ((blocks.length == 1)? blocks[0].getNumBytes(): 0); blockSize = Math.max(fsNamesys.getDefaultBlockSize(), first); } } PermissionStatus permissions = fsNamesys.getUpgradePermission(); if (logVersion <= -11) { permissions = PermissionStatus.read(in); } CodingMatrix codingMatrix = CodingMatrix.getMatrixofCertainType(type); codingMatrix.readFields(in); /**added by tony**/ LongWritable offset= new LongWritable(); offset.readFields(in); long headeroffset = offset.get(); // clientname, clientMachine and block locations of last block. if (opcode == Ops.OP_ADD && logVersion <= -12) { clientName = FSImageSerialization.readString(in); clientMachine = FSImageSerialization.readString(in); if (-13 <= logVersion) { readDatanodeDescriptorArray(in); } } else { clientName = ""; clientMachine = ""; } // The open lease transaction re-creates a file if necessary. // Delete the file if it already exists. if (FSNamesystem.LOG.isDebugEnabled()) { FSNamesystem.LOG.debug(opcode + ": " + path + " numblocks : " + blocks.length + " clientHolder " + clientName + " clientMachine " + clientMachine); } fsDir.unprotectedDelete(path, mtime); /** modified by tony * add to the file tree */ INodeFile node = (INodeFile)fsDir.unprotectedAddFile( path, permissions, codingMatrix, headeroffset,fileSize, blocks, replication, mtime, atime, blockSize); if (isFileUnderConstruction) { numOpAdd++; // // Replace current node with a INodeUnderConstruction. // Recreate in-memory lease record. // // INodeFileUnderConstruction cons = new INodeFileUnderConstruction( // node.getLocalNameBytes(), // node.getReplication(), // node.getModificationTime(), // node.getPreferredBlockSize(), // node.getBlocks(), // node.getPermissionStatus(), // clientName, // clientMachine, // null); // TODO: INodeFileUnderConstruction cons = null; fsDir.replaceNode(path, node, cons); fsNamesys.leaseManager.addLease(cons.getClientName(), path); } break; } case Ops.OP_SET_REPLICATION: { numOpSetRepl++; path = FSImageSerialization.readString(in); short replication = fsNamesys.adjustReplication(readShort(in)); fsDir.unprotectedSetReplication(path, replication, null); break; } case Ops.OP_CONCAT_DELETE: { numOpConcatDelete++; int length = in.readInt(); if (length < 3) { // trg, srcs.., timestam throw new IOException("Incorrect data format. " + "Mkdir operation."); } String trg = FSImageSerialization.readString(in); int srcSize = length - 1 - 1; //trg and timestamp String [] srcs = new String [srcSize]; for(int i=0; i<srcSize;i++) { srcs[i]= FSImageSerialization.readString(in); } timestamp = readLong(in); fsDir.unprotectedConcat(trg, srcs); break; } case Ops.OP_RENAME_OLD: { numOpRenameOld++; int length = in.readInt(); if (length != 3) { throw new IOException("Incorrect data format. " + "Mkdir operation."); } String s = FSImageSerialization.readString(in); String d = FSImageSerialization.readString(in); timestamp = readLong(in); HdfsFileStatus dinfo = fsDir.getFileInfo(d, false); fsDir.unprotectedRenameTo(s, d, timestamp); fsNamesys.changeLease(s, d, dinfo); break; } case Ops.OP_DELETE: { numOpDelete++; int length = in.readInt(); if (length != 2) { throw new IOException("Incorrect data format. " + "delete operation."); } path = FSImageSerialization.readString(in); timestamp = readLong(in); fsDir.unprotectedDelete(path, timestamp); break; } case Ops.OP_MKDIR: { numOpMkDir++; PermissionStatus permissions = fsNamesys.getUpgradePermission(); int length = in.readInt(); if (-17 < logVersion && length != 2 || logVersion <= -17 && length != 3) { throw new IOException("Incorrect data format. " + "Mkdir operation."); } path = FSImageSerialization.readString(in); timestamp = readLong(in); // The disk format stores atimes for directories as well. // However, currently this is not being updated/used because of // performance reasons. if (LayoutVersion.supports(Feature.FILE_ACCESS_TIME, logVersion)) { atime = readLong(in); } if (logVersion <= -11) { permissions = PermissionStatus.read(in); } fsDir.unprotectedMkdir(path, permissions, timestamp); break; } case Ops.OP_SET_GENSTAMP: { numOpSetGenStamp++; long lw = in.readLong(); fsNamesys.setGenerationStamp(lw); break; } case Ops.OP_DATANODE_ADD: { numOpOther++; //Datanodes are not persistent any more. FSImageSerialization.DatanodeImage.skipOne(in); break; } case Ops.OP_DATANODE_REMOVE: { numOpOther++; DatanodeID nodeID = new DatanodeID(); nodeID.readFields(in); //Datanodes are not persistent any more. break; } case Ops.OP_SET_PERMISSIONS: { numOpSetPerm++; fsDir.unprotectedSetPermission( FSImageSerialization.readString(in), FsPermission.read(in)); break; } case Ops.OP_SET_OWNER: { numOpSetOwner++; fsDir.unprotectedSetOwner(FSImageSerialization.readString(in), FSImageSerialization.readString_EmptyAsNull(in), FSImageSerialization.readString_EmptyAsNull(in)); break; } case Ops.OP_SET_NS_QUOTA: { fsDir.unprotectedSetQuota(FSImageSerialization.readString(in), readLongWritable(in), FSConstants.QUOTA_DONT_SET); break; } case Ops.OP_CLEAR_NS_QUOTA: { fsDir.unprotectedSetQuota(FSImageSerialization.readString(in), FSConstants.QUOTA_RESET, FSConstants.QUOTA_DONT_SET); break; } case Ops.OP_SET_QUOTA: fsDir.unprotectedSetQuota(FSImageSerialization.readString(in), readLongWritable(in), readLongWritable(in)); break; case Ops.OP_TIMES: { numOpTimes++; int length = in.readInt(); if (length != 3) { throw new IOException("Incorrect data format. " + "times operation."); } path = FSImageSerialization.readString(in); mtime = readLong(in); atime = readLong(in); fsDir.unprotectedSetTimes(path, mtime, atime, true); break; } case Ops.OP_SYMLINK: { numOpSymlink++; int length = in.readInt(); if (length != 4) { throw new IOException("Incorrect data format. " + "symlink operation."); } path = FSImageSerialization.readString(in); String value = FSImageSerialization.readString(in); mtime = readLong(in); atime = readLong(in); PermissionStatus perm = PermissionStatus.read(in); fsDir.unprotectedSymlink(path, value, mtime, atime, perm); break; } case Ops.OP_RENAME: { numOpRename++; int length = in.readInt(); if (length != 3) { throw new IOException("Incorrect data format. " + "Mkdir operation."); } String s = FSImageSerialization.readString(in); String d = FSImageSerialization.readString(in); timestamp = readLong(in); Rename[] options = readRenameOptions(in); HdfsFileStatus dinfo = fsDir.getFileInfo(d, false); fsDir.unprotectedRenameTo(s, d, timestamp, options); fsNamesys.changeLease(s, d, dinfo); break; } case Ops.OP_GET_DELEGATION_TOKEN: { numOpGetDelegationToken++; DelegationTokenIdentifier delegationTokenId = new DelegationTokenIdentifier(); delegationTokenId.readFields(in); long expiryTime = readLong(in); fsNamesys.getDelegationTokenSecretManager() .addPersistedDelegationToken(delegationTokenId, expiryTime); break; } case Ops.OP_RENEW_DELEGATION_TOKEN: { numOpRenewDelegationToken++; DelegationTokenIdentifier delegationTokenId = new DelegationTokenIdentifier(); delegationTokenId.readFields(in); long expiryTime = readLong(in); fsNamesys.getDelegationTokenSecretManager() .updatePersistedTokenRenewal(delegationTokenId, expiryTime); break; } case Ops.OP_CANCEL_DELEGATION_TOKEN: { numOpCancelDelegationToken++; DelegationTokenIdentifier delegationTokenId = new DelegationTokenIdentifier(); delegationTokenId.readFields(in); fsNamesys.getDelegationTokenSecretManager() .updatePersistedTokenCancellation(delegationTokenId); break; } case Ops.OP_UPDATE_MASTER_KEY: { numOpUpdateMasterKey++; DelegationKey delegationKey = new DelegationKey(); delegationKey.readFields(in); fsNamesys.getDelegationTokenSecretManager().updatePersistedMasterKey( delegationKey); break; } default: { throw new IOException("Never seen opcode " + opcode); } } } } catch (IOException ex) { check203UpgradeFailure(logVersion, ex); } finally { if(closeOnExit) in.close(); } if (FSImage.LOG.isDebugEnabled()) { FSImage.LOG.debug("numOpAdd = " + numOpAdd + " numOpClose = " + numOpClose + " numOpDelete = " + numOpDelete + " numOpRenameOld = " + numOpRenameOld + " numOpSetRepl = " + numOpSetRepl + " numOpMkDir = " + numOpMkDir + " numOpSetPerm = " + numOpSetPerm + " numOpSetOwner = " + numOpSetOwner + " numOpSetGenStamp = " + numOpSetGenStamp + " numOpTimes = " + numOpTimes + " numOpConcatDelete = " + numOpConcatDelete + " numOpRename = " + numOpRename + " numOpGetDelegationToken = " + numOpGetDelegationToken + " numOpRenewDelegationToken = " + numOpRenewDelegationToken + " numOpCancelDelegationToken = " + numOpCancelDelegationToken + " numOpUpdateMasterKey = " + numOpUpdateMasterKey + " numOpOther = " + numOpOther); } return numEdits; } /** * A class to read in blocks stored in the old format. The only two * fields in the block were blockid and length. */ static class BlockTwo implements Writable { long blkid; long len; static { // register a ctor WritableFactories.setFactory (BlockTwo.class, new WritableFactory() { public Writable newInstance() { return new BlockTwo(); } }); } BlockTwo() { blkid = 0; len = 0; } ///////////////////////////////////// // Writable ///////////////////////////////////// public void write(DataOutput out) throws IOException { out.writeLong(blkid); out.writeLong(len); } public void readFields(DataInput in) throws IOException { this.blkid = in.readLong(); this.len = in.readLong(); } } /** This method is defined for compatibility reason. */ static private DatanodeDescriptor[] readDatanodeDescriptorArray(DataInput in ) throws IOException { DatanodeDescriptor[] locations = new DatanodeDescriptor[in.readInt()]; for (int i = 0; i < locations.length; i++) { locations[i] = new DatanodeDescriptor(); locations[i].readFieldsFromFSEditLog(in); } return locations; } static private short readShort(DataInputStream in) throws IOException { return Short.parseShort(FSImageSerialization.readString(in)); } static private long readLong(DataInputStream in) throws IOException { return Long.parseLong(FSImageSerialization.readString(in)); } // a place holder for reading a long private static final LongWritable longWritable = new LongWritable(); /** Read an integer from an input stream */ private static long readLongWritable(DataInputStream in) throws IOException { synchronized (longWritable) { longWritable.readFields(in); return longWritable.get(); } } static Rename[] readRenameOptions(DataInputStream in) throws IOException { BytesWritable writable = new BytesWritable(); writable.readFields(in); byte[] bytes = writable.getBytes(); Rename[] options = new Rename[bytes.length]; for (int i = 0; i < bytes.length; i++) { options[i] = Rename.valueOf(bytes[i]); } return options; } static private BlockInfo[] readBlocks( DataInputStream in, int logVersion, boolean isFileUnderConstruction, short replication) throws IOException { int numBlocks = in.readInt(); BlockInfo[] blocks = new BlockInfo[numBlocks]; Block blk = new Block(); BlockTwo oldblk = new BlockTwo(); for (int i = 0; i < numBlocks; i++) { if (logVersion <= -14) { blk.readFields(in); } else { oldblk.readFields(in); blk.set(oldblk.blkid, oldblk.len, GenerationStamp.GRANDFATHER_GENERATION_STAMP); } if(isFileUnderConstruction && i == numBlocks-1) blocks[i] = new BlockInfoUnderConstruction(blk, replication); else blocks[i] = new BlockInfo(blk, replication); } return blocks; } /** * Throw appropriate exception during upgrade from 203, when editlog loading * could fail due to opcode conflicts. */ private void check203UpgradeFailure(int logVersion, IOException ex) throws IOException { // 0.20.203 version version has conflicting opcodes with the later releases. // The editlog must be emptied by restarting the namenode, before proceeding // with the upgrade. if (Storage.is203LayoutVersion(logVersion) && logVersion != FSConstants.LAYOUT_VERSION) { String msg = "During upgrade failed to load the editlog version " + logVersion + " from release 0.20.203. Please go back to the old " + " release and restart the namenode. This empties the editlog " + " and saves the namespace. Resume the upgrade after this step."; throw new IOException(msg, ex); } else { throw ex; } } }
/* * 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.usergrid.security.shiro.utils; import java.util.Set; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.usergrid.management.ApplicationInfo; import org.apache.usergrid.management.OrganizationInfo; import org.apache.usergrid.management.UserInfo; import org.apache.usergrid.persistence.Identifier; import org.apache.usergrid.security.shiro.PrincipalCredentialsToken; import org.apache.usergrid.security.shiro.principals.UserPrincipal; import org.apache.commons.lang.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.UnavailableSecurityManagerException; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import com.google.common.collect.BiMap; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.apache.usergrid.security.shiro.Realm.ROLE_ADMIN_USER; import static org.apache.usergrid.security.shiro.Realm.ROLE_APPLICATION_ADMIN; import static org.apache.usergrid.security.shiro.Realm.ROLE_APPLICATION_USER; import static org.apache.usergrid.security.shiro.Realm.ROLE_ORGANIZATION_ADMIN; import static org.apache.usergrid.security.shiro.Realm.ROLE_SERVICE_ADMIN; public class SubjectUtils { private static final Logger logger = LoggerFactory.getLogger( SubjectUtils.class ); public static boolean isAnonymous() { Subject currentUser = getSubject(); if ( currentUser == null ) { return true; } if ( !currentUser.isAuthenticated() && !currentUser.isRemembered() ) { return true; } return false; } public static boolean isOrganizationAdmin() { if ( isServiceAdmin() ) { return true; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ); } public static BiMap<UUID, String> getOrganizations() { Subject currentUser = getSubject(); if ( !isOrganizationAdmin() ) { return null; } Session session = currentUser.getSession(); @SuppressWarnings( "unchecked" ) BiMap<UUID, String> organizations = ( BiMap<UUID, String> ) session.getAttribute( "organizations" ); return organizations; } public static boolean isPermittedAccessToOrganization( Identifier identifier ) { if ( isServiceAdmin() ) { return true; } OrganizationInfo organization = getOrganization( identifier ); if ( organization == null ) { return false; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.isPermitted( "organizations:access:" + organization.getUuid() ); } public static OrganizationInfo getOrganization( Identifier identifier ) { if ( identifier == null ) { return null; } UUID organizationId = null; String organizationName = null; BiMap<UUID, String> organizations = getOrganizations(); if ( organizations == null ) { return null; } if ( identifier.isName() ) { organizationName = identifier.getName().toLowerCase(); organizationId = organizations.inverse().get( organizationName ); } else if ( identifier.isUUID() ) { organizationId = identifier.getUUID(); organizationName = organizations.get( organizationId ); } if ( ( organizationId != null ) && ( organizationName != null ) ) { return new OrganizationInfo( organizationId, organizationName ); } return null; } public static OrganizationInfo getOrganization() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) { return null; } Session session = currentUser.getSession(); OrganizationInfo organization = ( OrganizationInfo ) session.getAttribute( "organization" ); return organization; } public static String getOrganizationName() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) { return null; } Session session = currentUser.getSession(); OrganizationInfo organization = ( OrganizationInfo ) session.getAttribute( "organization" ); if ( organization == null ) { return null; } return organization.getName(); } public static UUID getOrganizationId() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) { return null; } Session session = currentUser.getSession(); OrganizationInfo organization = ( OrganizationInfo ) session.getAttribute( "organization" ); if ( organization == null ) { return null; } return organization.getUuid(); } public static Set<String> getOrganizationNames() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) { return null; } BiMap<UUID, String> organizations = getOrganizations(); if ( organizations == null ) { return null; } return organizations.inverse().keySet(); } public static boolean isApplicationAdmin() { if ( isServiceAdmin() ) { return true; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } boolean admin = currentUser.hasRole( ROLE_APPLICATION_ADMIN ); return admin; } public static boolean isPermittedAccessToApplication( Identifier identifier ) { if ( isServiceAdmin() ) { return true; } ApplicationInfo application = getApplication( identifier ); if ( application == null ) { return false; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.isPermitted( "applications:access:" + application.getId() ); } public static boolean isApplicationAdmin( Identifier identifier ) { if ( isServiceAdmin() ) { return true; } ApplicationInfo application = getApplication( identifier ); if ( application == null ) { return false; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.isPermitted( "applications:admin:" + application.getId() ); } public static ApplicationInfo getApplication( Identifier identifier ) { if ( identifier == null ) { return null; } if ( !isApplicationAdmin() && !isApplicationUser() ) { return null; } String applicationName = null; UUID applicationId = null; BiMap<UUID, String> applications = getApplications(); if ( applications == null ) { return null; } if ( identifier.isName() ) { applicationName = identifier.getName().toLowerCase(); applicationId = applications.inverse().get( applicationName ); if ( applicationId == null ) { applicationId = applications.inverse().get( identifier.getName() ); } } else if ( identifier.isUUID() ) { applicationId = identifier.getUUID(); applicationName = applications.get( identifier.getUUID() ); } if ( ( applicationId != null ) && ( applicationName != null ) ) { return new ApplicationInfo( applicationId, applicationName ); } return null; } @SuppressWarnings( "unchecked" ) public static BiMap<UUID, String> getApplications() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !currentUser.hasRole( ROLE_APPLICATION_ADMIN ) && !currentUser.hasRole( ROLE_APPLICATION_USER ) ) { return null; } Session session = currentUser.getSession(); return ( BiMap<UUID, String> ) session.getAttribute( "applications" ); } public static boolean isServiceAdmin() { Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.hasRole( ROLE_SERVICE_ADMIN ); } public static boolean isApplicationUser() { Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.hasRole( ROLE_APPLICATION_USER ); } public static boolean isAdminUser() { if ( isServiceAdmin() ) { return true; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.hasRole( ROLE_ADMIN_USER ); } public static UserInfo getUser() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !( currentUser.getPrincipal() instanceof UserPrincipal ) ) { return null; } UserPrincipal principal = ( UserPrincipal ) currentUser.getPrincipal(); return principal.getUser(); } public static UserInfo getAdminUser() { UserInfo user = getUser(); if ( user == null ) { return null; } return user.isAdminUser() ? user : null; } public static UUID getSubjectUserId() { UserInfo info = getUser(); if ( info == null ) { return null; } return info.getUuid(); } public static boolean isUserActivated() { UserInfo user = getUser(); if ( user == null ) { return false; } return user.isActivated(); } public static boolean isUserEnabled() { UserInfo user = getUser(); if ( user == null ) { return false; } return !user.isDisabled(); } public static boolean isUser( Identifier identifier ) { if ( identifier == null ) { return false; } UserInfo user = getUser(); if ( user == null ) { return false; } if ( identifier.isUUID() ) { return user.getUuid().equals( identifier.getUUID() ); } if ( identifier.isEmail() ) { return user.getEmail().equalsIgnoreCase( identifier.getEmail() ); } if ( identifier.isName() ) { return user.getUsername().equals( identifier.getName() ); } return false; } public static boolean isPermittedAccessToUser( UUID userId ) { if ( isServiceAdmin() ) { return true; } if ( userId == null ) { return false; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.isPermitted( "users:access:" + userId ); } public static String getPermissionFromPath( UUID applicationId, String operations, String... paths ) { String permission = "applications:" + operations + ":" + applicationId; String p = StringUtils.join( paths, ',' ); permission += ( isNotBlank( p ) ? ":" + p : "" ); return permission; } public static Subject getSubject() { Subject currentUser = null; try { currentUser = SecurityUtils.getSubject(); } catch ( UnavailableSecurityManagerException e ) { logger.error( "getSubject(): Attempt to use Shiro prior to initialization" ); } return currentUser; } public static void checkPermission( String permission ) { Subject currentUser = getSubject(); if ( currentUser == null ) { return; } try { currentUser.checkPermission( permission ); } catch ( org.apache.shiro.authz.UnauthenticatedException e ) { logger.error( "checkPermission(): Subject is anonymous" ); } } public static void loginApplicationGuest( ApplicationInfo application ) { if ( application == null ) { logger.error( "loginApplicationGuest(): Null application" ); return; } if ( isAnonymous() ) { Subject subject = SubjectUtils.getSubject(); PrincipalCredentialsToken token = PrincipalCredentialsToken.getGuestCredentialsFromApplicationInfo( application ); subject.login( token ); } else { logger.error( "loginApplicationGuest(): Logging in non-anonymous user as guest not allowed" ); } } }
/* * Copyright (C) 2014 The Android Open Source 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.google.android.exoplayer.extractor.mp4; import android.util.Pair; import com.google.android.exoplayer.C; import com.google.android.exoplayer.MediaFormat; import com.google.android.exoplayer.ParserException; import com.google.android.exoplayer.extractor.GaplessInfo; import com.google.android.exoplayer.util.Ac3Util; import com.google.android.exoplayer.util.Assertions; import com.google.android.exoplayer.util.CodecSpecificDataUtil; import com.google.android.exoplayer.util.MimeTypes; import com.google.android.exoplayer.util.NalUnitUtil; import com.google.android.exoplayer.util.ParsableBitArray; import com.google.android.exoplayer.util.ParsableByteArray; import com.google.android.exoplayer.util.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Utility methods for parsing MP4 format atom payloads according to ISO 14496-12. */ /* package */ final class AtomParsers { private static final byte[] PIFF_TRACK_ENCRYPTION_BOX_EXTENDED_TYP = new byte[] {-119, 116, -37, -50, 123, -25, 76, 81, -124, -7, 113, 72, -7, -120, 37, 84}; /** * Parses a trak atom (defined in 14496-12). * * @param trak Atom to parse. * @param mvhd Movie header atom, used to get the timescale. * @param duration The duration in units of the timescale declared in the mvhd atom, or -1 if the * duration should be parsed from the tkhd atom. * @param isQuickTime True for QuickTime media. False otherwise. * @return A {@link Track} instance, or {@code null} if the track's type isn't supported. */ public static Track parseTrak(Atom.ContainerAtom trak, Atom.LeafAtom mvhd, long duration, boolean isQuickTime) { Atom.ContainerAtom mdia = trak.getContainerAtomOfType(Atom.TYPE_mdia); int trackType = parseHdlr(mdia.getLeafAtomOfType(Atom.TYPE_hdlr).data); if (trackType != Track.TYPE_soun && trackType != Track.TYPE_vide && trackType != Track.TYPE_text && trackType != Track.TYPE_sbtl && trackType != Track.TYPE_subt) { return null; } TkhdData tkhdData = parseTkhd(trak.getLeafAtomOfType(Atom.TYPE_tkhd).data); if (duration == -1) { duration = tkhdData.duration; } long movieTimescale = parseMvhd(mvhd.data); long durationUs; if (duration == -1) { durationUs = C.UNKNOWN_TIME_US; } else { durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, movieTimescale); } Atom.ContainerAtom stbl = mdia.getContainerAtomOfType(Atom.TYPE_minf) .getContainerAtomOfType(Atom.TYPE_stbl); Pair<Long, String> mdhdData = parseMdhd(mdia.getLeafAtomOfType(Atom.TYPE_mdhd).data); StsdData stsdData = parseStsd(stbl.getLeafAtomOfType(Atom.TYPE_stsd).data, tkhdData.id, durationUs, tkhdData.rotationDegrees, mdhdData.second, isQuickTime); Pair<long[], long[]> edtsData = parseEdts(trak.getContainerAtomOfType(Atom.TYPE_edts)); return stsdData.mediaFormat == null ? null : new Track(tkhdData.id, trackType, mdhdData.first, movieTimescale, durationUs, stsdData.mediaFormat, stsdData.trackEncryptionBoxes, stsdData.nalUnitLengthFieldLength, edtsData.first, edtsData.second); } /** * Parses an stbl atom (defined in 14496-12). * * @param track Track to which this sample table corresponds. * @param stblAtom stbl (sample table) atom to parse. * @return Sample table described by the stbl atom. * @throws ParserException If the resulting sample sequence does not contain a sync sample. */ public static TrackSampleTable parseStbl(Track track, Atom.ContainerAtom stblAtom) throws ParserException { // Array of sample sizes. ParsableByteArray stsz = stblAtom.getLeafAtomOfType(Atom.TYPE_stsz).data; // Entries are byte offsets of chunks. boolean chunkOffsetsAreLongs = false; Atom.LeafAtom chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stco); if (chunkOffsetsAtom == null) { chunkOffsetsAreLongs = true; chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_co64); } ParsableByteArray chunkOffsets = chunkOffsetsAtom.data; // Entries are (chunk number, number of samples per chunk, sample description index). ParsableByteArray stsc = stblAtom.getLeafAtomOfType(Atom.TYPE_stsc).data; // Entries are (number of samples, timestamp delta between those samples). ParsableByteArray stts = stblAtom.getLeafAtomOfType(Atom.TYPE_stts).data; // Entries are the indices of samples that are synchronization samples. Atom.LeafAtom stssAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stss); ParsableByteArray stss = stssAtom != null ? stssAtom.data : null; // Entries are (number of samples, timestamp offset). Atom.LeafAtom cttsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_ctts); ParsableByteArray ctts = cttsAtom != null ? cttsAtom.data : null; // Skip full atom. stsz.setPosition(Atom.FULL_HEADER_SIZE); int fixedSampleSize = stsz.readUnsignedIntToInt(); int sampleCount = stsz.readUnsignedIntToInt(); if (sampleCount == 0) { return new TrackSampleTable(new long[0], new int[0], 0, new long[0], new int[0]); } // Prepare to read chunk information. ChunkIterator chunkIterator = new ChunkIterator(stsc, chunkOffsets, chunkOffsetsAreLongs); // Prepare to read sample timestamps. stts.setPosition(Atom.FULL_HEADER_SIZE); int remainingTimestampDeltaChanges = stts.readUnsignedIntToInt() - 1; int remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt(); int timestampDeltaInTimeUnits = stts.readUnsignedIntToInt(); // Prepare to read sample timestamp offsets, if ctts is present. int remainingSamplesAtTimestampOffset = 0; int remainingTimestampOffsetChanges = 0; int timestampOffset = 0; if (ctts != null) { ctts.setPosition(Atom.FULL_HEADER_SIZE); remainingTimestampOffsetChanges = ctts.readUnsignedIntToInt(); } int nextSynchronizationSampleIndex = -1; int remainingSynchronizationSamples = 0; if (stss != null) { stss.setPosition(Atom.FULL_HEADER_SIZE); remainingSynchronizationSamples = stss.readUnsignedIntToInt(); nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1; } // True if we can rechunk fixed-sample-size data. Note that we only rechunk raw audio. boolean isRechunkable = fixedSampleSize != 0 && MimeTypes.AUDIO_RAW.equals(track.mediaFormat.mimeType) && remainingTimestampDeltaChanges == 0 && remainingTimestampOffsetChanges == 0 && remainingSynchronizationSamples == 0; long[] offsets; int[] sizes; int maximumSize = 0; long[] timestamps; int[] flags; if (!isRechunkable) { offsets = new long[sampleCount]; sizes = new int[sampleCount]; timestamps = new long[sampleCount]; flags = new int[sampleCount]; long timestampTimeUnits = 0; long offset = 0; int remainingSamplesInChunk = 0; for (int i = 0; i < sampleCount; i++) { // Advance to the next chunk if necessary. while (remainingSamplesInChunk == 0) { Assertions.checkState(chunkIterator.moveNext()); offset = chunkIterator.offset; remainingSamplesInChunk = chunkIterator.numSamples; } // Add on the timestamp offset if ctts is present. if (ctts != null) { while (remainingSamplesAtTimestampOffset == 0 && remainingTimestampOffsetChanges > 0) { remainingSamplesAtTimestampOffset = ctts.readUnsignedIntToInt(); // The BMFF spec (ISO 14496-12) states that sample offsets should be unsigned integers // in version 0 ctts boxes, however some streams violate the spec and use signed // integers instead. It's safe to always parse sample offsets as signed integers here, // because unsigned integers will still be parsed correctly (unless their top bit is // set, which is never true in practice because sample offsets are always small). timestampOffset = ctts.readInt(); remainingTimestampOffsetChanges--; } remainingSamplesAtTimestampOffset--; } offsets[i] = offset; sizes[i] = fixedSampleSize == 0 ? stsz.readUnsignedIntToInt() : fixedSampleSize; if (sizes[i] > maximumSize) { maximumSize = sizes[i]; } timestamps[i] = timestampTimeUnits + timestampOffset; // All samples are synchronization samples if the stss is not present. flags[i] = stss == null ? C.SAMPLE_FLAG_SYNC : 0; if (i == nextSynchronizationSampleIndex) { flags[i] = C.SAMPLE_FLAG_SYNC; remainingSynchronizationSamples--; if (remainingSynchronizationSamples > 0) { nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1; } } // Add on the duration of this sample. timestampTimeUnits += timestampDeltaInTimeUnits; remainingSamplesAtTimestampDelta--; if (remainingSamplesAtTimestampDelta == 0 && remainingTimestampDeltaChanges > 0) { remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt(); timestampDeltaInTimeUnits = stts.readUnsignedIntToInt(); remainingTimestampDeltaChanges--; } offset += sizes[i]; remainingSamplesInChunk--; } Assertions.checkArgument(remainingSamplesAtTimestampOffset == 0); // Remove trailing ctts entries with 0-valued sample counts. while (remainingTimestampOffsetChanges > 0) { Assertions.checkArgument(ctts.readUnsignedIntToInt() == 0); ctts.readInt(); // Ignore offset. remainingTimestampOffsetChanges--; } // Check all the expected samples have been seen. Assertions.checkArgument(remainingSynchronizationSamples == 0); Assertions.checkArgument(remainingSamplesAtTimestampDelta == 0); Assertions.checkArgument(remainingSamplesInChunk == 0); Assertions.checkArgument(remainingTimestampDeltaChanges == 0); } else { long[] chunkOffsetsBytes = new long[chunkIterator.length]; int[] chunkSampleCounts = new int[chunkIterator.length]; while (chunkIterator.moveNext()) { chunkOffsetsBytes[chunkIterator.index] = chunkIterator.offset; chunkSampleCounts[chunkIterator.index] = chunkIterator.numSamples; } FixedSampleSizeRechunker.Results rechunkedResults = FixedSampleSizeRechunker.rechunk( fixedSampleSize, chunkOffsetsBytes, chunkSampleCounts, timestampDeltaInTimeUnits); offsets = rechunkedResults.offsets; sizes = rechunkedResults.sizes; maximumSize = rechunkedResults.maximumSize; timestamps = rechunkedResults.timestamps; flags = rechunkedResults.flags; } if (track.editListDurations == null) { Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale); return new TrackSampleTable(offsets, sizes, maximumSize, timestamps, flags); } // See the BMFF spec (ISO 14496-12) subsection 8.6.6. Edit lists that truncate audio and // require prerolling from a sync sample after reordering are not supported. This // implementation handles simple discarding/delaying of samples. The extractor may place // further restrictions on what edited streams are playable. if (track.editListDurations.length == 1 && track.editListDurations[0] == 0) { // The current version of the spec leaves handling of an edit with zero segment_duration in // unfragmented files open to interpretation. We handle this as a special case and include all // samples in the edit. for (int i = 0; i < timestamps.length; i++) { timestamps[i] = Util.scaleLargeTimestamp(timestamps[i] - track.editListMediaTimes[0], C.MICROS_PER_SECOND, track.timescale); } return new TrackSampleTable(offsets, sizes, maximumSize, timestamps, flags); } // Count the number of samples after applying edits. int editedSampleCount = 0; int nextSampleIndex = 0; boolean copyMetadata = false; for (int i = 0; i < track.editListDurations.length; i++) { long mediaTime = track.editListMediaTimes[i]; if (mediaTime != -1) { long duration = Util.scaleLargeTimestamp(track.editListDurations[i], track.timescale, track.movieTimescale); int startIndex = Util.binarySearchCeil(timestamps, mediaTime, true, true); int endIndex = Util.binarySearchCeil(timestamps, mediaTime + duration, true, false); editedSampleCount += endIndex - startIndex; copyMetadata |= nextSampleIndex != startIndex; nextSampleIndex = endIndex; } } copyMetadata |= editedSampleCount != sampleCount; // Calculate edited sample timestamps and update the corresponding metadata arrays. long[] editedOffsets = copyMetadata ? new long[editedSampleCount] : offsets; int[] editedSizes = copyMetadata ? new int[editedSampleCount] : sizes; int editedMaximumSize = copyMetadata ? 0 : maximumSize; int[] editedFlags = copyMetadata ? new int[editedSampleCount] : flags; long[] editedTimestamps = new long[editedSampleCount]; long pts = 0; int sampleIndex = 0; for (int i = 0; i < track.editListDurations.length; i++) { long mediaTime = track.editListMediaTimes[i]; long duration = track.editListDurations[i]; if (mediaTime != -1) { long endMediaTime = mediaTime + Util.scaleLargeTimestamp(duration, track.timescale, track.movieTimescale); int startIndex = Util.binarySearchCeil(timestamps, mediaTime, true, true); int endIndex = Util.binarySearchCeil(timestamps, endMediaTime, true, false); if (copyMetadata) { int count = endIndex - startIndex; System.arraycopy(offsets, startIndex, editedOffsets, sampleIndex, count); System.arraycopy(sizes, startIndex, editedSizes, sampleIndex, count); System.arraycopy(flags, startIndex, editedFlags, sampleIndex, count); } for (int j = startIndex; j < endIndex; j++) { long ptsUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale); long timeInSegmentUs = Util.scaleLargeTimestamp(timestamps[j] - mediaTime, C.MICROS_PER_SECOND, track.timescale); editedTimestamps[sampleIndex] = ptsUs + timeInSegmentUs; if (copyMetadata && editedSizes[sampleIndex] > editedMaximumSize) { editedMaximumSize = sizes[j]; } sampleIndex++; } } pts += duration; } boolean hasSyncSample = false; for (int i = 0; i < editedFlags.length && !hasSyncSample; i++) { hasSyncSample |= (editedFlags[i] & C.SAMPLE_FLAG_SYNC) != 0; } if (!hasSyncSample) { throw new ParserException("The edited sample sequence does not contain a sync sample."); } return new TrackSampleTable(editedOffsets, editedSizes, editedMaximumSize, editedTimestamps, editedFlags); } /** * Parses a udta atom. * * @param udtaAtom The udta (user data) atom to parse. * @param isQuickTime True for QuickTime media. False otherwise. * @return Gapless playback information stored in the user data, or {@code null} if not present. */ public static GaplessInfo parseUdta(Atom.LeafAtom udtaAtom, boolean isQuickTime) { if (isQuickTime) { // Meta boxes are regular boxes rather than full boxes in QuickTime. For now, don't try and // parse one. return null; } ParsableByteArray udtaData = udtaAtom.data; udtaData.setPosition(Atom.HEADER_SIZE); while (udtaData.bytesLeft() >= Atom.HEADER_SIZE) { int atomSize = udtaData.readInt(); int atomType = udtaData.readInt(); if (atomType == Atom.TYPE_meta) { udtaData.setPosition(udtaData.getPosition() - Atom.HEADER_SIZE); udtaData.setLimit(udtaData.getPosition() + atomSize); return parseMetaAtom(udtaData); } else { udtaData.skipBytes(atomSize - Atom.HEADER_SIZE); } } return null; } private static GaplessInfo parseMetaAtom(ParsableByteArray data) { data.skipBytes(Atom.FULL_HEADER_SIZE); ParsableByteArray ilst = new ParsableByteArray(); while (data.bytesLeft() >= Atom.HEADER_SIZE) { int payloadSize = data.readInt() - Atom.HEADER_SIZE; int atomType = data.readInt(); if (atomType == Atom.TYPE_ilst) { ilst.reset(data.data, data.getPosition() + payloadSize); ilst.setPosition(data.getPosition()); GaplessInfo gaplessInfo = parseIlst(ilst); if (gaplessInfo != null) { return gaplessInfo; } } data.skipBytes(payloadSize); } return null; } private static GaplessInfo parseIlst(ParsableByteArray ilst) { while (ilst.bytesLeft() > 0) { int position = ilst.getPosition(); int endPosition = position + ilst.readInt(); int type = ilst.readInt(); if (type == Atom.TYPE_DASHES) { String lastCommentMean = null; String lastCommentName = null; String lastCommentData = null; while (ilst.getPosition() < endPosition) { int length = ilst.readInt() - Atom.FULL_HEADER_SIZE; int key = ilst.readInt(); ilst.skipBytes(4); if (key == Atom.TYPE_mean) { lastCommentMean = ilst.readString(length); } else if (key == Atom.TYPE_name) { lastCommentName = ilst.readString(length); } else if (key == Atom.TYPE_data) { ilst.skipBytes(4); lastCommentData = ilst.readString(length - 4); } else { ilst.skipBytes(length); } } if (lastCommentName != null && lastCommentData != null && "com.apple.iTunes".equals(lastCommentMean)) { return GaplessInfo.createFromComment(lastCommentName, lastCommentData); } } else { ilst.setPosition(endPosition); } } return null; } /** * Parses a mvhd atom (defined in 14496-12), returning the timescale for the movie. * * @param mvhd Contents of the mvhd atom to be parsed. * @return Timescale for the movie. */ private static long parseMvhd(ParsableByteArray mvhd) { mvhd.setPosition(Atom.HEADER_SIZE); int fullAtom = mvhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); mvhd.skipBytes(version == 0 ? 8 : 16); return mvhd.readUnsignedInt(); } /** * Parses a tkhd atom (defined in 14496-12). * * @return An object containing the parsed data. */ private static TkhdData parseTkhd(ParsableByteArray tkhd) { tkhd.setPosition(Atom.HEADER_SIZE); int fullAtom = tkhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); tkhd.skipBytes(version == 0 ? 8 : 16); int trackId = tkhd.readInt(); tkhd.skipBytes(4); boolean durationUnknown = true; int durationPosition = tkhd.getPosition(); int durationByteCount = version == 0 ? 4 : 8; for (int i = 0; i < durationByteCount; i++) { if (tkhd.data[durationPosition + i] != -1) { durationUnknown = false; break; } } long duration; if (durationUnknown) { tkhd.skipBytes(durationByteCount); duration = -1; } else { duration = version == 0 ? tkhd.readUnsignedInt() : tkhd.readUnsignedLongToLong(); if (duration == 0) { // 0 duration normally indicates that the file is fully fragmented (i.e. all of the media // samples are in fragments). Treat as unknown. duration = -1; } } tkhd.skipBytes(16); int a00 = tkhd.readInt(); int a01 = tkhd.readInt(); tkhd.skipBytes(4); int a10 = tkhd.readInt(); int a11 = tkhd.readInt(); int rotationDegrees; int fixedOne = 65536; if (a00 == 0 && a01 == fixedOne && a10 == -fixedOne && a11 == 0) { rotationDegrees = 90; } else if (a00 == 0 && a01 == -fixedOne && a10 == fixedOne && a11 == 0) { rotationDegrees = 270; } else if (a00 == -fixedOne && a01 == 0 && a10 == 0 && a11 == -fixedOne) { rotationDegrees = 180; } else { // Only 0, 90, 180 and 270 are supported. Treat anything else as 0. rotationDegrees = 0; } return new TkhdData(trackId, duration, rotationDegrees); } /** * Parses an hdlr atom. * * @param hdlr The hdlr atom to parse. * @return The track type. */ private static int parseHdlr(ParsableByteArray hdlr) { hdlr.setPosition(Atom.FULL_HEADER_SIZE + 4); return hdlr.readInt(); } /** * Parses an mdhd atom (defined in 14496-12). * * @param mdhd The mdhd atom to parse. * @return A pair consisting of the media timescale defined as the number of time units that pass * in one second, and the language code. */ private static Pair<Long, String> parseMdhd(ParsableByteArray mdhd) { mdhd.setPosition(Atom.HEADER_SIZE); int fullAtom = mdhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); mdhd.skipBytes(version == 0 ? 8 : 16); long timescale = mdhd.readUnsignedInt(); mdhd.skipBytes(version == 0 ? 4 : 8); int languageCode = mdhd.readUnsignedShort(); String language = "" + (char) (((languageCode >> 10) & 0x1F) + 0x60) + (char) (((languageCode >> 5) & 0x1F) + 0x60) + (char) (((languageCode) & 0x1F) + 0x60); return Pair.create(timescale, language); } /** * Parses a stsd atom (defined in 14496-12). * * @param stsd The stsd atom to parse. * @param trackId The track's identifier in its container. * @param durationUs The duration of the track in microseconds. * @param rotationDegrees The rotation of the track in degrees. * @param language The language of the track. * @param isQuickTime True for QuickTime media. False otherwise. * @return An object containing the parsed data. */ private static StsdData parseStsd(ParsableByteArray stsd, int trackId, long durationUs, int rotationDegrees, String language, boolean isQuickTime) { stsd.setPosition(Atom.FULL_HEADER_SIZE); int numberOfEntries = stsd.readInt(); StsdData out = new StsdData(numberOfEntries); for (int i = 0; i < numberOfEntries; i++) { int childStartPosition = stsd.getPosition(); int childAtomSize = stsd.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = stsd.readInt(); if (childAtomType == Atom.TYPE_avc1 || childAtomType == Atom.TYPE_avc3 || childAtomType == Atom.TYPE_encv || childAtomType == Atom.TYPE_mp4v || childAtomType == Atom.TYPE_hvc1 || childAtomType == Atom.TYPE_hev1 || childAtomType == Atom.TYPE_s263 || childAtomType == Atom.TYPE_vp09) { parseVideoSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, durationUs, rotationDegrees, out, i); } else if (childAtomType == Atom.TYPE_mp4a || childAtomType == Atom.TYPE_enca || childAtomType == Atom.TYPE_ac_3 || childAtomType == Atom.TYPE_ec_3 || childAtomType == Atom.TYPE_dtsc || childAtomType == Atom.TYPE_dtse || childAtomType == Atom.TYPE_dtsh || childAtomType == Atom.TYPE_dtsl || childAtomType == Atom.TYPE_samr || childAtomType == Atom.TYPE_sawb || childAtomType == Atom.TYPE_lpcm || childAtomType == Atom.TYPE_sowt) { parseAudioSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, durationUs, language, isQuickTime, out, i); } else if (childAtomType == Atom.TYPE_TTML) { out.mediaFormat = MediaFormat.createTextFormat(Integer.toString(trackId), MimeTypes.APPLICATION_TTML, MediaFormat.NO_VALUE, durationUs, language); } else if (childAtomType == Atom.TYPE_tx3g) { out.mediaFormat = MediaFormat.createTextFormat(Integer.toString(trackId), MimeTypes.APPLICATION_TX3G, MediaFormat.NO_VALUE, durationUs, language); } else if (childAtomType == Atom.TYPE_wvtt) { out.mediaFormat = MediaFormat.createTextFormat(Integer.toString(trackId), MimeTypes.APPLICATION_MP4VTT, MediaFormat.NO_VALUE, durationUs, language); } else if (childAtomType == Atom.TYPE_stpp) { out.mediaFormat = MediaFormat.createTextFormat(Integer.toString(trackId), MimeTypes.APPLICATION_TTML, MediaFormat.NO_VALUE, durationUs, language, 0 /* subsample timing is absolute */); } stsd.setPosition(childStartPosition + childAtomSize); } return out; } private static void parseVideoSampleEntry(ParsableByteArray parent, int atomType, int position, int size, int trackId, long durationUs, int rotationDegrees, StsdData out, int entryIndex) { parent.setPosition(position + Atom.HEADER_SIZE); parent.skipBytes(24); int width = parent.readUnsignedShort(); int height = parent.readUnsignedShort(); boolean pixelWidthHeightRatioFromPasp = false; float pixelWidthHeightRatio = 1; parent.skipBytes(50); int childPosition = parent.getPosition(); if (atomType == Atom.TYPE_encv) { parseSampleEntryEncryptionData(parent, position, size, out, entryIndex); parent.setPosition(childPosition); } List<byte[]> initializationData = null; String mimeType = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childStartPosition = parent.getPosition(); int childAtomSize = parent.readInt(); if (childAtomSize == 0 && parent.getPosition() - position == size) { // Handle optional terminating four zero bytes in MOV files. break; } Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_avcC) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H264; AvcCData avcCData = parseAvcCFromParent(parent, childStartPosition); initializationData = avcCData.initializationData; out.nalUnitLengthFieldLength = avcCData.nalUnitLengthFieldLength; if (!pixelWidthHeightRatioFromPasp) { pixelWidthHeightRatio = avcCData.pixelWidthAspectRatio; } } else if (childAtomType == Atom.TYPE_hvcC) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H265; Pair<List<byte[]>, Integer> hvcCData = parseHvcCFromParent(parent, childStartPosition); initializationData = hvcCData.first; out.nalUnitLengthFieldLength = hvcCData.second; } else if (childAtomType == Atom.TYPE_d263) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H263; } else if (childAtomType == Atom.TYPE_esds) { Assertions.checkState(mimeType == null); Pair<String, byte[]> mimeTypeAndInitializationData = parseEsdsFromParent(parent, childStartPosition); mimeType = mimeTypeAndInitializationData.first; initializationData = Collections.singletonList(mimeTypeAndInitializationData.second); } else if (childAtomType == Atom.TYPE_pasp) { pixelWidthHeightRatio = parsePaspFromParent(parent, childStartPosition); pixelWidthHeightRatioFromPasp = true; } else if (childAtomType == Atom.TYPE_vpcc) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_VP9; } childPosition += childAtomSize; } // If the media type was not recognized, ignore the track. if (mimeType == null) { return; } out.mediaFormat = MediaFormat.createVideoFormat(Integer.toString(trackId), mimeType, MediaFormat.NO_VALUE, MediaFormat.NO_VALUE, durationUs, width, height, initializationData, rotationDegrees, pixelWidthHeightRatio); } private static AvcCData parseAvcCFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE + 4); // Start of the AVCDecoderConfigurationRecord (defined in 14496-15) int nalUnitLengthFieldLength = (parent.readUnsignedByte() & 0x3) + 1; if (nalUnitLengthFieldLength == 3) { throw new IllegalStateException(); } List<byte[]> initializationData = new ArrayList<>(); float pixelWidthAspectRatio = 1; int numSequenceParameterSets = parent.readUnsignedByte() & 0x1F; for (int j = 0; j < numSequenceParameterSets; j++) { initializationData.add(NalUnitUtil.parseChildNalUnit(parent)); } int numPictureParameterSets = parent.readUnsignedByte(); for (int j = 0; j < numPictureParameterSets; j++) { initializationData.add(NalUnitUtil.parseChildNalUnit(parent)); } if (numSequenceParameterSets > 0) { // Parse the first sequence parameter set to obtain pixelWidthAspectRatio. ParsableBitArray spsDataBitArray = new ParsableBitArray(initializationData.get(0)); // Skip the NAL header consisting of the nalUnitLengthField and the type (1 byte). spsDataBitArray.setPosition(8 * (nalUnitLengthFieldLength + 1)); pixelWidthAspectRatio = NalUnitUtil.parseSpsNalUnit(spsDataBitArray).pixelWidthAspectRatio; } return new AvcCData(initializationData, nalUnitLengthFieldLength, pixelWidthAspectRatio); } private static Pair<List<byte[]>, Integer> parseHvcCFromParent(ParsableByteArray parent, int position) { // Skip to the NAL unit length size field. parent.setPosition(position + Atom.HEADER_SIZE + 21); int lengthSizeMinusOne = parent.readUnsignedByte() & 0x03; // Calculate the combined size of all VPS/SPS/PPS bitstreams. int numberOfArrays = parent.readUnsignedByte(); int csdLength = 0; int csdStartPosition = parent.getPosition(); for (int i = 0; i < numberOfArrays; i++) { parent.skipBytes(1); // completeness (1), nal_unit_type (7) int numberOfNalUnits = parent.readUnsignedShort(); for (int j = 0; j < numberOfNalUnits; j++) { int nalUnitLength = parent.readUnsignedShort(); csdLength += 4 + nalUnitLength; // Start code and NAL unit. parent.skipBytes(nalUnitLength); } } // Concatenate the codec-specific data into a single buffer. parent.setPosition(csdStartPosition); byte[] buffer = new byte[csdLength]; int bufferPosition = 0; for (int i = 0; i < numberOfArrays; i++) { parent.skipBytes(1); // completeness (1), nal_unit_type (7) int numberOfNalUnits = parent.readUnsignedShort(); for (int j = 0; j < numberOfNalUnits; j++) { int nalUnitLength = parent.readUnsignedShort(); System.arraycopy(NalUnitUtil.NAL_START_CODE, 0, buffer, bufferPosition, NalUnitUtil.NAL_START_CODE.length); bufferPosition += NalUnitUtil.NAL_START_CODE.length; System.arraycopy(parent.data, parent.getPosition(), buffer, bufferPosition, nalUnitLength); bufferPosition += nalUnitLength; parent.skipBytes(nalUnitLength); } } List<byte[]> initializationData = csdLength == 0 ? null : Collections.singletonList(buffer); return Pair.create(initializationData, lengthSizeMinusOne + 1); } /** * Parses the edts atom (defined in 14496-12 subsection 8.6.5). * * @param edtsAtom edts (edit box) atom to parse. * @return Pair of edit list durations and edit list media times, or a pair of nulls if they are * not present. */ private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) { Atom.LeafAtom elst; if (edtsAtom == null || (elst = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst)) == null) { return Pair.create(null, null); } ParsableByteArray elstData = elst.data; elstData.setPosition(Atom.HEADER_SIZE); int fullAtom = elstData.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); int entryCount = elstData.readUnsignedIntToInt(); long[] editListDurations = new long[entryCount]; long[] editListMediaTimes = new long[entryCount]; for (int i = 0; i < entryCount; i++) { editListDurations[i] = version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt(); editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt(); int mediaRateInteger = elstData.readShort(); if (mediaRateInteger != 1) { // The extractor does not handle dwell edits (mediaRateInteger == 0). throw new IllegalArgumentException("Unsupported media rate."); } elstData.skipBytes(2); } return Pair.create(editListDurations, editListMediaTimes); } private static float parsePaspFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE); int hSpacing = parent.readUnsignedIntToInt(); int vSpacing = parent.readUnsignedIntToInt(); return (float) hSpacing / vSpacing; } private static void parseAudioSampleEntry(ParsableByteArray parent, int atomType, int position, int size, int trackId, long durationUs, String language, boolean isQuickTime, StsdData out, int entryIndex) { parent.setPosition(position + Atom.HEADER_SIZE); int quickTimeSoundDescriptionVersion = 0; if (isQuickTime) { parent.skipBytes(8); quickTimeSoundDescriptionVersion = parent.readUnsignedShort(); parent.skipBytes(6); } else { parent.skipBytes(16); } int channelCount; int sampleRate; if (quickTimeSoundDescriptionVersion == 0 || quickTimeSoundDescriptionVersion == 1) { channelCount = parent.readUnsignedShort(); parent.skipBytes(6); // sampleSize, compressionId, packetSize. sampleRate = parent.readUnsignedFixedPoint1616(); if (quickTimeSoundDescriptionVersion == 1) { parent.skipBytes(16); } } else if (quickTimeSoundDescriptionVersion == 2) { parent.skipBytes(16); // always[3,16,Minus2,0,65536], sizeOfStructOnly sampleRate = (int) Math.round(parent.readDouble()); channelCount = parent.readUnsignedIntToInt(); // Skip always7F000000, sampleSize, formatSpecificFlags, constBytesPerAudioPacket, // constLPCMFramesPerAudioPacket. parent.skipBytes(20); } else { // Unsupported version. return; } int childPosition = parent.getPosition(); if (atomType == Atom.TYPE_enca) { atomType = parseSampleEntryEncryptionData(parent, position, size, out, entryIndex); parent.setPosition(childPosition); } // If the atom type determines a MIME type, set it immediately. String mimeType = null; if (atomType == Atom.TYPE_ac_3) { mimeType = MimeTypes.AUDIO_AC3; } else if (atomType == Atom.TYPE_ec_3) { mimeType = MimeTypes.AUDIO_E_AC3; } else if (atomType == Atom.TYPE_dtsc) { mimeType = MimeTypes.AUDIO_DTS; } else if (atomType == Atom.TYPE_dtsh || atomType == Atom.TYPE_dtsl) { mimeType = MimeTypes.AUDIO_DTS_HD; } else if (atomType == Atom.TYPE_dtse) { mimeType = MimeTypes.AUDIO_DTS_EXPRESS; } else if (atomType == Atom.TYPE_samr) { mimeType = MimeTypes.AUDIO_AMR_NB; } else if (atomType == Atom.TYPE_sawb) { mimeType = MimeTypes.AUDIO_AMR_WB; } else if (atomType == Atom.TYPE_lpcm || atomType == Atom.TYPE_sowt) { mimeType = MimeTypes.AUDIO_RAW; } byte[] initializationData = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_esds || (isQuickTime && childAtomType == Atom.TYPE_wave)) { int esdsAtomPosition = childAtomType == Atom.TYPE_esds ? childPosition : findEsdsPosition(parent, childPosition, childAtomSize); if (esdsAtomPosition != -1) { Pair<String, byte[]> mimeTypeAndInitializationData = parseEsdsFromParent(parent, esdsAtomPosition); mimeType = mimeTypeAndInitializationData.first; initializationData = mimeTypeAndInitializationData.second; if (MimeTypes.AUDIO_AAC.equals(mimeType)) { // TODO: Do we really need to do this? See [Internal: b/10903778] // Update sampleRate and channelCount from the AudioSpecificConfig initialization data. Pair<Integer, Integer> audioSpecificConfig = CodecSpecificDataUtil.parseAacAudioSpecificConfig(initializationData); sampleRate = audioSpecificConfig.first; channelCount = audioSpecificConfig.second; } } } else if (childAtomType == Atom.TYPE_dac3) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.mediaFormat = Ac3Util.parseAc3AnnexFFormat(parent, Integer.toString(trackId), durationUs, language); } else if (childAtomType == Atom.TYPE_dec3) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.mediaFormat = Ac3Util.parseEAc3AnnexFFormat(parent, Integer.toString(trackId), durationUs, language); } else if (childAtomType == Atom.TYPE_ddts) { out.mediaFormat = MediaFormat.createAudioFormat(Integer.toString(trackId), mimeType, MediaFormat.NO_VALUE, MediaFormat.NO_VALUE, durationUs, channelCount, sampleRate, null, language); } childPosition += childAtomSize; } if (out.mediaFormat == null && mimeType != null) { // TODO: Determine the correct PCM encoding. int pcmEncoding = MimeTypes.AUDIO_RAW.equals(mimeType) ? C.ENCODING_PCM_16BIT : MediaFormat.NO_VALUE; out.mediaFormat = MediaFormat.createAudioFormat(Integer.toString(trackId), mimeType, MediaFormat.NO_VALUE, MediaFormat.NO_VALUE, durationUs, channelCount, sampleRate, initializationData == null ? null : Collections.singletonList(initializationData), language, pcmEncoding); } } /** Returns the position of the esds box within a parent, or -1 if no esds box is found */ private static int findEsdsPosition(ParsableByteArray parent, int position, int size) { int childAtomPosition = parent.getPosition(); while (childAtomPosition - position < size) { parent.setPosition(childAtomPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childType = parent.readInt(); if (childType == Atom.TYPE_esds) { return childAtomPosition; } childAtomPosition += childAtomSize; } return -1; } /** Returns codec-specific initialization data contained in an esds box. */ private static Pair<String, byte[]> parseEsdsFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE + 4); // Start of the ES_Descriptor (defined in 14496-1) parent.skipBytes(1); // ES_Descriptor tag parseExpandableClassSize(parent); parent.skipBytes(2); // ES_ID int flags = parent.readUnsignedByte(); if ((flags & 0x80 /* streamDependenceFlag */) != 0) { parent.skipBytes(2); } if ((flags & 0x40 /* URL_Flag */) != 0) { parent.skipBytes(parent.readUnsignedShort()); } if ((flags & 0x20 /* OCRstreamFlag */) != 0) { parent.skipBytes(2); } // Start of the DecoderConfigDescriptor (defined in 14496-1) parent.skipBytes(1); // DecoderConfigDescriptor tag parseExpandableClassSize(parent); // Set the MIME type based on the object type indication (14496-1 table 5). int objectTypeIndication = parent.readUnsignedByte(); String mimeType; switch (objectTypeIndication) { case 0x6B: mimeType = MimeTypes.AUDIO_MPEG; return Pair.create(mimeType, null); case 0x20: mimeType = MimeTypes.VIDEO_MP4V; break; case 0x21: mimeType = MimeTypes.VIDEO_H264; break; case 0x23: mimeType = MimeTypes.VIDEO_H265; break; case 0x40: case 0x66: case 0x67: case 0x68: mimeType = MimeTypes.AUDIO_AAC; break; case 0xA5: mimeType = MimeTypes.AUDIO_AC3; break; case 0xA6: mimeType = MimeTypes.AUDIO_E_AC3; break; case 0xA9: case 0xAC: mimeType = MimeTypes.AUDIO_DTS; return Pair.create(mimeType, null); case 0xAA: case 0xAB: mimeType = MimeTypes.AUDIO_DTS_HD; return Pair.create(mimeType, null); default: mimeType = null; break; } parent.skipBytes(12); // Start of the AudioSpecificConfig. parent.skipBytes(1); // AudioSpecificConfig tag int initializationDataSize = parseExpandableClassSize(parent); byte[] initializationData = new byte[initializationDataSize]; parent.readBytes(initializationData, 0, initializationDataSize); return Pair.create(mimeType, initializationData); } /** * Parses encryption data from an audio/video sample entry, populating {@code out} and returning * the unencrypted atom type, or 0 if no sinf atom was present. */ private static int parseSampleEntryEncryptionData(ParsableByteArray parent, int position, int size, StsdData out, int entryIndex) { int childPosition = parent.getPosition(); while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_sinf) { Pair<Integer, TrackEncryptionBox> result = parseSinfFromParent(parent, childPosition, childAtomSize); Integer dataFormat = result.first; Assertions.checkArgument(dataFormat != null, "frma atom is mandatory"); out.trackEncryptionBoxes[entryIndex] = result.second; return dataFormat; } childPosition += childAtomSize; } // This enca/encv box does not have a data format so return an invalid atom type. return 0; } private static Pair<Integer, TrackEncryptionBox> parseSinfFromParent(ParsableByteArray parent, int position, int size) { int childPosition = position + Atom.HEADER_SIZE; TrackEncryptionBox trackEncryptionBox = null; Integer dataFormat = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_frma) { dataFormat = parent.readInt(); } else if (childAtomType == Atom.TYPE_schm) { parent.skipBytes(4); parent.readInt(); // schemeType. Expect cenc parent.readInt(); // schemeVersion. Expect 0x00010000 } else if (childAtomType == Atom.TYPE_schi) { trackEncryptionBox = parseSchiFromParent(parent, childPosition, childAtomSize); } childPosition += childAtomSize; } return Pair.create(dataFormat, trackEncryptionBox); } private static TrackEncryptionBox parseSchiFromParent(ParsableByteArray parent, int position, int size) { int childPosition = position + Atom.HEADER_SIZE; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_tenc) { parent.skipBytes(6); boolean defaultIsEncrypted = parent.readUnsignedByte() == 1; int defaultInitVectorSize = parent.readUnsignedByte(); byte[] defaultKeyId = new byte[16]; parent.readBytes(defaultKeyId, 0, defaultKeyId.length); return new TrackEncryptionBox(defaultIsEncrypted, defaultInitVectorSize, defaultKeyId); } else if (childAtomType == Atom.TYPE_uuid) { // Parses the PIFF extension "Track Encryption Box" 'uuid' box as described // in "Portable encoding of audio-video objects: The Protected Interoperable File Format // (PIFF),John A. Bocharov et al, Section 5.3.3.1 byte[] scratch = new byte[16]; parent.readBytes(scratch, 0, scratch.length); if (Arrays.equals(scratch, PIFF_TRACK_ENCRYPTION_BOX_EXTENDED_TYP)) { parent.skipBytes(4); // skip version and flags parent.skipBytes(3); // skip algorithm ID int defaultInitVectorSize = parent.readUnsignedByte(); parent.readBytes(scratch, 0, scratch.length); return new TrackEncryptionBox(true, defaultInitVectorSize, scratch); } } childPosition += childAtomSize; } return null; } /** Parses the size of an expandable class, as specified by ISO 14496-1 subsection 8.3.3. */ private static int parseExpandableClassSize(ParsableByteArray data) { int currentByte = data.readUnsignedByte(); int size = currentByte & 0x7F; while ((currentByte & 0x80) == 0x80) { currentByte = data.readUnsignedByte(); size = (size << 7) | (currentByte & 0x7F); } return size; } private AtomParsers() { // Prevent instantiation. } private static final class ChunkIterator { public final int length; public int index; public int numSamples; public long offset; private final boolean chunkOffsetsAreLongs; private final ParsableByteArray chunkOffsets; private final ParsableByteArray stsc; private int nextSamplesPerChunkChangeIndex; private int remainingSamplesPerChunkChanges; public ChunkIterator(ParsableByteArray stsc, ParsableByteArray chunkOffsets, boolean chunkOffsetsAreLongs) { this.stsc = stsc; this.chunkOffsets = chunkOffsets; this.chunkOffsetsAreLongs = chunkOffsetsAreLongs; chunkOffsets.setPosition(Atom.FULL_HEADER_SIZE); length = chunkOffsets.readUnsignedIntToInt(); stsc.setPosition(Atom.FULL_HEADER_SIZE); remainingSamplesPerChunkChanges = stsc.readUnsignedIntToInt(); Assertions.checkState(stsc.readInt() == 1, "first_chunk must be 1"); index = -1; } public boolean moveNext() { if (++index == length) { return false; } offset = chunkOffsetsAreLongs ? chunkOffsets.readUnsignedLongToLong() : chunkOffsets.readUnsignedInt(); if (index == nextSamplesPerChunkChangeIndex) { numSamples = stsc.readUnsignedIntToInt(); stsc.skipBytes(4); // Skip sample_description_index nextSamplesPerChunkChangeIndex = --remainingSamplesPerChunkChanges > 0 ? (stsc.readUnsignedIntToInt() - 1) : -1; } return true; } } /** * Holds data parsed from a tkhd atom. */ private static final class TkhdData { private final int id; private final long duration; private final int rotationDegrees; public TkhdData(int id, long duration, int rotationDegrees) { this.id = id; this.duration = duration; this.rotationDegrees = rotationDegrees; } } /** * Holds data parsed from an stsd atom and its children. */ private static final class StsdData { public final TrackEncryptionBox[] trackEncryptionBoxes; public MediaFormat mediaFormat; public int nalUnitLengthFieldLength; public StsdData(int numberOfEntries) { trackEncryptionBoxes = new TrackEncryptionBox[numberOfEntries]; nalUnitLengthFieldLength = -1; } } /** * Holds data parsed from an AvcC atom. */ private static final class AvcCData { public final List<byte[]> initializationData; public final int nalUnitLengthFieldLength; public final float pixelWidthAspectRatio; public AvcCData(List<byte[]> initializationData, int nalUnitLengthFieldLength, float pixelWidthAspectRatio) { this.initializationData = initializationData; this.nalUnitLengthFieldLength = nalUnitLengthFieldLength; this.pixelWidthAspectRatio = pixelWidthAspectRatio; } } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.impl; import java.util.ArrayList; import java.util.List; import org.drools.workbench.models.guided.dtable.shared.model.AttributeCol52; import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52; import org.drools.workbench.screens.guided.dtable.client.widget.table.GuidedDecisionTableView; import org.drools.workbench.screens.guided.dtable.client.widget.table.model.GuidedDecisionTableUiCell; import org.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.ModelSynchronizer.VetoException; import org.drools.workbench.screens.guided.rule.client.editor.RuleAttributeWidget; import org.junit.Test; import org.uberfire.ext.wires.core.grids.client.model.GridRow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class RowSynchronizerTest extends BaseSynchronizerTest { @Test public void testAppend() throws VetoException { modelSynchronizer.appendRow(); assertEquals(1, model.getData().size()); assertEquals(1, uiModel.getRowCount()); assertEquals(GuidedDecisionTableView.ROW_HEIGHT, uiModel.getRow(0).getHeight(), 0.0); } @Test public void testInsert() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.insertRow(0); assertEquals(2, model.getData().size()); assertEquals(2, uiModel.getRowCount()); assertEquals(GuidedDecisionTableView.ROW_HEIGHT, uiModel.getRow(0).getHeight(), 0.0); assertEquals(GuidedDecisionTableView.ROW_HEIGHT, uiModel.getRow(1).getHeight(), 0.0); } @Test public void testDeleteUnmergedData() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.deleteRow(0); assertEquals(0, model.getData().size()); assertEquals(0, uiModel.getRowCount()); } @Test public void testDeleteMergedData_Block() throws VetoException { uiModel.setMerged(true); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); uiModel.setCellValue(0, 1, new GuidedDecisionTableUiCell<String>("a")); uiModel.setCellValue(1, 1, new GuidedDecisionTableUiCell<String>("a")); uiModel.setCellValue(2, 1, new GuidedDecisionTableUiCell<String>("b")); uiModel.collapseCell(0, 1); modelSynchronizer.deleteRow(0); assertEquals(1, model.getData().size()); assertEquals(1, uiModel.getRowCount()); } @Test public void testDeleteMergedData_WholeBlock() throws VetoException { uiModel.setMerged(true); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); uiModel.setCellValue(0, 1, new GuidedDecisionTableUiCell<String>("a")); uiModel.setCellValue(1, 1, new GuidedDecisionTableUiCell<String>("a")); uiModel.setCellValue(2, 1, new GuidedDecisionTableUiCell<String>("a")); uiModel.collapseCell(0, 1); modelSynchronizer.deleteRow(0); assertEquals(0, model.getData().size()); assertEquals(0, uiModel.getRowCount()); } @Test public void testMoveRowMoveUpTopBlock() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); final List<DTCellValue52> row0 = model.getData().get(0); final List<DTCellValue52> row1 = model.getData().get(1); final List<DTCellValue52> row2 = model.getData().get(2); uiModel.moveRowsTo(0, new ArrayList<GridRow>() {{ add(uiRow2); }}); assertEquals(uiRow2, uiModel.getRow(0)); assertEquals(uiRow0, uiModel.getRow(1)); assertEquals(uiRow1, uiModel.getRow(2)); assertEquals(row2, model.getData().get(0)); assertEquals(row0, model.getData().get(1)); assertEquals(row1, model.getData().get(2)); } @Test public void testMoveRowMoveUpMidBlock() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); final List<DTCellValue52> row0 = model.getData().get(0); final List<DTCellValue52> row1 = model.getData().get(1); final List<DTCellValue52> row2 = model.getData().get(2); uiModel.moveRowsTo(1, new ArrayList<GridRow>() {{ add(uiRow2); }}); assertEquals(uiRow0, uiModel.getRow(0)); assertEquals(uiRow2, uiModel.getRow(1)); assertEquals(uiRow1, uiModel.getRow(2)); assertEquals(row0, model.getData().get(0)); assertEquals(row2, model.getData().get(1)); assertEquals(row1, model.getData().get(2)); } @Test public void testMoveRowsMoveUp() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); final List<DTCellValue52> row0 = model.getData().get(0); final List<DTCellValue52> row1 = model.getData().get(1); final List<DTCellValue52> row2 = model.getData().get(2); uiModel.moveRowsTo(0, new ArrayList<GridRow>() {{ add(uiRow1); add(uiRow2); }}); assertEquals(uiRow1, uiModel.getRow(0)); assertEquals(uiRow2, uiModel.getRow(1)); assertEquals(uiRow0, uiModel.getRow(2)); assertEquals(row1, model.getData().get(0)); assertEquals(row2, model.getData().get(1)); assertEquals(row0, model.getData().get(2)); } @Test public void testMoveRowMoveDownEndBlock() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); final List<DTCellValue52> row0 = model.getData().get(0); final List<DTCellValue52> row1 = model.getData().get(1); final List<DTCellValue52> row2 = model.getData().get(2); uiModel.moveRowsTo(2, new ArrayList<GridRow>() {{ add(uiRow0); }}); assertEquals(uiRow1, uiModel.getRow(0)); assertEquals(uiRow2, uiModel.getRow(1)); assertEquals(uiRow0, uiModel.getRow(2)); assertEquals(row1, model.getData().get(0)); assertEquals(row2, model.getData().get(1)); assertEquals(row0, model.getData().get(2)); } @Test public void testMoveRowMoveDownMidBlock() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); final List<DTCellValue52> row0 = model.getData().get(0); final List<DTCellValue52> row1 = model.getData().get(1); final List<DTCellValue52> row2 = model.getData().get(2); uiModel.moveRowsTo(1, new ArrayList<GridRow>() {{ add(uiRow0); }}); assertEquals(uiRow1, uiModel.getRow(0)); assertEquals(uiRow0, uiModel.getRow(1)); assertEquals(uiRow2, uiModel.getRow(2)); assertEquals(row1, model.getData().get(0)); assertEquals(row0, model.getData().get(1)); assertEquals(row2, model.getData().get(2)); } @Test public void testMoveRowsMoveDown() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); final List<DTCellValue52> row0 = model.getData().get(0); final List<DTCellValue52> row1 = model.getData().get(1); final List<DTCellValue52> row2 = model.getData().get(2); uiModel.moveRowsTo(2, new ArrayList<GridRow>() {{ add(uiRow0); add(uiRow1); }}); assertEquals(uiRow2, uiModel.getRow(0)); assertEquals(uiRow0, uiModel.getRow(1)); assertEquals(uiRow1, uiModel.getRow(2)); assertEquals(row2, model.getData().get(0)); assertEquals(row0, model.getData().get(1)); assertEquals(row1, model.getData().get(2)); } @Test public void testAppendRowNumbers() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); assertEquals(1, uiModel.getRow(0).getCells().get(0).getValue().getValue()); assertEquals(2, uiModel.getRow(1).getCells().get(0).getValue().getValue()); assertEquals(1, model.getData().get(0).get(0).getNumericValue()); assertEquals(2, model.getData().get(1).get(0).getNumericValue()); } @Test public void testInsertRowNumbers() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.insertRow(0); assertEquals(1, uiModel.getRow(0).getCells().get(0).getValue().getValue()); assertEquals(2, uiModel.getRow(1).getCells().get(0).getValue().getValue()); assertEquals(1, model.getData().get(0).get(0).getNumericValue()); assertEquals(2, model.getData().get(1).get(0).getNumericValue()); } @Test public void testDeleteRowNumbers() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.deleteRow(0); assertEquals(1, uiModel.getRow(0).getCells().get(0).getValue().getValue()); assertEquals(1, model.getData().get(0).get(0).getNumericValue()); } @Test public void testMoveRowsMoveDownCheckRowNumbers() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow0 = uiModel.getRow(0); final GridRow uiRow1 = uiModel.getRow(1); uiModel.moveRowsTo(2, new ArrayList<GridRow>() {{ add(uiRow0); add(uiRow1); }}); assertEquals(1, uiModel.getRow(0).getCells().get(0).getValue().getValue()); assertEquals(2, uiModel.getRow(1).getCells().get(0).getValue().getValue()); assertEquals(3, uiModel.getRow(2).getCells().get(0).getValue().getValue()); assertEquals(1, model.getData().get(0).get(0).getNumericValue()); assertEquals(2, model.getData().get(1).get(0).getNumericValue()); assertEquals(3, model.getData().get(2).get(0).getNumericValue()); } @Test public void testMoveRowsMoveUpCheckRowNumbers() throws VetoException { modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); modelSynchronizer.appendRow(); final GridRow uiRow1 = uiModel.getRow(1); final GridRow uiRow2 = uiModel.getRow(2); uiModel.moveRowsTo(0, new ArrayList<GridRow>() {{ add(uiRow1); add(uiRow2); }}); assertEquals(1, uiModel.getRow(0).getCells().get(0).getValue().getValue()); assertEquals(2, uiModel.getRow(1).getCells().get(0).getValue().getValue()); assertEquals(3, uiModel.getRow(2).getCells().get(0).getValue().getValue()); assertEquals(1, model.getData().get(0).get(0).getNumericValue()); assertEquals(2, model.getData().get(1).get(0).getNumericValue()); assertEquals(3, model.getData().get(2).get(0).getNumericValue()); } @Test public void checkBooleanDefaultValueTrue() throws VetoException { final AttributeCol52 column = new AttributeCol52(); column.setAttribute(RuleAttributeWidget.ENABLED_ATTR); column.setDefaultValue(new DTCellValue52(true)); modelSynchronizer.appendColumn(column); modelSynchronizer.appendRow(); assertTrue((Boolean) uiModel.getRow(0).getCells().get(2).getValue().getValue()); assertTrue(model.getData().get(0).get(2).getBooleanValue()); } @Test public void checkBooleanDefaultValueFalse() throws VetoException { final AttributeCol52 column = new AttributeCol52(); column.setAttribute(RuleAttributeWidget.ENABLED_ATTR); column.setDefaultValue(new DTCellValue52(false)); modelSynchronizer.appendColumn(column); modelSynchronizer.appendRow(); assertFalse((Boolean) uiModel.getRow(0).getCells().get(2).getValue().getValue()); assertFalse(model.getData().get(0).get(2).getBooleanValue()); } @Test public void checkBooleanDefaultValueNotSet() throws VetoException { final AttributeCol52 column = new AttributeCol52(); column.setAttribute(RuleAttributeWidget.ENABLED_ATTR); modelSynchronizer.appendColumn(column); modelSynchronizer.appendRow(); assertFalse((Boolean) uiModel.getRow(0).getCells().get(2).getValue().getValue()); assertFalse(model.getData().get(0).get(2).getBooleanValue()); } }
/* ownCloud Android Library is available under MIT license * Copyright (C) 2016 ownCloud GmbH. * * 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.owncloud.android.lib.common.network; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.conn.ssl.X509HostnameVerifier; import android.content.Context; import com.owncloud.android.lib.common.utils.Log_OC; public class NetworkUtils { final private static String TAG = NetworkUtils.class.getSimpleName(); /** Default timeout for waiting data from the server */ public static final int DEFAULT_DATA_TIMEOUT = 60000; /** Default timeout for establishing a connection */ public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; /** Standard name for protocol TLS version 1.2 in Java Secure Socket Extension (JSSE) API */ public static final String PROTOCOL_TLSv1_2 = "TLSv1.2"; /** Standard name for protocol TLS version 1.0 in JSSE API */ public static final String PROTOCOL_TLSv1_0 = "TLSv1"; /** Connection manager for all the OwnCloudClients */ private static MultiThreadedHttpConnectionManager mConnManager = null; private static Protocol mDefaultHttpsProtocol = null; private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null; private static X509HostnameVerifier mHostnameVerifier = null; /** * Registers or unregisters the proper components for advanced SSL handling. * @throws IOException */ @SuppressWarnings("deprecation") public static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException { Protocol pr = null; try { pr = Protocol.getProtocol("https"); if (pr != null && mDefaultHttpsProtocol == null) { mDefaultHttpsProtocol = pr; } } catch (IllegalStateException e) { // nothing to do here; really } boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory); if (register && !isRegistered) { Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443)); } else if (!register && isRegistered) { if (mDefaultHttpsProtocol != null) { Protocol.registerProtocol("https", mDefaultHttpsProtocol); } } } public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext; try { sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0"); sslContext = SSLContext.getInstance("TLSv1"); // should be available in any device; see reference of supported protocols in // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html } sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; } private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks"; private static String LOCAL_TRUSTSTORE_PASSWORD = "password"; private static KeyStore mKnownServersStore = null; /** * Returns the local store of reliable server certificates, explicitly accepted by the user. * * Returns a KeyStore instance with empty content if the local store was never created. * * Loads the store from the storage environment if needed. * * @param context Android context where the operation is being performed. * @return KeyStore instance with explicitly-accepted server certificates. * @throws KeyStoreException When the KeyStore instance could not be created. * @throws IOException When an existing local trust store could not be loaded. * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm. * @throws CertificateException When an exception occurred while loading the certificates from the local * trust store. */ private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (mKnownServersStore == null) { //mKnownServersStore = KeyStore.getInstance("BKS"); mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType()); File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME); Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath()); if (localTrustStoreFile.exists()) { InputStream in = new FileInputStream(localTrustStoreFile); try { mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { in.close(); } } else { // next is necessary to initialize an empty KeyStore instance mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } } return mKnownServersStore; } public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); FileOutputStream fos = null; try { fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { fos.close(); } } static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() { if (mConnManager == null) { mConnManager = new MultiThreadedHttpConnectionManager(); mConnManager.getParams().setDefaultMaxConnectionsPerHost(5); mConnManager.getParams().setMaxTotalConnections(5); } return mConnManager; } public static boolean isCertInKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); Log_OC.d(TAG, "Certificate - HashCode: " + cert.hashCode() + " " + Boolean.toString(knownServers.isCertificateEntry(Integer.toString(cert.hashCode())))); return knownServers.isCertificateEntry(Integer.toString(cert.hashCode())); } }
package com.ss.bth; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.TypeAlias; import org.springframework.data.mongodb.core.index.CompoundIndex; import org.springframework.data.mongodb.core.index.CompoundIndexes; import org.springframework.data.mongodb.core.mapping.Document; /** * Created by Samuil on 21-11-2015 * A User Model class */ @Document(collection = "users") @TypeAlias("users") @CompoundIndexes({ @CompoundIndex(name = "email_code", def = "{'primaryEmail' : 1, 'activationCode': 1}", unique = true) }) public final class User { @Id private String id; private double rating; private String firstName; private String lastName; private String primaryEmail; private String secondaryEmail; private String password; private String address; private String city; private int zipCode; private String telephone; private String mobile; private String activationCode; private boolean isActivated; private boolean isBlocked; public User() { } private User(UserBuilder userBuilder) { this.firstName = userBuilder.firstName; this.lastName = userBuilder.lastName; this.primaryEmail = userBuilder.primaryEmail; this.secondaryEmail = userBuilder.secondaryEmail; this.password = userBuilder.password; this.address = userBuilder.address; this.city = userBuilder.city; this.zipCode = userBuilder.zipCode; this.telephone = userBuilder.telephone; this.mobile = userBuilder.mobile; this.activationCode = userBuilder.activationCode; this.isActivated = userBuilder.isActivated; this.isBlocked = userBuilder.isBlocked; } public void update(double rating, String firstName, String lastName, String secondaryEmail, String password, String address, String city, int zipCode, String telephone, String mobile, boolean isBlocked) { StringUtil strUtil = new StringUtil(); if (rating >= 1 && rating <= 5) this.rating = rating; if (!strUtil.isBlank(firstName) && !strUtil.isEmpty(firstName) && strUtil.isLengthBetween(firstName, 2, 30)) this.firstName = firstName; if (!strUtil.isBlank(lastName) && !strUtil.isEmpty(lastName) && strUtil.isLengthBetween(lastName, 2, 30)) this.lastName = lastName; if (!strUtil.isBlank(secondaryEmail) && !strUtil.isEmpty(secondaryEmail)) this.secondaryEmail = secondaryEmail; if (!strUtil.isBlank(password) && !strUtil.isEmpty(password)) this.password = password; if (!strUtil.isBlank(address) && !strUtil.isEmpty(address) && strUtil.isLengthBetween(address, 5, 50)) this.address = address; if (!strUtil.isBlank(city) && !strUtil.isEmpty(city) && strUtil.isLengthBetween(city, 2, 50)) this.city = city; if (zipCode >= 10000 && zipCode <= 99999) this.zipCode = zipCode; if (!strUtil.isBlank(telephone) && !strUtil.isEmpty(telephone) && strUtil.isLengthBetween(telephone, 9, 10)) this.telephone = telephone; if (!strUtil.isBlank(mobile) && !strUtil.isEmpty(mobile) && strUtil.isLengthBetween(mobile, 9, 10)) this.mobile = mobile; if (this.isBlocked != isBlocked) this.isBlocked = isBlocked; } public String getId() { return id; } public double getRating() { return rating; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getPrimaryEmail() { return primaryEmail; } public String getSecondaryEmail() { return secondaryEmail; } public String getPassword() { return password; } public String getAddress() { return address; } public String getCity() { return city; } public int getZipCode() { return zipCode; } public String getTelephone() { return telephone; } public String getMobile() { return mobile; } public String getActivationCode() { return activationCode; } public boolean isActivated() { return isActivated; } public boolean isBlocked() { return isBlocked; } static UserBuilder getBuilder() { return new UserBuilder(); } public void setActivated(boolean activated) { isActivated = activated; } static class UserBuilder { private double rating; private String firstName; private String lastName; private String primaryEmail; private String secondaryEmail; private String password; private String address; private String city; private int zipCode; private String telephone; private String mobile; private String activationCode; private boolean isActivated; private boolean isBlocked; private UserBuilder() { } public UserBuilder setRating(double rating) { this.rating = rating; return this; } public UserBuilder setFirstName(String firstName) { this.firstName = firstName; return this; } public UserBuilder setLastName(String lastName) { this.lastName = lastName; return this; } public UserBuilder setPrimaryEmail(String primaryEmail) { this.primaryEmail = primaryEmail; return this; } public UserBuilder setSecondaryEmail(String secondaryEmail) { this.secondaryEmail = secondaryEmail; return this; } public UserBuilder setPassword(String password) { this.password = password; return this; } public UserBuilder setAddress(String address) { this.address = address; return this; } public UserBuilder setCity(String city) { this.city = city; return this; } public UserBuilder setZipCode(int zipCode) { this.zipCode = zipCode; return this; } public UserBuilder setTelephone(String telephone) { this.telephone = telephone; return this; } public UserBuilder setMobile(String mobile) { this.mobile = mobile; return this; } public UserBuilder setActivated(boolean activated) { this.isActivated = activated; return this; } public UserBuilder setBlocked(boolean blocked) { this.isBlocked = blocked; return this; } public UserBuilder setActivationCode(String activationCode) { this.activationCode = activationCode; return this; } User build() { User build = new User(this); return build; } } public class StringUtil { public boolean isEmpty(String str) { if ((str != null) && (str.trim().length() > 0)) return false; else return true; } public boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((!Character.isWhitespace(str.charAt(i)))) { return false; } } return true; } public boolean isLengthBetween(String str, int min, int max) { int strLen; if (str == null || (strLen = str.length()) == 0) { return false; } if (strLen >= min && strLen <= max) return true; else return false; } } }
/* * 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.beam.sdk.transforms; import static org.apache.beam.sdk.TestUtils.KvMatcher.isKv; import static org.apache.beam.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.Matchers.empty; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.assertThat; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.beam.sdk.coders.AtomicCoder; import org.apache.beam.sdk.coders.BigEndianIntegerCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CoderProviders; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.MapCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.beam.sdk.testing.DataflowPortabilityApiUnsupported; import org.apache.beam.sdk.testing.LargeKeys; import org.apache.beam.sdk.testing.NeedsRunner; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.testing.TestStream; import org.apache.beam.sdk.testing.UsesTestStreamWithProcessingTime; import org.apache.beam.sdk.testing.ValidatesRunner; import org.apache.beam.sdk.transforms.display.DisplayData; import org.apache.beam.sdk.transforms.windowing.AfterPane; import org.apache.beam.sdk.transforms.windowing.AfterProcessingTime; import org.apache.beam.sdk.transforms.windowing.AfterWatermark; import org.apache.beam.sdk.transforms.windowing.FixedWindows; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; import org.apache.beam.sdk.transforms.windowing.InvalidWindows; import org.apache.beam.sdk.transforms.windowing.Repeatedly; import org.apache.beam.sdk.transforms.windowing.Sessions; import org.apache.beam.sdk.transforms.windowing.SlidingWindows; import org.apache.beam.sdk.transforms.windowing.TimestampCombiner; import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TimestampedValue; import org.apache.beam.sdk.values.WindowingStrategy; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; import org.hamcrest.Matcher; import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.experimental.runners.Enclosed; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for GroupByKey. */ @SuppressWarnings({"rawtypes", "unchecked"}) @RunWith(Enclosed.class) public class GroupByKeyTest implements Serializable { /** Shared test base class with setup/teardown helpers. */ public abstract static class SharedTestBase { @Rule public transient TestPipeline p = TestPipeline.create(); @Rule public transient ExpectedException thrown = ExpectedException.none(); } /** Tests validating basic {@link GroupByKey} scenarios. */ @RunWith(JUnit4.class) public static class BasicTests extends SharedTestBase { @Test @Category(ValidatesRunner.class) public void testGroupByKey() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList( KV.of("k1", 3), KV.of("k5", Integer.MAX_VALUE), KV.of("k5", Integer.MIN_VALUE), KV.of("k2", 66), KV.of("k1", 4), KV.of("k2", -33), KV.of("k3", 0)); PCollection<KV<String, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<KV<String, Iterable<Integer>>> output = input.apply(GroupByKey.create()); SerializableFunction<Iterable<KV<String, Iterable<Integer>>>, Void> checker = containsKvs( kv("k1", 3, 4), kv("k5", Integer.MIN_VALUE, Integer.MAX_VALUE), kv("k2", 66, -33), kv("k3", 0)); PAssert.that(output).satisfies(checker); PAssert.that(output).inWindow(GlobalWindow.INSTANCE).satisfies(checker); p.run(); } @Test @Category(ValidatesRunner.class) public void testGroupByKeyEmpty() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList(); PCollection<KV<String, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<KV<String, Iterable<Integer>>> output = input.apply(GroupByKey.create()); PAssert.that(output).empty(); p.run(); } /** * Tests that when a processing time timers comes in after a window is expired it does not cause * a spurious output. */ @Test @Category({ValidatesRunner.class, UsesTestStreamWithProcessingTime.class}) public void testCombiningAccumulatingProcessingTime() throws Exception { PCollection<Integer> triggeredSums = p.apply( TestStream.create(VarIntCoder.of()) .advanceWatermarkTo(new Instant(0)) .addElements( TimestampedValue.of(2, new Instant(2)), TimestampedValue.of(5, new Instant(5))) .advanceWatermarkTo(new Instant(100)) .advanceProcessingTime(Duration.millis(10)) .advanceWatermarkToInfinity()) .apply( Window.<Integer>into(FixedWindows.of(Duration.millis(100))) .withTimestampCombiner(TimestampCombiner.EARLIEST) .accumulatingFiredPanes() .withAllowedLateness(Duration.ZERO) .triggering( Repeatedly.forever( AfterProcessingTime.pastFirstElementInPane() .plusDelayOf(Duration.millis(10))))) .apply(Sum.integersGlobally().withoutDefaults()); PAssert.that(triggeredSums).containsInAnyOrder(7); p.run(); } @Test public void testGroupByKeyNonDeterministic() throws Exception { List<KV<Map<String, String>, Integer>> ungroupedPairs = Arrays.asList(); PCollection<KV<Map<String, String>, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder( KvCoder.of( MapCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()), BigEndianIntegerCoder.of()))); thrown.expect(IllegalStateException.class); thrown.expectMessage("must be deterministic"); input.apply(GroupByKey.create()); } // AfterPane.elementCountAtLeast(1) is not OK @Test public void testGroupByKeyFinishingTriggerRejected() { PCollection<KV<String, String>> input = p.apply(Create.of(KV.of("hello", "goodbye"))) .apply( Window.<KV<String, String>>configure() .discardingFiredPanes() .triggering(AfterPane.elementCountAtLeast(1))); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Unsafe trigger"); input.apply(GroupByKey.create()); } // AfterWatermark.pastEndOfWindow() is OK with 0 allowed lateness @Test public void testGroupByKeyFinishingEndOfWindowTriggerOk() { PCollection<KV<String, String>> input = p.apply(Create.of(KV.of("hello", "goodbye"))) .apply( Window.<KV<String, String>>configure() .discardingFiredPanes() .triggering(AfterWatermark.pastEndOfWindow()) .withAllowedLateness(Duration.ZERO)); // OK input.apply(GroupByKey.create()); } // AfterWatermark.pastEndOfWindow().withEarlyFirings() is OK with 0 allowed lateness @Test public void testGroupByKeyFinishingEndOfWindowEarlyFiringsTriggerOk() { PCollection<KV<String, String>> input = p.apply(Create.of(KV.of("hello", "goodbye"))) .apply( Window.<KV<String, String>>configure() .discardingFiredPanes() .triggering( AfterWatermark.pastEndOfWindow() .withEarlyFirings(AfterPane.elementCountAtLeast(1))) .withAllowedLateness(Duration.ZERO)); // OK input.apply(GroupByKey.create()); } // AfterWatermark.pastEndOfWindow() is not OK with > 0 allowed lateness @Test public void testGroupByKeyFinishingEndOfWindowTriggerNotOk() { PCollection<KV<String, String>> input = p.apply(Create.of(KV.of("hello", "goodbye"))) .apply( Window.<KV<String, String>>configure() .discardingFiredPanes() .triggering(AfterWatermark.pastEndOfWindow()) .withAllowedLateness(Duration.millis(10))); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Unsafe trigger"); input.apply(GroupByKey.create()); } // AfterWatermark.pastEndOfWindow().withEarlyFirings() is not OK with > 0 allowed lateness @Test public void testGroupByKeyFinishingEndOfWindowEarlyFiringsTriggerNotOk() { PCollection<KV<String, String>> input = p.apply(Create.of(KV.of("hello", "goodbye"))) .apply( Window.<KV<String, String>>configure() .discardingFiredPanes() .triggering( AfterWatermark.pastEndOfWindow() .withEarlyFirings(AfterPane.elementCountAtLeast(1))) .withAllowedLateness(Duration.millis(10))); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Unsafe trigger"); input.apply(GroupByKey.create()); } // AfterWatermark.pastEndOfWindow().withLateFirings() is always OK @Test public void testGroupByKeyEndOfWindowLateFiringsOk() { PCollection<KV<String, String>> input = p.apply(Create.of(KV.of("hello", "goodbye"))) .apply( Window.<KV<String, String>>configure() .discardingFiredPanes() .triggering( AfterWatermark.pastEndOfWindow() .withLateFirings(AfterPane.elementCountAtLeast(1))) .withAllowedLateness(Duration.millis(10))); // OK input.apply(GroupByKey.create()); } @Test @Category(NeedsRunner.class) public void testRemerge() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList(); PCollection<KV<String, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) .apply(Window.into(Sessions.withGapDuration(Duration.standardMinutes(1)))); PCollection<KV<String, Iterable<Iterable<Integer>>>> middle = input .apply("GroupByKey", GroupByKey.create()) .apply("Remerge", Window.remerge()) .apply("GroupByKeyAgain", GroupByKey.create()) .apply("RemergeAgain", Window.remerge()); p.run(); Assert.assertTrue( middle .getWindowingStrategy() .getWindowFn() .isCompatible(Sessions.withGapDuration(Duration.standardMinutes(1)))); } @Test public void testGroupByKeyDirectUnbounded() { PCollection<KV<String, Integer>> input = p.apply( new PTransform<PBegin, PCollection<KV<String, Integer>>>() { @Override public PCollection<KV<String, Integer>> expand(PBegin input) { return PCollection.createPrimitiveOutputInternal( input.getPipeline(), WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED, KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())); } }); thrown.expect(IllegalStateException.class); thrown.expectMessage( "GroupByKey cannot be applied to non-bounded PCollection in the GlobalWindow without " + "a trigger. Use a Window.into or Window.triggering transform prior to GroupByKey."); input.apply("GroupByKey", GroupByKey.create()); } /** * Tests that when two elements are combined via a GroupByKey their output timestamp agrees with * the windowing function customized to actually be the same as the default, the earlier of the * two values. */ @Test @Category(ValidatesRunner.class) public void testTimestampCombinerEarliest() { p.apply( Create.timestamped( TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) .apply( Window.<KV<Integer, String>>into(FixedWindows.of(Duration.standardMinutes(10))) .withTimestampCombiner(TimestampCombiner.EARLIEST)) .apply(GroupByKey.create()) .apply(ParDo.of(new AssertTimestamp(new Instant(0)))); p.run(); } /** * Tests that when two elements are combined via a GroupByKey their output timestamp agrees with * the windowing function customized to use the latest value. */ @Test @Category(ValidatesRunner.class) public void testTimestampCombinerLatest() { p.apply( Create.timestamped( TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) .apply( Window.<KV<Integer, String>>into(FixedWindows.of(Duration.standardMinutes(10))) .withTimestampCombiner(TimestampCombiner.LATEST)) .apply(GroupByKey.create()) .apply(ParDo.of(new AssertTimestamp(new Instant(10)))); p.run(); } @Test public void testGroupByKeyGetName() { Assert.assertEquals("GroupByKey", GroupByKey.<String, Integer>create().getName()); } @Test public void testDisplayData() { GroupByKey<String, String> groupByKey = GroupByKey.create(); GroupByKey<String, String> groupByFewKeys = GroupByKey.createWithFewKeys(); DisplayData gbkDisplayData = DisplayData.from(groupByKey); DisplayData fewKeysDisplayData = DisplayData.from(groupByFewKeys); assertThat(gbkDisplayData.items(), empty()); assertThat(fewKeysDisplayData, hasDisplayItem("fewKeys", true)); } /** Verify that runners correctly hash/group on the encoded value and not the value itself. */ @Test @Category({ValidatesRunner.class, DataflowPortabilityApiUnsupported.class}) public void testGroupByKeyWithBadEqualsHashCode() throws Exception { final int numValues = 10; final int numKeys = 5; p.getCoderRegistry() .registerCoderProvider( CoderProviders.fromStaticMethods(BadEqualityKey.class, DeterministicKeyCoder.class)); // construct input data List<KV<BadEqualityKey, Long>> input = new ArrayList<>(); for (int i = 0; i < numValues; i++) { for (int key = 0; key < numKeys; key++) { input.add(KV.of(new BadEqualityKey(key), 1L)); } } // We first ensure that the values are randomly partitioned in the beginning. // Some runners might otherwise keep all values on the machine where // they are initially created. PCollection<KV<BadEqualityKey, Long>> dataset1 = p.apply(Create.of(input)) .apply(ParDo.of(new AssignRandomKey())) .apply(Reshuffle.of()) .apply(Values.create()); // Make the GroupByKey and Count implicit, in real-world code // this would be a Count.perKey() PCollection<KV<BadEqualityKey, Long>> result = dataset1.apply(GroupByKey.create()).apply(Combine.groupedValues(new CountFn())); PAssert.that(result).satisfies(new AssertThatCountPerKeyCorrect(numValues)); PAssert.that(result.apply(Keys.create())).satisfies(new AssertThatAllKeysExist(numKeys)); p.run(); } @Test @Category({ValidatesRunner.class, LargeKeys.Above10KB.class}) public void testLargeKeys10KB() throws Exception { runLargeKeysTest(p, 10 << 10); } @Test @Category({ValidatesRunner.class, LargeKeys.Above100KB.class}) public void testLargeKeys100KB() throws Exception { runLargeKeysTest(p, 100 << 10); } @Test @Category({ValidatesRunner.class, LargeKeys.Above1MB.class}) public void testLargeKeys1MB() throws Exception { runLargeKeysTest(p, 1 << 20); } @Test @Category({ValidatesRunner.class, LargeKeys.Above10MB.class}) public void testLargeKeys10MB() throws Exception { runLargeKeysTest(p, 10 << 20); } @Test @Category({ValidatesRunner.class, LargeKeys.Above100MB.class}) public void testLargeKeys100MB() throws Exception { runLargeKeysTest(p, 100 << 20); } } /** Tests validating GroupByKey behaviors with windowing. */ @RunWith(JUnit4.class) public static class WindowTests extends SharedTestBase { @Test @Category(ValidatesRunner.class) public void testGroupByKeyAndWindows() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList( KV.of("k1", 3), // window [0, 5) KV.of("k5", Integer.MAX_VALUE), // window [0, 5) KV.of("k5", Integer.MIN_VALUE), // window [0, 5) KV.of("k2", 66), // window [0, 5) KV.of("k1", 4), // window [5, 10) KV.of("k2", -33), // window [5, 10) KV.of("k3", 0)); // window [5, 10) PCollection<KV<String, Integer>> input = p.apply( Create.timestamped(ungroupedPairs, Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L)) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<KV<String, Iterable<Integer>>> output = input.apply(Window.into(FixedWindows.of(new Duration(5)))).apply(GroupByKey.create()); PAssert.that(output) .satisfies( containsKvs( kv("k1", 3), kv("k1", 4), kv("k5", Integer.MAX_VALUE, Integer.MIN_VALUE), kv("k2", 66), kv("k2", -33), kv("k3", 0))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(0L), Duration.millis(5L))) .satisfies( containsKvs( kv("k1", 3), kv("k5", Integer.MIN_VALUE, Integer.MAX_VALUE), kv("k2", 66))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(5L), Duration.millis(5L))) .satisfies(containsKvs(kv("k1", 4), kv("k2", -33), kv("k3", 0))); p.run(); } @Test @Category(ValidatesRunner.class) public void testGroupByKeyMultipleWindows() { PCollection<KV<String, Integer>> windowedInput = p.apply( Create.timestamped( TimestampedValue.of(KV.of("foo", 1), new Instant(1)), TimestampedValue.of(KV.of("foo", 4), new Instant(4)), TimestampedValue.of(KV.of("bar", 3), new Instant(3)))) .apply( Window.into(SlidingWindows.of(Duration.millis(5L)).every(Duration.millis(3L)))); PCollection<KV<String, Iterable<Integer>>> output = windowedInput.apply(GroupByKey.create()); PAssert.that(output) .satisfies( containsKvs(kv("foo", 1, 4), kv("foo", 1), kv("foo", 4), kv("bar", 3), kv("bar", 3))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(-3L), Duration.millis(5L))) .satisfies(containsKvs(kv("foo", 1))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(0L), Duration.millis(5L))) .satisfies(containsKvs(kv("foo", 1, 4), kv("bar", 3))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(3L), Duration.millis(5L))) .satisfies(containsKvs(kv("foo", 4), kv("bar", 3))); p.run(); } @Test @Category(ValidatesRunner.class) public void testGroupByKeyMergingWindows() { PCollection<KV<String, Integer>> windowedInput = p.apply( Create.timestamped( TimestampedValue.of(KV.of("foo", 1), new Instant(1)), TimestampedValue.of(KV.of("foo", 4), new Instant(4)), TimestampedValue.of(KV.of("bar", 3), new Instant(3)), TimestampedValue.of(KV.of("foo", 9), new Instant(9)))) .apply(Window.into(Sessions.withGapDuration(Duration.millis(4L)))); PCollection<KV<String, Iterable<Integer>>> output = windowedInput.apply(GroupByKey.create()); PAssert.that(output).satisfies(containsKvs(kv("foo", 1, 4), kv("foo", 9), kv("bar", 3))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(1L), new Instant(8L))) .satisfies(containsKvs(kv("foo", 1, 4))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(3L), new Instant(7L))) .satisfies(containsKvs(kv("bar", 3))); PAssert.that(output) .inWindow(new IntervalWindow(new Instant(9L), new Instant(13L))) .satisfies(containsKvs(kv("foo", 9))); p.run(); } @Test @Category(NeedsRunner.class) public void testIdentityWindowFnPropagation() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList(); PCollection<KV<String, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) .apply(Window.into(FixedWindows.of(Duration.standardMinutes(1)))); PCollection<KV<String, Iterable<Integer>>> output = input.apply(GroupByKey.create()); p.run(); Assert.assertTrue( output .getWindowingStrategy() .getWindowFn() .isCompatible(FixedWindows.of(Duration.standardMinutes(1)))); } @Test @Category(NeedsRunner.class) public void testWindowFnInvalidation() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList(); PCollection<KV<String, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) .apply(Window.into(Sessions.withGapDuration(Duration.standardMinutes(1)))); PCollection<KV<String, Iterable<Integer>>> output = input.apply(GroupByKey.create()); p.run(); Assert.assertTrue( output .getWindowingStrategy() .getWindowFn() .isCompatible( new InvalidWindows( "Invalid", Sessions.withGapDuration(Duration.standardMinutes(1))))); } @Test public void testInvalidWindowsDirect() { List<KV<String, Integer>> ungroupedPairs = Arrays.asList(); PCollection<KV<String, Integer>> input = p.apply( Create.of(ungroupedPairs) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) .apply(Window.into(Sessions.withGapDuration(Duration.standardMinutes(1)))); thrown.expect(IllegalStateException.class); thrown.expectMessage("GroupByKey must have a valid Window merge function"); input.apply("GroupByKey", GroupByKey.create()).apply("GroupByKeyAgain", GroupByKey.create()); } } private static KV<String, Collection<Integer>> kv(String key, Integer... values) { return KV.of(key, ImmutableList.copyOf(values)); } private static SerializableFunction<Iterable<KV<String, Iterable<Integer>>>, Void> containsKvs( KV<String, Collection<Integer>>... kvs) { return new ContainsKVs(ImmutableList.copyOf(kvs)); } /** * A function that asserts that the input element contains the expected {@link KV KVs} in any * order, where values appear in any order. */ private static class ContainsKVs implements SerializableFunction<Iterable<KV<String, Iterable<Integer>>>, Void> { private final List<KV<String, Collection<Integer>>> expectedKvs; private ContainsKVs(List<KV<String, Collection<Integer>>> expectedKvs) { this.expectedKvs = expectedKvs; } @Override public Void apply(Iterable<KV<String, Iterable<Integer>>> input) { List<Matcher<? super KV<String, Iterable<Integer>>>> matchers = new ArrayList<>(); for (KV<String, Collection<Integer>> expected : expectedKvs) { Integer[] values = expected.getValue().toArray(new Integer[0]); matchers.add(isKv(equalTo(expected.getKey()), containsInAnyOrder(values))); } assertThat(input, containsInAnyOrder(matchers.toArray(new Matcher[0]))); return null; } } private static class AssertTimestamp<K, V> extends DoFn<KV<K, V>, Void> { private final Instant timestamp; public AssertTimestamp(Instant timestamp) { this.timestamp = timestamp; } @ProcessElement public void processElement(ProcessContext c) throws Exception { assertThat(c.timestamp(), equalTo(timestamp)); } } private static String bigString(char c, int size) { char[] buf = new char[size]; for (int i = 0; i < size; i++) { buf[i] = c; } return new String(buf); } private static void runLargeKeysTest(TestPipeline p, final int keySize) throws Exception { PCollection<KV<String, Integer>> result = p.apply(Create.of("a", "a", "b")) .apply( "Expand", ParDo.of( new DoFn<String, KV<String, String>>() { @ProcessElement public void process(ProcessContext c) { c.output(KV.of(bigString(c.element().charAt(0), keySize), c.element())); } })) .apply(GroupByKey.create()) .apply( "Count", ParDo.of( new DoFn<KV<String, Iterable<String>>, KV<String, Integer>>() { @ProcessElement public void process(ProcessContext c) { int size = 0; for (String value : c.element().getValue()) { size++; } c.output(KV.of(c.element().getKey(), size)); } })); PAssert.that(result) .satisfies( values -> { assertThat( values, containsInAnyOrder( KV.of(bigString('a', keySize), 2), KV.of(bigString('b', keySize), 1))); return null; }); p.run(); } /** * This is a bogus key class that returns random hash values from {@link #hashCode()} and always * returns {@code false} for {@link #equals(Object)}. The results of the test are correct if the * runner correctly hashes and sorts on the encoded bytes. */ static class BadEqualityKey { long key; public BadEqualityKey() {} public BadEqualityKey(long key) { this.key = key; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return ThreadLocalRandom.current().nextInt(); } } /** Deterministic {@link Coder} for {@link BadEqualityKey}. */ static class DeterministicKeyCoder extends AtomicCoder<BadEqualityKey> { public static DeterministicKeyCoder of() { return INSTANCE; } ///////////////////////////////////////////////////////////////////////////// private static final DeterministicKeyCoder INSTANCE = new DeterministicKeyCoder(); private DeterministicKeyCoder() {} @Override public void encode(BadEqualityKey value, OutputStream outStream) throws IOException { new DataOutputStream(outStream).writeLong(value.key); } @Override public BadEqualityKey decode(InputStream inStream) throws IOException { return new BadEqualityKey(new DataInputStream(inStream).readLong()); } @Override public void verifyDeterministic() {} } /** Creates a KV that wraps the original KV together with a random key. */ static class AssignRandomKey extends DoFn<KV<BadEqualityKey, Long>, KV<Long, KV<BadEqualityKey, Long>>> { @ProcessElement public void processElement(ProcessContext c) throws Exception { c.output(KV.of(ThreadLocalRandom.current().nextLong(), c.element())); } } static class CountFn implements SerializableFunction<Iterable<Long>, Long> { @Override public Long apply(Iterable<Long> input) { long result = 0L; for (Long in : input) { result += in; } return result; } } static class AssertThatCountPerKeyCorrect implements SerializableFunction<Iterable<KV<BadEqualityKey, Long>>, Void> { private final int numValues; AssertThatCountPerKeyCorrect(int numValues) { this.numValues = numValues; } @Override public Void apply(Iterable<KV<BadEqualityKey, Long>> input) { for (KV<BadEqualityKey, Long> val : input) { Assert.assertEquals(numValues, (long) val.getValue()); } return null; } } static class AssertThatAllKeysExist implements SerializableFunction<Iterable<BadEqualityKey>, Void> { private final int numKeys; AssertThatAllKeysExist(int numKeys) { this.numKeys = numKeys; } private static <T> Iterable<Object> asStructural( final Iterable<T> iterable, final Coder<T> coder) { return StreamSupport.stream(iterable.spliterator(), false) .map( input -> { try { return coder.structuralValue(input); } catch (Exception e) { Assert.fail("Could not structural values."); throw new RuntimeException(); // to satisfy the compiler... } }) .collect(Collectors.toList()); } @Override public Void apply(Iterable<BadEqualityKey> input) { final DeterministicKeyCoder keyCoder = DeterministicKeyCoder.of(); List<BadEqualityKey> expectedList = new ArrayList<>(); for (int key = 0; key < numKeys; key++) { expectedList.add(new BadEqualityKey(key)); } Iterable<Object> structuralInput = asStructural(input, keyCoder); Iterable<Object> structuralExpected = asStructural(expectedList, keyCoder); for (Object expected : structuralExpected) { assertThat(structuralInput, hasItem(expected)); } return null; } } }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * ResidualSplit.java * Copyright (C) 2003 University of Waikato, Hamilton, New Zealand * */ package weka.classifiers.trees.lmt; import weka.classifiers.trees.j48.ClassifierSplitModel; import weka.classifiers.trees.j48.Distribution; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.core.RevisionUtils; import weka.core.Utils; /** * Helper class for logistic model trees (weka.classifiers.trees.lmt.LMT) to implement the * splitting criterion based on residuals of the LogitBoost algorithm. * * @author Niels Landwehr * @version $Revision: 1.4 $ */ public class ResidualSplit extends ClassifierSplitModel{ /** for serialization */ private static final long serialVersionUID = -5055883734183713525L; /**The attribute selected for the split*/ protected Attribute m_attribute; /**The index of the attribute selected for the split*/ protected int m_attIndex; /**Number of instances in the set*/ protected int m_numInstances; /**Number of classed*/ protected int m_numClasses; /**The set of instances*/ protected Instances m_data; /**The Z-values (LogitBoost response) for the set of instances*/ protected double[][] m_dataZs; /**The LogitBoost-weights for the set of instances*/ protected double[][] m_dataWs; /**The split point (for numeric attributes)*/ protected double m_splitPoint; /** *Creates a split object *@param attIndex the index of the attribute to split on */ public ResidualSplit(int attIndex) { m_attIndex = attIndex; } /** * Builds the split. * Needs the Z/W values of LogitBoost for the set of instances. */ public void buildClassifier(Instances data, double[][] dataZs, double[][] dataWs) throws Exception { m_numClasses = data.numClasses(); m_numInstances = data.numInstances(); if (m_numInstances == 0) throw new Exception("Can't build split on 0 instances"); //save data/Zs/Ws m_data = data; m_dataZs = dataZs; m_dataWs = dataWs; m_attribute = data.attribute(m_attIndex); //determine number of subsets and split point for numeric attributes if (m_attribute.isNominal()) { m_splitPoint = 0.0; m_numSubsets = m_attribute.numValues(); } else { getSplitPoint(); m_numSubsets = 2; } //create distribution for data m_distribution = new Distribution(data, this); } /** * Selects split point for numeric attribute. */ protected boolean getSplitPoint() throws Exception{ //compute possible split points double[] splitPoints = new double[m_numInstances]; int numSplitPoints = 0; Instances sortedData = new Instances(m_data); sortedData.sort(sortedData.attribute(m_attIndex)); double last, current; last = sortedData.instance(0).value(m_attIndex); for (int i = 0; i < m_numInstances - 1; i++) { current = sortedData.instance(i+1).value(m_attIndex); if (!Utils.eq(current, last)){ splitPoints[numSplitPoints++] = (last + current) / 2.0; } last = current; } //compute entropy for all split points double[] entropyGain = new double[numSplitPoints]; for (int i = 0; i < numSplitPoints; i++) { m_splitPoint = splitPoints[i]; entropyGain[i] = entropyGain(); } //get best entropy gain int bestSplit = -1; double bestGain = -Double.MAX_VALUE; for (int i = 0; i < numSplitPoints; i++) { if (entropyGain[i] > bestGain) { bestGain = entropyGain[i]; bestSplit = i; } } if (bestSplit < 0) return false; m_splitPoint = splitPoints[bestSplit]; return true; } /** * Computes entropy gain for current split. */ public double entropyGain() throws Exception{ int numSubsets; if (m_attribute.isNominal()) { numSubsets = m_attribute.numValues(); } else { numSubsets = 2; } double[][][] splitDataZs = new double[numSubsets][][]; double[][][] splitDataWs = new double[numSubsets][][]; //determine size of the subsets int[] subsetSize = new int[numSubsets]; for (int i = 0; i < m_numInstances; i++) { int subset = whichSubset(m_data.instance(i)); if (subset < 0) throw new Exception("ResidualSplit: no support for splits on missing values"); subsetSize[subset]++; } for (int i = 0; i < numSubsets; i++) { splitDataZs[i] = new double[subsetSize[i]][]; splitDataWs[i] = new double[subsetSize[i]][]; } int[] subsetCount = new int[numSubsets]; //sort Zs/Ws into subsets for (int i = 0; i < m_numInstances; i++) { int subset = whichSubset(m_data.instance(i)); splitDataZs[subset][subsetCount[subset]] = m_dataZs[i]; splitDataWs[subset][subsetCount[subset]] = m_dataWs[i]; subsetCount[subset]++; } //calculate entropy gain double entropyOrig = entropy(m_dataZs, m_dataWs); double entropySplit = 0.0; for (int i = 0; i < numSubsets; i++) { entropySplit += entropy(splitDataZs[i], splitDataWs[i]); } return entropyOrig - entropySplit; } /** * Helper function to compute entropy from Z/W values. */ protected double entropy(double[][] dataZs, double[][] dataWs){ //method returns entropy * sumOfWeights double entropy = 0.0; int numInstances = dataZs.length; for (int j = 0; j < m_numClasses; j++) { //compute mean for class double m = 0.0; double sum = 0.0; for (int i = 0; i < numInstances; i++) { m += dataZs[i][j] * dataWs[i][j]; sum += dataWs[i][j]; } m /= sum; //sum up entropy for class for (int i = 0; i < numInstances; i++) { entropy += dataWs[i][j] * Math.pow(dataZs[i][j] - m,2); } } return entropy; } /** * Checks if there are at least 2 subsets that contain >= minNumInstances. */ public boolean checkModel(int minNumInstances){ //checks if there are at least 2 subsets that contain >= minNumInstances int count = 0; for (int i = 0; i < m_distribution.numBags(); i++) { if (m_distribution.perBag(i) >= minNumInstances) count++; } return (count >= 2); } /** * Returns name of splitting attribute (left side of condition). */ public final String leftSide(Instances data) { return data.attribute(m_attIndex).name(); } /** * Prints the condition satisfied by instances in a subset. */ public final String rightSide(int index,Instances data) { StringBuffer text; text = new StringBuffer(); if (data.attribute(m_attIndex).isNominal()) text.append(" = "+ data.attribute(m_attIndex).value(index)); else if (index == 0) text.append(" <= "+ Utils.doubleToString(m_splitPoint,6)); else text.append(" > "+ Utils.doubleToString(m_splitPoint,6)); return text.toString(); } public final int whichSubset(Instance instance) throws Exception { if (instance.isMissing(m_attIndex)) return -1; else{ if (instance.attribute(m_attIndex).isNominal()) return (int)instance.value(m_attIndex); else if (Utils.smOrEq(instance.value(m_attIndex),m_splitPoint)) return 0; else return 1; } } /** Method not in use*/ public void buildClassifier(Instances data) { //method not in use } /**Method not in use*/ public final double [] weights(Instance instance){ //method not in use return null; } /**Method not in use*/ public final String sourceExpression(int index, Instances data) { //method not in use return ""; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 1.4 $"); } }
package edu.washington.nsre.extraction; import com.google.common.collect.HashMultimap; import com.google.gson.Gson; import edu.stanford.nlp.stats.ClassicCounter; import edu.stanford.nlp.stats.Counter; import edu.stanford.nlp.stats.Counters; import edu.stanford.nlp.stats.IntCounter; import edu.washington.nsre.ilp.IntegerLinearProgramming; import edu.washington.nsre.util.DR; import edu.washington.nsre.util.DW; import java.util.*; import java.util.Map.Entry; public class EventDiscovery { static Gson gson = new Gson(); public static Set<String> no = new HashSet<String>(); static { String[] lightverblist = new String[] { "make", "give", "do", "be", "have", "say", "think", "ask", "announce", "warn", "urge", "defeat" }; for (String v : lightverblist) { no.add(v); } } public static void candidateEventRelations(String inputParallel, int K, String output) { DR dr = new DR(inputParallel); List<String[]> b = null; List<String[]> tow = new ArrayList<String[]>(); HashMultimap<String, String> rel2eecs = HashMultimap.create(); List<String[]> rel_eec_bipartitegraph = new ArrayList<String[]>(); Counter<String> va1a2count = new IntCounter<String>(); while ((b = dr.readBlock(0)) != null) { String eecname = b.get(0)[0]; HashMap<String, Tuple> events2sentence = new HashMap<String, Tuple>(); List<Tuple> tuples = new ArrayList<Tuple>(); String arg1 = null; String arg2 = null; Counter<String> dist1 = new ClassicCounter<String>(); Counter<String> dist2 = new ClassicCounter<String>(); Set<String> arg1types = new HashSet<String>(); Set<String> arg2types = new HashSet<String>(); for (String[] l : b) { Tuple t = gson.fromJson(l[2], Tuple.class); if (arg1 == null) { arg1 = t.getArg1(); arg2 = t.getArg2(); } Counter<String> temp1 = t.getArg1FineGrainedNer(); Counter<String> temp2 = t.getArg2FineGrainedNer(); // arg1types.add(Counters.argmax(temp1)); // arg2types.add(Counters.argmax(temp2)); arg1types.add(t.getArg1StanfordNer()); arg2types.add(t.getArg2StanfordNer()); Counters.addInPlace(dist1, temp1); Counters.addInPlace(dist2, temp2); tuples.add(t); } // if (dist1 == null || dist2 == null) // continue; double maxs1 = Counters.max(dist1); double maxs2 = Counters.max(dist2); for (String arg1type : dist1.keySet()) { double s = dist1.getCount(arg1type); if (s > maxs1 * 0.9) { arg1types.add(arg1type); } } for (String arg2type : dist2.keySet()) { double s = dist2.getCount(arg2type); if (s > maxs2 * 0.9) { arg2types.add(arg2type); } } Set<String> verbs = new HashSet<String>(); for (Tuple t : tuples) { if (t.getRel() != null && t.getRelHead() != null) { String v = t.getRel(); String h = t.getRelHead(); if (v.startsWith(h)) { verbs.add(t.getRel()); } } } for (String v : verbs) { String v0 = v.split(" ")[0]; if (no.contains(v0)) { continue; } // for (String arg1type : dist1.keySet()) { // for (String arg2type : dist2.keySet()) { for (String arg1type : arg1types) { for (String arg2type : arg2types) { if (arg1type.equals("/misc") || arg2type.equals("/misc")) continue; // if (dist1.getCount(arg1type) >= maxs1 * 0.9 && // dist2.getCount(arg2type) >= maxs2 * 0.9) { // va1a2count.incrementCount(v + "@" + arg1type // + "@" + arg2type); String rel = v + "@" + arg1type + "@" + arg2type; // rel2eecs.put(rel, arg1words[arg1words.length // - 1] + "\t" // + arg2words[arg2words.length - 1]); rel2eecs.put(rel, eecname); rel_eec_bipartitegraph.add(new String[] { "r#" + rel, "e#" + eecname }); } } } } } // for debug purpose { DW dw0 = new DW(output + ".debug"); Set<String> set1 = rel2eecs.get("beat@/organization@/organization"); Set<String> set2 = rel2eecs.get("beat@/location@/location"); for (String x : set1) { if (set2.contains(x)) { dw0.write(x); } } dw0.close(); } DW dw = new DW(output); Set<String> valides = cover_fix_buckets(rel_eec_bipartitegraph, K); for (String a : valides) { if (a.startsWith("r#")) { String target = a.replace("r#", ""); String[] abc = target.split("@"); dw.write(target, abc[1], abc[0], abc[2]); } } dw.close(); } // public static void candidateFluentRelations(String input_eecs, String // input_xiaotypes, int K, String output) { // HashMap<String, Counter<String>> arg2xiaotypescores = new HashMap<String, // Counter<String>>(); // { // DR dr = new DR(input_xiaotypes); // String[] l; // while ((l = dr.read()) != null) { // String eec = l[0]; // String[] abc = eec.split("@"); // int k = Integer.parseInt(l[1]) - 1; // String arg = abc[k]; // HashMap<String, Double> toprint = gson.fromJson(l[2], HashMap.class); // if (!arg2xiaotypescores.containsKey(arg)) { // arg2xiaotypescores.put(arg, Counters.fromMap(toprint)); // } // } // dr.close(); // } // { // DW dw1 = new DW(output); // // DW dwsim = new DW(output + ".sim"); // // // DW dw2 = new DW(output + ".nocover"); // HashMultimap<String, String> rel2eecs = HashMultimap.create(); // List<String[]> rel_eec_bipartitegraph = new ArrayList<String[]>(); // Counter<String> va1a2count = new IntCounter<String>(); // DR dr = new DR(input_eecs); // String[] l; // while ((l = dr.read()) != null) { // String eecname = l[0]; // Eec eec = gson.fromJson(l[1], Eec.class); // String arg1 = eec.getArg1(); // String arg2 = eec.getArg2(); // Counter<String> dist1 = arg2xiaotypescores.get(arg1); // Counter<String> dist2 = arg2xiaotypescores.get(arg2); // if (dist1 == null || dist2 == null) // continue; // double maxs1 = Counters.max(dist1); // double maxs2 = Counters.max(dist2); // Set<String> verbs = new HashSet<String>(); // for (Tuple t : eec.tuples) { // String v = t.getRel(); // String h = t.getRelHead(); // if (v.startsWith(h)) { // verbs.add(t.getRel()); // } // } // String[] arg1words = arg1.split(" "); // String[] arg2words = arg2.split(" "); // for (String v : verbs) { // String v0 = v.split(" ")[0]; // if (no.contains(v0)) { // continue; // } // for (String arg1type : dist1.keySet()) { // for (String arg2type : dist2.keySet()) { // if (dist1.getCount(arg1type) >= maxs1 - 0.01 && dist2.getCount(arg2type) // >= maxs2 - 0.01) { // // va1a2count.incrementCount(v + "@" + arg1type // // + "@" + arg2type); // String rel = v + "@" + arg1type + "@" + arg2type; // // rel2eecs.put(rel, arg1words[arg1words.length // // - 1] + "\t" // // + arg2words[arg2words.length - 1]); // rel2eecs.put(rel, eecname); // rel_eec_bipartitegraph.add(new String[] { "r#" + rel, "e#" + eecname }); // } // } // } // } // } // Set<String> valides = cover_fix_buckets(rel_eec_bipartitegraph, K); // for (String a : valides) { // if (a.startsWith("r#")) { // String target = a.replace("r#", ""); // String[] abc = target.split("@"); // dw1.write(target, abc[1], abc[0], abc[2]); // } // } // dw1.close(); // } // // } /** Fix number of buckets */ public static Set<String> cover_fix_buckets(List<String[]> rel_eec_bipartitegraph, int MAX_BUCKETS) { Set<String> picked = new HashSet<String>(); // List<String[]> res = new ArrayList<String[]>(); double infinity = 0; HashMap<String, Double> edge2score = new HashMap<String, Double>(); // HashMultimap<String, String> bucket2edges = HashMultimap.create(); // HashMultimap<String, String> element2edges = HashMultimap.create(); HashMultimap<String, String> bucket2elements = HashMultimap.create(); HashMultimap<String, String> element2bucket = HashMultimap.create(); HashMultimap<String, String> verb2buckets = HashMultimap.create(); for (String[] l : rel_eec_bipartitegraph) { String bucket = l[0]; String element = l[1]; bucket2elements.put(bucket, element); element2bucket.put(element, bucket); String firstverb = (bucket.split("@")[0]).split(" ")[0]; verb2buckets.put(firstverb, bucket); } IntegerLinearProgramming ilp = new IntegerLinearProgramming(); Counter<String> object = new ClassicCounter<String>(); for (Entry<String, Double> e : edge2score.entrySet()) { String edgename = e.getKey(); double edgescore = e.getValue(); object.incrementCount(edgename, edgescore); } for (String element : element2bucket.keySet()) { String variable = element; object.incrementCount(variable, 1); } ilp.setObjective(object, true); // at most MAX_BUCKETS buckets are non-empty Counter<String> max_buckets = new ClassicCounter<String>(); for (String bucket : bucket2elements.keySet()) { String variable = bucket; max_buckets.incrementCount(variable, 1.0); } ilp.addConstraint(max_buckets, false, 1.0, true, MAX_BUCKETS); // each ball can only appear in one bucket for (String element : element2bucket.keySet()) { Set<String> buckets = element2bucket.get(element); /*** the element is covered? */ Counter<String> covered = new ClassicCounter<String>(); covered.incrementCount(element, -1); for (String b : buckets) { covered.incrementCount(b); } ilp.addConstraint(covered, true, 0.0, false, buckets.size()); /** the element should be covered by only one bucket */ Counter<String> uniq = new ClassicCounter<String>(); for (String b : buckets) { uniq.incrementCount(b); } ilp.addConstraint(uniq, false, 0.0, true, 1); } for (String v : verb2buckets.keySet()) { Set<String> buckets = verb2buckets.get(v); Counter<String> atmost2 = new ClassicCounter<String>(); for (String b : buckets) { atmost2.incrementCount(b); } ilp.addConstraint(atmost2, false, 0.0, true, 2); } HashMap<String, Double> variable2score = ilp.run(); for (Entry<String, Double> e : variable2score.entrySet()) { String varname = e.getKey(); double val = e.getValue(); // D.p(varname, val); if (val > 0.99) { picked.add(varname); } } return picked; } public static void main(String[] args) { String inputParallel = args[0]; int K = Integer.parseInt(args[1]); String output = args[2]; candidateEventRelations(inputParallel, K, output); // candidateFluentRelations(input_eecs, input_types, K, output); } }
package org.spongycastle.pqc.math.ntru.polynomial; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.SecureRandom; import org.spongycastle.pqc.math.ntru.util.ArrayEncoder; import org.spongycastle.pqc.math.ntru.util.Util; import org.spongycastle.util.Arrays; /** * A <code>TernaryPolynomial</code> with a "low" number of nonzero coefficients. */ public class SparseTernaryPolynomial implements TernaryPolynomial { /** * Number of bits to use for each coefficient. Determines the upper bound for <code>N</code>. */ private static final int BITS_PER_INDEX = 11; private int N; private int[] ones; private int[] negOnes; /** * Constructs a new polynomial. * * @param N total number of coefficients including zeros * @param ones indices of coefficients equal to 1 * @param negOnes indices of coefficients equal to -1 */ SparseTernaryPolynomial(int N, int[] ones, int[] negOnes) { this.N = N; this.ones = ones; this.negOnes = negOnes; } /** * Constructs a <code>DenseTernaryPolynomial</code> from a <code>IntegerPolynomial</code>. The two polynomials are * independent of each other. * * @param intPoly the original polynomial */ public SparseTernaryPolynomial(IntegerPolynomial intPoly) { this(intPoly.coeffs); } /** * Constructs a new <code>SparseTernaryPolynomial</code> with a given set of coefficients. * * @param coeffs the coefficients */ public SparseTernaryPolynomial(int[] coeffs) { N = coeffs.length; ones = new int[N]; negOnes = new int[N]; int onesIdx = 0; int negOnesIdx = 0; for (int i = 0; i < N; i++) { int c = coeffs[i]; switch (c) { case 1: ones[onesIdx++] = i; break; case -1: negOnes[negOnesIdx++] = i; break; case 0: break; default: throw new IllegalArgumentException("Illegal value: " + c + ", must be one of {-1, 0, 1}"); } } ones = Arrays.copyOf(ones, onesIdx); negOnes = Arrays.copyOf(negOnes, negOnesIdx); } /** * Decodes a byte array encoded with {@link #toBinary()} to a ploynomial. * * @param is an input stream containing an encoded polynomial * @param N number of coefficients including zeros * @param numOnes number of coefficients equal to 1 * @param numNegOnes number of coefficients equal to -1 * @return the decoded polynomial * @throws IOException */ public static SparseTernaryPolynomial fromBinary(InputStream is, int N, int numOnes, int numNegOnes) throws IOException { int maxIndex = 1 << BITS_PER_INDEX; int bitsPerIndex = 32 - Integer.numberOfLeadingZeros(maxIndex - 1); int data1Len = (numOnes * bitsPerIndex + 7) / 8; byte[] data1 = Util.readFullLength(is, data1Len); int[] ones = ArrayEncoder.decodeModQ(data1, numOnes, maxIndex); int data2Len = (numNegOnes * bitsPerIndex + 7) / 8; byte[] data2 = Util.readFullLength(is, data2Len); int[] negOnes = ArrayEncoder.decodeModQ(data2, numNegOnes, maxIndex); return new SparseTernaryPolynomial(N, ones, negOnes); } /** * Generates a random polynomial with <code>numOnes</code> coefficients equal to 1, * <code>numNegOnes</code> coefficients equal to -1, and the rest equal to 0. * * @param N number of coefficients * @param numOnes number of 1's * @param numNegOnes number of -1's */ public static SparseTernaryPolynomial generateRandom(int N, int numOnes, int numNegOnes, SecureRandom random) { int[] coeffs = Util.generateRandomTernary(N, numOnes, numNegOnes, random); return new SparseTernaryPolynomial(coeffs); } public IntegerPolynomial mult(IntegerPolynomial poly2) { int[] b = poly2.coeffs; if (b.length != N) { throw new IllegalArgumentException("Number of coefficients must be the same"); } int[] c = new int[N]; for (int idx = 0; idx != ones.length; idx++) { int i = ones[idx]; int j = N - 1 - i; for (int k = N - 1; k >= 0; k--) { c[k] += b[j]; j--; if (j < 0) { j = N - 1; } } } for (int idx = 0; idx != negOnes.length; idx++) { int i = negOnes[idx]; int j = N - 1 - i; for (int k = N - 1; k >= 0; k--) { c[k] -= b[j]; j--; if (j < 0) { j = N - 1; } } } return new IntegerPolynomial(c); } public IntegerPolynomial mult(IntegerPolynomial poly2, int modulus) { IntegerPolynomial c = mult(poly2); c.mod(modulus); return c; } public BigIntPolynomial mult(BigIntPolynomial poly2) { BigInteger[] b = poly2.coeffs; if (b.length != N) { throw new IllegalArgumentException("Number of coefficients must be the same"); } BigInteger[] c = new BigInteger[N]; for (int i = 0; i < N; i++) { c[i] = BigInteger.ZERO; } for (int idx = 0; idx != ones.length; idx++) { int i = ones[idx]; int j = N - 1 - i; for (int k = N - 1; k >= 0; k--) { c[k] = c[k].add(b[j]); j--; if (j < 0) { j = N - 1; } } } for (int idx = 0; idx != negOnes.length; idx++) { int i = negOnes[idx]; int j = N - 1 - i; for (int k = N - 1; k >= 0; k--) { c[k] = c[k].subtract(b[j]); j--; if (j < 0) { j = N - 1; } } } return new BigIntPolynomial(c); } public int[] getOnes() { return ones; } public int[] getNegOnes() { return negOnes; } /** * Encodes the polynomial to a byte array writing <code>BITS_PER_INDEX</code> bits for each coefficient. * * @return the encoded polynomial */ public byte[] toBinary() { int maxIndex = 1 << BITS_PER_INDEX; byte[] bin1 = ArrayEncoder.encodeModQ(ones, maxIndex); byte[] bin2 = ArrayEncoder.encodeModQ(negOnes, maxIndex); byte[] bin = Arrays.copyOf(bin1, bin1.length + bin2.length); System.arraycopy(bin2, 0, bin, bin1.length, bin2.length); return bin; } public IntegerPolynomial toIntegerPolynomial() { int[] coeffs = new int[N]; for (int idx = 0; idx != ones.length; idx++) { int i = ones[idx]; coeffs[i] = 1; } for (int idx = 0; idx != negOnes.length; idx++) { int i = negOnes[idx]; coeffs[i] = -1; } return new IntegerPolynomial(coeffs); } public int size() { return N; } public void clear() { for (int i = 0; i < ones.length; i++) { ones[i] = 0; } for (int i = 0; i < negOnes.length; i++) { negOnes[i] = 0; } } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + N; result = prime * result + Arrays.hashCode(negOnes); result = prime * result + Arrays.hashCode(ones); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SparseTernaryPolynomial other = (SparseTernaryPolynomial)obj; if (N != other.N) { return false; } if (!Arrays.areEqual(negOnes, other.negOnes)) { return false; } if (!Arrays.areEqual(ones, other.ones)) { return false; } return true; } }
/* * 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.cassandra.distributed.test; import java.io.IOException; import java.io.Serializable; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import com.google.common.util.concurrent.Uninterruptibles; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.DataRange; import org.apache.cassandra.db.Keyspace; import org.apache.cassandra.db.PartitionPosition; import org.apache.cassandra.db.filter.ColumnFilter; import org.apache.cassandra.db.rows.UnfilteredRowIterator; import org.apache.cassandra.dht.AbstractBounds; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.distributed.Cluster; import org.apache.cassandra.distributed.api.ConsistencyLevel; import org.apache.cassandra.distributed.api.Feature; import org.apache.cassandra.distributed.api.ICluster; import org.apache.cassandra.distributed.api.IInvokableInstance; import org.apache.cassandra.distributed.api.IIsolatedExecutor.SerializableRunnable; import org.apache.cassandra.distributed.impl.InstanceKiller; import org.apache.cassandra.io.sstable.CorruptSSTableException; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.format.ForwardingSSTableReader; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.sstable.format.SSTableReadsListener; import org.apache.cassandra.io.util.ChannelProxy; import org.apache.cassandra.net.Verb; import org.apache.cassandra.repair.RepairParallelism; import org.apache.cassandra.repair.messages.RepairOption; import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.service.ActiveRepairService.ParentRepairStatus; import org.apache.cassandra.service.StorageService; import org.awaitility.Awaitility; @RunWith(Parameterized.class) public class FailingRepairTest extends TestBaseImpl implements Serializable { private static ICluster<IInvokableInstance> CLUSTER; private final Verb messageType; private final RepairParallelism parallelism; private final boolean withTracing; private final SerializableRunnable setup; public FailingRepairTest(Verb messageType, RepairParallelism parallelism, boolean withTracing, SerializableRunnable setup) { this.messageType = messageType; this.parallelism = parallelism; this.withTracing = withTracing; this.setup = setup; } @Parameters(name = "{0}/{1}/{2}") public static Collection<Object[]> messages() { List<Object[]> tests = new ArrayList<>(); for (RepairParallelism parallelism : RepairParallelism.values()) { for (Boolean withTracing : Arrays.asList(Boolean.TRUE, Boolean.FALSE)) { tests.add(new Object[]{ Verb.VALIDATION_REQ, parallelism, withTracing, failingReaders(Verb.VALIDATION_REQ, parallelism, withTracing) }); } } return tests; } private static SerializableRunnable failingReaders(Verb type, RepairParallelism parallelism, boolean withTracing) { return () -> { String cfName = getCfName(type, parallelism, withTracing); ColumnFamilyStore cf = Keyspace.open(KEYSPACE).getColumnFamilyStore(cfName); cf.forceBlockingFlush(); Set<SSTableReader> remove = cf.getLiveSSTables(); Set<SSTableReader> replace = new HashSet<>(); if (type == Verb.VALIDATION_REQ) { for (SSTableReader r : remove) replace.add(new FailingSSTableReader(r)); } else { throw new UnsupportedOperationException("verb: " + type); } cf.getTracker().removeUnsafe(remove); cf.addSSTables(replace); }; } private static String getCfName(Verb type, RepairParallelism parallelism, boolean withTracing) { return type.name().toLowerCase() + "_" + parallelism.name().toLowerCase() + "_" + withTracing; } @BeforeClass public static void setupCluster() throws IOException { // streaming requires networking ATM // streaming also requires gossip or isn't setup properly CLUSTER = init(Cluster.build() .withNodes(2) .withConfig(c -> c.with(Feature.NETWORK) .with(Feature.GOSSIP) .set("disk_failure_policy", "die")) .start()); CLUSTER.setUncaughtExceptionsFilter((throwable) -> { if (throwable.getClass().toString().contains("InstanceShutdown") || // can't check instanceof as it is thrown by a different classloader throwable.getMessage() != null && throwable.getMessage().contains("Parent repair session with id")) return true; return false; }); } @AfterClass public static void teardownCluster() throws Exception { if (CLUSTER != null) CLUSTER.close(); } @Before public void cleanupState() { for (int i = 1; i <= CLUSTER.size(); i++) { IInvokableInstance inst = CLUSTER.get(i); if (inst.isShutdown()) inst.startup(); inst.runOnInstance(InstanceKiller::clear); } } @Test(timeout = 10 * 60 * 1000) public void testFailingMessage() throws IOException { final int replica = 1; final int coordinator = 2; String tableName = getCfName(messageType, parallelism, withTracing); String fqtn = KEYSPACE + "." + tableName; CLUSTER.schemaChange("CREATE TABLE " + fqtn + " (k INT, PRIMARY KEY (k))"); // create data which will NOT conflict int lhsOffset = 10; int rhsOffset = 20; int limit = rhsOffset + (rhsOffset - lhsOffset); // setup data which is consistent on both sides for (int i = 0; i < lhsOffset; i++) CLUSTER.coordinator(replica) .execute("INSERT INTO " + fqtn + " (k) VALUES (?)", ConsistencyLevel.ALL, i); // create data on LHS which does NOT exist in RHS for (int i = lhsOffset; i < rhsOffset; i++) CLUSTER.get(replica).executeInternal("INSERT INTO " + fqtn + " (k) VALUES (?)", i); // create data on RHS which does NOT exist in LHS for (int i = rhsOffset; i < limit; i++) CLUSTER.get(coordinator).executeInternal("INSERT INTO " + fqtn + " (k) VALUES (?)", i); // at this point, the two nodes should be out of sync, so confirm missing data // node 1 Object[][] node1Records = toRows(IntStream.range(0, rhsOffset)); Object[][] node1Actuals = toNaturalOrder(CLUSTER.get(replica).executeInternal("SELECT k FROM " + fqtn)); Assert.assertArrayEquals(node1Records, node1Actuals); // node 2 Object[][] node2Records = toRows(IntStream.concat(IntStream.range(0, lhsOffset), IntStream.range(rhsOffset, limit))); Object[][] node2Actuals = toNaturalOrder(CLUSTER.get(coordinator).executeInternal("SELECT k FROM " + fqtn)); Assert.assertArrayEquals(node2Records, node2Actuals); // Inject the failure CLUSTER.get(replica).runOnInstance(() -> setup.run()); // run a repair which is expected to fail List<String> repairStatus = CLUSTER.get(coordinator).callOnInstance(() -> { // need all ranges on the host String ranges = StorageService.instance.getLocalAndPendingRanges(KEYSPACE).stream() .map(r -> r.left + ":" + r.right) .collect(Collectors.joining(",")); Map<String, String> args = new HashMap<String, String>() {{ put(RepairOption.PARALLELISM_KEY, parallelism.getName()); put(RepairOption.PRIMARY_RANGE_KEY, "false"); put(RepairOption.INCREMENTAL_KEY, "false"); put(RepairOption.TRACE_KEY, Boolean.toString(withTracing)); put(RepairOption.PULL_REPAIR_KEY, "false"); put(RepairOption.FORCE_REPAIR_KEY, "false"); put(RepairOption.RANGES_KEY, ranges); put(RepairOption.COLUMNFAMILIES_KEY, tableName); }}; int cmd = StorageService.instance.repairAsync(KEYSPACE, args); Assert.assertFalse("repair return status was 0, expected non-zero return status, 0 indicates repair not submitted", cmd == 0); List<String> status; do { Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); status = StorageService.instance.getParentRepairStatus(cmd); } while (status == null || status.get(0).equals(ParentRepairStatus.IN_PROGRESS.name())); return status; }); Assert.assertEquals(repairStatus.toString(), ParentRepairStatus.FAILED, ParentRepairStatus.valueOf(repairStatus.get(0))); // its possible that the coordinator gets the message that the replica failed before the replica completes // shutting down; this then means that isKilled could be updated after the fact IInvokableInstance replicaInstance = CLUSTER.get(replica); Awaitility.await().atMost(Duration.ofSeconds(30)).until(replicaInstance::isShutdown); Assert.assertEquals("coordinator should not be killed", 0, CLUSTER.get(coordinator).killAttempts()); } private static Object[][] toNaturalOrder(Object[][] actuals) { // data is returned in token order, so rather than try to be fancy and order expected in token order // convert it to natural int[] values = new int[actuals.length]; for (int i = 0; i < values.length; i++) values[i] = (Integer) actuals[i][0]; Arrays.sort(values); return toRows(IntStream.of(values)); } private static Object[][] toRows(IntStream values) { return values .mapToObj(v -> new Object[]{ v }) .toArray(Object[][]::new); } private static final class FailingSSTableReader extends ForwardingSSTableReader { private FailingSSTableReader(SSTableReader delegate) { super(delegate); } public ISSTableScanner getScanner() { return new FailingISSTableScanner(); } public ISSTableScanner getScanner(Collection<Range<Token>> ranges) { return new FailingISSTableScanner(); } public ISSTableScanner getScanner(Iterator<AbstractBounds<PartitionPosition>> rangeIterator) { return new FailingISSTableScanner(); } public ISSTableScanner getScanner(ColumnFilter columns, DataRange dataRange, SSTableReadsListener listener) { return new FailingISSTableScanner(); } public ChannelProxy getDataChannel() { throw new RuntimeException(); } public String toString() { return "FailingSSTableReader[" + super.toString() + "]"; } } private static final class FailingISSTableScanner implements ISSTableScanner { public long getLengthInBytes() { return 0; } public long getCompressedLengthInBytes() { return 0; } public long getCurrentPosition() { return 0; } public long getBytesScanned() { return 0; } public Set<SSTableReader> getBackingSSTables() { return Collections.emptySet(); } public TableMetadata metadata() { return null; } public void close() { } public boolean hasNext() { throw new CorruptSSTableException(new IOException("Test commands it"), "mahahahaha!"); } public UnfilteredRowIterator next() { throw new CorruptSSTableException(new IOException("Test commands it"), "mahahahaha!"); } } }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.siddhi.extension.regex; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.wso2.siddhi.core.ExecutionPlanRuntime; import org.wso2.siddhi.core.SiddhiManager; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.query.output.callback.QueryCallback; import org.wso2.siddhi.core.stream.input.InputHandler; import org.wso2.siddhi.core.util.EventPrinter; public class RegExFunctionExtensionTestCase { static final Logger log = Logger.getLogger(RegExFunctionExtensionTestCase.class); private volatile int count; private volatile boolean eventArrived; @Before public void init() { count = 0; eventArrived = false; } @Test public void testFindFunctionExtensionTestCase() throws InterruptedException { log.info("FindFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "@config(async = 'true')define stream inputStream (symbol string, price long, regex string);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:find(regex, symbol) as aboutWSO2 " + "insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event inEvent : inEvents) { count++; if (count == 1) { Assert.assertEquals(true, inEvent.getData(1)); } if (count == 2) { Assert.assertEquals(true, inEvent.getData(1)); } if (count == 3) { Assert.assertEquals(true, inEvent.getData(1)); } if (count == 4) { Assert.assertEquals(false, inEvent.getData(1)); } eventArrived = true; } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"21 products are produced by WSO2 currently", 60.5f, "\\d\\d(.*)WSO2"}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware(.*)"}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware"}); inputHandler.send(new Object[]{"21 products are produced by WSO2 currently", 60.5f, "\\d(.*)WSO22"}); Thread.sleep(100); Assert.assertEquals(4, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); } @Test public void testFindStartFromIndexFunctionExtensionTestCase() throws InterruptedException { log.info("FindStartFromIndexFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "@config(async = 'true')define stream inputStream (symbol string, price long, regex string, startingIndex int);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:find(regex, symbol, startingIndex) as aboutWSO2 " + "insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event inEvent : inEvents) { count++; if (count == 1) { Assert.assertEquals(true, inEvent.getData(1)); } if (count == 2) { Assert.assertEquals(false, inEvent.getData(1)); } eventArrived = true; } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"21 products are produced within 10 years by WSO2 currently by WSO2 employees", 60.5f, "\\d\\d(.*)WSO2", 30}); inputHandler.send(new Object[]{"21 products are produced within 10 years by WSO2 currently by WSO2 employees", 60.5f, "\\d\\d(.*)WSO2", 35}); Thread.sleep(100); Assert.assertEquals(2, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); } @Test public void testMatchesFunctionExtension() throws InterruptedException { log.info("MatchesFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "@config(async = 'true')define stream inputStream (symbol string, price long, regex string);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:matches(regex, symbol) as aboutWSO2 " + "insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event inEvent : inEvents) { count++; if (count == 1) { Assert.assertEquals(false, inEvent.getData(1)); } if (count == 2) { Assert.assertEquals(true, inEvent.getData(1)); } if (count == 3) { Assert.assertEquals(false, inEvent.getData(1)); } eventArrived = true; } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"21 products are produced by WSO2 currently", 60.5f, "\\d\\d(.*)WSO2"}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware(.*)"}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware"}); Thread.sleep(100); Assert.assertEquals(3, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); } @Test public void testLookingAtFunctionExtension() throws InterruptedException { log.info("LookingAtFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "@config(async = 'true')define stream inputStream (symbol string, price long, regex string);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:lookingAt(regex, symbol) as aboutWSO2 " + "insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event inEvent : inEvents) { count++; if (count == 1) { Assert.assertEquals(true, inEvent.getData(1)); } if (count == 2) { Assert.assertEquals(false, inEvent.getData(1)); } if (count == 3) { Assert.assertEquals(true, inEvent.getData(1)); } eventArrived = true; } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"21 products are produced by WSO2 currently in Sri Lanka", 60.5f, "\\d\\d(.*)WSO2"}); inputHandler.send(new Object[]{"sample test string and WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware(.*)"}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware"}); Thread.sleep(100); Assert.assertEquals(3, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); } @Test public void testGroupFunctionExtension() throws InterruptedException { log.info("GroupFunctionExtensionTestCase TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "@config(async = 'true')define stream inputStream (symbol string, price long, regex string, group int);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:group(regex, symbol, group) as aboutWSO2 " + "insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event inEvent : inEvents) { count++; if (count == 1) { Assert.assertEquals("WSO2 employees", inEvent.getData(1)); } if (count == 2) { Assert.assertEquals("21", inEvent.getData(1)); } if (count == 3) { Assert.assertEquals(" is situated in trace and its a ", inEvent.getData(1)); } if (count == 4) { Assert.assertEquals(null, inEvent.getData(1)); } eventArrived = true; } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"21 products are produced within 10 years by WSO2 currently by WSO2 employees", 60.5f, "(\\d\\d)(.*)(WSO2.*)", 3}); inputHandler.send(new Object[]{"21 products are produced within 10 years by WSO2 currently by WSO2 employees", 60.5f, "(\\d\\d)(.*)(WSO2.*)", 1}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware", 1}); inputHandler.send(new Object[]{"WSO2 is situated in trace and its a middleware company", 60.5f, "WSO2(.*)middleware", 2}); Thread.sleep(100); Assert.assertEquals(4, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); } }
/* * 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.ignite.internal.processors.cache; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.QueryEntity; import org.apache.ignite.cache.QueryIndex; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cache.query.QueryCursor; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheMode.REPLICATED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * */ public class IgniteCacheDistributedJoinPartitionedAndReplicatedTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** */ private static final String PERSON_CACHE = "person"; /** */ private static final String ORG_CACHE = "org"; /** */ private static final String ACCOUNT_CACHE = "acc"; /** */ private boolean client; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); TcpDiscoverySpi spi = ((TcpDiscoverySpi)cfg.getDiscoverySpi()); spi.setIpFinder(IP_FINDER); cfg.setClientMode(client); return cfg; } /** * @param name Cache name. * @param cacheMode Cache mode. * @return Cache configuration. */ private CacheConfiguration configuration(String name, CacheMode cacheMode) { CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME); ccfg.setName(name); ccfg.setWriteSynchronizationMode(FULL_SYNC); ccfg.setAtomicityMode(ATOMIC); ccfg.setCacheMode(cacheMode); if (cacheMode == PARTITIONED) ccfg.setBackups(1); return ccfg; } /** * @param idx Use index flag. * @param persCacheMode Person cache mode. * @param orgCacheMode Organization cache mode. * @param accCacheMode Account cache mode. * @return Configurations. */ private List<CacheConfiguration> caches(boolean idx, CacheMode persCacheMode, CacheMode orgCacheMode, CacheMode accCacheMode) { List<CacheConfiguration> ccfgs = new ArrayList<>(); { CacheConfiguration ccfg = configuration(PERSON_CACHE, persCacheMode); QueryEntity entity = new QueryEntity(); entity.setKeyType(Integer.class.getName()); entity.setValueType(Person.class.getName()); entity.addQueryField("orgId", Integer.class.getName(), null); entity.addQueryField("name", String.class.getName(), null); if (idx) entity.setIndexes(F.asList(new QueryIndex("orgId"), new QueryIndex("name"))); ccfg.setQueryEntities(F.asList(entity)); ccfgs.add(ccfg); } { CacheConfiguration ccfg = configuration(ORG_CACHE, orgCacheMode); QueryEntity entity = new QueryEntity(); entity.setKeyType(Integer.class.getName()); entity.setValueType(Organization.class.getName()); entity.addQueryField("name", String.class.getName(), null); if (idx) entity.setIndexes(F.asList(new QueryIndex("name"))); ccfg.setQueryEntities(F.asList(entity)); ccfgs.add(ccfg); } { CacheConfiguration ccfg = configuration(ACCOUNT_CACHE, accCacheMode); QueryEntity entity = new QueryEntity(); entity.setKeyType(Integer.class.getName()); entity.setValueType(Account.class.getName()); entity.addQueryField("orgId", Integer.class.getName(), null); entity.addQueryField("personId", Integer.class.getName(), null); entity.addQueryField("name", String.class.getName(), null); if (idx) { entity.setIndexes(F.asList(new QueryIndex("orgId"), new QueryIndex("personId"), new QueryIndex("name"))); } ccfg.setQueryEntities(F.asList(entity)); ccfgs.add(ccfg); } return ccfgs; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGridsMultiThreaded(2); client = true; startGrid(2); } /** * @throws Exception If failed. */ public void testJoin1() throws Exception { join(true, REPLICATED, PARTITIONED, PARTITIONED); } /** * @throws Exception If failed. */ public void testJoin2() throws Exception { fail("https://issues.apache.org/jira/browse/IGNITE-5956"); join(true, PARTITIONED, REPLICATED, PARTITIONED); } /** * @throws Exception If failed. */ public void testJoin3() throws Exception { join(true, PARTITIONED, PARTITIONED, REPLICATED); } /** * @param idx Use index flag. * @param persCacheMode Person cache mode. * @param orgCacheMode Organization cache mode. * @param accCacheMode Account cache mode. * @throws Exception If failed. */ private void join(boolean idx, CacheMode persCacheMode, CacheMode orgCacheMode, CacheMode accCacheMode) throws Exception { Ignite client = grid(2); for (CacheConfiguration ccfg : caches(idx, persCacheMode, orgCacheMode, accCacheMode)) client.createCache(ccfg); try { IgniteCache<Object, Object> personCache = client.cache(PERSON_CACHE); IgniteCache<Object, Object> orgCache = client.cache(ORG_CACHE); IgniteCache<Object, Object> accCache = client.cache(ACCOUNT_CACHE); Affinity<Object> aff = client.affinity(PERSON_CACHE); AtomicInteger pKey = new AtomicInteger(100_000); AtomicInteger orgKey = new AtomicInteger(); AtomicInteger accKey = new AtomicInteger(); ClusterNode node0 = ignite(0).cluster().localNode(); ClusterNode node1 = ignite(1).cluster().localNode(); /** * One organization, one person, two accounts. */ { int orgId1 = keyForNode(aff, orgKey, node0); orgCache.put(orgId1, new Organization("obj-" + orgId1)); int pid1 = keyForNode(aff, pKey, node0); personCache.put(pid1, new Person(orgId1, "o1-p1")); accCache.put(keyForNode(aff, accKey, node0), new Account(pid1, orgId1, "a0")); accCache.put(keyForNode(aff, accKey, node1), new Account(pid1, orgId1, "a1")); } IgniteCache<Object, Object> qryCache = replicated(orgCache) ? personCache : orgCache; checkQuery("select p._key, p.name, a.name " + "from \"person\".Person p, \"acc\".Account a " + "where p._key = a.personId", qryCache, false, 2); checkQuery("select o.name, p._key, p.name, a.name " + "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key", qryCache, false, 2); checkQuery("select o.name, p._key, p.name, a.name " + "from \"org\".Organization o, \"acc\".Account a, \"person\".Person p " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key", qryCache, false, 2); checkQuery("select o.name, p._key, p.name, a.name " + "from \"person\".Person p, \"org\".Organization o, \"acc\".Account a " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key", qryCache, false, 2); checkQuery("select * from (select o.name n1, p._key, p.name n2, a.name n3 " + "from \"acc\".Account a, \"person\".Person p, \"org\".Organization o " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key)", qryCache, false, 2); checkQuery("select * from (select o.name n1, p._key, p.name n2, a.name n3 " + "from \"person\".Person p, \"acc\".Account a, \"org\".Organization o " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key)", qryCache, false, 2); List<List<?>> res = checkQuery("select count(*) " + "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key", qryCache, false, 1); assertEquals(2L, res.get(0).get(0)); checkQueries(qryCache, 2); { int orgId2 = keyForNode(aff, orgKey, node1); orgCache.put(orgId2, new Organization("obj-" + orgId2)); int pid2 = keyForNode(aff, pKey, node0); personCache.put(pid2, new Person(orgId2, "o2-p1")); accCache.put(keyForNode(aff, accKey, node0), new Account(pid2, orgId2, "a3")); accCache.put(keyForNode(aff, accKey, node1), new Account(pid2, orgId2, "a4")); } checkQuery("select o.name, p._key, p.name, a.name " + "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key", qryCache, false, 4); checkQuery("select o.name, p._key, p.name, a.name " + "from \"org\".Organization o inner join \"person\".Person p on p.orgId = o._key " + "inner join \"acc\".Account a on p._key = a.personId and a.orgId=o._key", qryCache, false, 4); res = checkQuery("select count(*) " + "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key", qryCache, false, 1); assertEquals(4L, res.get(0).get(0)); checkQuery("select o.name, p._key, p.name, a.name " + "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " + "where p.orgId = o._key and a.orgId = o._key and a.orgId=o._key", qryCache, false, 4); res = checkQuery("select count(*) " + "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " + "where p.orgId = o._key and a.orgId = o._key and a.orgId=o._key", qryCache, false, 1); assertEquals(4L, res.get(0).get(0)); checkQueries(qryCache, 4); } finally { client.destroyCache(PERSON_CACHE); client.destroyCache(ORG_CACHE); client.destroyCache(ACCOUNT_CACHE); } } /** * @param qryCache Query cache. * @param expSize Expected results size. */ private void checkQueries(IgniteCache<Object, Object> qryCache, int expSize) { String[] cacheNames = {"\"org\".Organization o", "\"person\".Person p", "\"acc\".Account a"}; for (int c1 = 0; c1 < cacheNames.length; c1++) { for (int c2 = 0; c2 < cacheNames.length; c2++) { if (c2 == c1) continue; for (int c3 = 0; c3 < cacheNames.length; c3++) { if (c3 == c1 || c3 == c2) continue; String cache1 = cacheNames[c1]; String cache2 = cacheNames[c2]; String cache3 = cacheNames[c3]; String qry = "select o.name, p._key, p.name, a.name from " + cache1 + ", " + cache2 + ", " + cache3 + " " + "where p.orgId = o._key and p._key = a.personId and a.orgId=o._key"; checkQuery(qry, qryCache, false, expSize); qry = "select o.name, p._key, p.name, a.name from " + cache1 + ", " + cache2 + ", " + cache3 + " " + "where p.orgId = o._key and a.orgId = o._key and a.orgId=o._key"; checkQuery(qry, qryCache, false, expSize); } } } } /** * @param sql SQL. * @param cache Cache. * @param enforceJoinOrder Enforce join order flag. * @param expSize Expected results size. * @param args Arguments. * @return Results. */ private List<List<?>> checkQuery(String sql, IgniteCache<Object, Object> cache, boolean enforceJoinOrder, int expSize, Object... args) { SqlFieldsQuery qry = new SqlFieldsQuery(sql); qry.setDistributedJoins(true); qry.setEnforceJoinOrder(enforceJoinOrder); qry.setArgs(args); log.info("Plan: " + queryPlan(cache, qry)); QueryCursor<List<?>> cur = cache.query(qry); List<List<?>> res = cur.getAll(); if (expSize != res.size()) log.info("Results: " + res); assertEquals(expSize, res.size()); return res; } /** * @param cache Cache. * @return {@code True} if cache is replicated. */ private boolean replicated(IgniteCache<?, ?> cache) { return cache.getConfiguration(CacheConfiguration.class).getCacheMode() == REPLICATED; } /** * */ private static class Account implements Serializable { /** */ int personId; /** */ int orgId; /** */ String name; /** * @param personId Person ID. * @param orgId Organization ID. * @param name Name. */ public Account(int personId, int orgId, String name) { this.personId = personId; this.orgId = orgId; this.name = name; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(Account.class, this); } } /** * */ private static class Person implements Serializable { /** */ int orgId; /** */ String name; /** * @param orgId Organization ID. * @param name Name. */ public Person(int orgId, String name) { this.orgId = orgId; this.name = name; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(Person.class, this); } } /** * */ private static class Organization implements Serializable { /** */ String name; /** * @param name Name. */ public Organization(String name) { this.name = name; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(Organization.class, this); } } }
/* * 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.nifi.web.api.dto; import org.apache.nifi.web.api.dto.action.ActionDTO; import org.apache.nifi.web.api.dto.flow.FlowBreadcrumbDTO; import org.apache.nifi.web.api.dto.flow.ProcessGroupFlowDTO; import org.apache.nifi.web.api.dto.status.ConnectionStatusDTO; import org.apache.nifi.web.api.dto.status.ConnectionStatusSnapshotDTO; import org.apache.nifi.web.api.dto.status.PortStatusDTO; import org.apache.nifi.web.api.dto.status.PortStatusSnapshotDTO; import org.apache.nifi.web.api.dto.status.ProcessGroupStatusDTO; import org.apache.nifi.web.api.dto.status.ProcessGroupStatusSnapshotDTO; import org.apache.nifi.web.api.dto.status.ProcessorStatusDTO; import org.apache.nifi.web.api.dto.status.ProcessorStatusSnapshotDTO; import org.apache.nifi.web.api.dto.status.RemoteProcessGroupStatusDTO; import org.apache.nifi.web.api.dto.status.RemoteProcessGroupStatusSnapshotDTO; import org.apache.nifi.web.api.dto.status.StatusHistoryDTO; import org.apache.nifi.web.api.entity.AccessPolicyEntity; import org.apache.nifi.web.api.entity.AccessPolicySummaryEntity; import org.apache.nifi.web.api.entity.ActionEntity; import org.apache.nifi.web.api.entity.AllowableValueEntity; import org.apache.nifi.web.api.entity.BulletinEntity; import org.apache.nifi.web.api.entity.ComponentReferenceEntity; import org.apache.nifi.web.api.entity.ConnectionEntity; import org.apache.nifi.web.api.entity.ConnectionStatusEntity; import org.apache.nifi.web.api.entity.ConnectionStatusSnapshotEntity; import org.apache.nifi.web.api.entity.ControllerConfigurationEntity; import org.apache.nifi.web.api.entity.ControllerServiceEntity; import org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentEntity; import org.apache.nifi.web.api.entity.FlowBreadcrumbEntity; import org.apache.nifi.web.api.entity.FunnelEntity; import org.apache.nifi.web.api.entity.LabelEntity; import org.apache.nifi.web.api.entity.PortEntity; import org.apache.nifi.web.api.entity.PortStatusEntity; import org.apache.nifi.web.api.entity.PortStatusSnapshotEntity; import org.apache.nifi.web.api.entity.ProcessGroupEntity; import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity; import org.apache.nifi.web.api.entity.ProcessGroupStatusEntity; import org.apache.nifi.web.api.entity.ProcessGroupStatusSnapshotEntity; import org.apache.nifi.web.api.entity.ProcessorEntity; import org.apache.nifi.web.api.entity.ProcessorStatusEntity; import org.apache.nifi.web.api.entity.ProcessorStatusSnapshotEntity; import org.apache.nifi.web.api.entity.RemoteProcessGroupEntity; import org.apache.nifi.web.api.entity.RemoteProcessGroupPortEntity; import org.apache.nifi.web.api.entity.RemoteProcessGroupStatusEntity; import org.apache.nifi.web.api.entity.RemoteProcessGroupStatusSnapshotEntity; import org.apache.nifi.web.api.entity.ReportingTaskEntity; import org.apache.nifi.web.api.entity.SnippetEntity; import org.apache.nifi.web.api.entity.StatusHistoryEntity; import org.apache.nifi.web.api.entity.TenantEntity; import org.apache.nifi.web.api.entity.UserEntity; import org.apache.nifi.web.api.entity.UserGroupEntity; import java.util.Date; import java.util.List; public final class EntityFactory { public StatusHistoryEntity createStatusHistoryEntity(final StatusHistoryDTO statusHistory, final PermissionsDTO permissions) { final StatusHistoryEntity entity = new StatusHistoryEntity(); entity.setCanRead(permissions.getCanRead()); entity.setStatusHistory(statusHistory); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ProcessorStatusEntity createProcessorStatusEntity(final ProcessorStatusDTO status, final PermissionsDTO permissions) { final ProcessorStatusEntity entity = new ProcessorStatusEntity(); entity.setCanRead(permissions.getCanRead()); entity.setProcessorStatus(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ProcessorStatusSnapshotEntity createProcessorStatusSnapshotEntity(final ProcessorStatusSnapshotDTO status, final PermissionsDTO permissions) { final ProcessorStatusSnapshotEntity entity = new ProcessorStatusSnapshotEntity(); entity.setId(status.getId()); entity.setCanRead(permissions.getCanRead()); entity.setProcessorStatusSnapshot(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ConnectionStatusEntity createConnectionStatusEntity(final ConnectionStatusDTO status, final PermissionsDTO permissions) { final ConnectionStatusEntity entity = new ConnectionStatusEntity(); entity.setCanRead(permissions.getCanRead()); entity.setConnectionStatus(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ConnectionStatusSnapshotEntity createConnectionStatusSnapshotEntity(final ConnectionStatusSnapshotDTO status, final PermissionsDTO permissions) { final ConnectionStatusSnapshotEntity entity = new ConnectionStatusSnapshotEntity(); entity.setId(status.getId()); entity.setCanRead(permissions.getCanRead()); entity.setConnectionStatusSnapshot(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ProcessGroupStatusEntity createProcessGroupStatusEntity(final ProcessGroupStatusDTO status, final PermissionsDTO permissions) { final ProcessGroupStatusEntity entity = new ProcessGroupStatusEntity(); entity.setCanRead(permissions.getCanRead()); entity.setProcessGroupStatus(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ProcessGroupStatusSnapshotEntity createProcessGroupStatusSnapshotEntity(final ProcessGroupStatusSnapshotDTO status, final PermissionsDTO permissions) { final ProcessGroupStatusSnapshotEntity entity = new ProcessGroupStatusSnapshotEntity(); entity.setId(status.getId()); entity.setCanRead(permissions.getCanRead()); entity.setProcessGroupStatusSnapshot(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public RemoteProcessGroupStatusEntity createRemoteProcessGroupStatusEntity(final RemoteProcessGroupStatusDTO status, final PermissionsDTO permissions) { final RemoteProcessGroupStatusEntity entity = new RemoteProcessGroupStatusEntity(); entity.setCanRead(permissions.getCanRead()); entity.setRemoteProcessGroupStatus(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public RemoteProcessGroupStatusSnapshotEntity createRemoteProcessGroupStatusSnapshotEntity(final RemoteProcessGroupStatusSnapshotDTO status, final PermissionsDTO permissions) { final RemoteProcessGroupStatusSnapshotEntity entity = new RemoteProcessGroupStatusSnapshotEntity(); entity.setId(status.getId()); entity.setCanRead(permissions.getCanRead()); entity.setRemoteProcessGroupStatusSnapshot(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public PortStatusEntity createPortStatusEntity(final PortStatusDTO status, final PermissionsDTO permissions) { final PortStatusEntity entity = new PortStatusEntity(); entity.setCanRead(permissions.getCanRead()); entity.setPortStatus(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public PortStatusSnapshotEntity createPortStatusSnapshotEntity(final PortStatusSnapshotDTO status, final PermissionsDTO permissions) { final PortStatusSnapshotEntity entity = new PortStatusSnapshotEntity(); entity.setId(status.getId()); entity.setCanRead(permissions.getCanRead()); entity.setPortStatusSnapshot(status); // always set the status, as it's always allowed... just need to provide permission context for merging responses return entity; } public ControllerConfigurationEntity createControllerConfigurationEntity(final ControllerConfigurationDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final ControllerConfigurationEntity entity = new ControllerConfigurationEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public ProcessGroupFlowEntity createProcessGroupFlowEntity(final ProcessGroupFlowDTO dto, final PermissionsDTO permissions) { final ProcessGroupFlowEntity entity = new ProcessGroupFlowEntity(); entity.setProcessGroupFlow(dto); entity.setPermissions(permissions); return entity; } public ProcessorEntity createProcessorEntity(final ProcessorDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final ProcessorStatusDTO status, final List<BulletinEntity> bulletins) { final ProcessorEntity entity = new ProcessorEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setStatus(status); entity.setId(dto.getId()); entity.setInputRequirement(dto.getInputRequirement()); entity.setPosition(dto.getPosition()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); entity.setBulletins(bulletins); } } return entity; } public PortEntity createPortEntity(final PortDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final PortStatusDTO status, final List<BulletinEntity> bulletins) { final PortEntity entity = new PortEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setStatus(status); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); entity.setPortType(dto.getType()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); entity.setBulletins(bulletins); } } return entity; } public ProcessGroupEntity createProcessGroupEntity(final ProcessGroupDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final ProcessGroupStatusDTO status, final List<BulletinEntity> bulletins) { final ProcessGroupEntity entity = new ProcessGroupEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setStatus(status); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); entity.setInputPortCount(dto.getInputPortCount()); entity.setOutputPortCount(dto.getOutputPortCount()); entity.setRunningCount(dto.getRunningCount()); entity.setStoppedCount(dto.getStoppedCount()); entity.setInvalidCount(dto.getInvalidCount()); entity.setDisabledCount(dto.getDisabledCount()); entity.setActiveRemotePortCount(dto.getActiveRemotePortCount()); entity.setInactiveRemotePortCount(dto.getInactiveRemotePortCount()); entity.setBulletins(bulletins); // include bulletins as authorized descendant component bulletins should be available if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public LabelEntity createLabelEntity(final LabelDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final LabelEntity entity = new LabelEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); final DimensionsDTO dimensions = new DimensionsDTO(); dimensions.setHeight(dto.getHeight()); dimensions.setWidth(dto.getWidth()); entity.setDimensions(dimensions); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public UserEntity createUserEntity(final UserDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final UserEntity entity = new UserEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public TenantEntity createTenantEntity(final TenantDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final TenantEntity entity = new TenantEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public AccessPolicySummaryEntity createAccessPolicySummaryEntity(final AccessPolicySummaryDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final AccessPolicySummaryEntity entity = new AccessPolicySummaryEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public ComponentReferenceEntity createComponentReferenceEntity(final ComponentReferenceDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final ComponentReferenceEntity entity = new ComponentReferenceEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); entity.setParentGroupId(dto.getParentGroupId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public UserGroupEntity createUserGroupEntity(final UserGroupDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final UserGroupEntity entity = new UserGroupEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public AccessPolicyEntity createAccessPolicyEntity(final AccessPolicyDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final AccessPolicyEntity entity = new AccessPolicyEntity(); entity.setRevision(revision); entity.setGenerated(new Date()); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public FunnelEntity createFunnelEntity(final FunnelDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final FunnelEntity entity = new FunnelEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public ConnectionEntity createConnectionEntity(final ConnectionDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final ConnectionStatusDTO status) { final ConnectionEntity entity = new ConnectionEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setStatus(status); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); entity.setBends(dto.getBends()); entity.setLabelIndex(dto.getLabelIndex()); entity.setzIndex(dto.getzIndex()); entity.setSourceId(dto.getSource().getId()); entity.setSourceGroupId(dto.getSource().getGroupId()); entity.setSourceType(dto.getSource().getType()); entity.setDestinationId(dto.getDestination().getId()); entity.setDestinationGroupId(dto.getDestination().getGroupId()); entity.setDestinationType(dto.getDestination().getType()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public RemoteProcessGroupEntity createRemoteProcessGroupEntity(final RemoteProcessGroupDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final RemoteProcessGroupStatusDTO status, final List<BulletinEntity> bulletins) { final RemoteProcessGroupEntity entity = new RemoteProcessGroupEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setStatus(status); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); entity.setInputPortCount(dto.getInputPortCount()); entity.setOutputPortCount(dto.getOutputPortCount()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); entity.setBulletins(bulletins); } } return entity; } public RemoteProcessGroupPortEntity createRemoteProcessGroupPortEntity(final RemoteProcessGroupPortDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final RemoteProcessGroupPortEntity entity = new RemoteProcessGroupPortEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setRemoteProcessGroupPort(dto); } } return entity; } public SnippetEntity createSnippetEntity(final SnippetDTO dto) { final SnippetEntity entity = new SnippetEntity(); entity.setSnippet(dto); return entity; } public ReportingTaskEntity createReportingTaskEntity(final ReportingTaskDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final List<BulletinEntity> bulletins) { final ReportingTaskEntity entity = new ReportingTaskEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); entity.setBulletins(bulletins); } } return entity; } public ControllerServiceEntity createControllerServiceEntity(final ControllerServiceDTO dto, final RevisionDTO revision, final PermissionsDTO permissions, final List<BulletinEntity> bulletins) { final ControllerServiceEntity entity = new ControllerServiceEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); entity.setPosition(dto.getPosition()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); entity.setBulletins(bulletins); } } return entity; } public ControllerServiceReferencingComponentEntity createControllerServiceReferencingComponentEntity( final ControllerServiceReferencingComponentDTO dto, final RevisionDTO revision, final PermissionsDTO permissions) { final ControllerServiceReferencingComponentEntity entity = new ControllerServiceReferencingComponentEntity(); entity.setRevision(revision); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setComponent(dto); } } return entity; } public FlowBreadcrumbEntity createFlowBreadcrumbEntity(final FlowBreadcrumbDTO dto, final PermissionsDTO permissions) { final FlowBreadcrumbEntity entity = new FlowBreadcrumbEntity(); if (dto != null) { entity.setPermissions(permissions); entity.setId(dto.getId()); if (permissions != null && permissions.getCanRead()) { entity.setBreadcrumb(dto); } } return entity; } public AllowableValueEntity createAllowableValueEntity(final AllowableValueDTO dto, final boolean canRead) { final AllowableValueEntity entity = new AllowableValueEntity(); entity.setCanRead(canRead); entity.setAllowableValue(dto); return entity; } public ActionEntity createActionEntity(final ActionDTO dto, final boolean canRead) { final ActionEntity entity = new ActionEntity(); if (dto != null) { entity.setId(dto.getId()); entity.setSourceId(dto.getSourceId()); entity.setTimestamp(dto.getTimestamp()); entity.setCanRead(canRead); if (canRead) { entity.setAction(dto); } } return entity; } public BulletinEntity createBulletinEntity(final BulletinDTO dto, final boolean canRead) { final BulletinEntity entity = new BulletinEntity(); if (dto != null) { entity.setId(dto.getId()); entity.setSourceId(dto.getSourceId()); entity.setGroupId(dto.getGroupId()); entity.setTimestamp(dto.getTimestamp()); entity.setNodeAddress(dto.getNodeAddress()); entity.setCanRead(canRead); if (canRead) { entity.setBulletin(dto); } } return entity; } }
/* * 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.launcher.daemon.bootstrap; import com.google.common.io.Files; import org.gradle.api.UncheckedIOException; import org.gradle.api.logging.LogLevel; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.internal.classpath.DefaultClassPath; import org.gradle.internal.concurrent.CompositeStoppable; import org.gradle.internal.logging.LoggingManagerInternal; import org.gradle.internal.logging.services.LoggingServiceRegistry; import org.gradle.internal.nativeintegration.ProcessEnvironment; import org.gradle.internal.nativeintegration.services.NativeServices; import org.gradle.internal.remote.Address; import org.gradle.internal.serialize.kryo.KryoBackedDecoder; import org.gradle.internal.service.scopes.GradleUserHomeScopeServiceRegistry; import org.gradle.launcher.bootstrap.EntryPoint; import org.gradle.launcher.bootstrap.ExecutionListener; import org.gradle.launcher.daemon.configuration.DaemonServerConfiguration; import org.gradle.launcher.daemon.configuration.DefaultDaemonServerConfiguration; import org.gradle.launcher.daemon.context.DaemonContext; import org.gradle.launcher.daemon.logging.DaemonMessages; import org.gradle.launcher.daemon.server.Daemon; import org.gradle.launcher.daemon.server.DaemonServices; import org.gradle.launcher.daemon.server.MasterExpirationStrategy; import org.gradle.launcher.daemon.server.expiry.DaemonExpirationStrategy; import org.gradle.process.internal.shutdown.ShutdownHookActionRegister; import org.gradle.process.internal.streams.EncodedStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; /** * The entry point for a daemon process. * * If the daemon hits the specified idle timeout the process will exit with 0. If the daemon encounters an internal error or is explicitly stopped (which can be via receiving a stop command, or * unexpected client disconnection) the process will exit with 1. */ public class DaemonMain extends EntryPoint { private static final Logger LOGGER = Logging.getLogger(DaemonMain.class); public static final String SINGLE_USE_FLAG = "--single-use"; private PrintStream originalOut; private PrintStream originalErr; @Override protected void doAction(String[] args, ExecutionListener listener) { //The first argument is not really used but it is very useful in diagnosing, i.e. running 'jps -m' if (args.length != 1) { invalidArgs("Following arguments are required: <gradle-version>"); } // Read configuration from stdin List<String> startupOpts; File gradleHomeDir; File daemonBaseDir; int idleTimeoutMs; int periodicCheckIntervalMs; boolean singleUse; String daemonUid; List<File> additionalClassPath; KryoBackedDecoder decoder = new KryoBackedDecoder(new EncodedStream.EncodedInput(System.in)); try { gradleHomeDir = new File(decoder.readString()); daemonBaseDir = new File(decoder.readString()); idleTimeoutMs = decoder.readSmallInt(); periodicCheckIntervalMs = decoder.readSmallInt(); singleUse = decoder.readBoolean(); daemonUid = decoder.readString(); int argCount = decoder.readSmallInt(); startupOpts = new ArrayList<String>(argCount); for (int i = 0; i < argCount; i++) { startupOpts.add(decoder.readString()); } int additionalClassPathLength = decoder.readSmallInt(); additionalClassPath = new ArrayList<File>(additionalClassPathLength); for (int i = 0; i < additionalClassPathLength; i++) { additionalClassPath.add(new File(decoder.readString())); } } catch (EOFException e) { throw new UncheckedIOException(e); } NativeServices.initialize(gradleHomeDir); DaemonServerConfiguration parameters = new DefaultDaemonServerConfiguration(daemonUid, daemonBaseDir, idleTimeoutMs, periodicCheckIntervalMs, singleUse, startupOpts); LoggingServiceRegistry loggingRegistry = LoggingServiceRegistry.newCommandLineProcessLogging(); LoggingManagerInternal loggingManager = loggingRegistry.newInstance(LoggingManagerInternal.class); DaemonServices daemonServices = new DaemonServices(parameters, loggingRegistry, loggingManager, new DefaultClassPath(additionalClassPath)); File daemonLog = daemonServices.getDaemonLogFile(); // Any logging prior to this point will not end up in the daemon log file. initialiseLogging(loggingManager, daemonLog); // Detach the process from the parent terminal/console ProcessEnvironment processEnvironment = daemonServices.get(ProcessEnvironment.class); processEnvironment.maybeDetachProcess(); LOGGER.debug("Assuming the daemon was started with following jvm opts: {}", startupOpts); Daemon daemon = daemonServices.get(Daemon.class); daemon.start(); try { DaemonContext daemonContext = daemonServices.get(DaemonContext.class); Long pid = daemonContext.getPid(); daemonStarted(pid, daemon.getUid(), daemon.getAddress(), daemonLog); DaemonExpirationStrategy expirationStrategy = daemonServices.get(MasterExpirationStrategy.class); daemon.stopOnExpiration(expirationStrategy, parameters.getPeriodicCheckIntervalMs()); } finally { daemon.stop(); // TODO: Stop all daemon services CompositeStoppable.stoppable(daemonServices.get(GradleUserHomeScopeServiceRegistry.class)).stop(); } } private static void invalidArgs(String message) { System.out.println("USAGE: <gradle version>"); System.out.println(message); System.exit(1); } protected void daemonStarted(Long pid, String uid, Address address, File daemonLog) { //directly printing to the stream to avoid log level filtering. new DaemonStartupCommunication().printDaemonStarted(originalOut, pid, uid, address, daemonLog); try { originalOut.close(); originalErr.close(); //TODO - make this work on windows //originalIn.close(); } finally { originalOut = null; originalErr = null; } } protected void initialiseLogging(LoggingManagerInternal loggingManager, File daemonLog) { //create log file PrintStream result; try { Files.createParentDirs(daemonLog); result = new PrintStream(new FileOutputStream(daemonLog), true); } catch (Exception e) { throw new RuntimeException("Unable to create daemon log file", e); } final PrintStream log = result; ShutdownHookActionRegister.addAction(new Runnable() { public void run() { //just in case we have a bug related to logging, //printing some exit info directly to file: log.println(DaemonMessages.DAEMON_VM_SHUTTING_DOWN); } }); //close all streams and redirect IO redirectOutputsAndInput(log); //after redirecting we need to add the new std out/err to the renderer singleton //so that logging gets its way to the daemon log: loggingManager.attachSystemOutAndErr(); //Making the daemon infrastructure log with DEBUG. This is only for the infrastructure! //Each build request carries it's own log level and it is used during the execution of the build (see LogToClient) loggingManager.setLevelInternal(LogLevel.DEBUG); loggingManager.start(); } private void redirectOutputsAndInput(PrintStream printStream) { this.originalOut = System.out; this.originalErr = System.err; //InputStream originalIn = System.in; System.setOut(printStream); System.setErr(printStream); System.setIn(new ByteArrayInputStream(new byte[0])); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.common.type; import com.facebook.presto.common.block.AbstractMapBlock.HashTables; import com.facebook.presto.common.block.Block; import com.facebook.presto.common.block.BlockBuilder; import com.facebook.presto.common.block.BlockBuilderStatus; import com.facebook.presto.common.block.MapBlock; import com.facebook.presto.common.block.MapBlockBuilder; import com.facebook.presto.common.block.SingleMapBlock; import com.facebook.presto.common.function.SqlFunctionProperties; import java.lang.invoke.MethodHandle; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.TypeUtils.checkElementNotNull; import static com.facebook.presto.common.type.TypeUtils.hashPosition; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; public class MapType extends AbstractType { private final Type keyType; private final Type valueType; private static final String MAP_NULL_ELEMENT_MSG = "MAP comparison not supported for null value elements"; private static final int EXPECTED_BYTES_PER_ENTRY = 32; private final MethodHandle keyNativeHashCode; private final MethodHandle keyBlockHashCode; private final MethodHandle keyBlockNativeEquals; private final MethodHandle keyBlockEquals; public MapType( Type keyType, Type valueType, MethodHandle keyBlockNativeEquals, MethodHandle keyBlockEquals, MethodHandle keyNativeHashCode, MethodHandle keyBlockHashCode) { super(new TypeSignature(StandardTypes.MAP, TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(valueType.getTypeSignature())), Block.class); if (!keyType.isComparable()) { throw new IllegalArgumentException(format("key type must be comparable, got %s", keyType)); } this.keyType = keyType; this.valueType = valueType; requireNonNull(keyBlockNativeEquals, "keyBlockNativeEquals is null"); requireNonNull(keyNativeHashCode, "keyNativeHashCode is null"); requireNonNull(keyBlockHashCode, "keyBlockHashCode is null"); this.keyBlockNativeEquals = keyBlockNativeEquals; this.keyNativeHashCode = keyNativeHashCode; this.keyBlockHashCode = keyBlockHashCode; this.keyBlockEquals = keyBlockEquals; } @Override public BlockBuilder createBlockBuilder(BlockBuilderStatus blockBuilderStatus, int expectedEntries, int expectedBytesPerEntry) { return new MapBlockBuilder( keyType, valueType, keyBlockNativeEquals, keyBlockEquals, keyNativeHashCode, keyBlockHashCode, blockBuilderStatus, expectedEntries); } @Override public BlockBuilder createBlockBuilder(BlockBuilderStatus blockBuilderStatus, int expectedEntries) { return createBlockBuilder(blockBuilderStatus, expectedEntries, EXPECTED_BYTES_PER_ENTRY); } public Type getKeyType() { return keyType; } public Type getValueType() { return valueType; } @Override public boolean isComparable() { return valueType.isComparable(); } @Override public long hash(Block block, int position) { Block mapBlock = getObject(block, position); long result = 0; for (int i = 0; i < mapBlock.getPositionCount(); i += 2) { result += hashPosition(keyType, mapBlock, i) ^ hashPosition(valueType, mapBlock, i + 1); } return result; } @Override public boolean equalTo(Block leftBlock, int leftPosition, Block rightBlock, int rightPosition) { Block leftMapBlock = leftBlock.getBlock(leftPosition); Block rightMapBlock = rightBlock.getBlock(rightPosition); if (leftMapBlock.getPositionCount() != rightMapBlock.getPositionCount()) { return false; } Map<KeyWrapper, Integer> wrappedLeftMap = new HashMap<>(); for (int position = 0; position < leftMapBlock.getPositionCount(); position += 2) { wrappedLeftMap.put(new KeyWrapper(keyType, leftMapBlock, position), position + 1); } for (int position = 0; position < rightMapBlock.getPositionCount(); position += 2) { KeyWrapper key = new KeyWrapper(keyType, rightMapBlock, position); Integer leftValuePosition = wrappedLeftMap.get(key); if (leftValuePosition == null) { return false; } int rightValuePosition = position + 1; checkElementNotNull(leftMapBlock.isNull(leftValuePosition), MAP_NULL_ELEMENT_MSG); checkElementNotNull(rightMapBlock.isNull(rightValuePosition), MAP_NULL_ELEMENT_MSG); if (!valueType.equalTo(leftMapBlock, leftValuePosition, rightMapBlock, rightValuePosition)) { return false; } } return true; } private static final class KeyWrapper { private final Type type; private final Block block; private final int position; public KeyWrapper(Type type, Block block, int position) { this.type = type; this.block = block; this.position = position; } public Block getBlock() { return this.block; } public int getPosition() { return this.position; } @Override public int hashCode() { return Long.hashCode(type.hash(block, position)); } @Override public boolean equals(Object obj) { if (obj == null || !getClass().equals(obj.getClass())) { return false; } KeyWrapper other = (KeyWrapper) obj; return type.equalTo(this.block, this.position, other.getBlock(), other.getPosition()); } } @Override public Object getObjectValue(SqlFunctionProperties properties, Block block, int position) { if (block.isNull(position)) { return null; } Block singleMapBlock = block.getBlock(position); if (!(singleMapBlock instanceof SingleMapBlock)) { throw new UnsupportedOperationException("Map is encoded with legacy block representation"); } Map<Object, Object> map = new HashMap<>(); for (int i = 0; i < singleMapBlock.getPositionCount(); i += 2) { map.put(keyType.getObjectValue(properties, singleMapBlock, i), valueType.getObjectValue(properties, singleMapBlock, i + 1)); } return Collections.unmodifiableMap(map); } @Override public void appendTo(Block block, int position, BlockBuilder blockBuilder) { if (block.isNull(position)) { blockBuilder.appendNull(); } else { block.writePositionTo(position, blockBuilder); } } @Override public Block getObject(Block block, int position) { return block.getBlock(position); } @Override public Block getBlockUnchecked(Block block, int internalPosition) { return block.getBlockUnchecked(internalPosition); } @Override public void writeObject(BlockBuilder blockBuilder, Object value) { if (!(value instanceof SingleMapBlock)) { throw new IllegalArgumentException("Maps must be represented with SingleMapBlock"); } blockBuilder.appendStructure((Block) value); } @Override public List<Type> getTypeParameters() { return asList(getKeyType(), getValueType()); } @Override public String getDisplayName() { return "map(" + keyType.getDisplayName() + ", " + valueType.getDisplayName() + ")"; } public Block createBlockFromKeyValue(int positionCount, Optional<boolean[]> mapIsNull, int[] offsets, Block keyBlock, Block valueBlock) { return MapBlock.fromKeyValueBlock( positionCount, mapIsNull, offsets, keyBlock, valueBlock, this, keyBlockNativeEquals, keyNativeHashCode, keyBlockHashCode); } /** * Create a map block directly without per element validations. * <p> * Internal use by com.facebook.presto.spi.Block only. */ public static Block createMapBlockInternal( TypeManager typeManager, Type keyType, int startOffset, int positionCount, Optional<boolean[]> mapIsNull, int[] offsets, Block keyBlock, Block valueBlock, HashTables hashTables) { // TypeManager caches types. Therefore, it is important that we go through it instead of coming up with the MethodHandles directly. // BIGINT is chosen arbitrarily here. Any type will do. MapType mapType = (MapType) typeManager.getType(new TypeSignature(StandardTypes.MAP, TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(BIGINT.getTypeSignature()))); return MapBlock.createMapBlockInternal(startOffset, positionCount, mapIsNull, offsets, keyBlock, valueBlock, hashTables, keyType, mapType.keyBlockNativeEquals, mapType.keyNativeHashCode, mapType.keyBlockHashCode); } }
/* * 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.cassandra.tools; import java.io.IOException; import java.net.InetAddress; import java.util.Set; import javax.net.ssl.SSLContext; import com.datastax.driver.core.AuthProvider; import com.datastax.driver.core.JdkSSLOptions; import com.datastax.driver.core.SSLOptions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.config.EncryptionOptions; import org.apache.cassandra.io.sstable.SSTableLoader; import org.apache.cassandra.security.SSLFactory; import org.apache.cassandra.streaming.*; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.JVMStabilityInspector; import org.apache.cassandra.utils.NativeSSTableLoaderClient; import org.apache.cassandra.utils.OutputHandler; public class BulkLoader { public static void main(String args[]) throws BulkLoadException { LoaderOptions options = LoaderOptions.builder().parseArgs(args).build(); load(options); } public static void load(LoaderOptions options) throws BulkLoadException { DatabaseDescriptor.toolInitialization(); OutputHandler handler = new OutputHandler.SystemOutput(options.verbose, options.debug); SSTableLoader loader = new SSTableLoader( options.directory.getAbsoluteFile(), new ExternalClient( options.hosts, options.nativePort, options.authProvider, options.storagePort, options.sslStoragePort, options.serverEncOptions, buildSSLOptions(options.clientEncOptions)), handler, options.connectionsPerHost); DatabaseDescriptor.setStreamThroughputOutboundMegabitsPerSec(options.throttle); DatabaseDescriptor.setInterDCStreamThroughputOutboundMegabitsPerSec(options.interDcThrottle); StreamResultFuture future = null; ProgressIndicator indicator = new ProgressIndicator(); try { if (options.noProgress) { future = loader.stream(options.ignores); } else { future = loader.stream(options.ignores, indicator); } } catch (Exception e) { JVMStabilityInspector.inspectThrowable(e); System.err.println(e.getMessage()); if (e.getCause() != null) { System.err.println(e.getCause()); } e.printStackTrace(System.err); throw new BulkLoadException(e); } try { future.get(); if (!options.noProgress) { indicator.printSummary(options.connectionsPerHost); } // Give sockets time to gracefully close Thread.sleep(1000); } catch (Exception e) { System.err.println("Streaming to the following hosts failed:"); System.err.println(loader.getFailedHosts()); e.printStackTrace(System.err); throw new BulkLoadException(e); } } // Return true when everything is at 100% static class ProgressIndicator implements StreamEventHandler { private long start; private long lastProgress; private long lastTime; private long peak = 0; private int totalFiles = 0; private final Multimap<InetAddress, SessionInfo> sessionsByHost = HashMultimap.create(); public ProgressIndicator() { start = lastTime = System.nanoTime(); } public void onSuccess(StreamState finalState) { } public void onFailure(Throwable t) { } public synchronized void handleStreamEvent(StreamEvent event) { if (event.eventType == StreamEvent.Type.STREAM_PREPARED) { SessionInfo session = ((StreamEvent.SessionPreparedEvent) event).session; sessionsByHost.put(session.peer, session); } else if (event.eventType == StreamEvent.Type.FILE_PROGRESS || event.eventType == StreamEvent.Type.STREAM_COMPLETE) { ProgressInfo progressInfo = null; if (event.eventType == StreamEvent.Type.FILE_PROGRESS) { progressInfo = ((StreamEvent.ProgressEvent) event).progress; } long time = System.nanoTime(); long deltaTime = time - lastTime; StringBuilder sb = new StringBuilder(); sb.append("\rprogress: "); long totalProgress = 0; long totalSize = 0; boolean updateTotalFiles = totalFiles == 0; // recalculate progress across all sessions in all hosts and display for (InetAddress peer : sessionsByHost.keySet()) { sb.append("[").append(peer).append("]"); for (SessionInfo session : sessionsByHost.get(peer)) { long size = session.getTotalSizeToSend(); long current = 0; int completed = 0; if (progressInfo != null && session.peer.equals(progressInfo.peer) && session.sessionIndex == progressInfo.sessionIndex) { session.updateProgress(progressInfo); } for (ProgressInfo progress : session.getSendingFiles()) { if (progress.isCompleted()) { completed++; } current += progress.currentBytes; } totalProgress += current; totalSize += size; sb.append(session.sessionIndex).append(":"); sb.append(completed).append("/").append(session.getTotalFilesToSend()); sb.append(" ").append(String.format("%-3d", size == 0 ? 100L : current * 100L / size)).append("% "); if (updateTotalFiles) { totalFiles += session.getTotalFilesToSend(); } } } lastTime = time; long deltaProgress = totalProgress - lastProgress; lastProgress = totalProgress; sb.append("total: ").append(totalSize == 0 ? 100L : totalProgress * 100L / totalSize).append("% "); sb.append(FBUtilities.prettyPrintMemoryPerSecond(deltaProgress, deltaTime)); long average = bytesPerSecond(totalProgress, time - start); if (average > peak) { peak = average; } sb.append(" (avg: ").append(FBUtilities.prettyPrintMemoryPerSecond(totalProgress, time - start)).append(")"); System.out.println(sb.toString()); } } private long bytesPerSecond(long bytes, long timeInNano) { return timeInNano != 0 ? (long) (((double) bytes / timeInNano) * 1000 * 1000 * 1000) : 0; } private void printSummary(int connectionsPerHost) { long end = System.nanoTime(); long durationMS = ((end - start) / (1000000)); StringBuilder sb = new StringBuilder(); sb.append("\nSummary statistics: \n"); sb.append(String.format(" %-24s: %-10d%n", "Connections per host ", connectionsPerHost)); sb.append(String.format(" %-24s: %-10d%n", "Total files transferred ", totalFiles)); sb.append(String.format(" %-24s: %-10s%n", "Total bytes transferred ", FBUtilities.prettyPrintMemory(lastProgress))); sb.append(String.format(" %-24s: %-10s%n", "Total duration ", durationMS + " ms")); sb.append(String.format(" %-24s: %-10s%n", "Average transfer rate ", FBUtilities.prettyPrintMemoryPerSecond(lastProgress, end - start))); sb.append(String.format(" %-24s: %-10s%n", "Peak transfer rate ", FBUtilities.prettyPrintMemoryPerSecond(peak))); System.out.println(sb.toString()); } } private static SSLOptions buildSSLOptions(EncryptionOptions.ClientEncryptionOptions clientEncryptionOptions) { if (!clientEncryptionOptions.enabled) { return null; } SSLContext sslContext; try { sslContext = SSLFactory.createSSLContext(clientEncryptionOptions, true); } catch (IOException e) { throw new RuntimeException("Could not create SSL Context.", e); } return JdkSSLOptions.builder() .withSSLContext(sslContext) .withCipherSuites(clientEncryptionOptions.cipher_suites) .build(); } static class ExternalClient extends NativeSSTableLoaderClient { private final int storagePort; private final int sslStoragePort; private final EncryptionOptions.ServerEncryptionOptions serverEncOptions; public ExternalClient(Set<InetAddress> hosts, int port, AuthProvider authProvider, int storagePort, int sslStoragePort, EncryptionOptions.ServerEncryptionOptions serverEncryptionOptions, SSLOptions sslOptions) { super(hosts, port, authProvider, sslOptions); this.storagePort = storagePort; this.sslStoragePort = sslStoragePort; serverEncOptions = serverEncryptionOptions; } @Override public StreamConnectionFactory getConnectionFactory() { return new BulkLoadConnectionFactory(storagePort, sslStoragePort, serverEncOptions, false); } } public static class CmdLineOptions extends Options { /** * Add option with argument and argument name * @param opt shortcut for option name * @param longOpt complete option name * @param argName argument name * @param description description of the option * @return updated Options object */ public Options addOption(String opt, String longOpt, String argName, String description) { Option option = new Option(opt, longOpt, true, description); option.setArgName(argName); return addOption(option); } /** * Add option without argument * @param opt shortcut for option name * @param longOpt complete option name * @param description description of the option * @return updated Options object */ public Options addOption(String opt, String longOpt, String description) { return addOption(new Option(opt, longOpt, false, description)); } } }
/* * 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.felix.dm.impl.dependencies; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Proxy; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.apache.felix.dm.Component; import org.apache.felix.dm.ComponentDependencyDeclaration; import org.apache.felix.dm.Dependency; import org.apache.felix.dm.DependencyService; import org.apache.felix.dm.InvocationUtil; import org.apache.felix.dm.ServiceDependency; import org.apache.felix.dm.ServiceUtil; import org.apache.felix.dm.impl.DefaultNullObject; import org.apache.felix.dm.impl.Logger; import org.apache.felix.dm.tracker.ServiceTracker; import org.apache.felix.dm.tracker.ServiceTrackerCustomizer; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogService; /** * Service dependency that can track an OSGi service. * * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a> */ public class ServiceDependencyImpl extends DependencyBase implements ServiceDependency, ServiceTrackerCustomizer, ComponentDependencyDeclaration { protected List m_services = new ArrayList(); protected volatile ServiceTracker m_tracker; protected BundleContext m_context; protected volatile Class m_trackedServiceName; private Object m_nullObject; private volatile String m_trackedServiceFilter; private volatile String m_trackedServiceFilterUnmodified; private volatile ServiceReference m_trackedServiceReference; private Object m_callbackInstance; private String m_callbackAdded; private String m_callbackChanged; private String m_callbackRemoved; private String m_callbackSwapped; private boolean m_autoConfig; protected ServiceReference m_reference; protected Object m_serviceInstance; private String m_autoConfigInstance; private boolean m_autoConfigInvoked; private Object m_defaultImplementation; private Object m_defaultImplementationInstance; private boolean m_isAvailable; private boolean m_propagate; private Object m_propagateCallbackInstance; private String m_propagateCallbackMethod; private final Map m_sr = new HashMap(); /* <DependencyService, Set<Tuple<ServiceReference, Object>> */ private Map m_componentByRank = new HashMap(); /* <Component, Map<Long, Map<Integer, Tuple>>> */ private static final Comparator COMPARATOR = new Comparator() { public int getRank(ServiceReference ref) { Object ranking = ref.getProperty(Constants.SERVICE_RANKING); if (ranking != null && (ranking instanceof Integer)) { return ((Integer) ranking).intValue(); } return 0; } public int compare(Object a, Object b) { ServiceReference ra = (ServiceReference) a, rb = (ServiceReference) b; int ranka = getRank(ra); int rankb = getRank(rb); if (ranka < rankb) { return -1; } else if (ranka > rankb) { return 1; } return 0; } }; private static final class Tuple /* <ServiceReference, Object> */ { private final ServiceReference m_serviceReference; private final Object m_service; public Tuple(ServiceReference first, Object last) { m_serviceReference = first; m_service = last; } public ServiceReference getServiceReference() { return m_serviceReference; } public Object getService() { return m_service; } public boolean equals(Object obj) { return ((Tuple) obj).getServiceReference().equals(getServiceReference()); } public int hashCode() { return m_serviceReference.hashCode(); } } /** * Entry to wrap service properties behind a Map. */ private static final class ServicePropertiesMapEntry implements Map.Entry { private final String m_key; private Object m_value; public ServicePropertiesMapEntry(String key, Object value) { m_key = key; m_value = value; } public Object getKey() { return m_key; } public Object getValue() { return m_value; } public String toString() { return m_key + "=" + m_value; } public Object setValue(Object value) { Object oldValue = m_value; m_value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return eq(m_key, e.getKey()) && eq(m_value, e.getValue()); } public int hashCode() { return ((m_key == null) ? 0 : m_key.hashCode()) ^ ((m_value == null) ? 0 : m_value.hashCode()); } private static final boolean eq(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } } /** * Wraps service properties behind a Map. */ private final static class ServicePropertiesMap extends AbstractMap { private final ServiceReference m_ref; public ServicePropertiesMap(ServiceReference ref) { m_ref = ref; } public Object get(Object key) { return m_ref.getProperty(key.toString()); } public int size() { return m_ref.getPropertyKeys().length; } public Set entrySet() { Set set = new HashSet(); String[] keys = m_ref.getPropertyKeys(); for (int i = 0; i < keys.length; i++) { set.add(new ServicePropertiesMapEntry(keys[i], m_ref.getProperty(keys[i]))); } return set; } } /** * Creates a new service dependency. * * @param context the bundle context * @param logger the logger */ public ServiceDependencyImpl(BundleContext context, Logger logger) { super(logger); m_context = context; m_autoConfig = true; } /** Copying constructor that clones an existing instance. */ public ServiceDependencyImpl(ServiceDependencyImpl prototype) { super(prototype); synchronized (prototype) { m_context = prototype.m_context; m_autoConfig = prototype.m_autoConfig; m_trackedServiceName = prototype.m_trackedServiceName; m_nullObject = prototype.m_nullObject; m_trackedServiceFilter = prototype.m_trackedServiceFilter; m_trackedServiceFilterUnmodified = prototype.m_trackedServiceFilterUnmodified; m_trackedServiceReference = prototype.m_trackedServiceReference; m_callbackInstance = prototype.m_callbackInstance; m_callbackAdded = prototype.m_callbackAdded; m_callbackChanged = prototype.m_callbackChanged; m_callbackRemoved = prototype.m_callbackRemoved; m_autoConfigInstance = prototype.m_autoConfigInstance; m_defaultImplementation = prototype.m_defaultImplementation; } } public Dependency createCopy() { return new ServiceDependencyImpl(this); } public synchronized boolean isAutoConfig() { return m_autoConfig; } public synchronized boolean isAvailable() { return m_isAvailable; } public synchronized Object getService() { Object service = null; if (m_isStarted) { service = m_tracker.getService(); } if (service == null && isAutoConfig()) { service = getDefaultImplementation(); if (service == null) { service = getNullObject(); } } return service; } public Object lookupService() { Object service = null; if (m_isStarted) { service = getService(); } else { ServiceReference[] refs = null; ServiceReference ref = null; if (m_trackedServiceName != null) { if (m_trackedServiceFilter != null) { try { refs = m_context.getServiceReferences(m_trackedServiceName.getName(), m_trackedServiceFilter); if (refs != null) { Arrays.sort(refs, COMPARATOR); ref = refs[0]; } } catch (InvalidSyntaxException e) { throw new IllegalStateException("Invalid filter definition for dependency."); } } else if (m_trackedServiceReference != null) { ref = m_trackedServiceReference; } else { ref = m_context.getServiceReference(m_trackedServiceName.getName()); } if (ref != null) { service = m_context.getService(ref); } } else { throw new IllegalStateException("Could not lookup dependency, no service name specified."); } } if (service == null && isAutoConfig()) { service = getDefaultImplementation(); if (service == null) { service = getNullObject(); } } return service; } // TODO lots of duplication in lookupService() public ServiceReference lookupServiceReference() { ServiceReference service = null; if (m_isStarted) { service = m_tracker.getServiceReference(); } else { ServiceReference[] refs = null; ServiceReference ref = null; if (m_trackedServiceName != null) { if (m_trackedServiceFilter != null) { try { refs = m_context.getServiceReferences(m_trackedServiceName.getName(), m_trackedServiceFilter); if (refs != null) { Arrays.sort(refs, COMPARATOR); ref = refs[0]; } } catch (InvalidSyntaxException e) { throw new IllegalStateException("Invalid filter definition for dependency."); } } else if (m_trackedServiceReference != null) { ref = m_trackedServiceReference; } else { ref = m_context.getServiceReference(m_trackedServiceName.getName()); } if (ref != null) { service = ref; } } else { throw new IllegalStateException("Could not lookup dependency, no service name specified."); } } return service; } private Object getNullObject() { if (m_nullObject == null) { Class trackedServiceName; synchronized (this) { trackedServiceName = m_trackedServiceName; } try { m_nullObject = Proxy.newProxyInstance(trackedServiceName.getClassLoader(), new Class[] {trackedServiceName}, new DefaultNullObject()); } catch (Exception e) { m_logger.log(Logger.LOG_ERROR, "Could not create null object for " + trackedServiceName + ".", e); } } return m_nullObject; } private Object getDefaultImplementation() { if (m_defaultImplementation != null) { if (m_defaultImplementation instanceof Class) { try { m_defaultImplementationInstance = ((Class) m_defaultImplementation).newInstance(); } catch (Exception e) { m_logger.log(Logger.LOG_ERROR, "Could not create default implementation instance of class " + m_defaultImplementation + ".", e); } } else { m_defaultImplementationInstance = m_defaultImplementation; } } return m_defaultImplementationInstance; } public synchronized Class getInterface() { return m_trackedServiceName; } public void start(DependencyService service) { boolean needsStarting = false; synchronized (this) { m_services.add(service); if (!m_isStarted) { if (m_trackedServiceName != null) { if (m_trackedServiceFilter != null) { try { m_tracker = new ServiceTracker(m_context, m_context.createFilter(m_trackedServiceFilter), this); } catch (InvalidSyntaxException e) { throw new IllegalStateException("Invalid filter definition for dependency: " + m_trackedServiceFilter); } } else if (m_trackedServiceReference != null) { m_tracker = new ServiceTracker(m_context, m_trackedServiceReference, this); } else { m_tracker = new ServiceTracker(m_context, m_trackedServiceName.getName(), this); } } else { throw new IllegalStateException("Could not create tracker for dependency, no service name specified."); } m_isStarted = true; needsStarting = true; } } if (needsStarting) { m_tracker.open(); } } public void stop(DependencyService service) { boolean needsStopping = false; synchronized (this) { if (m_services.size() == 1 && m_services.contains(service)) { m_isStarted = false; needsStopping = true; } } if (needsStopping) { m_tracker.close(); m_tracker = null; } //moved this down synchronized (this) { m_services.remove(service); } } public Object addingService(ServiceReference ref) { Object service = m_context.getService(ref); // first check to make sure the service is actually an instance of our service if (!m_trackedServiceName.isInstance(service)) { return null; } return service; } public void addedService(ServiceReference ref, Object service) { boolean makeAvailable = makeAvailable(); Object[] services; synchronized (this) { services = m_services.toArray(); } for (int i = 0; i < services.length; i++) { DependencyService ds = (DependencyService) services[i]; if (makeAvailable) { if (ds.isInstantiated() && isInstanceBound() && isRequired()) { invokeAdded(ds, ref, service); } // The dependency callback will be defered until all required dependency are available. ds.dependencyAvailable(this); if (!isRequired()) { // For optional dependency, we always invoke callback, because at this point, we know // that the service has been started, and the service start method has been called. // (See the ServiceImpl.bindService method, which will activate optional dependencies using // startTrackingOptional() method). invokeAdded(ds, ref, service); } } else { ds.dependencyChanged(this); // At this point, either the dependency is optional (meaning that the service has been started, // because if not, then our dependency would not be active); or the dependency is required, // meaning that either the service is not yet started, or already started. // In all cases, we have to inject the required dependency. // we only try to invoke the method here if we are really already instantiated if (ds.isInstantiated() && ds.getCompositionInstances().length > 0) { invokeAdded(ds, ref, service); } } } } public void modifiedService(ServiceReference ref, Object service) { Object[] services; synchronized (this) { services = m_services.toArray(); } for (int i = 0; i < services.length; i++) { DependencyService ds = (DependencyService) services[i]; ds.dependencyChanged(this); if (ds.isRegistered()) { invokeChanged(ds, ref, service); } } } public void removedService(ServiceReference ref, Object service) { boolean makeUnavailable = makeUnavailable(); Object[] services; synchronized (this) { services = m_services.toArray(); } for (int i = 0; i < services.length; i++) { DependencyService ds = (DependencyService) services[i]; if (makeUnavailable) { ds.dependencyUnavailable(this); if (!isRequired() || (ds.isInstantiated() && isInstanceBound())) { invokeRemoved(ds, ref, service); } } else { ds.dependencyChanged(this); invokeRemoved(ds, ref, service); } } // unget what we got in addingService (see ServiceTracker 701.4.1) m_context.ungetService(ref); } public void invokeAdded(DependencyService dependencyService, ServiceReference reference, Object service) { boolean added = false; synchronized (m_sr) { Set set = (Set) m_sr.get(dependencyService); if (set == null) { set = new HashSet(); m_sr.put(dependencyService, set); } added = set.add(new Tuple(reference, service)); } if (added) { // when a changed callback is specified we might not call the added callback just yet if (m_callbackSwapped != null) { handleAspectAwareAdded(dependencyService, reference, service); } else { invoke(dependencyService, reference, service, m_callbackAdded); } } } private void handleAspectAwareAdded(DependencyService dependencyService, ServiceReference reference, Object service) { if (componentIsDependencyManagerFactory(dependencyService)) { // component is either aspect or adapter factory instance, these must be ignored. return; } boolean invokeAdded = false; Integer ranking = ServiceUtil.getRankingAsInteger(reference); Tuple highestRankedService = null; synchronized (m_componentByRank) { Long originalServiceId = ServiceUtil.getServiceIdAsLong(reference); Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */ if (componentMap == null) { // create new componentMap componentMap = new HashMap(); /* <Long, Map<Integer, Tuple>> */ m_componentByRank.put(dependencyService, componentMap); } Map rankings = (Map) componentMap.get(originalServiceId); /* <Integer, Tuple> */ if (rankings == null) { // new component added rankings = new HashMap(); /* <Integer, Tuple> */ componentMap.put(originalServiceId, rankings); rankings.put(ranking, new Tuple(reference, service)); invokeAdded = true; } if (!invokeAdded) { highestRankedService = swapHighestRankedService(dependencyService, originalServiceId, reference, service, ranking); } } if (invokeAdded) { invoke(dependencyService, reference, service, m_callbackAdded); } else { invokeSwappedCallback(dependencyService, highestRankedService.getServiceReference(), highestRankedService.getService(), reference, service); } } private boolean componentIsDependencyManagerFactory(DependencyService dependencyService) { Object component = dependencyService.getService(); if (component != null) { String className = component.getClass().getName(); return className.startsWith("org.apache.felix.dm") && !className.startsWith("org.apache.felix.dm.impl.AdapterServiceImpl$AdapterImpl") && !className.startsWith("org.apache.felix.dm.test"); } return false; } private Tuple swapHighestRankedService(DependencyService dependencyService, Long serviceId, ServiceReference newReference, Object newService, Integer newRanking) { // does a component with a higher ranking exists synchronized (m_componentByRank) { Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */ Map rankings = (Map) componentMap.get(serviceId); /* <Integer, Tuple> */ Entry highestEntry = getHighestRankedService(dependencyService, serviceId); /* <Integer, Tuple> */ rankings.remove(highestEntry.getKey()); rankings.put(newRanking, new Tuple(newReference, newService)); return (Tuple) highestEntry.getValue(); } } private Entry getHighestRankedService(DependencyService dependencyService, Long serviceId) { /* <Integer, Tuple> */ Entry highestEntry = null; /* <Integer, Tuple> */ Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */ Map rankings = (Map) componentMap.get(serviceId); /* <Integer, Tuple> */ if (rankings != null) { for (Iterator entryIterator = rankings.entrySet().iterator(); entryIterator.hasNext(); ) { /* <Integer, Tuple> */ Entry mapEntry = (Entry) entryIterator.next(); if (highestEntry == null) { highestEntry = mapEntry; } else { if (((Integer)mapEntry.getKey()).intValue() > ((Integer)highestEntry.getKey()).intValue()) { highestEntry = mapEntry; } } } } return highestEntry; } private boolean isLastService(DependencyService dependencyService, ServiceReference reference, Object object, Long serviceId) { // get the collection of rankings Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */ Map rankings = null; /* <Integer, Tuple> */ if (componentMap != null) { rankings = (Map) componentMap.get(serviceId); } // if there is only one element left in the collection of rankings // and this last element has the same ranking as the supplied service (in other words, it is the same) // then this is the last service // NOTE: it is possible that there is only one element, but that it's not equal to the supplied service, // because an aspect on top of the original service is being removed (but the original service is still // there). That in turn triggers: // 1) a call to added(original-service) // 2) that causes a swap // 3) a call to removed(aspect-service) <-- that's what we're talking about return (componentMap != null && rankings != null && rankings.size() == 1 && ((Entry)rankings.entrySet().iterator().next()).getKey() .equals(ServiceUtil.getRankingAsInteger(reference))); } public void invokeChanged(DependencyService dependencyService, ServiceReference reference, Object service) { invoke(dependencyService, reference, service, m_callbackChanged); } public void invokeRemoved(DependencyService dependencyService, ServiceReference reference, Object service) { boolean removed = false; synchronized (m_sr) { Set set = (Set) m_sr.get(dependencyService); removed = (set != null && set.remove(new Tuple(reference, service))); } if (removed) { if (m_callbackSwapped != null) { handleAspectAwareRemoved(dependencyService, reference, service); } else { invoke(dependencyService, reference, service, m_callbackRemoved); } } } private void handleAspectAwareRemoved(DependencyService dependencyService, ServiceReference reference, Object service) { if (componentIsDependencyManagerFactory(dependencyService)) { // component is either aspect or adapter factory instance, these must be ignored. return; } Long serviceId = ServiceUtil.getServiceIdAsLong(reference); synchronized (m_componentByRank) { if (isLastService(dependencyService, reference, service, serviceId)) { invoke(dependencyService, reference, service, m_callbackRemoved); } Long originalServiceId = ServiceUtil.getServiceIdAsLong(reference); Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */ if (componentMap != null) { Map rankings = (Map) componentMap.get(originalServiceId); /* <Integer, Tuple> */ for (Iterator entryIterator = rankings.entrySet().iterator(); entryIterator.hasNext(); ) { Entry mapEntry = (Entry) entryIterator.next(); if (((Tuple)mapEntry.getValue()).getServiceReference().equals(reference)) { // remove the reference rankings.remove(mapEntry.getKey()); } } if (rankings.size() == 0) { componentMap.remove(originalServiceId); } if (componentMap.size() == 0) { m_componentByRank.remove(dependencyService); } } } } public void invoke(DependencyService dependencyService, ServiceReference reference, Object service, String name) { if (name != null) { dependencyService.invokeCallbackMethod(getCallbackInstances(dependencyService), name, new Class[][] { {Component.class, ServiceReference.class, m_trackedServiceName}, {Component.class, ServiceReference.class, Object.class}, {Component.class, ServiceReference.class}, {Component.class, m_trackedServiceName}, {Component.class, Object.class}, {Component.class}, {Component.class, Map.class, m_trackedServiceName}, {ServiceReference.class, m_trackedServiceName}, {ServiceReference.class, Object.class}, {ServiceReference.class}, {m_trackedServiceName}, {Object.class}, {}, {Map.class, m_trackedServiceName} }, new Object[][] { {dependencyService, reference, service}, {dependencyService, reference, service}, {dependencyService, reference}, {dependencyService, service}, {dependencyService, service}, {dependencyService}, {dependencyService, new ServicePropertiesMap(reference), service}, {reference, service}, {reference, service}, {reference}, {service}, {service}, {}, {new ServicePropertiesMap(reference), service} } ); } } private void invokeSwappedCallback(DependencyService component, ServiceReference previousReference, Object previous, ServiceReference currentServiceReference, Object current) { component.invokeCallbackMethod(getCallbackInstances(component), m_callbackSwapped, new Class[][] { { m_trackedServiceName, m_trackedServiceName }, { Object.class, Object.class }, { ServiceReference.class, m_trackedServiceName, ServiceReference.class, m_trackedServiceName }, { ServiceReference.class, Object.class, ServiceReference.class, Object.class } }, new Object[][] { { previous, current }, { previous, current }, { previousReference, previous, currentServiceReference, current }, { previousReference, previous, currentServiceReference, current } }); } protected synchronized boolean makeAvailable() { if (!isAvailable()) { m_isAvailable = true; return true; } return false; } private synchronized boolean makeUnavailable() { if ((isAvailable()) && (m_tracker.getServiceReference() == null)) { m_isAvailable = false; return true; } return false; } private synchronized Object[] getCallbackInstances(DependencyService dependencyService) { if (m_callbackInstance == null) { return dependencyService.getCompositionInstances(); } else { return new Object[] { m_callbackInstance }; } } // ----- CREATION /** * Sets the name of the service that should be tracked. * * @param serviceName the name of the service * @return this service dependency */ public synchronized ServiceDependency setService(Class serviceName) { setService(serviceName, null, null); return this; } /** * Sets the name of the service that should be tracked. You can either specify * only the name, only the filter, or the name and a filter. * <p> * If you specify name and filter, the filter is used * to track the service and should only return services of the type that was specified * in the name. To make sure of this, the filter is actually extended internally to * filter on the correct name. * <p> * If you specify only the filter, the name is assumed to be a service of type * <code>Object</code> which means that, when auto configuration is on, instances * of that service will be injected in any field of type <code>Object</code>. * * @param serviceName the name of the service * @param serviceFilter the filter condition * @return this service dependency */ public synchronized ServiceDependency setService(Class serviceName, String serviceFilter) { setService(serviceName, null, serviceFilter); return this; } /** * Sets the name of the service that should be tracked. The name is assumed to be * a service of type <code>Object</code> which means that, when auto configuration * is on, instances of that service will be injected in any field of type * <code>Object</code>. * * @param serviceFilter the filter condition * @return this service dependency */ public synchronized ServiceDependency setService(String serviceFilter) { if (serviceFilter == null) { throw new IllegalArgumentException("Service filter cannot be null."); } setService(null, null, serviceFilter); return this; } /** * Sets the name of the service that should be tracked. By specifying the service * reference of the service you want to track, you can directly track a single * service. The name you use must match the type of service referred to by the * service reference and it is up to you to make sure that is the case. * * @param serviceName the name of the service * @param serviceReference the service reference to track * @return this service dependency */ public synchronized ServiceDependency setService(Class serviceName, ServiceReference serviceReference) { setService(serviceName, serviceReference, null); return this; } /** Internal method to set the name, service reference and/or filter. */ private void setService(Class serviceName, ServiceReference serviceReference, String serviceFilter) { ensureNotActive(); if (serviceName == null) { m_trackedServiceName = Object.class; } else { m_trackedServiceName = serviceName; } if (serviceFilter != null) { m_trackedServiceFilterUnmodified = serviceFilter; if (serviceName == null) { m_trackedServiceFilter = serviceFilter; } else { m_trackedServiceFilter ="(&(" + Constants.OBJECTCLASS + "=" + serviceName.getName() + ")" + serviceFilter + ")"; } } else { m_trackedServiceFilterUnmodified = null; m_trackedServiceFilter = null; } if (serviceReference != null) { m_trackedServiceReference = serviceReference; if (serviceFilter != null) { throw new IllegalArgumentException("Cannot specify both a filter and a service reference."); } } else { m_trackedServiceReference = null; } } /** * Sets the default implementation for this service dependency. You can use this to supply * your own implementation that will be used instead of a Null Object when the dependency is * not available. This is also convenient if the service dependency is not an interface * (which would cause the Null Object creation to fail) but a class. * * @param implementation the instance to use or the class to instantiate if you want to lazily * instantiate this implementation * @return this service dependency */ public synchronized ServiceDependency setDefaultImplementation(Object implementation) { ensureNotActive(); m_defaultImplementation = implementation; return this; } /** * Sets the required flag which determines if this service is required or not. * * @param required the required flag * @return this service dependency */ public synchronized ServiceDependency setRequired(boolean required) { ensureNotActive(); setIsRequired(required); return this; } public ServiceDependency setInstanceBound(boolean isInstanceBound) { setIsInstanceBound(isInstanceBound); return this; } /** * Sets auto configuration for this service. Auto configuration allows the * dependency to fill in any attributes in the service implementation that * are of the same type as this dependency. Default is on. * * @param autoConfig the value of auto config * @return this service dependency */ public synchronized ServiceDependency setAutoConfig(boolean autoConfig) { ensureNotActive(); m_autoConfig = autoConfig; m_autoConfigInvoked = true; return this; } /** * Sets auto configuration for this service. Auto configuration allows the * dependency to fill in the attribute in the service implementation that * has the same type and instance name. * * @param instanceName the name of attribute to auto config * @return this service dependency */ public synchronized ServiceDependency setAutoConfig(String instanceName) { ensureNotActive(); m_autoConfig = (instanceName != null); m_autoConfigInstance = instanceName; m_autoConfigInvoked = true; return this; } /** * Sets the callbacks for this service. These callbacks can be used as hooks whenever a * dependency is added or removed. When you specify callbacks, the auto configuration * feature is automatically turned off, because we're assuming you don't need it in this * case. * * @param added the method to call when a service was added * @param removed the method to call when a service was removed * @return this service dependency */ public synchronized ServiceDependency setCallbacks(String added, String removed) { return setCallbacks((Object) null, added, null, removed); } /** * Sets the callbacks for this service. These callbacks can be used as hooks whenever a * dependency is added, changed or removed. When you specify callbacks, the auto * configuration feature is automatically turned off, because we're assuming you don't * need it in this case. * * @param added the method to call when a service was added * @param changed the method to call when a service was changed * @param removed the method to call when a service was removed * @return this service dependency */ public synchronized ServiceDependency setCallbacks(String added, String changed, String removed) { return setCallbacks((Object) null, added, changed, removed); } /** * Sets the callbacks for this service. These callbacks can be used as hooks whenever a * dependency is added, changed or removed. When you specify callbacks, the auto * configuration feature is automatically turned off, because we're assuming you don't * need it in this case. * @param added the method to call when a service was added * @param changed the method to call when a service was changed * @param removed the method to call when a service was removed * @param swapped the method to call when the service was swapped due to addition or * removal of an aspect * @return this service dependency */ public synchronized ServiceDependency setCallbacks(String added, String changed, String removed, String swapped) { return setCallbacks((Object) null, added, changed, removed, swapped); } /** * Sets the callbacks for this service. These callbacks can be used as hooks whenever a * dependency is added or removed. They are called on the instance you provide. When you * specify callbacks, the auto configuration feature is automatically turned off, because * we're assuming you don't need it in this case. * * @param instance the instance to call the callbacks on * @param added the method to call when a service was added * @param removed the method to call when a service was removed * @return this service dependency */ public synchronized ServiceDependency setCallbacks(Object instance, String added, String removed) { return setCallbacks(instance, added, (String) null, removed); } /** * Sets the callbacks for this service. These callbacks can be used as hooks whenever a * dependency is added, changed or removed. They are called on the instance you provide. When you * specify callbacks, the auto configuration feature is automatically turned off, because * we're assuming you don't need it in this case. * * @param instance the instance to call the callbacks on * @param added the method to call when a service was added * @param changed the method to call when a service was changed * @param removed the method to call when a service was removed * @return this service dependency */ public synchronized ServiceDependency setCallbacks(Object instance, String added, String changed, String removed) { return setCallbacks(instance, added, changed, removed, null); } /** * Sets the callbacks for this service. These callbacks can be used as hooks whenever a * dependency is added, changed or removed. When you specify callbacks, the auto * configuration feature is automatically turned off, because we're assuming you don't * need it in this case. * @param instance the instance to call the callbacks on * @param added the method to call when a service was added * @param changed the method to call when a service was changed * @param removed the method to call when a service was removed * @param swapped the method to call when the service was swapped due to addition or * removal of an aspect * @return this service dependency */ public synchronized ServiceDependency setCallbacks(Object instance, String added, String changed, String removed, String swapped) { ensureNotActive(); // if at least one valid callback is specified, we turn off auto configuration, unless // someone already explicitly invoked autoConfig if ((added != null || removed != null || changed != null || swapped != null) && ! m_autoConfigInvoked) { setAutoConfig(false); } m_callbackInstance = instance; m_callbackAdded = added; m_callbackChanged = changed; m_callbackRemoved = removed; m_callbackSwapped = swapped; return this; } private void ensureNotActive() { if (m_tracker != null) { throw new IllegalStateException("Cannot modify state while active."); } } public synchronized String toString() { return "ServiceDependency[" + m_trackedServiceName + " " + m_trackedServiceFilterUnmodified + "]"; } public String getAutoConfigName() { return m_autoConfigInstance; } public Object getAutoConfigInstance() { return lookupService(); } public Class getAutoConfigType() { return getInterface(); } public String getName() { StringBuilder sb = new StringBuilder(); if (m_trackedServiceName != null) { sb.append(m_trackedServiceName.getName()); if (m_trackedServiceFilterUnmodified != null) { sb.append(' '); sb.append(m_trackedServiceFilterUnmodified); } } if (m_trackedServiceReference != null) { sb.append("{service.id=" + m_trackedServiceReference.getProperty(Constants.SERVICE_ID)+"}"); } return sb.toString(); } public String getType() { return "service"; } public void invokeAdded(DependencyService service) { ServiceReference[] refs = m_tracker.getServiceReferences(); if (refs != null) { for (int i = 0; i < refs.length; i++) { ServiceReference sr = refs[i]; Object svc = m_context.getService(sr); invokeAdded(service, sr, svc); } } } public void invokeRemoved(DependencyService service) { Set references = null; synchronized (m_sr) { references = (Set) m_sr.get(service); } Tuple[] refs = (Tuple[]) (references != null ? references.toArray(new Tuple[references.size()]) : new Tuple[0]); for (int i = 0; i < refs.length; i++) { ServiceReference sr = refs[i].getServiceReference(); Object svc = refs[i].getService(); invokeRemoved(service, sr, svc); } if (references != null) { references.clear(); } } public Dictionary getProperties() { ServiceReference reference = lookupServiceReference(); Object service = lookupService(); if (reference != null) { if (m_propagateCallbackInstance != null && m_propagateCallbackMethod != null) { try { return (Dictionary) InvocationUtil.invokeCallbackMethod(m_propagateCallbackInstance, m_propagateCallbackMethod, new Class[][] {{ ServiceReference.class, Object.class }, { ServiceReference.class }}, new Object[][] {{ reference, service }, { reference }}); } catch (InvocationTargetException e) { m_logger.log(LogService.LOG_WARNING, "Exception while invoking callback method", e.getCause()); } catch (Exception e) { m_logger.log(LogService.LOG_WARNING, "Exception while trying to invoke callback method", e); } throw new IllegalStateException("Could not invoke callback"); } else { Properties props = new Properties(); String[] keys = reference.getPropertyKeys(); for (int i = 0; i < keys.length; i++) { if (!(keys[i].equals(Constants.SERVICE_ID) || keys[i].equals(Constants.SERVICE_PID))) { props.put(keys[i], reference.getProperty(keys[i])); } } return props; } } else { throw new IllegalStateException("cannot find service reference"); } } public boolean isPropagated() { return m_propagate; } public ServiceDependency setPropagate(boolean propagate) { ensureNotActive(); m_propagate = propagate; return this; } public ServiceDependency setPropagate(Object instance, String method) { setPropagate(instance != null && method != null); m_propagateCallbackInstance = instance; m_propagateCallbackMethod = method; return this; } }
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.client5.testing.external; import java.util.Objects; import javax.net.ssl.SSLContext; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpOptions; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HeaderElements; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.ssl.SSLContexts; import org.apache.hc.core5.util.TextUtils; import org.apache.hc.core5.util.TimeValue; public class HttpClientCompatibilityTest { public static void main(final String... args) throws Exception { final HttpClientCompatibilityTest[] tests = new HttpClientCompatibilityTest[] { new HttpClientCompatibilityTest( new HttpHost("localhost", 8080, "http"), null, null), new HttpClientCompatibilityTest( new HttpHost("test-httpd", 8080, "http"), new HttpHost("localhost", 8888), null), new HttpClientCompatibilityTest( new HttpHost("test-httpd", 8080, "http"), new HttpHost("localhost", 8889), new UsernamePasswordCredentials("squid", "nopassword".toCharArray())), new HttpClientCompatibilityTest( new HttpHost("localhost", 8443, "https"), null, null), new HttpClientCompatibilityTest( new HttpHost("test-httpd", 8443, "https"), new HttpHost("localhost", 8888), null), new HttpClientCompatibilityTest( new HttpHost("test-httpd", 8443, "https"), new HttpHost("localhost", 8889), new UsernamePasswordCredentials("squid", "nopassword".toCharArray())) }; for (final HttpClientCompatibilityTest test: tests) { try { test.execute(); } finally { test.shutdown(); } } } private final HttpHost target; private final HttpHost proxy; private final BasicCredentialsProvider credentialsProvider; private final PoolingHttpClientConnectionManager connManager; private final CloseableHttpClient client; HttpClientCompatibilityTest( final HttpHost target, final HttpHost proxy, final Credentials proxyCreds) throws Exception { this.target = target; this.proxy = proxy; this.credentialsProvider = new BasicCredentialsProvider(); final RequestConfig requestConfig = RequestConfig.custom() .setProxy(proxy) .build(); if (proxy != null && proxyCreds != null) { this.credentialsProvider.setCredentials(new AuthScope(proxy), proxyCreds); } final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(getClass().getResource("/test-ca.keystore"), "nopassword".toCharArray()).build(); this.connManager = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) .build(); this.client = HttpClients.custom() .setConnectionManager(this.connManager) .setDefaultRequestConfig(requestConfig) .build(); } void shutdown() throws Exception { client.close(); } enum TestResult {OK, NOK} private void logResult(final TestResult result, final HttpRequest request, final String message) { final StringBuilder buf = new StringBuilder(); buf.append(result); if (buf.length() == 2) { buf.append(" "); } buf.append(": ").append(target); if (proxy != null) { buf.append(" via ").append(proxy); } buf.append(": "); buf.append(request.getMethod()).append(" ").append(request.getRequestUri()); if (message != null && !TextUtils.isBlank(message)) { buf.append(" -> ").append(message); } System.out.println(buf.toString()); } void execute() { // Initial ping { final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); final HttpOptions options = new HttpOptions("*"); try (ClassicHttpResponse response = client.execute(target, options, context)) { final int code = response.getCode(); EntityUtils.consume(response.getEntity()); if (code == HttpStatus.SC_OK) { logResult(TestResult.OK, options, Objects.toString(response.getFirstHeader("server"))); } else { logResult(TestResult.NOK, options, "(status " + code + ")"); } } catch (final Exception ex) { logResult(TestResult.NOK, options, "(" + ex.getMessage() + ")"); } } // Basic GET requests { connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); final String[] requestUris = new String[] {"/", "/news.html", "/status.html"}; for (final String requestUri: requestUris) { final HttpGet httpGet = new HttpGet(requestUri); try (ClassicHttpResponse response = client.execute(target, httpGet, context)) { final int code = response.getCode(); EntityUtils.consume(response.getEntity()); if (code == HttpStatus.SC_OK) { logResult(TestResult.OK, httpGet, "200"); } else { logResult(TestResult.NOK, httpGet, "(status " + code + ")"); } } catch (final Exception ex) { logResult(TestResult.NOK, httpGet, "(" + ex.getMessage() + ")"); } } } // Wrong target auth scope { connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS); credentialsProvider.setCredentials( new AuthScope("http", "otherhost", -1, "Restricted Files", null), new UsernamePasswordCredentials("testuser", "nopassword".toCharArray())); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); final HttpGet httpGetSecret = new HttpGet("/private/big-secret.txt"); try (ClassicHttpResponse response = client.execute(target, httpGetSecret, context)) { final int code = response.getCode(); EntityUtils.consume(response.getEntity()); if (code == HttpStatus.SC_UNAUTHORIZED) { logResult(TestResult.OK, httpGetSecret, "401 (wrong target auth scope)"); } else { logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")"); } } catch (final Exception ex) { logResult(TestResult.NOK, httpGetSecret, "(" + ex.getMessage() + ")"); } } // Wrong target credentials { connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS); credentialsProvider.setCredentials( new AuthScope(target), new UsernamePasswordCredentials("testuser", "wrong password".toCharArray())); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); final HttpGet httpGetSecret = new HttpGet("/private/big-secret.txt"); try (ClassicHttpResponse response = client.execute(target, httpGetSecret, context)) { final int code = response.getCode(); EntityUtils.consume(response.getEntity()); if (code == HttpStatus.SC_UNAUTHORIZED) { logResult(TestResult.OK, httpGetSecret, "401 (wrong target creds)"); } else { logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")"); } } catch (final Exception ex) { logResult(TestResult.NOK, httpGetSecret, "(" + ex.getMessage() + ")"); } } // Correct target credentials { connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS); credentialsProvider.setCredentials( new AuthScope(target), new UsernamePasswordCredentials("testuser", "nopassword".toCharArray())); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); final HttpGet httpGetSecret = new HttpGet("/private/big-secret.txt"); try (ClassicHttpResponse response = client.execute(target, httpGetSecret, context)) { final int code = response.getCode(); EntityUtils.consume(response.getEntity()); if (code == HttpStatus.SC_OK) { logResult(TestResult.OK, httpGetSecret, "200 (correct target creds)"); } else { logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")"); } } catch (final Exception ex) { logResult(TestResult.NOK, httpGetSecret, "(" + ex.getMessage() + ")"); } } // Correct target credentials (no keep-alive) { connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS); credentialsProvider.setCredentials( new AuthScope(target), new UsernamePasswordCredentials("testuser", "nopassword".toCharArray())); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); final HttpGet httpGetSecret = new HttpGet("/private/big-secret.txt"); httpGetSecret.setHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE); try (ClassicHttpResponse response = client.execute(target, httpGetSecret, context)) { final int code = response.getCode(); EntityUtils.consume(response.getEntity()); if (code == HttpStatus.SC_OK) { logResult(TestResult.OK, httpGetSecret, "200 (correct target creds / no keep-alive)"); } else { logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")"); } } catch (final Exception ex) { logResult(TestResult.NOK, httpGetSecret, "(" + ex.getMessage() + ")"); } } } }
/* * 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.psi.impl; import com.google.common.annotations.VisibleForTesting; import com.intellij.injected.editor.DocumentWindow; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.*; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.DocumentRunnable; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.PrioritizedInternalDocumentListener; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.EditorDocumentPriorities; import com.intellij.openapi.editor.impl.FrozenDocument; import com.intellij.openapi.editor.impl.event.RetargetRangeMarkers; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.util.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.file.impl.FileManagerImpl; import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.text.BlockSupport; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.*; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.util.*; import java.util.concurrent.ConcurrentMap; public abstract class PsiDocumentManagerBase extends PsiDocumentManager implements DocumentListener, ProjectComponent { static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiDocumentManagerImpl"); private static final Key<Document> HARD_REF_TO_DOCUMENT = Key.create("HARD_REFERENCE_TO_DOCUMENT"); private final Key<PsiFile> HARD_REF_TO_PSI = Key.create("HARD_REF_TO_PSI"); // has to be different for each project to avoid mixups private static final Key<List<Runnable>> ACTION_AFTER_COMMIT = Key.create("ACTION_AFTER_COMMIT"); protected final Project myProject; private final PsiManager myPsiManager; private final DocumentCommitProcessor myDocumentCommitProcessor; protected final Set<Document> myUncommittedDocuments = ContainerUtil.newConcurrentSet(); private final Map<Document, UncommittedInfo> myUncommittedInfos = ContainerUtil.newConcurrentMap(); protected boolean myStopTrackingDocuments; private boolean myPerformBackgroundCommit = true; private volatile boolean myIsCommitInProgress; private final PsiToDocumentSynchronizer mySynchronizer; private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); protected PsiDocumentManagerBase(@NotNull final Project project, @NotNull PsiManager psiManager, @NotNull MessageBus bus, @NonNls @NotNull final DocumentCommitProcessor documentCommitProcessor) { myProject = project; myPsiManager = psiManager; myDocumentCommitProcessor = documentCommitProcessor; mySynchronizer = new PsiToDocumentSynchronizer(this, bus); myPsiManager.addPsiTreeChangeListener(mySynchronizer); bus.connect().subscribe(PsiDocumentTransactionListener.TOPIC, new PsiDocumentTransactionListener() { @Override public void transactionStarted(@NotNull Document document, @NotNull PsiFile file) { myUncommittedDocuments.remove(document); } @Override public void transactionCompleted(@NotNull Document document, @NotNull PsiFile file) { } }); } @Override @Nullable public PsiFile getPsiFile(@NotNull Document document) { if (document instanceof DocumentWindow && !((DocumentWindow)document).isValid()) { return null; } final PsiFile userData = document.getUserData(HARD_REF_TO_PSI); if (userData != null) { return ensureValidFile(userData, "From hard ref"); } PsiFile psiFile = getCachedPsiFile(document); if (psiFile != null) { return ensureValidFile(psiFile, "Cached PSI"); } final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; psiFile = getPsiFile(virtualFile); if (psiFile == null) return null; fireFileCreated(document, psiFile); return psiFile; } @NotNull private static PsiFile ensureValidFile(@NotNull PsiFile psiFile, @NotNull String debugInfo) { if (!psiFile.isValid()) throw new PsiInvalidElementAccessException(psiFile, debugInfo); return psiFile; } @Deprecated // todo remove when Database Navigator plugin doesn't need that anymore // todo to be removed in idea 17 public static void cachePsi(@NotNull Document document, @Nullable PsiFile file) { LOG.warn("Unsupported method"); } public void associatePsi(@NotNull Document document, @Nullable PsiFile file) { document.putUserData(HARD_REF_TO_PSI, file); } @Override public PsiFile getCachedPsiFile(@NotNull Document document) { final PsiFile userData = document.getUserData(HARD_REF_TO_PSI); if (userData != null) return userData; final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; return getCachedPsiFile(virtualFile); } @Nullable FileViewProvider getCachedViewProvider(@NotNull Document document) { final VirtualFile virtualFile = getVirtualFile(document); if (virtualFile == null) return null; return getCachedViewProvider(virtualFile); } private FileViewProvider getCachedViewProvider(@NotNull VirtualFile virtualFile) { return ((PsiManagerEx)myPsiManager).getFileManager().findCachedViewProvider(virtualFile); } @Nullable private static VirtualFile getVirtualFile(@NotNull Document document) { final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; return virtualFile; } @Nullable PsiFile getCachedPsiFile(@NotNull VirtualFile virtualFile) { return ((PsiManagerEx)myPsiManager).getFileManager().getCachedPsiFile(virtualFile); } @Nullable private PsiFile getPsiFile(@NotNull VirtualFile virtualFile) { return ((PsiManagerEx)myPsiManager).getFileManager().findFile(virtualFile); } @Override public Document getDocument(@NotNull PsiFile file) { if (file instanceof PsiBinaryFile) return null; Document document = getCachedDocument(file); if (document != null) { if (!file.getViewProvider().isPhysical() && document.getUserData(HARD_REF_TO_PSI) == null) { PsiUtilCore.ensureValid(file); associatePsi(document, file); } return document; } FileViewProvider viewProvider = file.getViewProvider(); if (!viewProvider.isEventSystemEnabled()) return null; document = FileDocumentManager.getInstance().getDocument(viewProvider.getVirtualFile()); if (document != null) { if (document.getTextLength() != file.getTextLength()) { String message = "Document/PSI mismatch: " + file + " (" + file.getClass() + "); physical=" + viewProvider.isPhysical(); if (document.getTextLength() + file.getTextLength() < 8096) { message += "\n=== document ===\n" + document.getText() + "\n=== PSI ===\n" + file.getText(); } throw new AssertionError(message); } if (!viewProvider.isPhysical()) { PsiUtilCore.ensureValid(file); associatePsi(document, file); file.putUserData(HARD_REF_TO_DOCUMENT, document); } } return document; } @Override public Document getCachedDocument(@NotNull PsiFile file) { if (!file.isPhysical()) return null; VirtualFile vFile = file.getViewProvider().getVirtualFile(); return FileDocumentManager.getInstance().getCachedDocument(vFile); } @Override public void commitAllDocuments() { ApplicationManager.getApplication().assertIsDispatchThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); if (myUncommittedDocuments.isEmpty()) return; final Document[] documents = getUncommittedDocuments(); for (Document document : documents) { commitDocument(document); } LOG.assertTrue(!hasUncommitedDocuments(), myUncommittedDocuments); } @Override public void performForCommittedDocument(@NotNull final Document doc, @NotNull final Runnable action) { final Document document = doc instanceof DocumentWindow ? ((DocumentWindow)doc).getDelegate() : doc; if (isCommitted(document)) { action.run(); } else { addRunOnCommit(document, action); } } private final Map<Object, Runnable> actionsWhenAllDocumentsAreCommitted = new LinkedHashMap<>(); //accessed from EDT only private static final Object PERFORM_ALWAYS_KEY = new Object() { @Override @NonNls public String toString() { return "PERFORM_ALWAYS"; } }; /** * Cancel previously registered action and schedules (new) action to be executed when all documents are committed. * * @param key the (unique) id of the action. * @param action The action to be executed after automatic commit. * This action will overwrite any action which was registered under this key earlier. * The action will be executed in EDT. * @return true if action has been run immediately, or false if action was scheduled for execution later. */ public boolean cancelAndRunWhenAllCommitted(@NonNls @NotNull Object key, @NotNull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myProject.isDisposed()) { action.run(); return true; } if (myUncommittedDocuments.isEmpty()) { if (!isCommitInProgress()) { // in case of fireWriteActionFinished() we didn't execute 'actionsWhenAllDocumentsAreCommitted' yet assert actionsWhenAllDocumentsAreCommitted.isEmpty() : actionsWhenAllDocumentsAreCommitted; } action.run(); return true; } checkWeAreOutsideAfterCommitHandler(); actionsWhenAllDocumentsAreCommitted.put(key, action); return false; } public static void addRunOnCommit(@NotNull Document document, @NotNull Runnable action) { synchronized (ACTION_AFTER_COMMIT) { List<Runnable> list = document.getUserData(ACTION_AFTER_COMMIT); if (list == null) { document.putUserData(ACTION_AFTER_COMMIT, list = new SmartList<>()); } list.add(action); } } @Override public void commitDocument(@NotNull final Document doc) { final Document document = doc instanceof DocumentWindow ? ((DocumentWindow)doc).getDelegate() : doc; if (isEventSystemEnabled(document)) { ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); } if (!isCommitted(document)) { doCommit(document); } } private boolean isEventSystemEnabled(Document document) { FileViewProvider viewProvider = getCachedViewProvider(document); return viewProvider != null && viewProvider.isEventSystemEnabled() && !SingleRootFileViewProvider.isFreeThreaded(viewProvider); } // public for Upsource public boolean finishCommit(@NotNull final Document document, @NotNull final List<Processor<Document>> finishProcessors, final boolean synchronously, @NotNull final Object reason) { assert !myProject.isDisposed() : "Already disposed"; ApplicationManager.getApplication().assertIsDispatchThread(); final boolean[] ok = {true}; Runnable runnable = new DocumentRunnable(document, myProject) { @Override public void run() { ok[0] = finishCommitInWriteAction(document, finishProcessors, synchronously); } }; if (synchronously) { runnable.run(); } else { ApplicationManager.getApplication().runWriteAction(runnable); } if (ok[0]) { // otherwise changes maybe not synced to the document yet, and injectors will crash if (!mySynchronizer.isDocumentAffectedByTransactions(document)) { InjectedLanguageManager.getInstance(myProject).startRunInjectors(document, synchronously); } // run after commit actions outside write action runAfterCommitActions(document); if (DebugUtil.DO_EXPENSIVE_CHECKS && !ApplicationInfoImpl.isInStressTest()) { checkAllElementsValid(document, reason); } } return ok[0]; } protected boolean finishCommitInWriteAction(@NotNull final Document document, @NotNull final List<Processor<Document>> finishProcessors, final boolean synchronously) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myProject.isDisposed()) return false; assert !(document instanceof DocumentWindow); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile != null) { getSmartPointerManager().fastenBelts(virtualFile); } FileViewProvider viewProvider = getCachedViewProvider(document); myIsCommitInProgress = true; boolean success = true; try { if (viewProvider != null) { success = commitToExistingPsi(document, finishProcessors, synchronously, virtualFile, viewProvider); } else { handleCommitWithoutPsi(document); } } catch (Throwable e) { forceReload(virtualFile, viewProvider); LOG.error(e); } finally { if (success) { myUncommittedDocuments.remove(document); } myIsCommitInProgress = false; } return success; } private boolean commitToExistingPsi(@NotNull Document document, @NotNull List<Processor<Document>> finishProcessors, boolean synchronously, @Nullable VirtualFile virtualFile, @NotNull FileViewProvider viewProvider) { for (Processor<Document> finishRunnable : finishProcessors) { boolean success = finishRunnable.process(document); if (synchronously) { assert success : finishRunnable + " in " + finishProcessors; } if (!success) { return false; } } clearUncommittedInfo(document); if (virtualFile != null) { getSmartPointerManager().updatePointerTargetsAfterReparse(virtualFile); } viewProvider.contentsSynchronized(); return true; } void forceReload(VirtualFile virtualFile, @Nullable FileViewProvider viewProvider) { if (viewProvider instanceof SingleRootFileViewProvider) { ((SingleRootFileViewProvider)viewProvider).markInvalidated(); } if (virtualFile != null) { ((FileManagerImpl)((PsiManagerEx)myPsiManager).getFileManager()).forceReload(virtualFile); } } private void checkAllElementsValid(@NotNull Document document, @NotNull final Object reason) { final PsiFile psiFile = getCachedPsiFile(document); if (psiFile != null) { psiFile.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (!element.isValid()) { throw new AssertionError("Commit to '" + psiFile.getVirtualFile() + "' has led to invalid element: " + element + "; Reason: '" + reason + "'"); } } }); } } private void doCommit(@NotNull final Document document) { assert !myIsCommitInProgress : "Do not call commitDocument() from inside PSI change listener"; // otherwise there are many clients calling commitAllDocs() on PSI childrenChanged() if (getSynchronizer().isDocumentAffectedByTransactions(document)) return; final PsiFile psiFile = getPsiFile(document); if (psiFile == null) { myUncommittedDocuments.remove(document); return; // the project must be closing or file deleted } Runnable runnable = () -> { myIsCommitInProgress = true; try { myDocumentCommitProcessor.commitSynchronously(document, myProject, psiFile); } finally { myIsCommitInProgress = false; } assert !isInUncommittedSet(document) : "Document :" + document; }; if (SingleRootFileViewProvider.isFreeThreaded(psiFile.getViewProvider())) { runnable.run(); } else { ApplicationManager.getApplication().runWriteAction(runnable); } } // true if the PSI is being modified and events being sent public boolean isCommitInProgress() { return myIsCommitInProgress; } @Override public <T> T commitAndRunReadAction(@NotNull final Computable<T> computation) { final Ref<T> ref = Ref.create(null); commitAndRunReadAction(() -> ref.set(computation.compute())); return ref.get(); } @Override public void reparseFiles(@NotNull Collection<VirtualFile> files, boolean includeOpenFiles) { FileContentUtilCore.reparseFiles(files); } @Override public void commitAndRunReadAction(@NotNull final Runnable runnable) { final Application application = ApplicationManager.getApplication(); if (SwingUtilities.isEventDispatchThread()) { commitAllDocuments(); runnable.run(); return; } if (ApplicationManager.getApplication().isReadAccessAllowed()) { LOG.error("Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock otherwise. "+Thread.currentThread()); } while (true) { boolean executed = application.runReadAction((Computable<Boolean>)() -> { if (myUncommittedDocuments.isEmpty()) { runnable.run(); return true; } return false; }); if (executed) break; final Semaphore semaphore = new Semaphore(); semaphore.down(); application.invokeLater(() -> { if (myProject.isDisposed()) { // committedness doesn't matter anymore; give clients a chance to do checkCanceled semaphore.up(); return; } performWhenAllCommitted(() -> semaphore.up()); }, ModalityState.any()); semaphore.waitFor(); } } /** * Schedules action to be executed when all documents are committed. * * @return true if action has been run immediately, or false if action was scheduled for execution later. */ @Override public boolean performWhenAllCommitted(@NotNull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); checkWeAreOutsideAfterCommitHandler(); assert !myProject.isDisposed() : "Already disposed: " + myProject; if (myUncommittedDocuments.isEmpty()) { action.run(); return true; } CompositeRunnable actions = (CompositeRunnable)actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY); if (actions == null) { actions = new CompositeRunnable(); actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, actions); } actions.add(action); TransactionId current = TransactionGuard.getInstance().getContextTransaction(); if (current != ModalityState.NON_MODAL) { // re-add all uncommitted documents into the queue with this new modality // because this client obviously expects them to commit even inside modal dialog for (Document document : myUncommittedDocuments) { myDocumentCommitProcessor.commitAsynchronously(myProject, document, "re-added with modality "+current+" because performWhenAllCommitted("+current+") was called", current); } } return false; } @Override public void performLaterWhenAllCommitted(@NotNull final Runnable runnable) { performLaterWhenAllCommitted(runnable, ModalityState.defaultModalityState()); } @Override public void performLaterWhenAllCommitted(@NotNull final Runnable runnable, final ModalityState modalityState) { final Runnable whenAllCommitted = () -> ApplicationManager.getApplication().invokeLater(() -> { if (hasUncommitedDocuments()) { // no luck, will try later performLaterWhenAllCommitted(runnable); } else { runnable.run(); } }, modalityState, myProject.getDisposed()); if (ApplicationManager.getApplication().isDispatchThread() && isInsideCommitHandler()) { whenAllCommitted.run(); } else { UIUtil.invokeLaterIfNeeded(() -> performWhenAllCommitted(whenAllCommitted)); } } private static class CompositeRunnable extends ArrayList<Runnable> implements Runnable { @Override public void run() { for (Runnable runnable : this) { runnable.run(); } } } private void runAfterCommitActions(@NotNull Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); List<Runnable> list; synchronized (ACTION_AFTER_COMMIT) { list = document.getUserData(ACTION_AFTER_COMMIT); if (list != null) { list = new ArrayList<>(list); document.putUserData(ACTION_AFTER_COMMIT, null); } } if (list != null) { for (final Runnable runnable : list) { runnable.run(); } } if (!hasUncommitedDocuments() && !actionsWhenAllDocumentsAreCommitted.isEmpty()) { List<Map.Entry<Object, Runnable>> entries = new ArrayList<>( new LinkedHashMap<>(actionsWhenAllDocumentsAreCommitted).entrySet()); beforeCommitHandler(); try { for (Map.Entry<Object, Runnable> entry : entries) { Runnable action = entry.getValue(); try { action.run(); } catch (ProcessCanceledException e) { // some actions are that crazy to use PCE for their own control flow. // swallow and ignore to not disrupt completely unrelated control flow. } catch (Throwable e) { LOG.error("During running " + action, e); } } } finally { actionsWhenAllDocumentsAreCommitted.clear(); } } } private void beforeCommitHandler() { actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, EmptyRunnable.getInstance()); // to prevent listeners from registering new actions during firing } private void checkWeAreOutsideAfterCommitHandler() { if (isInsideCommitHandler()) { throw new IncorrectOperationException("You must not call performWhenAllCommitted()/cancelAndRunWhenCommitted() from within after-commit handler"); } } private boolean isInsideCommitHandler() { return actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY) == EmptyRunnable.getInstance(); } @Override public void addListener(@NotNull Listener listener) { myListeners.add(listener); } @Override public void removeListener(@NotNull Listener listener) { myListeners.remove(listener); } @Override public boolean isDocumentBlockedByPsi(@NotNull Document doc) { return false; } @Override public void doPostponedOperationsAndUnblockDocument(@NotNull Document doc) { } void fireDocumentCreated(@NotNull Document document, PsiFile file) { for (Listener listener : myListeners) { listener.documentCreated(document, file); } } private void fireFileCreated(@NotNull Document document, @NotNull PsiFile file) { for (Listener listener : myListeners) { listener.fileCreated(file, document); } } @Override @NotNull public CharSequence getLastCommittedText(@NotNull Document document) { return getLastCommittedDocument(document).getImmutableCharSequence(); } @Override public long getLastCommittedStamp(@NotNull Document document) { if (document instanceof DocumentWindow) document = ((DocumentWindow)document).getDelegate(); return getLastCommittedDocument(document).getModificationStamp(); } @Override @Nullable public Document getLastCommittedDocument(@NotNull PsiFile file) { Document document = getDocument(file); return document == null ? null : getLastCommittedDocument(document); } @NotNull public DocumentEx getLastCommittedDocument(@NotNull Document document) { if (document instanceof FrozenDocument) return (DocumentEx)document; if (document instanceof DocumentWindow) { DocumentWindow window = (DocumentWindow)document; Document delegate = window.getDelegate(); if (delegate instanceof FrozenDocument) return (DocumentEx)window; if (!window.isValid()) { throw new AssertionError("host committed: " + isCommitted(delegate) + ", window=" + window); } UncommittedInfo info = myUncommittedInfos.get(delegate); DocumentWindow answer = info == null ? null : info.myFrozenWindows.get(document); if (answer == null) answer = freezeWindow(window); if (info != null) answer = ConcurrencyUtil.cacheOrGet(info.myFrozenWindows, window, answer); return (DocumentEx)answer; } assert document instanceof DocumentImpl; UncommittedInfo info = myUncommittedInfos.get(document); return info != null ? info.myFrozen : ((DocumentImpl)document).freeze(); } @NotNull protected DocumentWindow freezeWindow(@NotNull DocumentWindow document) { throw new UnsupportedOperationException(); } @NotNull public List<DocumentEvent> getEventsSinceCommit(@NotNull Document document) { assert document instanceof DocumentImpl; UncommittedInfo info = myUncommittedInfos.get(document); if (info != null) { return info.myEvents; } return Collections.emptyList(); } @Override @NotNull public Document[] getUncommittedDocuments() { ApplicationManager.getApplication().assertReadAccessAllowed(); Document[] documents = myUncommittedDocuments.toArray(new Document[myUncommittedDocuments.size()]); return ArrayUtil.stripTrailingNulls(documents); } boolean isInUncommittedSet(@NotNull Document document) { if (document instanceof DocumentWindow) document = ((DocumentWindow)document).getDelegate(); return myUncommittedDocuments.contains(document); } @Override public boolean isUncommited(@NotNull Document document) { return !isCommitted(document); } @Override public boolean isCommitted(@NotNull Document document) { if (document instanceof DocumentWindow) document = ((DocumentWindow)document).getDelegate(); if (getSynchronizer().isInSynchronization(document)) return true; return (!(document instanceof DocumentEx) || !((DocumentEx)document).isInEventsHandling()) && !isInUncommittedSet(document); } @Override public boolean hasUncommitedDocuments() { return !myIsCommitInProgress && !myUncommittedDocuments.isEmpty(); } @Override public void beforeDocumentChange(@NotNull DocumentEvent event) { if (myStopTrackingDocuments || myProject.isDisposed()) return; final Document document = event.getDocument(); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); boolean isRelevant = virtualFile != null && isRelevant(virtualFile); if (document instanceof DocumentImpl && !myUncommittedInfos.containsKey(document)) { myUncommittedInfos.put(document, new UncommittedInfo((DocumentImpl)document)); } final FileViewProvider viewProvider = getCachedViewProvider(document); boolean inMyProject = viewProvider != null && viewProvider.getManager() == myPsiManager; if (!isRelevant || !inMyProject) { return; } final List<PsiFile> files = viewProvider.getAllFiles(); PsiFile psiCause = null; for (PsiFile file : files) { if (file == null) { throw new AssertionError("View provider "+viewProvider+" ("+viewProvider.getClass()+") returned null in its files array: "+files+" for file "+viewProvider.getVirtualFile()); } if (PsiToDocumentSynchronizer.isInsideAtomicChange(file)) { psiCause = file; } } if (psiCause == null) { beforeDocumentChangeOnUnlockedDocument(viewProvider); } ((SingleRootFileViewProvider)viewProvider).beforeDocumentChanged(psiCause); } protected void beforeDocumentChangeOnUnlockedDocument(@NotNull final FileViewProvider viewProvider) { } @Override public void documentChanged(DocumentEvent event) { if (myStopTrackingDocuments || myProject.isDisposed()) return; final Document document = event.getDocument(); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); boolean isRelevant = virtualFile != null && isRelevant(virtualFile); final FileViewProvider viewProvider = getCachedViewProvider(document); if (viewProvider == null) { handleCommitWithoutPsi(document); return; } boolean inMyProject = viewProvider.getManager() == myPsiManager; if (!isRelevant || !inMyProject) { clearUncommittedInfo(document); return; } List<PsiFile> files = viewProvider.getAllFiles(); boolean commitNecessary = files.stream().noneMatch(file -> PsiToDocumentSynchronizer.isInsideAtomicChange(file) || !(file instanceof PsiFileImpl)); boolean forceCommit = ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.class) && (SystemProperties.getBooleanProperty("idea.force.commit.on.external.change", false) || ApplicationManager.getApplication().isHeadlessEnvironment() && !ApplicationManager.getApplication().isUnitTestMode()); // Consider that it's worth to perform complete re-parse instead of merge if the whole document text is replaced and // current document lines number is roughly above 5000. This makes sense in situations when external change is performed // for the huge file (that causes the whole document to be reloaded and 'merge' way takes a while to complete). if (event.isWholeTextReplaced() && document.getTextLength() > 100000) { document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE); } if (commitNecessary) { assert !(document instanceof DocumentWindow); myUncommittedDocuments.add(document); if (forceCommit) { commitDocument(document); } else if (!((DocumentEx)document).isInBulkUpdate() && myPerformBackgroundCommit) { myDocumentCommitProcessor.commitAsynchronously(myProject, document, event, TransactionGuard.getInstance().getContextTransaction()); } } else { clearUncommittedInfo(document); } } void handleCommitWithoutPsi(@NotNull Document document) { final UncommittedInfo prevInfo = clearUncommittedInfo(document); if (prevInfo == null) { return; } if (!myProject.isInitialized() || myProject.isDisposed()) { return; } myUncommittedDocuments.remove(document); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !FileIndexFacade.getInstance(myProject).isInContent(virtualFile)) { return; } final PsiFile psiFile = getPsiFile(document); if (psiFile == null) { return; } // we can end up outside write action here if the document has forUseInNonAWTThread=true ApplicationManager.getApplication().runWriteAction(new ExternalChangeAction() { @Override public void run() { FileViewProvider viewProvider = psiFile.getViewProvider(); if (viewProvider instanceof SingleRootFileViewProvider) { ((SingleRootFileViewProvider)viewProvider).onContentReload(); } else { LOG.error("Invalid view provider: " + viewProvider + " of " + viewProvider.getClass()); } } }); } @Nullable private UncommittedInfo clearUncommittedInfo(@NotNull Document document) { UncommittedInfo info = myUncommittedInfos.remove(document); if (info != null) { getSmartPointerManager().updatePointers(document, info.myFrozen, info.myEvents); info.removeListener(); } return info; } private SmartPointerManagerImpl getSmartPointerManager() { return (SmartPointerManagerImpl)SmartPointerManager.getInstance(myProject); } private boolean isRelevant(@NotNull VirtualFile virtualFile) { return !virtualFile.getFileType().isBinary() && !myProject.isDisposed(); } public static boolean checkConsistency(@NotNull PsiFile psiFile, @NotNull Document document) { //todo hack if (psiFile.getVirtualFile() == null) return true; CharSequence editorText = document.getCharsSequence(); int documentLength = document.getTextLength(); if (psiFile.textMatches(editorText)) { LOG.assertTrue(psiFile.getTextLength() == documentLength); return true; } char[] fileText = psiFile.textToCharArray(); @SuppressWarnings("NonConstantStringShouldBeStringBuffer") @NonNls String error = "File '" + psiFile.getName() + "' text mismatch after reparse. " + "File length=" + fileText.length + "; Doc length=" + documentLength + "\n"; int i = 0; for (; i < documentLength; i++) { if (i >= fileText.length) { error += "editorText.length > psiText.length i=" + i + "\n"; break; } if (i >= editorText.length()) { error += "editorText.length > psiText.length i=" + i + "\n"; break; } if (editorText.charAt(i) != fileText[i]) { error += "first unequal char i=" + i + "\n"; break; } } //error += "*********************************************" + "\n"; //if (i <= 500){ // error += "Equal part:" + editorText.subSequence(0, i) + "\n"; //} //else{ // error += "Equal part start:\n" + editorText.subSequence(0, 200) + "\n"; // error += "................................................" + "\n"; // error += "................................................" + "\n"; // error += "................................................" + "\n"; // error += "Equal part end:\n" + editorText.subSequence(i - 200, i) + "\n"; //} error += "*********************************************" + "\n"; error += "Editor Text tail:(" + (documentLength - i) + ")\n";// + editorText.subSequence(i, Math.min(i + 300, documentLength)) + "\n"; error += "*********************************************" + "\n"; error += "Psi Text tail:(" + (fileText.length - i) + ")\n"; error += "*********************************************" + "\n"; if (document instanceof DocumentWindow) { error += "doc: '" + document.getText() + "'\n"; error += "psi: '" + psiFile.getText() + "'\n"; error += "ast: '" + psiFile.getNode().getText() + "'\n"; error += psiFile.getLanguage() + "\n"; PsiElement context = InjectedLanguageManager.getInstance(psiFile.getProject()).getInjectionHost(psiFile); if (context != null) { error += "context: " + context + "; text: '" + context.getText() + "'\n"; error += "context file: " + context.getContainingFile() + "\n"; } error += "document window ranges: " + Arrays.asList(((DocumentWindow)document).getHostRanges()) + "\n"; } LOG.error(error); //document.replaceString(0, documentLength, psiFile.getText()); return false; } @VisibleForTesting public void clearUncommittedDocuments() { for (UncommittedInfo info : myUncommittedInfos.values()) { info.removeListener(); } myUncommittedInfos.clear(); myUncommittedDocuments.clear(); mySynchronizer.cleanupForNextTest(); } @TestOnly public void disableBackgroundCommit(@NotNull Disposable parentDisposable) { assert myPerformBackgroundCommit; myPerformBackgroundCommit = false; Disposer.register(parentDisposable, new Disposable() { @Override public void dispose() { myPerformBackgroundCommit = true; } }); } @Override public void projectOpened() { } @Override public void projectClosed() { } @Override public void initComponent() { } @Override public void disposeComponent() { clearUncommittedDocuments(); } @NotNull @Override public String getComponentName() { return getClass().getSimpleName(); } @NotNull public PsiToDocumentSynchronizer getSynchronizer() { return mySynchronizer; } private static class UncommittedInfo extends DocumentAdapter implements PrioritizedInternalDocumentListener { private final DocumentImpl myOriginal; private final FrozenDocument myFrozen; private final List<DocumentEvent> myEvents = ContainerUtil.newArrayList(); private final ConcurrentMap<DocumentWindow, DocumentWindow> myFrozenWindows = ContainerUtil.newConcurrentMap(); private UncommittedInfo(DocumentImpl original) { myOriginal = original; myFrozen = original.freeze(); myOriginal.addDocumentListener(this); } @Override public int getPriority() { return EditorDocumentPriorities.RANGE_MARKER; } @Override public void documentChanged(DocumentEvent e) { myEvents.add(e); } @Override public void moveTextHappened(int start, int end, int base) { myEvents.add(new RetargetRangeMarkers(myOriginal, start, end, base)); } public void removeListener() { myOriginal.removeDocumentListener(this); } } }
/* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2002 Elmar Grom * * 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.izforge.izpack.util.os; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.StringTool; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Vector; /*---------------------------------------------------------------------------*/ /** * This is the Microsoft Windows specific implementation of <code>Shortcut</code>. * * @author Elmar Grom * @version 0.0.1 / 3/4/02 */ /*---------------------------------------------------------------------------*/ public class Win_Shortcut extends Shortcut { // ------------------------------------------------------------------------ // Constant Definitions // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Variable Declarations // ------------------------------------------------------------------------ private ShellLink shortcut; private static String myClass = Win_Shortcut.class.getName() + ": "; private static final String CLASS = "Class: "; /** * SUPPORTED = true */ private static final boolean SUPPORTED = true; /*--------------------------------------------------------------------------*/ /** * This method initializes the object. It is used as a replacement for the constructor because * of the way it is instantiated through the <code>TargetFactory</code>. * * @param type the type or classification of the program group in which the link should exist. * The following types are recognized: <br> * <ul> * <li>{@link com.izforge.izpack.util.os.Shortcut#APPLICATIONS} * <li>{@link com.izforge.izpack.util.os.Shortcut#START_MENU} * <li>{@link com.izforge.izpack.util.os.Shortcut#DESKTOP} * <li>{@link com.izforge.izpack.util.os.Shortcut#START_UP} * </ul> * @param name the name of the shortcut. */ public void initialize(int type, String name) throws Exception { Debug.log(CLASS + myClass + ".initialize() '" + Integer.toString(type) + "', '" + name + "'"); switch (type) { case APPLICATIONS: { shortcut = new ShellLink(ShellLink.PROGRAM_MENU, name); break; } case START_MENU: { shortcut = new ShellLink(ShellLink.START_MENU, name); break; } case DESKTOP: { shortcut = new ShellLink(ShellLink.DESKTOP, name); break; } case START_UP: { shortcut = new ShellLink(ShellLink.STARTUP, name); break; } default: { shortcut = new ShellLink(ShellLink.PROGRAM_MENU, name); break; } } } /*--------------------------------------------------------------------------*/ /** * Returns the base path of the shortcut depending on type. The base path is the directory that * the short cut, (or its program group) will be created in. For instance, on Windows NT, a * shortcut with user-type ALL_USERS, and link-type DESKTOP might have the base path * "C:\Program&nbsp;Files\All&nbsp;Users\Desktop" * * @see #setLinkType(int) * @see #setUserType(int) * <p/> * translates from ShellLink-UserTypes to Shortcut-UserTypes. */ public String getBasePath() throws Exception { String result = shortcut.getLinkPath(shortcut.getUserType()); Debug.log(CLASS + myClass + ".getBasePath() '" + result + "'"); return result; } /** * Returns a list of currently existing program groups, based on the requested type. For example * if the type is <code>APPLICATIONS</code> then all the names of the program groups in the * Start Menu\Programs menu would be returned. * * @param userType the type of user for the program group set. (as Shortcut.utype) * @return a <code>Vector</code> of <code>String</code> objects that represent the names of * the existing program groups. It is theoretically possible that this list is empty. * @see #APPLICATIONS * @see #START_MENU */ public Vector<String> getProgramGroups(int userType) { int logentry = 0; Debug.log(CLASS + myClass + ".getProgramGroups()-" + logentry++ + " '" + Integer.toString(userType) + "'"); // ---------------------------------------------------- // translate the user type // ---------------------------------------------------- int type = ShellLink.CURRENT_USER; if (userType == ALL_USERS) { type = ShellLink.ALL_USERS; } else { type = ShellLink.CURRENT_USER; } // ---------------------------------------------------- // get a list of all files and directories that are // located at the link path. // ---------------------------------------------------- String linkPath = shortcut.getLinkPath(type); Debug.log(CLASS + myClass + ".getProgramGroups()-" + logentry++ + " '" + linkPath + "'"); // in case there is a problem obtaining a path return // an empty vector (there are no preexisting program // groups) if (linkPath == null) { return (new Vector<String>()); } File path = new File(linkPath); File[] file = path.listFiles(); // ---------------------------------------------------- // build a vector that contains only the names of // the directories. // ---------------------------------------------------- Vector<String> groups = new Vector<String>(); if (file != null) { for (File aFile : file) { String aFilename = aFile.getName(); if (aFile.isDirectory()) { Debug.log(CLASS + myClass + ".getProgramGroups()-" + logentry++ + " '" + aFilename + "'"); groups.add(aFilename); } else { Debug.log(CLASS + myClass + ".getProgramGroups()-" + logentry++ + " Skip (NoDirectory): '" + aFilename + "'"); } } } return (groups); } /*--------------------------------------------------------------------------*/ /** * Returns the fully qualified file name under which the link is saved on disk. <b>Note: </b> * this method returns valid results only if the instance was created from a file on disk or * after a successful save operation. * * @return the fully qualified file name for the shell link */ public String getFileName() { String aFilename = shortcut.getFileName(); Debug.log(CLASS + myClass + ".getFileName() '" + aFilename + "'"); return (aFilename); } /*--------------------------------------------------------------------------*/ /** * Returns the path of the directory where the link file is stored, if it was necessary during * the previous save operation to create the directory. This method returns <code>null</code> * if no save operation was carried out or there was no need to create a directory during the * previous save operation. * * @return the path of the directory where the link file is stored or <code>null</code> if no * save operation was carried out or there was no need to create a directory during the previous * save operation. */ public String getDirectoryCreated() { String directoryCreated = shortcut.getDirectoryCreated(); Debug.log(CLASS + myClass + ".getDirectoryCreated() '" + directoryCreated + "'"); return (directoryCreated); } /*--------------------------------------------------------------------------*/ /** * Returns <code>true</code> if the target OS supports current user and all users. * * @return <code>true</code> if the target OS supports current and all users. */ public boolean multipleUsers() { boolean result = false; // Win NT4 won't have PROGRAMS for CURRENT_USER. // Win 98 may not have 'Start Menu\Programs' for ALL_USERS String allUsers = shortcut.getallUsersLinkPath(); Debug.log(CLASS + myClass + ".multipleUsers()-1 '" + allUsers + "'"); String currentUsers = shortcut.getcurrentUserLinkPath(); Debug.log(CLASS + myClass + ".multipleUsers()-2 '" + currentUsers + "'"); if (allUsers == null || currentUsers == null) { result = false; } else { result = allUsers.length() > 0 && currentUsers.length() > 0; } Debug.log(CLASS + myClass + ".multipleUsers()-3 '" + result + "'"); return (result); } /*--------------------------------------------------------------------------*/ /** * Signals that this flavor of <code>{@link com.izforge.izpack.util.os.Shortcut}</code> * supports the creation of shortcuts. * * @return always <code>true</code> */ public boolean supported() { Debug.log(CLASS + myClass + ".supported() '" + SUPPORTED + "'"); return (SUPPORTED); } /*--------------------------------------------------------------------------*/ /** * Sets the command line arguments that will be passed to the target when the link is activated. * * @param arguments the command line arguments */ public void setArguments(String arguments) { Debug.log(CLASS + myClass + ".setArguments() '" + arguments + "'"); shortcut.setArguments(arguments); } /*--------------------------------------------------------------------------*/ /** * Sets the description string that is used to identify the link in a menu or on the desktop. * * @param description the descriptiojn string */ public void setDescription(String description) { Debug.log(CLASS + myClass + ".setDescription() '" + description + "'"); shortcut.setDescription(description); } /*--------------------------------------------------------------------------*/ /** * Sets the location of the icon that is shown for the shortcut on the desktop. * * @param path a fully qualified file name of a file that contains the icon. * @param index the index of the specific icon to use in the file. If there is only one icon in * the file, use an index of 0. */ public void setIconLocation(String path, int index) { Debug.log(CLASS + myClass + ".setIconLocation() '" + path + "', '" + Integer.toString(index) + "'"); shortcut.setIconLocation(path, index); } /*--------------------------------------------------------------------------*/ /** * returns icon Location * * @return iconLocation */ public String getIconLocation() { String result = shortcut.getIconLocation(); Debug.log(CLASS + myClass + ".getIconLocation() '" + result + "'"); return result; } /*--------------------------------------------------------------------------*/ /** * Sets the name of the program group this ShellLinbk should be placed in. * * @param groupName the name of the program group */ public void setProgramGroup(String groupName) { Debug.log(CLASS + myClass + ".setProgramGroup() '" + groupName + "'"); shortcut.setProgramGroup(groupName); } /*--------------------------------------------------------------------------*/ /** * Sets the show command that is passed to the target application when the link is activated. * The show command determines if the the window will be restored to the previous size, * minimized, maximized or visible at all. <br> * <br> * <b>Note: </b> <br> * Using <code>HIDE</code> will cause the target window not to show at all. There is not even * a button on the taskbar. This is a very useful setting when batch files are used to launch a * Java application as it will then appear to run just like any native Windows application. <br> * * @param show the show command. Valid settings are: <br> * <ul> * <li>{@link com.izforge.izpack.util.os.Shortcut#HIDE} * <li>{@link com.izforge.izpack.util.os.Shortcut#NORMAL} * <li>{@link com.izforge.izpack.util.os.Shortcut#MINIMIZED} * <li>{@link com.izforge.izpack.util.os.Shortcut#MAXIMIZED} * </ul> * @see #getShowCommand internally maps from Shortcut. to ShellLink. */ public void setShowCommand(int show) throws IllegalArgumentException { Debug.log(CLASS + myClass + ".setShowCommand() '" + Integer.toString(show) + "'"); switch (show) { case HIDE: { shortcut.setShowCommand(ShellLink.MINNOACTIVE); break; } case NORMAL: { shortcut.setShowCommand(ShellLink.NORMAL); break; } case MINIMIZED: { shortcut.setShowCommand(ShellLink.MINNOACTIVE); break; } case MAXIMIZED: { shortcut.setShowCommand(ShellLink.MAXIMIZED); break; } default: { throw (new IllegalArgumentException(show + "is not recognized as a show command")); } } } /* * returns current showCommand. internally maps from ShellLink. to Shortcut. * */ public int getShowCommand() { int showCommand = shortcut.getShowCommand(); Debug.log(CLASS + myClass + ".getShowCommand() '" + Integer.toString(showCommand) + "'"); switch (showCommand) { case ShellLink.NORMAL: showCommand = NORMAL; break; // both MINNOACTIVE and MINIMIZED map to Shortcut.MINIMIZED case ShellLink.MINNOACTIVE: case ShellLink.MINIMIZED: showCommand = MINIMIZED; break; case ShellLink.MAXIMIZED: showCommand = MAXIMIZED; break; default: break; } return showCommand; } /*--------------------------------------------------------------------------*/ /** * Sets the absolute path to the shortcut target. * * @param path the fully qualified file name of the target */ public void setTargetPath(String path) { Debug.log(CLASS + myClass + ".setTargetPath() '" + path + "'"); shortcut.setTargetPath(path); } /*--------------------------------------------------------------------------*/ /** * Sets the working directory for the link target. * * @param dir the working directory */ public void setWorkingDirectory(String dir) { Debug.log(CLASS + myClass + ".setWorkingDirectory() '" + dir + "'"); shortcut.setWorkingDirectory(dir); } /*--------------------------------------------------------------------------*/ /** * Gets the working directory for the link target. * * @return the working directory. */ public String getWorkingDirectory() { String result = shortcut.getWorkingDirectory(); Debug.log(CLASS + myClass + ".getWorkingDirectory() '" + result + "'"); return result; } /*--------------------------------------------------------------------------*/ /** * Sets the name shown in a menu or on the desktop for the link. * * @param name The name that the link should display on a menu or on the desktop. Do not include * a file extension. */ public void setLinkName(String name) { Debug.log(CLASS + myClass + ".setLinkName() '" + name + "'"); shortcut.setLinkName(name); } /*--------------------------------------------------------------------------*/ /** * Gets the type of link types are: <br> * <ul> * <li>{@link com.izforge.izpack.util.os.Shortcut#DESKTOP} * <li>{@link com.izforge.izpack.util.os.Shortcut#APPLICATIONS} * <li>{@link com.izforge.izpack.util.os.Shortcut#START_MENU} * <li>{@link com.izforge.izpack.util.os.Shortcut#START_UP} * </ul> * maps from ShellLink-types to Shortcut-types. */ public int getLinkType() { int typ = shortcut.getLinkType(); Debug.log(CLASS + myClass + ".getLinkType() '" + typ + "'"); switch (typ) { case ShellLink.DESKTOP: typ = DESKTOP; break; case ShellLink.PROGRAM_MENU: typ = APPLICATIONS; break; case ShellLink.START_MENU: typ = START_MENU; break; case ShellLink.STARTUP: typ = START_UP; break; default: break; } return typ; } /*--------------------------------------------------------------------------*/ /** * Sets the type of link * * @param type The type of link desired. The following values can be set: <br> * (note APPLICATION on Windows is 'Start Menu\Programs') APPLICATION is a Mac term. * <ul> * <li>{@link com.izforge.izpack.util.os.Shortcut#DESKTOP} * <li>{@link com.izforge.izpack.util.os.Shortcut#APPLICATIONS} * <li>{@link com.izforge.izpack.util.os.Shortcut#START_MENU} * <li>{@link com.izforge.izpack.util.os.Shortcut#START_UP} * </ul> * @throws IllegalArgumentException if an an invalid type is passed * @throws UnsupportedEncodingException */ public void setLinkType(int type) throws IllegalArgumentException, UnsupportedEncodingException { Debug.log(CLASS + myClass + ".setLinkType() '" + type + "'"); switch (type) { case DESKTOP: { shortcut.setLinkType(ShellLink.DESKTOP); break; } case APPLICATIONS: { shortcut.setLinkType(ShellLink.PROGRAM_MENU); break; } case START_MENU: { shortcut.setLinkType(ShellLink.START_MENU); break; } case START_UP: { shortcut.setLinkType(ShellLink.STARTUP); break; } default: { throw (new IllegalArgumentException(type + "is not recognized as a valid link type")); } } } /*--------------------------------------------------------------------------*/ /** * Gets the user type for the link * * @return userType * @see #CURRENT_USER * @see #ALL_USERS */ public int getUserType() { int utype = shortcut.getUserType(); Debug.log(CLASS + myClass + ".getUserType() '" + utype + "'"); switch (utype) { case ShellLink.ALL_USERS: utype = ALL_USERS; break; case ShellLink.CURRENT_USER: utype = CURRENT_USER; break; } return utype; } /*--------------------------------------------------------------------------*/ /** * Sets the user type for the link * * @param type the type of user for the link. * @see Shortcut#CURRENT_USER * @see Shortcut#ALL_USERS * <p/> * if the linkPath for that type is empty, refuse to set. */ /*--------------------------------------------------------------------------*/ public void setUserType(int type) { Debug.log(CLASS + myClass + ".setUserType() '" + type + "'"); if (type == CURRENT_USER) { if (shortcut.getcurrentUserLinkPath().length() > 0) { shortcut.setUserType(ShellLink.CURRENT_USER); } } else if (type == ALL_USERS) { if (shortcut.getallUsersLinkPath().length() > 0) { shortcut.setUserType(ShellLink.ALL_USERS); } } } /*--------------------------------------------------------------------------*/ /** * Saves this link. * * @throws Exception if problems are encountered */ public void save() throws Exception { shortcut.save(); } /*--------------------------------------------------------------------------*/ /** * Gets the link hotKey * * @return int hotKey */ public int getHotkey() { int result = shortcut.getHotkey(); Debug.log(CLASS + myClass + ".getHotkey() '" + result + "'"); return result; } /*--------------------------------------------------------------------------*/ /** * Sets the link hotKey * * @param hotkey incoming 2 byte hotkey is: high byte modifier: SHIFT = 0x01 CONTROL= 0x02 ALT = 0x04 EXT = * 0x08 * <p/> * lower byte contains ascii letter. ie 0x0278 represents CTRL+x 0x068a represents CTRL+ALT+z */ public void setHotkey(int hotkey) { Debug.log(CLASS + myClass + ".setHotkey() '" + hotkey + "'"); shortcut.setHotkey(hotkey); } /** * Gets the Folders where to place the program-groups and their shortcuts, for the given * usertype. * * @see com.izforge.izpack.util.os.Shortcut#getProgramsFolder(int) */ public String getProgramsFolder(int current_user) { /** CURRENT_USER = 0; the constant to use for selecting the current user. */ int USER = 0; if (current_user == Shortcut.CURRENT_USER) { USER = ShellLink.CURRENT_USER; } else if (current_user == Shortcut.ALL_USERS) { USER = ShellLink.ALL_USERS; } String result = null; try { result = new String(shortcut.getLinkPath(USER).getBytes(StringTool.getPlatformEncoding()), StringTool.getPlatformEncoding()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Debug.log(CLASS + myClass + ".getProgramsFolder() '" + current_user + "', '" + result + "'"); return result; } } /*---------------------------------------------------------------------------*/
package android.support.v7.internal.widget; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.res.Configuration; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.support.v4.view.NestedScrollingParent; import android.support.v4.view.NestedScrollingParentHelper; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorCompat; import android.support.v4.view.ViewPropertyAnimatorListener; import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; import android.support.v4.widget.ScrollerCompat; import android.support.v7.appcompat.R.attr; import android.support.v7.appcompat.R.id; import android.support.v7.internal.view.menu.MenuPresenter.Callback; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.Window.Callback; public class ActionBarOverlayLayout extends ViewGroup implements NestedScrollingParent, DecorContentParent { static final int[] ATTRS; private final int ACTION_BAR_ANIMATE_DELAY = 600; private int mActionBarHeight; private ActionBarContainer mActionBarTop; private ActionBarVisibilityCallback mActionBarVisibilityCallback; private final Runnable mAddActionBarHideOffset = new Runnable() { public final void run() { ActionBarOverlayLayout.this.haltActionBarHideOffsetAnimations(); ActionBarOverlayLayout.access$002(ActionBarOverlayLayout.this, ViewCompat.animate(ActionBarOverlayLayout.this.mActionBarTop).translationY(-ActionBarOverlayLayout.this.mActionBarTop.getHeight()).setListener(ActionBarOverlayLayout.this.mTopAnimatorListener)); } }; private boolean mAnimatingForFling; private final Rect mBaseContentInsets = new Rect(); private final Rect mBaseInnerInsets = new Rect(); private ContentFrameLayout mContent; private final Rect mContentInsets = new Rect(); private ViewPropertyAnimatorCompat mCurrentActionBarTopAnimator; private DecorToolbar mDecorToolbar; private ScrollerCompat mFlingEstimator; private boolean mHasNonEmbeddedTabs; private boolean mHideOnContentScroll; private int mHideOnContentScrollReference; private boolean mIgnoreWindowContentOverlay; private final Rect mInnerInsets = new Rect(); private final Rect mLastBaseContentInsets = new Rect(); private final Rect mLastInnerInsets = new Rect(); private int mLastSystemUiVisibility; public boolean mOverlayMode; private final NestedScrollingParentHelper mParentHelper; private final Runnable mRemoveActionBarHideOffset = new Runnable() { public final void run() { ActionBarOverlayLayout.this.haltActionBarHideOffsetAnimations(); ActionBarOverlayLayout.access$002(ActionBarOverlayLayout.this, ViewCompat.animate(ActionBarOverlayLayout.this.mActionBarTop).translationY(0.0F).setListener(ActionBarOverlayLayout.this.mTopAnimatorListener)); } }; private final ViewPropertyAnimatorListener mTopAnimatorListener = new ViewPropertyAnimatorListenerAdapter() { public final void onAnimationCancel(View paramAnonymousView) { ActionBarOverlayLayout.access$002(ActionBarOverlayLayout.this, null); ActionBarOverlayLayout.access$102$d909110(ActionBarOverlayLayout.this); } public final void onAnimationEnd(View paramAnonymousView) { ActionBarOverlayLayout.access$002(ActionBarOverlayLayout.this, null); ActionBarOverlayLayout.access$102$d909110(ActionBarOverlayLayout.this); } }; private Drawable mWindowContentOverlay; private int mWindowVisibility = 0; static { int[] arrayOfInt = new int[2]; arrayOfInt[0] = R.attr.actionBarSize; arrayOfInt[1] = 16842841; ATTRS = arrayOfInt; } public ActionBarOverlayLayout(Context paramContext) { this(paramContext, null); } public ActionBarOverlayLayout(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); init(paramContext); this.mParentHelper = new NestedScrollingParentHelper(this); } private static boolean applyInsets$614d7dc0(View paramView, Rect paramRect, boolean paramBoolean) { LayoutParams localLayoutParams = (LayoutParams)paramView.getLayoutParams(); int i = localLayoutParams.leftMargin; int j = paramRect.left; boolean bool = false; if (i != j) { bool = true; localLayoutParams.leftMargin = paramRect.left; } if (localLayoutParams.topMargin != paramRect.top) { bool = true; localLayoutParams.topMargin = paramRect.top; } if (localLayoutParams.rightMargin != paramRect.right) { bool = true; localLayoutParams.rightMargin = paramRect.right; } if ((paramBoolean) && (localLayoutParams.bottomMargin != paramRect.bottom)) { bool = true; localLayoutParams.bottomMargin = paramRect.bottom; } return bool; } private void haltActionBarHideOffsetAnimations() { removeCallbacks(this.mRemoveActionBarHideOffset); removeCallbacks(this.mAddActionBarHideOffset); if (this.mCurrentActionBarTopAnimator != null) { this.mCurrentActionBarTopAnimator.cancel(); } } private void init(Context paramContext) { int i = 1; TypedArray localTypedArray = getContext().getTheme().obtainStyledAttributes(ATTRS); this.mActionBarHeight = localTypedArray.getDimensionPixelSize(0, 0); this.mWindowContentOverlay = localTypedArray.getDrawable(i); if (this.mWindowContentOverlay == null) { int j = i; setWillNotDraw(j); localTypedArray.recycle(); if (paramContext.getApplicationInfo().targetSdkVersion >= 19) { break label88; } } for (;;) { this.mIgnoreWindowContentOverlay = i; this.mFlingEstimator = ScrollerCompat.create(paramContext, null); return; int k = 0; break; label88: i = 0; } } private void pullChildren() { View localView; if (this.mContent == null) { this.mContent = ((ContentFrameLayout)findViewById(R.id.action_bar_activity_content)); this.mActionBarTop = ((ActionBarContainer)findViewById(R.id.action_bar_container)); localView = findViewById(R.id.action_bar); if (!(localView instanceof DecorToolbar)) { break label61; } } for (DecorToolbar localDecorToolbar = (DecorToolbar)localView;; localDecorToolbar = ((Toolbar)localView).getWrapper()) { this.mDecorToolbar = localDecorToolbar; return; label61: if (!(localView instanceof Toolbar)) { break; } } throw new IllegalStateException("Can't make a decor toolbar out of " + localView.getClass().getSimpleName()); } public final boolean canShowOverflowMenu() { pullChildren(); return this.mDecorToolbar.canShowOverflowMenu(); } protected boolean checkLayoutParams(ViewGroup.LayoutParams paramLayoutParams) { return paramLayoutParams instanceof LayoutParams; } public final void dismissPopups() { pullChildren(); this.mDecorToolbar.dismissPopupMenus(); } public void draw(Canvas paramCanvas) { super.draw(paramCanvas); if ((this.mWindowContentOverlay != null) && (!this.mIgnoreWindowContentOverlay)) { if (this.mActionBarTop.getVisibility() != 0) { break label82; } } label82: for (int i = (int)(0.5F + (this.mActionBarTop.getBottom() + ViewCompat.getTranslationY(this.mActionBarTop)));; i = 0) { this.mWindowContentOverlay.setBounds(0, i, getWidth(), i + this.mWindowContentOverlay.getIntrinsicHeight()); this.mWindowContentOverlay.draw(paramCanvas); return; } } protected boolean fitSystemWindows(Rect paramRect) { pullChildren(); ViewCompat.getWindowSystemUiVisibility(this); boolean bool = applyInsets$614d7dc0(this.mActionBarTop, paramRect, false); this.mBaseInnerInsets.set(paramRect); ViewUtils.computeFitSystemWindows(this, this.mBaseInnerInsets, this.mBaseContentInsets); if (!this.mLastBaseContentInsets.equals(this.mBaseContentInsets)) { bool = true; this.mLastBaseContentInsets.set(this.mBaseContentInsets); } if (bool) { requestLayout(); } return true; } protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams paramLayoutParams) { return new LayoutParams(paramLayoutParams); } public int getActionBarHideOffset() { if (this.mActionBarTop != null) { return -(int)ViewCompat.getTranslationY(this.mActionBarTop); } return 0; } public int getNestedScrollAxes() { return this.mParentHelper.mNestedScrollAxes; } public CharSequence getTitle() { pullChildren(); return this.mDecorToolbar.getTitle(); } public final boolean hideOverflowMenu() { pullChildren(); return this.mDecorToolbar.hideOverflowMenu(); } public final void initFeature(int paramInt) { pullChildren(); switch (paramInt) { default: return; case 2: this.mDecorToolbar.initProgress(); return; case 5: this.mDecorToolbar.initIndeterminateProgress(); return; } setOverlayMode(true); } public final boolean isOverflowMenuShowPending() { pullChildren(); return this.mDecorToolbar.isOverflowMenuShowPending(); } public final boolean isOverflowMenuShowing() { pullChildren(); return this.mDecorToolbar.isOverflowMenuShowing(); } protected void onConfigurationChanged(Configuration paramConfiguration) { if (Build.VERSION.SDK_INT >= 8) { super.onConfigurationChanged(paramConfiguration); } init(getContext()); ViewCompat.requestApplyInsets(this); } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); haltActionBarHideOffsetAnimations(); } protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i = getChildCount(); int j = getPaddingLeft(); getPaddingRight(); int k = getPaddingTop(); getPaddingBottom(); for (int m = 0; m < i; m++) { View localView = getChildAt(m); if (localView.getVisibility() != 8) { LayoutParams localLayoutParams = (LayoutParams)localView.getLayoutParams(); int n = localView.getMeasuredWidth(); int i1 = localView.getMeasuredHeight(); int i2 = j + localLayoutParams.leftMargin; int i3 = k + localLayoutParams.topMargin; localView.layout(i2, i3, i2 + n, i3 + i1); } } } protected void onMeasure(int paramInt1, int paramInt2) { pullChildren(); measureChildWithMargins(this.mActionBarTop, paramInt1, 0, paramInt2, 0); LayoutParams localLayoutParams1 = (LayoutParams)this.mActionBarTop.getLayoutParams(); int i = Math.max(0, this.mActionBarTop.getMeasuredWidth() + localLayoutParams1.leftMargin + localLayoutParams1.rightMargin); int j = Math.max(0, this.mActionBarTop.getMeasuredHeight() + localLayoutParams1.topMargin + localLayoutParams1.bottomMargin); int k = ViewUtils.combineMeasuredStates(0, ViewCompat.getMeasuredState(this.mActionBarTop)); int m; int i1; label137: Rect localRect4; if ((0x100 & ViewCompat.getWindowSystemUiVisibility(this)) != 0) { m = 1; if (m == 0) { break label419; } i1 = this.mActionBarHeight; if ((this.mHasNonEmbeddedTabs) && (this.mActionBarTop.getTabContainer() != null)) { i1 += this.mActionBarHeight; } this.mContentInsets.set(this.mBaseContentInsets); this.mInnerInsets.set(this.mBaseInnerInsets); if ((this.mOverlayMode) || (m != 0)) { break label450; } Rect localRect3 = this.mContentInsets; localRect3.top = (i1 + localRect3.top); localRect4 = this.mContentInsets; } label419: label450: Rect localRect2; for (localRect4.bottom = (0 + localRect4.bottom);; localRect2.bottom = (0 + localRect2.bottom)) { applyInsets$614d7dc0(this.mContent, this.mContentInsets, true); if (!this.mLastInnerInsets.equals(this.mInnerInsets)) { this.mLastInnerInsets.set(this.mInnerInsets); this.mContent.dispatchFitSystemWindows(this.mInnerInsets); } measureChildWithMargins(this.mContent, paramInt1, 0, paramInt2, 0); LayoutParams localLayoutParams2 = (LayoutParams)this.mContent.getLayoutParams(); int i2 = Math.max(i, this.mContent.getMeasuredWidth() + localLayoutParams2.leftMargin + localLayoutParams2.rightMargin); int i3 = Math.max(j, this.mContent.getMeasuredHeight() + localLayoutParams2.topMargin + localLayoutParams2.bottomMargin); int i4 = ViewUtils.combineMeasuredStates(k, ViewCompat.getMeasuredState(this.mContent)); int i5 = i2 + (getPaddingLeft() + getPaddingRight()); int i6 = Math.max(i3 + (getPaddingTop() + getPaddingBottom()), getSuggestedMinimumHeight()); setMeasuredDimension(ViewCompat.resolveSizeAndState(Math.max(i5, getSuggestedMinimumWidth()), paramInt1, i4), ViewCompat.resolveSizeAndState(i6, paramInt2, i4 << 16)); return; m = 0; break; int n = this.mActionBarTop.getVisibility(); i1 = 0; if (n == 8) { break label137; } i1 = this.mActionBarTop.getMeasuredHeight(); break label137; Rect localRect1 = this.mInnerInsets; localRect1.top = (i1 + localRect1.top); localRect2 = this.mInnerInsets; } } public boolean onNestedFling(View paramView, float paramFloat1, float paramFloat2, boolean paramBoolean) { if ((!this.mHideOnContentScroll) || (!paramBoolean)) { return false; } this.mFlingEstimator.fling$69c647f5(0, (int)paramFloat2, 0, 0); int i = this.mFlingEstimator.getFinalY(); int j = this.mActionBarTop.getHeight(); int k = 0; if (i > j) { k = 1; } if (k != 0) { haltActionBarHideOffsetAnimations(); this.mAddActionBarHideOffset.run(); } for (;;) { this.mAnimatingForFling = true; return true; haltActionBarHideOffsetAnimations(); this.mRemoveActionBarHideOffset.run(); } } public boolean onNestedPreFling(View paramView, float paramFloat1, float paramFloat2) { return false; } public void onNestedPreScroll(View paramView, int paramInt1, int paramInt2, int[] paramArrayOfInt) {} public void onNestedScroll(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { this.mHideOnContentScrollReference = (paramInt2 + this.mHideOnContentScrollReference); setActionBarHideOffset(this.mHideOnContentScrollReference); } public void onNestedScrollAccepted(View paramView1, View paramView2, int paramInt) { this.mParentHelper.mNestedScrollAxes = paramInt; this.mHideOnContentScrollReference = getActionBarHideOffset(); haltActionBarHideOffsetAnimations(); if (this.mActionBarVisibilityCallback != null) { this.mActionBarVisibilityCallback.onContentScrollStarted(); } } public boolean onStartNestedScroll(View paramView1, View paramView2, int paramInt) { if (((paramInt & 0x2) == 0) || (this.mActionBarTop.getVisibility() != 0)) { return false; } return this.mHideOnContentScroll; } public void onStopNestedScroll(View paramView) { if ((this.mHideOnContentScroll) && (!this.mAnimatingForFling)) { if (this.mHideOnContentScrollReference <= this.mActionBarTop.getHeight()) { haltActionBarHideOffsetAnimations(); postDelayed(this.mRemoveActionBarHideOffset, 600L); } } else { return; } haltActionBarHideOffsetAnimations(); postDelayed(this.mAddActionBarHideOffset, 600L); } public void onWindowSystemUiVisibilityChanged(int paramInt) { boolean bool1 = true; if (Build.VERSION.SDK_INT >= 16) { super.onWindowSystemUiVisibilityChanged(paramInt); } pullChildren(); int i = paramInt ^ this.mLastSystemUiVisibility; this.mLastSystemUiVisibility = paramInt; boolean bool2; boolean bool3; if ((paramInt & 0x4) == 0) { bool2 = bool1; if ((paramInt & 0x100) == 0) { break label122; } bool3 = bool1; label51: if (this.mActionBarVisibilityCallback != null) { ActionBarVisibilityCallback localActionBarVisibilityCallback = this.mActionBarVisibilityCallback; if (bool3) { break label128; } label69: localActionBarVisibilityCallback.enableContentAnimations(bool1); if ((!bool2) && (bool3)) { break label133; } this.mActionBarVisibilityCallback.showForSystem(); } } for (;;) { if (((i & 0x100) != 0) && (this.mActionBarVisibilityCallback != null)) { ViewCompat.requestApplyInsets(this); } return; bool2 = false; break; label122: bool3 = false; break label51; label128: bool1 = false; break label69; label133: this.mActionBarVisibilityCallback.hideForSystem(); } } protected void onWindowVisibilityChanged(int paramInt) { super.onWindowVisibilityChanged(paramInt); this.mWindowVisibility = paramInt; if (this.mActionBarVisibilityCallback != null) { this.mActionBarVisibilityCallback.onWindowVisibilityChanged(paramInt); } } public void setActionBarHideOffset(int paramInt) { haltActionBarHideOffsetAnimations(); int i = Math.max(0, Math.min(paramInt, this.mActionBarTop.getHeight())); ViewCompat.setTranslationY(this.mActionBarTop, -i); } public void setActionBarVisibilityCallback(ActionBarVisibilityCallback paramActionBarVisibilityCallback) { this.mActionBarVisibilityCallback = paramActionBarVisibilityCallback; if (getWindowToken() != null) { this.mActionBarVisibilityCallback.onWindowVisibilityChanged(this.mWindowVisibility); if (this.mLastSystemUiVisibility != 0) { onWindowSystemUiVisibilityChanged(this.mLastSystemUiVisibility); ViewCompat.requestApplyInsets(this); } } } public void setHasNonEmbeddedTabs(boolean paramBoolean) { this.mHasNonEmbeddedTabs = paramBoolean; } public void setHideOnContentScrollEnabled(boolean paramBoolean) { if (paramBoolean != this.mHideOnContentScroll) { this.mHideOnContentScroll = paramBoolean; if (!paramBoolean) { haltActionBarHideOffsetAnimations(); setActionBarHideOffset(0); } } } public void setIcon(int paramInt) { pullChildren(); this.mDecorToolbar.setIcon(paramInt); } public void setIcon(Drawable paramDrawable) { pullChildren(); this.mDecorToolbar.setIcon(paramDrawable); } public void setLogo(int paramInt) { pullChildren(); this.mDecorToolbar.setLogo(paramInt); } public final void setMenu(Menu paramMenu, MenuPresenter.Callback paramCallback) { pullChildren(); this.mDecorToolbar.setMenu(paramMenu, paramCallback); } public final void setMenuPrepared() { pullChildren(); this.mDecorToolbar.setMenuPrepared(); } public void setOverlayMode(boolean paramBoolean) { this.mOverlayMode = paramBoolean; if ((paramBoolean) && (getContext().getApplicationInfo().targetSdkVersion < 19)) {} for (boolean bool = true;; bool = false) { this.mIgnoreWindowContentOverlay = bool; return; } } public void setShowingForActionMode(boolean paramBoolean) {} public void setUiOptions(int paramInt) {} public void setWindowCallback(Window.Callback paramCallback) { pullChildren(); this.mDecorToolbar.setWindowCallback(paramCallback); } public void setWindowTitle(CharSequence paramCharSequence) { pullChildren(); this.mDecorToolbar.setWindowTitle(paramCharSequence); } public boolean shouldDelayChildPressedState() { return false; } public final boolean showOverflowMenu() { pullChildren(); return this.mDecorToolbar.showOverflowMenu(); } public static abstract interface ActionBarVisibilityCallback { public abstract void enableContentAnimations(boolean paramBoolean); public abstract void hideForSystem(); public abstract void onContentScrollStarted(); public abstract void onWindowVisibilityChanged(int paramInt); public abstract void showForSystem(); } public static final class LayoutParams extends ViewGroup.MarginLayoutParams { public LayoutParams() { super(-1); } public LayoutParams(Context paramContext, AttributeSet paramAttributeSet) { super(paramAttributeSet); } public LayoutParams(ViewGroup.LayoutParams paramLayoutParams) { super(); } } } /* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar * Qualified Name: android.support.v7.internal.widget.ActionBarOverlayLayout * JD-Core Version: 0.7.0.1 */
/** * @author Jeremy Rayner */ package org.codehaus.groovy.tck; import java.io.*; import java.nio.charset.Charset; import org.apache.tools.ant.*; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.*; import org.apache.tools.ant.util.*; /** * Generates test files. This task can take the following * arguments: * <ul> * <li>sourcedir * <li>destdir * </ul> * Both are required. * <p> * When this task executes, it will recursively scan the sourcedir * looking for source files to expand into testcases. This task makes its * generation decision based on timestamp. * * Based heavily on the Javac implementation in Ant * * @author <a href="mailto:jeremy.rayner@bigfoot.com">Jeremy Rayner</a> * @version $Revision$ */ public class GenerateTestCases extends MatchingTask { private BatchGenerate batchGenerate = new BatchGenerate(); private Path src; private File destDir; private Path compileClasspath; private Path compileSourcepath; private String encoding; protected boolean failOnError = true; protected boolean listFiles = false; protected File[] compileList = new File[0]; public GenerateTestCases() { } /** * Adds a path for source compilation. * * @return a nested src element. */ public Path createSrc() { if (src == null) { src = new Path(getProject()); } return src.createPath(); } /** * Recreate src. * * @return a nested src element. */ protected Path recreateSrc() { src = null; return createSrc(); } /** * Set the source directories to find the source Java files. * @param srcDir the source directories as a path */ public void setSrcdir(Path srcDir) { if (src == null) { src = srcDir; } else { src.append(srcDir); } batchGenerate.setSrcdirPath(src.toString()); } /** * Gets the source dirs to find the source java files. * @return the source directorys as a path */ public Path getSrcdir() { return src; } /** * Set the destination directory into which the Java source * files should be compiled. * @param destDir the destination director */ public void setDestdir(File destDir) { this.destDir = destDir; } /** * Enable verbose compiling which will display which files * are being compiled * @param verbose */ public void setVerbose(boolean verbose) { batchGenerate.setVerbose( verbose ); } /** * Gets the destination directory into which the java source files * should be compiled. * @return the destination directory */ public File getDestdir() { return destDir; } /** * Set the sourcepath to be used for this compilation. * @param sourcepath the source path */ public void setSourcepath(Path sourcepath) { if (compileSourcepath == null) { compileSourcepath = sourcepath; } else { compileSourcepath.append(sourcepath); } } /** * Gets the sourcepath to be used for this compilation. * @return the source path */ public Path getSourcepath() { return compileSourcepath; } /** * Adds a path to sourcepath. * @return a sourcepath to be configured */ public Path createSourcepath() { if (compileSourcepath == null) { compileSourcepath = new Path(getProject()); } return compileSourcepath.createPath(); } /** * Adds a reference to a source path defined elsewhere. * @param r a reference to a source path */ public void setSourcepathRef(Reference r) { createSourcepath().setRefid(r); } /** * Set the classpath to be used for this compilation. * * @param classpath an Ant Path object containing the compilation classpath. */ public void setClasspath(Path classpath) { if (compileClasspath == null) { compileClasspath = classpath; } else { compileClasspath.append(classpath); } } /** * Gets the classpath to be used for this compilation. * @return the class path */ public Path getClasspath() { return compileClasspath; } /** * Adds a path to the classpath. * @return a class path to be configured */ public Path createClasspath() { if (compileClasspath == null) { compileClasspath = new Path(getProject()); } return compileClasspath.createPath(); } /** * Adds a reference to a classpath defined elsewhere. * @param r a reference to a classpath */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } public String createEncoding() { if (encoding == null) { encoding = System.getProperty("file.encoding"); } return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public String getEncoding() { return encoding; } /** * If true, list the source files being handed off to the compiler. * @param list if true list the source files */ public void setListfiles(boolean list) { listFiles = list; } /** * Get the listfiles flag. * @return the listfiles flag */ public boolean getListfiles() { return listFiles; } /** * Indicates whether the build will continue * even if there are compilation errors; defaults to true. * @param fail if true halt the build on failure */ public void setFailonerror(boolean fail) { failOnError = fail; } /** * @param proceed inverse of failoferror */ public void setProceed(boolean proceed) { failOnError = !proceed; } /** * Gets the failonerror flag. * @return the failonerror flag */ public boolean getFailonerror() { return failOnError; } /** * Executes the task. * @exception BuildException if an error occurs */ public void execute() throws BuildException { checkParameters(); resetFileLists(); // scan source directories and dest directory to build up // compile lists String[] list = src.list(); for (int i = 0; i < list.length; i++) { File srcDir = getProject().resolveFile(list[i]); if (!srcDir.exists()) { throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", getLocation()); } DirectoryScanner ds = this.getDirectoryScanner(srcDir); String[] files = ds.getIncludedFiles(); scanDir(srcDir, destDir != null ? destDir : srcDir, files); } compile(); } /** * Clear the list of files to be compiled and copied.. */ protected void resetFileLists() { compileList = new File[0]; } /** * Scans the directory looking for source files to be compiled. * The results are returned in the class variable compileList * * @param srcDir The source directory * @param destDir The destination directory * @param files An array of filenames */ protected void scanDir(File srcDir, File destDir, String[] files) { GlobPatternMapper m = new GlobPatternMapper(); m.setFrom("*"); m.setTo("*.html"); SourceFileScanner sfs = new SourceFileScanner(this); File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); if (newFiles.length > 0) { File[] newCompileList = new File[compileList.length + newFiles.length]; System.arraycopy(compileList, 0, newCompileList, 0, compileList.length); System.arraycopy(newFiles, 0, newCompileList, compileList.length, newFiles.length); compileList = newCompileList; } } /** * Gets the list of files to be compiled. * @return the list of files as an array */ public File[] getFileList() { return compileList; } protected void checkParameters() throws BuildException { if (src == null) { throw new BuildException("srcdir attribute must be set!", getLocation()); } if (src.size() == 0) { throw new BuildException("srcdir attribute must be set!", getLocation()); } if (destDir != null && !destDir.isDirectory()) { throw new BuildException( "destination directory \"" + destDir + "\" does not exist " + "or is not a directory", getLocation()); } if (encoding != null && !Charset.isSupported(encoding)) { throw new BuildException("encoding \"\" not supported"); } } protected void compile() { if (compileList.length > 0) { log( "Generating Tests " + compileList.length + " source file" + (compileList.length == 1 ? "" : "s") + (destDir != null ? " to " + destDir : "")); if (listFiles) { for (int i = 0; i < compileList.length; i++) { String filename = compileList[i].getAbsolutePath(); log(filename); } } try { Path classpath = getClasspath(); if (classpath != null) { //@todo - is this useful? //batchOfBiscuits.setClasspath(classpath.toString()); } batchGenerate.setTargetDirectory(destDir); if (encoding != null) { batchGenerate.setSourceEncoding(encoding); } batchGenerate.addSources( compileList ); batchGenerate.compile( ); } catch (Exception e) { StringWriter writer = new StringWriter(); //@todo -- e.printStackTrace(); //new ErrorReporter( e, false ).write( new PrintWriter(writer) ); String message = writer.toString(); if (failOnError) { throw new BuildException(message, e, getLocation()); } else { log(message, Project.MSG_ERR); } } } } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.history.core; import com.intellij.history.core.changes.*; import com.intellij.history.core.revisions.Revision; import com.intellij.history.core.storage.TestContent; import com.intellij.history.core.tree.Entry; import com.intellij.history.core.tree.FileEntry; import com.intellij.history.core.tree.RootEntry; import com.intellij.history.integration.TestVirtualFile; import com.intellij.openapi.util.Clock; import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import java.util.Arrays; import java.util.Collection; import java.util.List; public abstract class LocalHistoryTestCase extends Assert { { FSRecords.connect(); } private static long myCurrentId = 0; public static long nextId() { return myCurrentId++; } protected static byte[] b(String s) { return s.getBytes(); } protected static Content c(String data) { return data == null ? null : new TestContent(b(data)); } public CreateFileChange createFile(RootEntry root, String path) { return createFile(root, path, null); } public CreateFileChange createFile(RootEntry root, String path, String content) { return createFile(root, path, content, -1, false); } public CreateFileChange createFile(RootEntry root, String path, String content, long timestamp, boolean isReadOnly) { root.ensureDirectoryExists(Paths.getParentOf(path)).addChild(new FileEntry(Paths.getNameOf(path), c(content), timestamp, isReadOnly)); return new CreateFileChange(nextId(), path); } public CreateDirectoryChange createDirectory(RootEntry root, String path) { root.ensureDirectoryExists(path); return new CreateDirectoryChange(nextId(), path); } public ContentChange changeContent(RootEntry root, String path, String content) { return changeContent(root, path, content, -1); } public ContentChange changeContent(RootEntry root, String path, String content, long timestamp) { Entry e = root.getEntry(path); ContentChange result = new ContentChange(nextId(), path, e.getContent(), e.getTimestamp()); e.setContent(c(content), timestamp); return result; } public ROStatusChange changeROStatus(RootEntry root, String path, boolean status) { Entry e = root.getEntry(path); ROStatusChange result = new ROStatusChange(nextId(), path, e.isReadOnly()); e.setReadOnly(status); return result; } public RenameChange rename(RootEntry root, String path, String newName) { Entry e = root.getEntry(path); RenameChange result = new RenameChange(nextId(), Paths.renamed(path, newName), e.getName()); e.setName(newName); return result; } public MoveChange move(RootEntry root, String path, String newParent) { Entry e = root.getEntry(path); MoveChange result = new MoveChange(nextId(), Paths.reparented(path, newParent), e.getParent().getPath()); e.getParent().removeChild(e); root.getEntry(newParent).addChild(e); return result; } public DeleteChange delete(RootEntry root, String path) { Entry e = root.getEntry(path); e.getParent().removeChild(e); return new DeleteChange(nextId(), path, e); } public <T extends StructuralChange> T add(LocalHistoryFacade vcs, T change) { vcs.beginChangeSet(); vcs.addChangeInTests(change); vcs.endChangeSet(null); return change; } public ChangeSet addChangeSet(LocalHistoryFacade facade, Change... changes) { return addChangeSet(facade, null, changes); } public ChangeSet addChangeSet(LocalHistoryFacade facade, String changeSetName, Change... changes) { facade.beginChangeSet(); for (Change each : changes) { if (each instanceof StructuralChange) { facade.addChangeInTests((StructuralChange)each); } else { facade.putLabelInTests((PutLabelChange)each); } } facade.endChangeSet(changeSetName); return (ChangeSet)facade.getChangeListInTests().getChangesInTests().get(0); } public static List<Revision> collectRevisions(LocalHistoryFacade facade, RootEntry root, String path, String projectId, @Nullable String pattern) { return new RevisionsCollector(facade, root, path, projectId, pattern).getResult(); } public static List<ChangeSet> collectChanges(LocalHistoryFacade facade, String path, String projectId, String pattern) { ChangeCollectingVisitor v = new ChangeCollectingVisitor(path, projectId, pattern); facade.accept(v); return v.getChanges(); } @SafeVarargs public static <T> T[] array(@NotNull T... objects) { return objects; } @SafeVarargs public static <T> List<T> list(@NotNull T... objects) { return Arrays.asList(objects); } protected static ChangeSet cs(Change... changes) { return cs(null, changes); } protected static ChangeSet cs(String name, Change... changes) { return cs(0, name, changes); } protected static ChangeSet cs(long timestamp, String name, Change... changes) { ChangeSet result = new ChangeSet(nextId(), timestamp); result.setName(name); for (Change each : changes) { result.addChange(each); } return result; } protected static void setCurrentTimestamp(long t) { Clock.setTime(t); } protected static void assertContent(String expected, Entry e) { assertContent(expected, e.getContent()); } protected static void assertContent(String expected, Content c) { assertEquals(expected, new String(c.getBytes())); } protected static void assertEquals(Object[] expected, Collection actual) { assertArrayEquals(actual.toString(), expected, actual.toArray()); } protected static TestVirtualFile testDir(String name) { return new TestVirtualFile(name); } protected static TestVirtualFile testFile(String name) { return testFile(name, ""); } protected static TestVirtualFile testFile(String name, String content) { return testFile(name, content, -1); } protected static TestVirtualFile testFile(String name, String content, long timestamp) { return testFile(name, content, timestamp, false); } protected static TestVirtualFile testFile(String name, String content, long timestamp, boolean isReadOnly) { return new TestVirtualFile(name, content, timestamp, isReadOnly); } }
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* Primitive-type-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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 it.unimi.dsi.fastutil.ints; /** A class providing static methods and objects that do useful things with type-specific functions. * * @see it.unimi.dsi.fastutil.Function * @see java.util.Collections */ public class Int2ShortFunctions { private Int2ShortFunctions() {} /** An immutable class representing an empty type-specific function. * * <P>This class may be useful to implement your own in case you subclass * a type-specific function. */ public static class EmptyFunction extends AbstractInt2ShortFunction implements java.io.Serializable, Cloneable { private static final long serialVersionUID = -7046029254386353129L; protected EmptyFunction() {} public short get( final int k ) { return ((short)0); } public boolean containsKey( final int k ) { return false; } public short defaultReturnValue() { return ((short)0); } public void defaultReturnValue( final short defRetValue ) { throw new UnsupportedOperationException(); } public Short get( final Object k ) { return null; } public int size() { return 0; } public void clear() {} private Object readResolve() { return EMPTY_FUNCTION; } public Object clone() { return EMPTY_FUNCTION; } } /** An empty type-specific function (immutable). It is serializable and cloneable. */ @SuppressWarnings("rawtypes") public static final EmptyFunction EMPTY_FUNCTION = new EmptyFunction(); /** An immutable class representing a type-specific singleton function. * * <P>This class may be useful to implement your own in case you subclass * a type-specific function. */ public static class Singleton extends AbstractInt2ShortFunction implements java.io.Serializable, Cloneable { private static final long serialVersionUID = -7046029254386353129L; protected final int key; protected final short value; protected Singleton( final int key, final short value ) { this.key = key; this.value = value; } public boolean containsKey( final int k ) { return ( (key) == (k) ); } public short get( final int k ) { if ( ( (key) == (k) ) ) return value; return defRetValue; } public int size() { return 1; } public Object clone() { return this; } } /** Returns a type-specific immutable function containing only the specified pair. The returned function is serializable and cloneable. * * <P>Note that albeit the returned function is immutable, its default return value may be changed. * * @param key the only key of the returned function. * @param value the only value of the returned function. * @return a type-specific immutable function containing just the pair <code>&lt;key,value></code>. */ public static Int2ShortFunction singleton( final int key, short value ) { return new Singleton ( key, value ); } /** Returns a type-specific immutable function containing only the specified pair. The returned function is serializable and cloneable. * * <P>Note that albeit the returned function is immutable, its default return value may be changed. * * @param key the only key of the returned function. * @param value the only value of the returned function. * @return a type-specific immutable function containing just the pair <code>&lt;key,value></code>. */ public static Int2ShortFunction singleton( final Integer key, final Short value ) { return new Singleton ( ((key).intValue()), ((value).shortValue()) ); } /** A synchronized wrapper class for functions. */ public static class SynchronizedFunction extends AbstractInt2ShortFunction implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; protected final Int2ShortFunction function; protected final Object sync; protected SynchronizedFunction( final Int2ShortFunction f, final Object sync ) { if ( f == null ) throw new NullPointerException(); this.function = f; this.sync = sync; } protected SynchronizedFunction( final Int2ShortFunction f ) { if ( f == null ) throw new NullPointerException(); this.function = f; this.sync = this; } public int size() { synchronized( sync ) { return function.size(); } } public boolean containsKey( final int k ) { synchronized( sync ) { return function.containsKey( k ); } } public short defaultReturnValue() { synchronized( sync ) { return function.defaultReturnValue(); } } public void defaultReturnValue( final short defRetValue ) { synchronized( sync ) { function.defaultReturnValue( defRetValue ); } } public short put( final int k, final short v ) { synchronized( sync ) { return function.put( k, v ); } } public void clear() { synchronized( sync ) { function.clear(); } } public String toString() { synchronized( sync ) { return function.toString(); } } public Short put( final Integer k, final Short v ) { synchronized( sync ) { return function.put( k, v ); } } public Short get( final Object k ) { synchronized( sync ) { return function.get( k ); } } public Short remove( final Object k ) { synchronized( sync ) { return function.remove( k ); } } public short remove( final int k ) { synchronized( sync ) { return function.remove( k ); } } public short get( final int k ) { synchronized( sync ) { return function.get( k ); } } public boolean containsKey( final Object ok ) { synchronized( sync ) { return function.containsKey( ok ); } } } /** Returns a synchronized type-specific function backed by the given type-specific function. * * @param f the function to be wrapped in a synchronized function. * @return a synchronized view of the specified function. * @see java.util.Collections#synchronizedMap(java.util.Map) */ public static Int2ShortFunction synchronize( final Int2ShortFunction f ) { return new SynchronizedFunction ( f ); } /** Returns a synchronized type-specific function backed by the given type-specific function, using an assigned object to synchronize. * * @param f the function to be wrapped in a synchronized function. * @param sync an object that will be used to synchronize the access to the function. * @return a synchronized view of the specified function. * @see java.util.Collections#synchronizedMap(java.util.Map) */ public static Int2ShortFunction synchronize( final Int2ShortFunction f, final Object sync ) { return new SynchronizedFunction ( f, sync ); } /** An unmodifiable wrapper class for functions. */ public static class UnmodifiableFunction extends AbstractInt2ShortFunction implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; protected final Int2ShortFunction function; protected UnmodifiableFunction( final Int2ShortFunction f ) { if ( f == null ) throw new NullPointerException(); this.function = f; } public int size() { return function.size(); } public boolean containsKey( final int k ) { return function.containsKey( k ); } public short defaultReturnValue() { return function.defaultReturnValue(); } public void defaultReturnValue( final short defRetValue ) { throw new UnsupportedOperationException(); } public short put( final int k, final short v ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public String toString() { return function.toString(); } public short remove( final int k ) { throw new UnsupportedOperationException(); } public short get( final int k ) { return function.get( k ); } public boolean containsKey( final Object ok ) { return function.containsKey( ok ); } } /** Returns an unmodifiable type-specific function backed by the given type-specific function. * * @param f the function to be wrapped in an unmodifiable function. * @return an unmodifiable view of the specified function. * @see java.util.Collections#unmodifiableMap(java.util.Map) */ public static Int2ShortFunction unmodifiable( final Int2ShortFunction f ) { return new UnmodifiableFunction ( f ); } }
package com.houseelectrics.serializer; /** * Created by roberttodd on 29/11/2014. */ public class JSONExplorerImpl { public final String JavaScriptNullDesignator = "null"; final char ObjectStart = '{'; final char ObjectEnd = '}'; Integer firstNonWhiteSpaceCharacterIndex(String str) { return firstNonWhiteSpaceCharacterIndex(str, 0, null); } Integer firstNonWhiteSpaceCharacterIndex(String str, int startPos, Integer endPos) { StringUtils.CharPredicate matcher= new StringUtils.CharPredicate() { public boolean match(char c) { return !Character.isWhitespace(c); } }; return StringUtils.firstCharPosition(str, matcher, startPos, endPos); } Integer lastNonWhiteSpaceCharacterIndex(String str) { StringUtils.CharPredicate matcher= new StringUtils.CharPredicate() { public boolean match(char c) { return !Character.isWhitespace(c); } }; return StringUtils.lastCharPosition(str, matcher); } public void explore(String json, JsonExploreListener listener) { Integer firstNWSCharIndex = firstNonWhiteSpaceCharacterIndex(json); Integer lastNonWSCharIndex = lastNonWhiteSpaceCharacterIndex(json); if (firstNWSCharIndex == null || lastNonWSCharIndex == null || json.charAt(firstNWSCharIndex.intValue()) != ObjectStart || json.charAt(lastNonWSCharIndex.intValue()) != ObjectEnd) { throw new RuntimeException("expected json to start with " + ObjectStart +" and end with " + ObjectEnd); } listener.JsonStartObject(null, 0); explore(json, firstNWSCharIndex.intValue() + 1, lastNonWSCharIndex.intValue(), listener); } //look for a propertyName terminated by : //look for a leaf value or object start // or continuation , or object end Integer readEscapedQuotedString(String json, int valueStartPos, char quoteChar, int to, StringBuilder result) { //StringBuilder sb = new StringBuilder(); int pos = valueStartPos; for (; pos < to; pos++) { char c = json.charAt(pos); if (c == '\\') { pos++; if (pos >= to) break; else c = json.charAt(pos); } else { if (c == quoteChar) break; } result.append(c); } if (pos == to) return null; else return pos; } interface TerminationListener { void terminate(int position); } protected int exploreFunctionCall(String json, int from, int to, final JsonExploreListener listener, String functionName) { TerminationListener terminator = new TerminationListener() { @Override public void terminate(int p) { listener.JsonEndFunction(p); } }; return exploreList(json, from, to, listener, ')', terminator, "function call"); } protected int exploreArray(String json, int from, int to, final JsonExploreListener listener) { TerminationListener terminator = new TerminationListener() { @Override public void terminate(int p) { listener.JsonEndArray(p); } }; return exploreList(json, from, to, listener, ']', terminator, "array"); } protected int exploreList(String json, int from, int to, JsonExploreListener listener, char terminatingChar, TerminationListener terminator, String listType) { // read arguments for (int pos = from+1; pos <= to; pos++) { Integer nextPos = firstNonWhiteSpaceCharacterIndex(json, pos, to); if (nextPos == null) { String strError = "expected whitespace char after char " + pos; throw new RuntimeException(strError); } pos = nextPos.intValue(); char c = json.charAt(pos); if (c==',') { //throw new Exception("multiple javascript list items not supported"); continue; } if (c == terminatingChar) { //listener.JsonEndFunction(pos); terminator.terminate(pos); return pos; } else if (c == ObjectStart) { listener.JsonStartObject(/*currentPropertyName*/null, pos); pos = explore(json, pos + 1, to, listener, null/*currentPropertyName*/); } else // process a leaf ! { pos = readNonObject(json, pos, to, listener, null); } } throw new RuntimeException(listType + " not terminated"); } boolean isQuoteChar(char cin) { return cin == '"' || cin == '\''; } protected int readNonObject(String json, int valueStartPos, int to, JsonExploreListener listener, String currentPropertyName) { int pos=-1; Integer valueEndPos; //Predicate<char> valueEndCondition; //Predicate<char> isQuoteChar = cin => cin == '"' || cin == '\''; StringUtils.Matcher valueEndCondition; //Predicate<char> isQuoteChar = cin=> cin=='"' || cin == '\''; char c = json.charAt(valueStartPos); boolean isQuoted = isQuoteChar(c); String value = null; boolean isFunctionCall = false; boolean isArray = false; if (!isQuoted) { valueEndCondition = new StringUtils.Matcher() { public boolean match(char cin, String strin, int posin) { return Character.isWhitespace(cin) || cin == ',' || cin == ObjectEnd || cin == '(' || cin==')' || cin==']'; } }; valueEndPos = StringUtils.firstCharPosition(json, valueEndCondition, valueStartPos, to); if (valueEndPos != null) { value = json.substring(valueStartPos, valueEndPos.intValue() /*- valueStartPos*/); // is this a function start ? char lastchar = json.charAt(valueEndPos.intValue()); if (lastchar == '(') { listener.JsonStartFunction(value, valueEndPos.intValue(), currentPropertyName); isFunctionCall = true; pos = exploreFunctionCall(json, valueEndPos.intValue(), to, listener, value); } else if (value.charAt(0) == '[') { listener.JsonStartArray(currentPropertyName, valueStartPos); isArray = true; pos = exploreArray(json, valueStartPos, to, listener); } if (value.equals(JavaScriptNullDesignator)) value = null; } } else { // this is wrong - whabout double, triple escaping ! // read escaped quoted value // todo - remove object creation ! StringBuilder sbValue = new StringBuilder(); valueEndPos = readEscapedQuotedString(json, valueStartPos + 1, c, to, sbValue); //valueEndCondition = (cin, strin, posin) => isQuoteChar(cin) && !(posin>0 && strin[posin-1]=='\\' ); //valueStartPos++; if (valueEndPos != null) value = sbValue.toString(); } if (null == valueEndPos) { String strError = "no end found for property " + currentPropertyName + " at position " + valueStartPos+ " in json " + json; throw new RuntimeException(strError); } // check here if it is a function call if (!isFunctionCall && !isArray) { listener.JsonLeaf(currentPropertyName, value, isQuoted); pos = valueEndPos.intValue() - 1; // point to the last char processed } if (pos == -1) throw new RuntimeException("pos not assigned correctly"); if (isQuoted) pos++; return pos; } public int explore(String json, int from, int to, JsonExploreListener listener ) { return explore(json, from, to, listener, null); } public int explore(String json, int from, int to, JsonExploreListener listener, String currentPropertyName) { int pos = from; for (; pos <= to; pos++) { StringUtils.Matcher matcher; matcher = new StringUtils.Matcher() { public boolean match(char cin, String str, int pos) { return cin != ',' && !Character.isWhitespace(cin); }; }; Integer nextPos = StringUtils.firstCharPosition(json, matcher, pos, to); //firstNonWhiteSpaceCharacterIndex(json, pos, to); if (nextPos == null) { String strError = "expected whitespace char after char " +pos; throw new RuntimeException(strError); } pos = nextPos.intValue(); char c = json.charAt(pos); if (c == '}') { listener.JsonEndObject(pos); return pos; } // read a property Name matcher = new StringUtils.Matcher() { public boolean match(char cin, String str, int pos) { return cin == ':'; }; }; Integer colonIndex = StringUtils.firstCharPosition(json, matcher, pos, to); if (null == colonIndex) { throw new RuntimeException("no end found to property name at char "+ pos + " property starts with " + json.substring(pos) + " in json " + json.substring(from)); } StringUtils.CharPredicate nonWhitespaceOrColon = new StringUtils.CharPredicate() { @Override public boolean match(char c) { return !Character.isWhitespace(c) && c!=':'; } }; int propertyNameEnd = StringUtils.lastCharPosition(json, nonWhitespaceOrColon, colonIndex, 0); // propertyNameEnd currentPropertyName = json.substring(pos, propertyNameEnd+1 /*- pos*/); if (currentPropertyName.charAt(0) == '"') currentPropertyName = currentPropertyName.substring(1); if (currentPropertyName.endsWith("\"")) currentPropertyName = currentPropertyName.substring(0, currentPropertyName.length() - 1); pos = colonIndex + 1; Integer valueStartPos = firstNonWhiteSpaceCharacterIndex(json, pos, to); if (valueStartPos == null) { String strError = "no value found for property " + currentPropertyName + " at position " + pos + " in json " + json; throw new RuntimeException(strError); } c = json.charAt(valueStartPos.intValue()); if (c == ObjectStart) { listener.JsonStartObject(currentPropertyName, valueStartPos.intValue()); pos = explore(json, valueStartPos.intValue() + 1, to, listener, currentPropertyName); } else // read a non object { pos = readNonObject(json, valueStartPos.intValue(), to, listener, currentPropertyName); } } return pos; } }
/* * Copyright 1997-2015 Optimatika (www.optimatika.se) * * 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.ojalgo.series; import java.awt.Color; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.ojalgo.function.BinaryFunction; import org.ojalgo.function.ParameterFunction; import org.ojalgo.function.UnaryFunction; import org.ojalgo.netio.ASCII; import org.ojalgo.series.primitive.DataSeries; import org.ojalgo.type.TypeUtils; import org.ojalgo.type.keyvalue.KeyValue; abstract class AbstractSeries<K extends Comparable<K>, V extends Number, I extends AbstractSeries<K, V, I>> extends TreeMap<K, V> implements BasicSeries<K, V> { private Color myColour = null; private String myName = null; protected AbstractSeries() { super(); } protected AbstractSeries(final Comparator<? super K> someC) { super(someC); } protected AbstractSeries(final Map<? extends K, ? extends V> someM) { super(someM); } protected AbstractSeries(final SortedMap<K, ? extends V> someM) { super(someM); } public I colour(final Color aPaint) { myColour = aPaint; return (I) this; } public V firstValue() { return this.get(this.firstKey()); } public Color getColour() { return myColour; } public DataSeries getDataSeries() { return DataSeries.wrap(this.getPrimitiveValues()); } public String getName() { return myName; } public double[] getPrimitiveValues() { final double[] retVal = new double[this.size()]; int i = 0; for (final V tmpValue : this.values()) { retVal[i] = tmpValue.doubleValue(); i++; } return retVal; } public V lastValue() { return this.get(this.lastKey()); } public void modify(final BasicSeries<K, V> aLeftArg, final BinaryFunction<V> aFunc) { K tmpKey; V tmpLeftArg; for (final Map.Entry<K, V> tmpEntry : this.entrySet()) { tmpKey = tmpEntry.getKey(); tmpLeftArg = aLeftArg.get(tmpKey); if (tmpLeftArg != null) { this.put(tmpKey, aFunc.invoke(tmpLeftArg, tmpEntry.getValue())); } else { this.remove(tmpKey); } } } public void modify(final BinaryFunction<V> aFunc, final BasicSeries<K, V> aRightArg) { K tmpKey; V tmpRightArg; for (final Map.Entry<K, V> tmpEntry : this.entrySet()) { tmpKey = tmpEntry.getKey(); tmpRightArg = aRightArg.get(tmpKey); if (tmpRightArg != null) { this.put(tmpKey, aFunc.invoke(tmpEntry.getValue(), tmpRightArg)); } else { this.remove(tmpKey); } } } public void modify(final BinaryFunction<V> aFunc, final V aRightArg) { for (final Map.Entry<K, V> tmpEntry : this.entrySet()) { this.put(tmpEntry.getKey(), aFunc.invoke(tmpEntry.getValue(), aRightArg)); } } public void modify(final ParameterFunction<V> aFunc, final int aParam) { for (final Map.Entry<K, V> tmpEntry : this.entrySet()) { this.put(tmpEntry.getKey(), aFunc.invoke(tmpEntry.getValue(), aParam)); } } public void modify(final UnaryFunction<V> aFunc) { for (final Map.Entry<K, V> tmpEntry : this.entrySet()) { this.put(tmpEntry.getKey(), aFunc.invoke(tmpEntry.getValue())); } } public void modify(final V aLeftArg, final BinaryFunction<V> aFunc) { for (final Map.Entry<K, V> tmpEntry : this.entrySet()) { this.put(tmpEntry.getKey(), aFunc.invoke(aLeftArg, tmpEntry.getValue())); } } public I name(final String aName) { myName = aName; return (I) this; } public void putAll(final Collection<? extends KeyValue<? extends K, ? extends V>> data) { for (final KeyValue<? extends K, ? extends V> tmpKeyValue : data) { this.put(tmpKeyValue.getKey(), tmpKeyValue.getValue()); } } @Override public String toString() { final StringBuilder retVal = this.toStringFirstPart(); this.appendLastPartToString(retVal); return retVal.toString(); } void appendLastPartToString(final StringBuilder retVal) { if (this.getColour() != null) { retVal.append(TypeUtils.toHexString(this.getColour())); retVal.append(ASCII.NBSP); } if (this.size() <= 30) { retVal.append(super.toString()); } else { retVal.append("First:"); retVal.append(this.firstEntry()); retVal.append(ASCII.NBSP); retVal.append("Last:"); retVal.append(this.lastEntry()); retVal.append(ASCII.NBSP); retVal.append("Size:"); retVal.append(this.size()); } } void setColour(final Color aPaint) { this.colour(aPaint); } void setName(final String aName) { this.name(aName); } StringBuilder toStringFirstPart() { final StringBuilder retVal = new StringBuilder(); if (this.getName() != null) { retVal.append(this.getName()); retVal.append(ASCII.NBSP); } return retVal; } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.apimgt.gateway.utils; import org.apache.axis2.clustering.ClusteringAgent; import org.apache.axis2.context.MessageContext; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.Mediator; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.rest.RESTConstants; import org.apache.synapse.transport.nhttp.NhttpConstants; import org.apache.synapse.transport.passthru.PassThroughConstants; import org.apache.synapse.transport.passthru.Pipe; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants; import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext; import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.gateway.threatprotection.utils.ThreatProtectorConstants; import org.wso2.carbon.apimgt.usage.publisher.DataPublisherUtil; import org.wso2.carbon.apimgt.usage.publisher.dto.ExecutionTimeDTO; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.mediation.registry.RegistryServiceHolder; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.util.Map; import java.util.Collection; import java.util.HashMap; import java.util.TreeMap; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GatewayUtils { private static final Log log = LogFactory.getLog(GatewayUtils.class); public static boolean isClusteringEnabled() { ClusteringAgent agent = ServiceReferenceHolder.getInstance().getServerConfigurationContext(). getAxisConfiguration().getClusteringAgent(); if (agent != null) { return true; } return false; } public static <T> Map<String, T> generateMap(Collection<T> list) { Map<String, T> map = new HashMap<String, T>(); for (T el : list) { map.put(el.toString(), el); } return map; } /** * Extracts the IP from Message Context. * * @param messageContext Axis2 Message Context. * @return IP as a String. */ public static String getIp(MessageContext messageContext) { //Set transport headers of the message TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) messageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); // Assigning an Empty String so that when doing comparisons, .equals method can be used without explicitly // checking for nullity. String remoteIP = ""; //Check whether headers map is null and x forwarded for header is present if (transportHeaderMap != null) { remoteIP = transportHeaderMap.get(APIMgtGatewayConstants.X_FORWARDED_FOR); } //Setting IP of the client by looking at x forded for header and if it's empty get remote address if (remoteIP != null && !remoteIP.isEmpty()) { if (remoteIP.indexOf(",") > 0) { remoteIP = remoteIP.substring(0, remoteIP.indexOf(",")); } } else { remoteIP = (String) messageContext.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR); } return remoteIP; } /** * Can be used to extract Query Params from {@code org.apache.axis2.context.MessageContext}. * * @param messageContext The Axis2 MessageContext * @return A Map with Name Value pairs. */ public static Map<String, String> getQueryParams(MessageContext messageContext) { String queryString = (String) messageContext.getProperty(NhttpConstants.REST_URL_POSTFIX); if (!StringUtils.isEmpty(queryString)) { if (queryString.indexOf("?") > -1) { queryString = queryString.substring(queryString.indexOf("?") + 1); } String[] queryParams = queryString.split("&"); Map<String, String> queryParamsMap = new HashMap<String, String>(); String[] queryParamArray; String queryParamName, queryParamValue = ""; for (String queryParam : queryParams) { queryParamArray = queryParam.split("="); if (queryParamArray.length == 2) { queryParamName = queryParamArray[0]; queryParamValue = queryParamArray[1]; } else { queryParamName = queryParamArray[0]; } queryParamsMap.put(queryParamName, queryParamValue); } return queryParamsMap; } return null; } public static Map getJWTClaims(AuthenticationContext authContext) { String[] jwtTokenArray = authContext.getCallerToken().split(Pattern.quote(".")); // decoding JWT try { byte[] jwtByteArray = Base64.decodeBase64(jwtTokenArray[1].getBytes("UTF-8")); String jwtAssertion = new String(jwtByteArray, "UTF-8"); JSONParser parser = new JSONParser(); return (Map) parser.parse(jwtAssertion); } catch (UnsupportedEncodingException e) { log.error("Error while decoding jwt header", e); } catch (ParseException e) { log.error("Error while parsing jwt header", e); } return null; } /** * Get the config system registry for tenants * * @param tenantDomain - The tenant domain * @return - A UserRegistry instance for the tenant * @throws APIManagementException */ public static UserRegistry getRegistry(String tenantDomain) throws APIManagementException { PrivilegedCarbonContext.startTenantFlow(); if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } else { PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); } int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); UserRegistry registry; try { registry = RegistryServiceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId); } catch (RegistryException e) { String msg = "Failed to get registry instance for the tenant : " + tenantDomain + e.getMessage(); throw new APIManagementException(msg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); } return registry; } /** * Delete the given registry property from the given tenant registry path * * @param propertyName property name * @param path resource path * @param tenantDomain * @throws APIManagementException */ public static void deleteRegistryProperty(String propertyName, String path, String tenantDomain) throws APIManagementException { UserRegistry registry = getRegistry(tenantDomain); PrivilegedCarbonContext.startTenantFlow(); if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } else { PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); } try { Resource resource = registry.get(path); if (resource != null && resource.getProperty(propertyName) != null) { resource.removeProperty(propertyName); registry.put(resource.getPath(), resource); resource.discard(); } } catch (RegistryException e) { throw new APIManagementException("Error while reading registry resource " + path + " for tenant " + tenantDomain); } finally { PrivilegedCarbonContext.endTenantFlow(); } } /** * Add/Update the given registry property from the given tenant registry * path * * @param propertyName property name * @param propertyValue property value * @param path resource path * @param tenantDomain * @throws APIManagementException */ public static void setRegistryProperty(String propertyName, String propertyValue, String path, String tenantDomain) throws APIManagementException { UserRegistry registry = getRegistry(tenantDomain); PrivilegedCarbonContext.startTenantFlow(); if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } else { PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); } try { Resource resource = registry.get(path); // add or update property if (resource.getProperty(propertyName) != null) { resource.setProperty(propertyName, propertyValue); } else { resource.addProperty(propertyName, propertyValue); } registry.put(resource.getPath(), resource); resource.discard(); } catch (RegistryException e) { throw new APIManagementException("Error while reading registry resource " + path + " for tenant " + tenantDomain); } finally { PrivilegedCarbonContext.endTenantFlow(); } } /** * Returns the alias string of API endpoint security password * * @param apiProviderName * @param apiName * @param version * @return */ public static String getAPIEndpointSecretAlias(String apiProviderName, String apiName, String version) { String secureVaultAlias = apiProviderName + "--" + apiName + version; return secureVaultAlias; } /** * return existing correlation ID in the message context or set new correlation ID to the message context. * * @param messageContext synapse message context * @return correlation ID */ public static String getAndSetCorrelationID(org.apache.synapse.MessageContext messageContext) { Object correlationObj = messageContext.getProperty(APIMgtGatewayConstants.AM_CORRELATION_ID); String correlationID; if (correlationObj != null) { correlationID = (String) correlationObj; } else { correlationID = UUID.randomUUID().toString(); messageContext.setProperty(APIMgtGatewayConstants.AM_CORRELATION_ID, correlationID); if (log.isDebugEnabled()) { log.debug("Setting correlation ID to message context."); } } return correlationID; } /** * This method handles threat violations. If the request propagates a threat, this method generates * an custom exception. * @param messageContext contains the message properties of the relevant API request which was * enabled the regexValidator message mediation in flow. * @param errorCode It depends on status of the error message. * @param desc Description of the error message.It describes the vulnerable type and where it happens. * @return here return true to continue the sequence. No need to return any value from this method. */ public static boolean handleThreat(org.apache.synapse.MessageContext messageContext, String errorCode, String desc) { messageContext.setProperty(APIMgtGatewayConstants.THREAT_FOUND, true); messageContext.setProperty(APIMgtGatewayConstants.THREAT_CODE, errorCode); messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_REQUEST); messageContext.setProperty(APIMgtGatewayConstants.THREAT_DESC, desc); Mediator sequence = messageContext.getSequence(APIMgtGatewayConstants.THREAT_FAULT); // Invoke the custom error handler specified by the user if (sequence != null && !sequence.mediate(messageContext)) { // If needed user should be able to prevent the rest of the fault handling // logic from getting executed } return true; } /** * This method use to clone the InputStream from the the message context. Basically * clone the request body. * @param messageContext contains the message properties of the relevant API request which was * enabled the regexValidator message mediation in flow. * @return cloned InputStreams. * @throws IOException this exception might occurred while cloning the inputStream. */ public static Map<String,InputStream> cloneRequestMessage(org.apache.synapse.MessageContext messageContext) throws IOException { BufferedInputStream bufferedInputStream = null; Map<String, InputStream> inputStreamMap = null; InputStream inputStreamSchema; InputStream inputStreamXml; InputStream inputStreamJSON; InputStream inputStreamOriginal; int requestBufferSize = 1024; org.apache.axis2.context.MessageContext axis2MC; Pipe pipe; axis2MC = ((Axis2MessageContext) messageContext). getAxis2MessageContext(); Object bufferSize = messageContext.getProperty(ThreatProtectorConstants.REQUEST_BUFFER_SIZE); if (bufferSize != null) { requestBufferSize = Integer.parseInt(bufferSize.toString()); } pipe = (Pipe) axis2MC.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null) { bufferedInputStream = new BufferedInputStream(pipe.getInputStream()); } if (bufferedInputStream != null) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[requestBufferSize]; int length; while ((length = bufferedInputStream.read(buffer)) > -1) { byteArrayOutputStream.write(buffer, 0, length); } byteArrayOutputStream.flush(); inputStreamMap = new HashMap<>(); inputStreamSchema = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); inputStreamXml = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); inputStreamOriginal = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); inputStreamJSON = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); inputStreamMap.put(ThreatProtectorConstants.SCHEMA, inputStreamSchema); inputStreamMap.put(ThreatProtectorConstants.XML, inputStreamXml); inputStreamMap.put(ThreatProtectorConstants.ORIGINAL, inputStreamOriginal); inputStreamMap.put(ThreatProtectorConstants.JSON, inputStreamJSON); } return inputStreamMap; } /** * This method use to set the originInput stream to the message Context * @param inputStreams cloned InputStreams * @param axis2MC axis2 message context */ public static void setOriginalInputStream(Map <String, InputStream> inputStreams, org.apache.axis2.context.MessageContext axis2MC) { InputStream inputStreamOriginal; if (inputStreams != null) { inputStreamOriginal = inputStreams.get(ThreatProtectorConstants.ORIGINAL); if (inputStreamOriginal != null) { BufferedInputStream bufferedInputStreamOriginal = new BufferedInputStream(inputStreamOriginal); axis2MC.setProperty(PassThroughConstants.BUFFERED_INPUT_STREAM, bufferedInputStreamOriginal); } } } /** * Build execution time related information using message context * @param messageContext * @return */ public static ExecutionTimeDTO getExecutionTime(org.apache.synapse.MessageContext messageContext) { Object securityLatency = messageContext.getProperty(APIMgtGatewayConstants.SECURITY_LATENCY); Object throttleLatency = messageContext.getProperty(APIMgtGatewayConstants.THROTTLING_LATENCY); Object reqMediationLatency = messageContext.getProperty(APIMgtGatewayConstants.REQUEST_MEDIATION_LATENCY); Object resMediationLatency = messageContext.getProperty(APIMgtGatewayConstants.RESPONSE_MEDIATION_LATENCY); Object otherLatency = messageContext.getProperty(APIMgtGatewayConstants.OTHER_LATENCY); Object backendLatency = messageContext.getProperty(APIMgtGatewayConstants.BACKEND_LATENCY); ExecutionTimeDTO executionTime = new ExecutionTimeDTO(); executionTime.setBackEndLatency(backendLatency == null ? 0 : ((Number) backendLatency).longValue()); executionTime.setOtherLatency(otherLatency == null ? 0 : ((Number) otherLatency).longValue()); executionTime.setRequestMediationLatency( reqMediationLatency == null ? 0 : ((Number) reqMediationLatency).longValue()); executionTime.setResponseMediationLatency( resMediationLatency == null ? 0 : ((Number) resMediationLatency).longValue()); executionTime.setSecurityLatency(securityLatency == null ? 0 : ((Number) securityLatency).longValue()); executionTime.setThrottlingLatency(throttleLatency == null ? 0 : ((Number) throttleLatency).longValue()); return executionTime; } public static String extractResource(org.apache.synapse.MessageContext mc) { Pattern resourcePattern = Pattern.compile("^/.+?/.+?([/?].+)$"); String resource = "/"; Matcher matcher = resourcePattern.matcher((String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH)); if (matcher.find()) { resource = matcher.group(1); } return resource; } public static String getHostName(org.apache.synapse.MessageContext messageContext) { String hostname = DataPublisherUtil.getApiManagerAnalyticsConfiguration().getDatacenterId(); if (hostname == null) { hostname = (String) messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME); } return hostname; } public static String getQualifiedApiName(String apiProviderName, String apiName, String version) { return apiProviderName + "--" + apiName + ":v" + version; } public static String getQualifiedDefaultApiName(String apiProviderName, String apiName) { return apiProviderName + "--" + apiName; } /** * This method extracts the endpoint address base path if query parameters are contained in endpoint * @param mc The message context * @return The endpoint address base path */ public static String extractAddressBasePath(org.apache.synapse.MessageContext mc) { String endpointAddress = (String) mc.getProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS); if (endpointAddress.contains("?")) { endpointAddress = endpointAddress.substring(0, endpointAddress.indexOf("?")); } return endpointAddress; } }
/* * (C) 2010 Research In Motion Ltd. All Rights Reserved. * RIM, Research In Motion -- Reg. U.S. Patent and Trademark Office * The RIM Logo and Inter@ctive are trademarks of Research In Motion, Limited * All materials confidential information of Research In Motion, Limited * * $Id: //depot/dev/cardhu/IES/common/master/util/src/main/java/provision/util/beans/BeanManager.java#1 $ * $Author: msimonsen $ $DateTime: 2012/12/12 09:03:29 $ $Change: 6006354 $ */ package provision.util.beans; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import provision.util.BaseException; import provision.util.BaseUtil; import provision.util.ReflectionException; import provision.util.ReflectionUtil; import provision.util.StringUtil; import provision.util.ToolkitEvents; /** * This class provides introspection utilities. * * @author Iulian Vlasov */ public class BeanManager { public static final char CHAINED_SEP = '.'; public static final char INDEXED_SEP_START = '['; public static final char INDEXED_SEP_END = ']'; public static final String PROPERTY_CLASS = "class"; static final int DEFAULT_CAPACITY = 10; private static Map<String, BeanHandle> beanHandles = BaseUtil.createMap(DEFAULT_CAPACITY, true); private static Map<String, String> beanAliases = BaseUtil.createMap(DEFAULT_CAPACITY, true); /** * Iterates through all registered beans. * * @return Iterator each element if a BeanHandle */ public static Iterator<BeanHandle> beanIterator() { return beanHandles.values().iterator(); } /** * Lookup a bean definition by name. * * @parm name String alias of the bean * @return BeanHandle bean definition */ public static BeanHandle lookup(String name) { String cls = beanAliases.get(name); if (cls != null) { return beanHandles.get(cls); } else { return beanHandles.get(name); } } /** * Register a bean from a String specifying its class. The bean is * registered under an alias identical with its class name. * * @parm bClass String bean class name * @return BeanHandle bean definition * @exception BeanException if bean cannot be registered */ public static BeanHandle registerBean(String bClass) throws BeanException { return registerBean(bClass, null); } /** * Register a bean from a String specifying its class. The bean is * registered under an alias. * * @parm bClass String bean class name * @parm bName String bean alias * @return BeanHandle bean definition * @exception BeanException if bean cannot be registered */ public static BeanHandle registerBean(String bClass, String bName) throws BeanException { if (BaseUtil.isEmpty(bClass)) return null; BeanHandle bHandle = (BeanHandle) lookup(bClass); if (bHandle == null) { try { if (BaseUtil.isEmpty(bName)) bName = bClass; Class<?> c = ReflectionUtil.newClass(bClass); BeanInfo info = Introspector.getBeanInfo(c); PropertyDescriptor[] pd = info.getPropertyDescriptors(); Map<String, PropertyDescriptor> props = BaseUtil.createMap(pd.length - 1, true); for (int i = 0; i < pd.length; i++) { String name = pd[i].getName(); if (name.equals(PROPERTY_CLASS)) continue; props.put(name, pd[i]); } bHandle = new BeanHandle(bName, c, props); beanHandles.put(bClass, bHandle); if (!bName.equals(bClass)) { beanAliases.put(bName, bClass); } } catch (IntrospectionException e) { throw new BeanException(ToolkitEvents.ERR_BEANS_INTROSPECTION, e, bClass); } } else { if (!BaseUtil.isEmpty(bName)) { if (!bHandle.getName().equals(bName)) { beanAliases.put(bName, bHandle.getBeanClass().getName()); } } } return bHandle; } /** * Register a bean from a Class object and returns a Map containing its * properties. * * @parm bClass Class bean class * @return Map bean properties * @exception BeanException if bean cannot be registered */ public static Map<String, PropertyDescriptor> getProperties(Class<?> bClass) throws BeanException { BeanHandle bHandle = registerBean(bClass.getName()); return bHandle.getProperties(); } /** * Register a bean from a Class name and returns a Map containing its * properties. * * @parm bClass String bean class name * @return Map bean properties * @exception BeanException if bean cannot be registered */ public static Map<String, PropertyDescriptor> getProperties(String bName) throws BeanException { BeanHandle bHandle = registerBean(bName, null); return bHandle.getProperties(); } /** * Initialize a bean from a Map object. Each key is mapped to a bean * property. Keys may contain CHAINED_SEP tokens in which case the bean * property is itself a bean. Keys may contain INDEXED_SEP_START and * INDEXED_SEP_END tokens in which case the bean property is an indexed * property. * * @parm bean Object bean instance * @parm Map map with property values * @exception BeanException if bean cannot be initialized */ public static void setState(Object bean, Map<String, Object> map) throws BeanException { if (BaseUtil.isEmpty(map)) return; Map<String, PropertyDescriptor> props = getProperties(bean.getClass()); for (String property : map.keySet()) { Object value = map.get(property); if ((property.indexOf(CHAINED_SEP) < 0) && (property.indexOf(INDEXED_SEP_START) < 0)) { // check straight writeable properties PropertyDescriptor pd = props.get(property); if ((pd == null) || (pd.getWriteMethod() == null)) continue; setProperty(bean, pd, value); } else { setProperty(bean, property, value); } } } /** * Obtain the value of a bean property. The property is specified by name. * * @param bean Java bean object * @param pName Name of the property * @return Value of the property * @exception BeanException if the specified property is invalid */ public static Object getProperty(Object bean, String pName) throws BeanException { Object value = null; String property = null; int sep = pName.indexOf(CHAINED_SEP); if (sep >= 0) { property = pName.substring(0, sep); Object beanProp = getProperty(bean, property, false); if (beanProp != null) { pName = pName.substring(sep + 1); value = getProperty(beanProp, pName); } } else { value = getProperty(bean, pName, false); } return value; } /** * */ @SuppressWarnings("unchecked") public static Object getProperty(Object bean, String pName, boolean required) throws BeanException { String property = null; int index = 0; int ssep = pName.indexOf(INDEXED_SEP_START); if (ssep >= 0) { int esep = pName.indexOf(INDEXED_SEP_END); if (esep <= ssep) { throw new BeanException(new IllegalArgumentException(pName)); } try { String sIndex = pName.substring(ssep + 1, esep); index = Integer.parseInt(sIndex); property = pName.substring(0, ssep); } catch (NumberFormatException e) { throw new BeanException(new IllegalArgumentException(pName)); } } else { property = pName; } Map props = getProperties(bean.getClass()); PropertyDescriptor pd = (PropertyDescriptor) props.get(property); if (pd == null) { throw new BeanException(new IllegalArgumentException(pName)); } Object value = null; if (ssep >= 0) { try { value = getProperty(bean, pd, index); } catch (IndexOutOfBoundsException e) { } } else { value = getProperty(bean, pd); } if ((value == null) && required) { if (ssep >= 0) { boolean isIndexed = (pd instanceof IndexedPropertyDescriptor); if (isIndexed) { value = ReflectionUtil.newObject(((IndexedPropertyDescriptor) pd).getIndexedPropertyType()); setProperty(bean, pd, index, value); } } else { value = ReflectionUtil.newObject(pd.getPropertyType()); setProperty(bean, pd, value); } } return value; } /** * Get the value of an object property. The property is specified by its * descriptor. * * @param object Object target object whose property is to be set * @param descriptor PropertyDescriptor of the propery to be set * @return Object value of the object's property * @exception BeanException if fails to get the property */ public static Object getProperty(Object bean, PropertyDescriptor pd) throws BeanException { try { Method m = pd.getReadMethod(); if (m == null) { throw new IllegalAccessException(pd.getName()); } return m.invoke(bean, new Object[0]); } catch (IllegalAccessException e) { throw new BeanException(e); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t instanceof BeanException) { throw (BeanException) t; } else { throw new BeanException(t); } } } /** * */ public static Object getProperty(Object bean, PropertyDescriptor pd, int index) throws BeanException { try { Object value = null; Method m = null; boolean isIndexed = (pd instanceof IndexedPropertyDescriptor); if (isIndexed) { m = ((IndexedPropertyDescriptor) pd).getIndexedReadMethod(); if (m == null) { // no indexed getter, try non-indexed getter m = pd.getReadMethod(); if (m == null) { throw new BeanException(new IllegalAccessException(pd.getName())); } // try to get an array property Object arProp = m.invoke(bean, new Object[0]); if (!arProp.getClass().isArray()) { throw new BeanException(new IllegalAccessException(pd.getName())); } value = Array.get(arProp, index); } value = m.invoke(bean, new Object[] { new Integer(index) }); } else { throw new BeanException(new IndexOutOfBoundsException(pd.getName())); } return value; } catch (IllegalAccessException e) { throw new BeanException(e); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t instanceof BeanException) { throw (BeanException) t; } else { throw new BeanException(t); } } } /** * Set the value of a bean property. The property is specified by name. * * @param bean Java bean object * @param pName Name of the property * @param Value of the property * @exception BeanException if the specified property is invalid or the value is * illegal. */ public static void setProperty(Object bean, String pName, Object value) throws BeanException { String property = null; int sep = pName.indexOf(CHAINED_SEP); if (sep >= 0) { property = pName.substring(0, sep); Object beanProp = getProperty(bean, property, true); pName = pName.substring(sep + 1); setProperty(beanProp, pName, value); } else { int index = 0; int ssep = pName.indexOf(INDEXED_SEP_START); if (ssep >= 0) { int esep = pName.indexOf(INDEXED_SEP_END); if (esep <= ssep) { throw new BeanException(new IllegalArgumentException(pName)); } try { String sIndex = pName.substring(ssep + 1, esep); index = Integer.parseInt(sIndex); property = pName.substring(0, ssep); } catch (NumberFormatException e) { throw new BeanException(new IllegalArgumentException(pName)); } } else { property = pName; } Map<String, PropertyDescriptor> props = getProperties(bean.getClass()); PropertyDescriptor pd = (PropertyDescriptor) props.get(property); if (pd == null) { throw new BeanException(new IllegalArgumentException(pName)); } if (ssep >= 0) { setProperty(bean, pd, index, value); } else { setProperty(bean, pd, value); } } } /** * */ public static void setProperty(Object bean, PropertyDescriptor pd, Object value) throws BeanException { try { // writeable ? Method m = pd.getWriteMethod(); if (m == null) { throw new BeanException(ToolkitEvents.ERR_BEANS_SETTER, bean.getClass(), pd.getName(), pd.getPropertyType()); } // cast value = ReflectionUtil.cast(value, pd.getPropertyType()); // set Throwable t = null; try { m.invoke(bean, new Object[] { value }); } catch (IllegalAccessException e) { t = e; } catch (InvocationTargetException ite) { t = ite.getTargetException(); } if (t != null) { String skey = ""; if (t instanceof Exception) { skey = ((Exception) t).getMessage(); t = ((Exception) t).getCause(); } throw new BeanException(ToolkitEvents.ERR_BEANS_SETTER_FAILED, bean.getClass(), pd.getName(), pd.getPropertyType(), value); } } catch (BeanException bxcp) { bxcp.setPropertyName(pd.getName()); bxcp.setPropertyType(pd.getPropertyType()); bxcp.setValue(value); throw bxcp; } } /** * Set an object property to the specified value. The property is specified * by its descriptor. * * @param object Object target object whose property is to be set * @param descriptor PropertyDescriptor of the propery to be set * @param value Object value to be store into the object's property * @exception BaseException if fails to set the property */ public static void setProperty(Object bean, PropertyDescriptor pd, int index, Object value) throws BaseException { try { boolean isIndexed = (pd instanceof IndexedPropertyDescriptor); Method m = null; if (isIndexed) { // writeable ? m = ((IndexedPropertyDescriptor) pd).getIndexedWriteMethod(); if (m == null) { // no indexed setter, try non-indexed getter m = pd.getReadMethod(); if (m == null) { throw new BeanException(ToolkitEvents.ERR_BEANS_SETTER, bean.getClass(), pd.getName(), pd.getPropertyType()); } // try to get an array property try { Object arProp = _set(m, bean, new Object[0]); if (!arProp.getClass().isArray()) { throw new BeanException( "Unable to map value to bean property (property is read-only and NOT an array)"); } Array.set(arProp, index, value); return; } catch (Exception e) { BeanException bxcp = new BeanException( "Unable to map value to bean property (property is read-only and failed to GET array) ", e); throw bxcp; } } // cast Class<?> propertyType = ((IndexedPropertyDescriptor) pd).getIndexedPropertyType(); value = ReflectionUtil.cast(value, propertyType); // set try { _set(m, bean, new Object[] { new Integer(index), value }); } catch (Exception e) { BeanException bxcp = new BeanException("Unable to map value to bean property (setter failed) ", e); throw bxcp; } } else { throw new BeanException("Unable to map value to bean property (non-indexed property and index is " + index); } } catch (BeanException bxcp) { if (bxcp.getPropertyName() == null) { bxcp.setPropertyName(pd.getName() + INDEXED_SEP_START + index + INDEXED_SEP_END); bxcp.setPropertyType(pd.getPropertyType()); bxcp.setValue(value); } throw bxcp; } } /** * */ public static String classToString(String cName) { StringBuffer sb = new StringBuffer(); try { sb.append("Class Properties: ").append(cName).append(StringUtil.NEWLINE); Map<String, PropertyDescriptor> props = getProperties(cName); for (PropertyDescriptor pd : props.values()) { if (pd.getName().equals(PROPERTY_CLASS)) continue; boolean isIndexed = (pd instanceof IndexedPropertyDescriptor); if (isIndexed) { sb.append(" INDEXED PROPERTY="); } else { sb.append(" SIMPLE PROPERTY="); } sb.append(pd.getName()); boolean isRead = false, isWrite = false; String type = null; if (isIndexed) { isRead = (((IndexedPropertyDescriptor) pd).getIndexedReadMethod() != null); isWrite = (((IndexedPropertyDescriptor) pd).getIndexedWriteMethod() != null); type = ((IndexedPropertyDescriptor) pd).getIndexedPropertyType().getName(); } else { isRead = (pd.getReadMethod() != null); isWrite = (pd.getWriteMethod() != null); type = pd.getPropertyType().getName(); } sb.append(" TYPE=").append(type); sb.append(" ACCESS=").append(isRead && isWrite ? "read/write" : (isRead ? "read" : "write")); sb.append(StringUtil.NEWLINE); } } catch (Exception e) { sb.append(e); } return sb.toString(); } /** * */ public static String beanToString(Object bean) { StringBuffer sb = new StringBuffer(); sb.append(bean.getClass().getName()); beanToString(bean, "", sb); return sb.toString(); } /** * */ public static void beanToString(Object bean, String indent, StringBuffer sb) { String tab = " "; try { Class<? extends Object> type = (bean == null ? null : bean.getClass()); if ((bean == null) || isSimpleClass(type)) { sb.append("=").append(bean); } else if (Collection.class.isInstance(bean)) { int index = 0; for (Object elem : (Collection<?>) bean) { sb.append(StringUtil.NEWLINE).append(indent).append(tab).append(index).append(". "); if ((elem == null) || isSimpleClass(elem.getClass())) { sb.append(elem); } else { sb.append(elem.getClass()); beanToString(elem, indent + tab + tab, sb); } index++; } } else if ((bean != null) && type.isArray()) { int length = Array.getLength(bean); for (int index = 0; index < length; index++) { Object elem = Array.get(bean, index); sb.append(StringUtil.NEWLINE).append(indent).append(index).append(". "); if ((elem == null) || isSimpleClass(elem.getClass())) { sb.append(elem); } else { beanToString(elem, indent + tab + tab, sb); } } } else { // traverse this bean Map<String, PropertyDescriptor> props = getProperties(type); if (!props.isEmpty()) { for (PropertyDescriptor pd : props.values()) { String name = pd.getName(); if (PROPERTY_CLASS.equals(name)) continue; boolean isIndexed = (pd instanceof IndexedPropertyDescriptor); // it's readable ? if ((!isIndexed && (pd.getReadMethod() == null)) || (isIndexed && (((IndexedPropertyDescriptor) pd).getIndexedReadMethod() == null))) { continue; } sb.append(StringUtil.NEWLINE).append(indent); sb.append(" "); if (isIndexed) { sb.append(((IndexedPropertyDescriptor) pd).getIndexedPropertyType().getName()); sb.append(tab).append(name); try { for (int index = 0;; index++) { Object value = BeanManager.getProperty(bean, pd, index); sb.append(StringUtil.NEWLINE).append(indent).append(index).append(". "); beanToString(value, indent + tab + tab, sb); } } catch (Exception e) { Throwable t = e.getCause(); if (t instanceof IndexOutOfBoundsException) { // no more elements } else { System.err.println(e); } } } else { String propType = pd.getPropertyType().getName(); sb.append(StringUtil.padRight(propType, 30)); sb.append(tab).append(":").append(name); Object value = BeanManager.getProperty(bean, pd); beanToString(value, indent + tab, sb); } } // for } // if isempty } // else } catch (Exception e) { System.err.println(e); } } private static Object _set(Method m, Object bean, Object[] values) throws BaseException { Throwable t = null; try { return m.invoke(bean, values); } catch (IllegalAccessException e) { throw new BaseException(e); } catch (InvocationTargetException ite) { t = ite.getTargetException(); if (t instanceof BaseException) { throw (BaseException) t; } else { throw new BaseException("setter failed", t); } } } /** * */ public static void traverseBean(Object bean, String parent, BeanPropertyCallback caller) { try { Class<? extends Object> type = (bean == null ? null : bean.getClass()); if (parent == null) parent = ""; StringBuffer ixName = new StringBuffer(); if ((bean == null) || isSimpleClass(type)) { caller.process(parent, bean); } else if (Collection.class.isInstance(bean)) { int index = 0; for (Object elem : (Collection<?>) bean) { ixName.setLength(0); ixName.append(parent).append(INDEXED_SEP_START).append(index).append(INDEXED_SEP_END); if ((elem == null) || isSimpleClass(elem.getClass())) { caller.process(ixName.toString(), elem); } else { traverseBean(elem, ixName.toString(), caller); } index++; } } else if ((bean != null) && type.isArray()) { int length = Array.getLength(bean); for (int index = 0; index < length; index++) { Object elem = Array.get(bean, index); ixName.setLength(0); ixName.append(parent).append(INDEXED_SEP_START).append(index).append(INDEXED_SEP_END); if ((elem == null) || isSimpleClass(elem.getClass())) { caller.process(ixName.toString(), elem); } else { traverseBean(elem, ixName.toString(), caller); } } } else { // traverse this bean Map<String, PropertyDescriptor> props = getProperties(type); if (!props.isEmpty()) { StringBuffer fullName = new StringBuffer(); for (PropertyDescriptor pd : props.values()) { String name = pd.getName(); if (PROPERTY_CLASS.equals(name)) continue; boolean isIndexed = (pd instanceof IndexedPropertyDescriptor); // it's readable ? if ((!isIndexed && (pd.getReadMethod() == null)) || (isIndexed && (((IndexedPropertyDescriptor) pd).getIndexedReadMethod() == null))) { continue; } fullName.setLength(0); if (parent.length() != 0) { fullName.append(parent).append("."); } fullName.append(name); if (isIndexed) { try { for (int index = 0;; index++) { Object value = BeanManager.getProperty(bean, pd, index); ixName.setLength(0); ixName.append(fullName).append(INDEXED_SEP_START).append(index).append( INDEXED_SEP_END); traverseBean(value, ixName.toString(), caller); } } catch (Exception e) { Throwable t = e.getCause(); if (t instanceof IndexOutOfBoundsException) { // no more elements } else { System.err.println(e); } } } else { Object value = BeanManager.getProperty(bean, pd); traverseBean(value, fullName.toString(), caller); } } // for } // if isempty } // else } catch (Exception e) { System.err.println(e); } } public static boolean isSimpleClass(Class<?> type) { return (type.isPrimitive() || java.sql.Timestamp.class.isAssignableFrom(type) || (type.getName().startsWith( "java.") && !Collection.class.isAssignableFrom(type) && !type.isArray())); } public static String getAsProperty(StringBuffer property) { int ix = property.indexOf("_"); if (ix == -1) return property.toString(); int len = property.length(); while (ix != -1) { if (ix + 1 < len) { char nextChar = property.charAt(ix + 1); property.deleteCharAt(ix); len--; property.setCharAt(ix, Character.toUpperCase(nextChar)); ix = property.indexOf("_", ix + 1); } else { ix = -1; } } return property.toString(); } public static String getAsProperty(String value) { return getAsProperty(value, true); } public static String getAsProperty(String value, boolean decap) { int ix = value.indexOf('_'); if (ix == -1) return value; String property = getAsProperty(new StringBuffer(decap ? value.toLowerCase() : value)); return property; } /** * @author Iulian Vlasov */ public interface BeanPropertyCallback { /** * Do some specific processing on the specified property. * * @parm fullName String full name of the property (including class * name) * @parm value Object value of the property * @exception BaseException if value cannot be processed */ public void process(String fullName, Object value) throws Exception; } /** * @param beanType * @param propName * @param propType * @return * @throws BeanException * @throws NoSuchMethodException */ public static Method getGetter(Class<?> beanType, String propName, Class<String> propType) throws BeanException { Method getter = null; Map<String, PropertyDescriptor> props = getProperties(beanType); PropertyDescriptor pd = props.get(propName); if ((pd == null) || ((getter = pd.getReadMethod()) == null) || ((propType != null) && !pd.getPropertyType().isAssignableFrom(propType))) { throw new BeanException(ToolkitEvents.ERR_BEANS_GETTER, beanType, propName, propType); } return getter; } public static boolean propertyExists(Object bean, String pName) throws BeanException { return (getPropertyDescriptor(bean, pName) != null); } public static Object createProperty(Object bean, String pName) throws BeanException, ReflectionException { return createProperty(bean, pName, null); } public static Object createProperty(Object bean, String pName, String implClass) { PropertyDescriptor pd = getPropertyDescriptor(bean, pName); Class<?> pType = pd.getPropertyType(); if (!StringUtil.isEmpty(implClass)) { return ReflectionUtil.newObject(implClass, pType); } else if (!pType.isInterface()) { return ReflectionUtil.newObject(pType); } else { return null; } } private static PropertyDescriptor getPropertyDescriptor(Object bean, String pName) throws BeanException { Map<String, PropertyDescriptor> props = getProperties(bean.getClass()); return props.get(pName); } public static boolean setterExists(Object bean, String pName) throws BeanException { PropertyDescriptor pd = getPropertyDescriptor(bean, pName); return ((pd != null) && (pd.getWriteMethod() != null)); } public static boolean isPropertyAssignableFrom(Object bean, String pName, Class<?> target) throws BeanException { PropertyDescriptor pd = getPropertyDescriptor(bean, pName); return ((pd != null) && pd.getPropertyType().isAssignableFrom(target)); } public static Iterable<String> getSetters(Object bean) throws BeanException { BeanHandle bh = registerBean(bean.getClass().getName()); final Iterator<PropertyDescriptor> values = bh.getProperties().values().iterator(); return new Iterable<String>() { public Iterator<String> iterator() { return new Iterator<String>() { private PropertyDescriptor pd; public boolean hasNext() { while (values.hasNext()) { this.pd = values.next(); if (pd.getWriteMethod() != null) { return true; } } return false; } public String next() { return pd.getName(); } public void remove() { } }; } }; } /** * Injects the * @param elem * @param bean */ public static void setProperties(Element elem, Object bean) throws BeanException { NamedNodeMap attrs = elem.getAttributes(); int aCount = attrs.getLength(); for (int i = 0; i < aCount; i++) { Attr attr = (Attr) attrs.item(i); String aName = attr.getName(); if (setterExists(bean, aName)) { String aValue = attr.getValue(); setProperty(bean, aName, aValue); } } } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.10.24 at 02:07:37 PM BST // package com.oracle.xmlns.apps.sales.opptymgmt.revenues.revenueservice; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for RevenueTerritory complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RevenueTerritory"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="RevnTerrId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="RevnId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="TerritoryId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="TerritoryVersionId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="ConflictId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="CreatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CreationDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="LastUpdateDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="LastUpdatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LastUpdateLogin" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ObjectVersionNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="UserLastUpdateDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartyName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartyId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="Name1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="OrganizationId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="EffectiveStartDate" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="EffectiveEndDate" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="RoleName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="RoleId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="TypeCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ForecastParticipationCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="AssignmentType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RevenueTerritory", propOrder = { "revnTerrId", "revnId", "territoryId", "territoryVersionId", "conflictId", "createdBy", "creationDate", "lastUpdateDate", "lastUpdatedBy", "lastUpdateLogin", "objectVersionNumber", "userLastUpdateDate", "name", "partyName", "partyId", "name1", "organizationId", "effectiveStartDate", "effectiveEndDate", "roleName", "roleId", "typeCode", "forecastParticipationCode", "assignmentType" }) public class RevenueTerritory { @XmlElement(name = "RevnTerrId") protected Long revnTerrId; @XmlElement(name = "RevnId") protected Long revnId; @XmlElement(name = "TerritoryId") protected Long territoryId; @XmlElementRef(name = "TerritoryVersionId", namespace = "http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> territoryVersionId; @XmlElement(name = "ConflictId") protected Long conflictId; @XmlElement(name = "CreatedBy") protected String createdBy; @XmlElement(name = "CreationDate") protected XMLGregorianCalendar creationDate; @XmlElement(name = "LastUpdateDate") protected XMLGregorianCalendar lastUpdateDate; @XmlElement(name = "LastUpdatedBy") protected String lastUpdatedBy; @XmlElementRef(name = "LastUpdateLogin", namespace = "http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> lastUpdateLogin; @XmlElement(name = "ObjectVersionNumber") protected Integer objectVersionNumber; @XmlElementRef(name = "UserLastUpdateDate", namespace = "http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> userLastUpdateDate; @XmlElement(name = "Name") protected String name; @XmlElement(name = "PartyName") protected String partyName; @XmlElement(name = "PartyId") protected Long partyId; @XmlElement(name = "Name1") protected String name1; @XmlElement(name = "OrganizationId") protected Long organizationId; @XmlElement(name = "EffectiveStartDate") protected XMLGregorianCalendar effectiveStartDate; @XmlElement(name = "EffectiveEndDate") protected XMLGregorianCalendar effectiveEndDate; @XmlElement(name = "RoleName") protected String roleName; @XmlElement(name = "RoleId") protected Long roleId; @XmlElementRef(name = "TypeCode", namespace = "http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> typeCode; @XmlElementRef(name = "ForecastParticipationCode", namespace = "http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> forecastParticipationCode; @XmlElementRef(name = "AssignmentType", namespace = "http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> assignmentType; /** * Gets the value of the revnTerrId property. * * @return * possible object is * {@link Long } * */ public Long getRevnTerrId() { return revnTerrId; } /** * Sets the value of the revnTerrId property. * * @param value * allowed object is * {@link Long } * */ public void setRevnTerrId(Long value) { this.revnTerrId = value; } /** * Gets the value of the revnId property. * * @return * possible object is * {@link Long } * */ public Long getRevnId() { return revnId; } /** * Sets the value of the revnId property. * * @param value * allowed object is * {@link Long } * */ public void setRevnId(Long value) { this.revnId = value; } /** * Gets the value of the territoryId property. * * @return * possible object is * {@link Long } * */ public Long getTerritoryId() { return territoryId; } /** * Sets the value of the territoryId property. * * @param value * allowed object is * {@link Long } * */ public void setTerritoryId(Long value) { this.territoryId = value; } /** * Gets the value of the territoryVersionId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getTerritoryVersionId() { return territoryVersionId; } /** * Sets the value of the territoryVersionId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setTerritoryVersionId(JAXBElement<Long> value) { this.territoryVersionId = ((JAXBElement<Long> ) value); } /** * Gets the value of the conflictId property. * * @return * possible object is * {@link Long } * */ public Long getConflictId() { return conflictId; } /** * Sets the value of the conflictId property. * * @param value * allowed object is * {@link Long } * */ public void setConflictId(Long value) { this.conflictId = value; } /** * Gets the value of the createdBy property. * * @return * possible object is * {@link String } * */ public String getCreatedBy() { return createdBy; } /** * Sets the value of the createdBy property. * * @param value * allowed object is * {@link String } * */ public void setCreatedBy(String value) { this.createdBy = value; } /** * Gets the value of the creationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreationDate() { return creationDate; } /** * Sets the value of the creationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreationDate(XMLGregorianCalendar value) { this.creationDate = value; } /** * Gets the value of the lastUpdateDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastUpdateDate() { return lastUpdateDate; } /** * Sets the value of the lastUpdateDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastUpdateDate(XMLGregorianCalendar value) { this.lastUpdateDate = value; } /** * Gets the value of the lastUpdatedBy property. * * @return * possible object is * {@link String } * */ public String getLastUpdatedBy() { return lastUpdatedBy; } /** * Sets the value of the lastUpdatedBy property. * * @param value * allowed object is * {@link String } * */ public void setLastUpdatedBy(String value) { this.lastUpdatedBy = value; } /** * Gets the value of the lastUpdateLogin property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getLastUpdateLogin() { return lastUpdateLogin; } /** * Sets the value of the lastUpdateLogin property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setLastUpdateLogin(JAXBElement<String> value) { this.lastUpdateLogin = ((JAXBElement<String> ) value); } /** * Gets the value of the objectVersionNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getObjectVersionNumber() { return objectVersionNumber; } /** * Sets the value of the objectVersionNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setObjectVersionNumber(Integer value) { this.objectVersionNumber = value; } /** * Gets the value of the userLastUpdateDate property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getUserLastUpdateDate() { return userLastUpdateDate; } /** * Sets the value of the userLastUpdateDate property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setUserLastUpdateDate(JAXBElement<XMLGregorianCalendar> value) { this.userLastUpdateDate = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the partyName property. * * @return * possible object is * {@link String } * */ public String getPartyName() { return partyName; } /** * Sets the value of the partyName property. * * @param value * allowed object is * {@link String } * */ public void setPartyName(String value) { this.partyName = value; } /** * Gets the value of the partyId property. * * @return * possible object is * {@link Long } * */ public Long getPartyId() { return partyId; } /** * Sets the value of the partyId property. * * @param value * allowed object is * {@link Long } * */ public void setPartyId(Long value) { this.partyId = value; } /** * Gets the value of the name1 property. * * @return * possible object is * {@link String } * */ public String getName1() { return name1; } /** * Sets the value of the name1 property. * * @param value * allowed object is * {@link String } * */ public void setName1(String value) { this.name1 = value; } /** * Gets the value of the organizationId property. * * @return * possible object is * {@link Long } * */ public Long getOrganizationId() { return organizationId; } /** * Sets the value of the organizationId property. * * @param value * allowed object is * {@link Long } * */ public void setOrganizationId(Long value) { this.organizationId = value; } /** * Gets the value of the effectiveStartDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getEffectiveStartDate() { return effectiveStartDate; } /** * Sets the value of the effectiveStartDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setEffectiveStartDate(XMLGregorianCalendar value) { this.effectiveStartDate = value; } /** * Gets the value of the effectiveEndDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getEffectiveEndDate() { return effectiveEndDate; } /** * Sets the value of the effectiveEndDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setEffectiveEndDate(XMLGregorianCalendar value) { this.effectiveEndDate = value; } /** * Gets the value of the roleName property. * * @return * possible object is * {@link String } * */ public String getRoleName() { return roleName; } /** * Sets the value of the roleName property. * * @param value * allowed object is * {@link String } * */ public void setRoleName(String value) { this.roleName = value; } /** * Gets the value of the roleId property. * * @return * possible object is * {@link Long } * */ public Long getRoleId() { return roleId; } /** * Sets the value of the roleId property. * * @param value * allowed object is * {@link Long } * */ public void setRoleId(Long value) { this.roleId = value; } /** * Gets the value of the typeCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getTypeCode() { return typeCode; } /** * Sets the value of the typeCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setTypeCode(JAXBElement<String> value) { this.typeCode = ((JAXBElement<String> ) value); } /** * Gets the value of the forecastParticipationCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getForecastParticipationCode() { return forecastParticipationCode; } /** * Sets the value of the forecastParticipationCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setForecastParticipationCode(JAXBElement<String> value) { this.forecastParticipationCode = ((JAXBElement<String> ) value); } /** * Gets the value of the assignmentType property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getAssignmentType() { return assignmentType; } /** * Sets the value of the assignmentType property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setAssignmentType(JAXBElement<String> value) { this.assignmentType = ((JAXBElement<String> ) value); } }
/* * Copyright 2020 ThoughtWorks, 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.thoughtworks.go.config; import com.thoughtworks.go.config.elastic.ClusterProfiles; import com.thoughtworks.go.config.materials.MaterialConfigs; import com.thoughtworks.go.config.policy.PolicyAware; import com.thoughtworks.go.config.policy.PolicyValidationContext; import com.thoughtworks.go.config.remote.ConfigReposConfig; import com.thoughtworks.go.config.rules.RulesAware; import com.thoughtworks.go.config.rules.RulesValidationContext; import com.thoughtworks.go.domain.materials.MaterialConfig; import com.thoughtworks.go.domain.packagerepository.PackageRepository; import com.thoughtworks.go.domain.scm.SCM; import java.util.HashMap; /** * @understands providing right state required to validate a given config element */ public class ConfigSaveValidationContext implements ValidationContext { private final Validatable immediateParent; private final ConfigSaveValidationContext parentContext; private HashMap<Class, Object> objectOfType; private HashMap<String, MaterialConfigs> fingerprintToMaterials = null; public ConfigSaveValidationContext(Validatable immediateParent) { this(immediateParent, null); } public ConfigSaveValidationContext(Validatable immediateParent, ConfigSaveValidationContext parentContext) { this.immediateParent = immediateParent; this.parentContext = parentContext; objectOfType = new HashMap<>(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ConfigSaveValidationContext)) { return false; } ConfigSaveValidationContext that = (ConfigSaveValidationContext) o; if (immediateParent != null ? !immediateParent.equals(that.immediateParent) : that.immediateParent != null) { return false; } if (parentContext != null ? !parentContext.equals(that.parentContext) : that.parentContext != null) { return false; } return true; } @Override public int hashCode() { int result = immediateParent != null ? immediateParent.hashCode() : 0; result = 31 * result + (parentContext != null ? parentContext.hashCode() : 0); return result; } @Override public ConfigSaveValidationContext withParent(Validatable current) { return new ConfigSaveValidationContext(current, this); } @Override public CruiseConfig getCruiseConfig() { return loadFirstOfType(CruiseConfig.class); } @Override public RulesValidationContext getRulesValidationContext() { RulesAware rulesAware = loadFirstOfType(RulesAware.class); return new RulesValidationContext(rulesAware.allowedActions(), rulesAware.allowedTypes()); } @Override public PolicyValidationContext getPolicyValidationContext() { PolicyAware policyAware = loadFirstOfType(PolicyAware.class); return new PolicyValidationContext(policyAware.allowedActions(), policyAware.allowedTypes()); } @Override public ConfigReposConfig getConfigRepos() { return getCruiseConfig().getConfigRepos(); } @Override public JobConfig getJob() { return loadFirstOfType(JobConfig.class); } private <T> T loadFirstOfType(Class<T> klass) { T obj = getFirstOfType(klass); if (obj == null) { throw new IllegalArgumentException(String.format("Could not find an object of type '%s'.", klass.getCanonicalName())); } return obj; } private <T> T getFirstOfType(Class<T> klass) { Object o = objectOfType.get(klass); if (o == null) { o = _getFirstOfType(klass); objectOfType.put(klass, o); } return (T) o; } private <T> T _getFirstOfType(Class<T> klass) { if (parentContext != null) { T obj = parentContext.getFirstOfType(klass); if (obj != null) { return obj; } } if (immediateParent == null) { return null; } else if (immediateParent.getClass().equals(klass)) { return (T) immediateParent; } else { // added because of higher hierarchy of configuration types. // now there are interfaces with more than one implementation // so when asking for CruiseConfig there are 2 matching classes - BasicCruiseConfig and MergeCruiseConfig if (klass.isAssignableFrom(immediateParent.getClass())) { return (T) immediateParent; } } return null; } @Override public StageConfig getStage() { return loadFirstOfType(StageConfig.class); } @Override public PipelineConfig getPipeline() { return loadFirstOfType(PipelineConfig.class); } @Override public PipelineTemplateConfig getTemplate() { return loadFirstOfType(PipelineTemplateConfig.class); } @Override public PipelineConfig getPipelineConfigByName(CaseInsensitiveString pipelineName) { return getCruiseConfig().getPipelineConfigByName(pipelineName); } @Override public boolean shouldCheckConfigRepo() { return true; } @Override public SecurityConfig getServerSecurityConfig() { return getCruiseConfig().server().security(); } @Override public boolean doesTemplateExist(CaseInsensitiveString template) { return getCruiseConfig().getTemplates().hasTemplateNamed(template); } @Override public SCM findScmById(String scmID) { return getCruiseConfig().getSCMs().find(scmID); } @Override public PackageRepository findPackageById(String packageId) { return getCruiseConfig().getPackageRepositories().findPackageRepositoryHaving(packageId); } @Override public String getParentDisplayName() { return getParentType().getAnnotation(ConfigTag.class).value(); } private Class<? extends Validatable> getParentType() { return getParent().getClass(); } @Override public Validatable getParent() { return immediateParent; } @Override public boolean isWithinTemplates() { return hasParentOfType(TemplatesConfig.class); } @Override public boolean isWithinPipelines() { return hasParentOfType(PipelineConfigs.class); } @Override public boolean isWithinEnvironment() { return hasParentOfType(EnvironmentConfig.class); } private <T> boolean hasParentOfType(Class<T> validatable) { return getFirstOfType(validatable) != null; } @Override public PipelineConfigs getPipelineGroup() { return loadFirstOfType(PipelineConfigs.class); } @Override public EnvironmentConfig getEnvironment() { return loadFirstOfType(EnvironmentConfig.class); } @Override public String toString() { return "ValidationContext{" + "immediateParent=" + immediateParent + ", parentContext=" + parentContext + '}'; } @Override public boolean isValidProfileId(String profileId) { return this.getCruiseConfig().getElasticConfig().getProfiles().find(profileId) != null; } @Override public ClusterProfiles getClusterProfiles() { return this.getCruiseConfig().getElasticConfig().getClusterProfiles(); } @Override public boolean shouldNotCheckRole() { return isWithinTemplates(); } @Override public ArtifactStores artifactStores() { return this.getCruiseConfig().getArtifactStores(); } public static ConfigSaveValidationContext forChain(Validatable... validatables) { ConfigSaveValidationContext tail = new ConfigSaveValidationContext(null); for (Validatable validatable : validatables) { tail = tail.withParent(validatable); } return tail; } @Override public MaterialConfigs getAllMaterialsByFingerPrint(String fingerprint) { if (fingerprintToMaterials == null || fingerprintToMaterials.isEmpty()) { primeForMaterialValidations(); } MaterialConfigs matchingMaterials = fingerprintToMaterials.get(fingerprint); return matchingMaterials == null ? new MaterialConfigs() : matchingMaterials; } private void primeForMaterialValidations() { CruiseConfig cruiseConfig = getCruiseConfig(); fingerprintToMaterials = new HashMap<>(); for (PipelineConfig pipelineConfig : cruiseConfig.getAllPipelineConfigs()) { for (MaterialConfig material : pipelineConfig.materialConfigs()) { String fingerprint = material.getFingerprint(); if (!fingerprintToMaterials.containsKey(fingerprint)) { fingerprintToMaterials.put(fingerprint, new MaterialConfigs()); } MaterialConfigs materialsForFingerprint = fingerprintToMaterials.get(fingerprint); materialsForFingerprint.add(material); } } } }
/* * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 6450200 6450205 6450207 6450211 * @summary Test proper handling of tasks that terminate abruptly * @run main/othervm -XX:-UseVMInterruptibleIO ThrowingTasks * @author Martin Buchholz */ import java.security.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; public class ThrowingTasks { static final Random rnd = new Random(); @SuppressWarnings("serial") static class UncaughtExceptions extends ConcurrentHashMap<Class<?>, Integer> { void inc(Class<?> key) { for (;;) { Integer i = get(key); if (i == null) { if (putIfAbsent(key, 1) == null) return; } else { if (replace(key, i, i + 1)) return; } } } } @SuppressWarnings("serial") static class UncaughtExceptionsTable extends Hashtable<Class<?>, Integer> { synchronized void inc(Class<?> key) { Integer i = get(key); put(key, (i == null) ? 1 : i + 1); } } static final UncaughtExceptions uncaughtExceptions = new UncaughtExceptions(); static final UncaughtExceptionsTable uncaughtExceptionsTable = new UncaughtExceptionsTable(); static final AtomicLong totalUncaughtExceptions = new AtomicLong(0); static final CountDownLatch uncaughtExceptionsLatch = new CountDownLatch(24); static final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { check(! Thread.currentThread().isInterrupted()); totalUncaughtExceptions.getAndIncrement(); uncaughtExceptions.inc(e.getClass()); uncaughtExceptionsTable.inc(e.getClass()); uncaughtExceptionsLatch.countDown(); }}; static final ThreadGroup tg = new ThreadGroup("Flaky"); static final ThreadFactory tf = new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(tg, r); t.setUncaughtExceptionHandler(handler); return t; }}; static final RuntimeException rte = new RuntimeException(); static final Error error = new Error(); static final Throwable weird = new Throwable(); static final Exception checkedException = new Exception(); static class Thrower implements Runnable { Throwable t; Thrower(Throwable t) { this.t = t; } @SuppressWarnings("deprecation") public void run() { if (t != null) Thread.currentThread().stop(t); } } static final Thrower noThrower = new Thrower(null); static final Thrower rteThrower = new Thrower(rte); static final Thrower errorThrower = new Thrower(error); static final Thrower weirdThrower = new Thrower(weird); static final Thrower checkedThrower = new Thrower(checkedException); static final List<Thrower> throwers = Arrays.asList( noThrower, rteThrower, errorThrower, weirdThrower, checkedThrower); static class Flaky implements Runnable { final Runnable beforeExecute; final Runnable execute; Flaky(Runnable beforeExecute, Runnable execute) { this.beforeExecute = beforeExecute; this.execute = execute; } public void run() { execute.run(); } } static final List<Flaky> flakes = new ArrayList<Flaky>(); static { for (Thrower x : throwers) for (Thrower y : throwers) flakes.add(new Flaky(x, y)); Collections.shuffle(flakes); } static final CountDownLatch allStarted = new CountDownLatch(flakes.size()); static final CountDownLatch allContinue = new CountDownLatch(1); static class PermissiveSecurityManger extends SecurityManager { public void checkPermission(Permission p) { /* bien sur, Monsieur */ } } static void checkTerminated(ThreadPoolExecutor tpe) { try { check(tpe.getQueue().isEmpty()); check(tpe.isShutdown()); check(tpe.isTerminated()); check(! tpe.isTerminating()); equal(tpe.getActiveCount(), 0); equal(tpe.getPoolSize(), 0); equal(tpe.getTaskCount(), tpe.getCompletedTaskCount()); check(tpe.awaitTermination(0, TimeUnit.SECONDS)); } catch (Throwable t) { unexpected(t); } } static class CheckingExecutor extends ThreadPoolExecutor { CheckingExecutor() { super(10, 10, 1L, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>(), tf); } @Override protected void beforeExecute(Thread t, Runnable r) { allStarted.countDown(); if (allStarted.getCount() < getCorePoolSize()) try { allContinue.await(); } catch (InterruptedException x) { unexpected(x); } beforeExecuteCount.getAndIncrement(); check(! isTerminated()); ((Flaky)r).beforeExecute.run(); } @Override protected void afterExecute(Runnable r, Throwable t) { //System.out.println(tg.activeCount()); afterExecuteCount.getAndIncrement(); check(((Thrower)((Flaky)r).execute).t == t); check(! isTerminated()); } @Override protected void terminated() { try { terminatedCount.getAndIncrement(); if (rnd.nextBoolean()) { check(isShutdown()); check(isTerminating()); check(! isTerminated()); check(! awaitTermination(0L, TimeUnit.MINUTES)); } } catch (Throwable t) { unexpected(t); } } } static final AtomicInteger beforeExecuteCount = new AtomicInteger(0); static final AtomicInteger afterExecuteCount = new AtomicInteger(0); static final AtomicInteger terminatedCount = new AtomicInteger(0); private static void realMain(String[] args) throws Throwable { if (rnd.nextBoolean()) System.setSecurityManager(new PermissiveSecurityManger()); CheckingExecutor tpe = new CheckingExecutor(); for (Runnable task : flakes) tpe.execute(task); if (rnd.nextBoolean()) { allStarted.await(); equal(tpe.getTaskCount(), (long) flakes.size()); equal(tpe.getCompletedTaskCount(), (long) flakes.size() - tpe.getCorePoolSize()); } allContinue.countDown(); //System.out.printf("thread count = %d%n", tg.activeCount()); uncaughtExceptionsLatch.await(); while (tg.activeCount() != tpe.getCorePoolSize() || tg.activeCount() != tpe.getCorePoolSize()) Thread.sleep(10); equal(tg.activeCount(), tpe.getCorePoolSize()); tpe.shutdown(); check(tpe.awaitTermination(10L, TimeUnit.MINUTES)); checkTerminated(tpe); //while (tg.activeCount() > 0) Thread.sleep(10); //System.out.println(uncaughtExceptions); List<Map<Class<?>, Integer>> maps = new ArrayList<Map<Class<?>, Integer>>(); maps.add(uncaughtExceptions); maps.add(uncaughtExceptionsTable); for (Map<Class<?>, Integer> map : maps) { equal(map.get(Exception.class), throwers.size()); equal(map.get(weird.getClass()), throwers.size()); equal(map.get(Error.class), throwers.size() + 1 + 2); equal(map.get(RuntimeException.class), throwers.size() + 1); equal(map.size(), 4); } equal(totalUncaughtExceptions.get(), 4L*throwers.size() + 4L); equal(beforeExecuteCount.get(), flakes.size()); equal(afterExecuteCount.get(), throwers.size()); equal(tpe.getCompletedTaskCount(), (long) flakes.size()); equal(terminatedCount.get(), 1); // check for termination operation idempotence tpe.shutdown(); tpe.shutdownNow(); check(tpe.awaitTermination(10L, TimeUnit.MINUTES)); checkTerminated(tpe); equal(terminatedCount.get(), 1); } //--------------------- Infrastructure --------------------------- static volatile int passed = 0, failed = 0; static void pass() {passed++;} static void fail() {failed++; Thread.dumpStack();} static void fail(String msg) {System.out.println(msg); fail();} static void unexpected(Throwable t) {failed++; t.printStackTrace();} static void check(boolean cond) {if (cond) pass(); else fail();} static void equal(Object x, Object y) { if (x == null ? y == null : x.equals(y)) pass(); else fail(x + " not equal to " + y);} public static void main(String[] args) throws Throwable { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} }
package com.digdug.wesjohnston.richedittext; import android.content.Context; import android.os.Looper; import android.support.test.InstrumentationRegistry; import android.text.style.ImageSpan; import android.view.KeyEvent; import org.junit.Test; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; /** * Created by Wes Johnston on 2/24/2017. */ public class TestImage extends StyleTest<ImageSpan> { @Override boolean verifyStyle(RichEditText edit) { return edit.getImage() != null; } @Override protected void verifyStyleType(ImageSpan style) { assertTrue(true); } @Override protected Class<ImageSpan> getClassType() { return ImageSpan.class; } @Override protected void toggleStyle(RichEditText edit) { edit.addImage(android.R.mipmap.sym_def_app_icon); } // Test that toggling a style works @Test @Override public void testStyle() { Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 5, 0, 1); assertEquals(true, verifyStyle(edit)); //testToggle(edit, null, null); //assertEquals(false, verifyStyle(edit)); } @Test @Override public void testTwoAreas() { Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 4, 0, 1); assertEquals(true, verifyStyle(edit)); testToggle(edit, 6, 8, 0, 1, 6, 7); assertEquals(true, verifyStyle(edit)); testToggle(edit, 2, 5, 0, 1, 4, 5, 2, 3); assertEquals(true, verifyStyle(edit)); } @Test @Override public void testShortenStart() { Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 12, 0, 1); assertEquals(true, verifyStyle(edit)); // testToggle(edit, 0, 5, 6, 12); // assertEquals(false, verifyStyle(edit)); } @Test @Override public void testTypeFront() { if (!looperPrepared) { Looper.prepare(); looperPrepared = true; } Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello world"); testToggle(edit, 5, 7, 5, 6); edit.setSelection(5); //assertEquals(true, verifyStyle(edit)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_1)); //assertEquals("", Html.toHtml(edit.getText())); verifySpans(edit, 6, 7); } @Test @Override public void testShortenMiddle() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 12, 0, 1); assertEquals(true, verifyStyle(edit)); //testToggle(edit, 3, 6, 0, 2, 7, 12); //assertEquals(false, verifyStyle(edit)); } @Test @Override public void testShortenEnd() { Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 12, 0, 1); assertEquals(true, verifyStyle(edit)); //testToggle(edit, 6, 12, 0, 5); //assertEquals(false, verifyStyle(edit)); } @Test @Override public void testTypeBack() { if (!looperPrepared) { Looper.prepare(); looperPrepared = true; } Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello world"); testToggle(edit, 5, 7, 5, 6); edit.setSelection(6); assertEquals(true, verifyStyle(edit)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_1)); verifySpans(edit, 5, 6); } @Override @Test public void testToggleMiddle() { if (!looperPrepared) { Looper.prepare(); looperPrepared = true; } Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 12, 0, 1); assertEquals(true, verifyStyle(edit)); testToggle(edit, 1, null, 0, 1, 1, 2); // assertEquals(false, verifyStyle(edit)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_1)); verifySpans(edit, 0, 1, 1, 2); } @Test @Override public void testExtendStart() { Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 0, 5, 0, 1); assertEquals(true, verifyStyle(edit)); testToggle(edit, 0, 8, 0, 1); assertEquals(true, verifyStyle(edit)); } @Test @Override public void testExtendEnd() { Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello World!"); testToggle(edit, 6, 12, 6, 7); assertEquals(true, verifyStyle(edit)); testToggle(edit, 0, 7, 0, 1); assertEquals(true, verifyStyle(edit)); } @Test @Override public void testNoSelection() { if (!looperPrepared) { Looper.prepare(); looperPrepared = true; } Context appContext = InstrumentationRegistry.getTargetContext(); RichEditText edit = new RichEditText(appContext); edit.setText("Hello world"); edit.setSelection(5); toggleStyle(edit); verifySpans(edit, 5, 6); assertEquals(true, verifyStyle(edit)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1)); edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_1)); verifySpans(edit, 5, 6); toggleStyle(edit); //assertEquals(false, verifyStyle(edit)); //edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_2)); //edit.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_2)); verifySpans(edit, 5, 6, 7, 8); } }
package com.noveogroup.screen_shot_report.widgets; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Point; import android.os.Parcelable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; import static android.graphics.Bitmap.Config.ARGB_8888; public class MarkView extends ImageView { private static final String LOG_TAG = MarkView.class.getName(); public static final Paint DEFAULT_PAINT = new Paint(); static { DEFAULT_PAINT.setStrokeWidth(5f); DEFAULT_PAINT.setColor(Color.MAGENTA); DEFAULT_PAINT.setStyle(Paint.Style.STROKE); DEFAULT_PAINT.setAntiAlias(true); } public static final Paint SUCCESS_PATH_PAINT = new Paint(DEFAULT_PAINT); static { SUCCESS_PATH_PAINT.setColor(Color.GREEN); } public static final Paint ERROR_PATH_PAINT = new Paint(DEFAULT_PAINT); static { ERROR_PATH_PAINT.setColor(Color.RED); } private final Matrix eMatrix = new Matrix(); { eMatrix.setTranslate(0f, 0f); } private final float[] utilValues = new float[9]; private Mark currentMark; private Paint currentMarkPaint = DEFAULT_PAINT; private boolean drawable = true; private ArrayList<Mark> marks = new ArrayList<Mark>(); private OnSizeChangedListener onSizeChangedListener = new OnSizeChangedListener() { @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { } }; private OnComputeScrollListener onComputeScrollListener = new OnComputeScrollListener() { @Override public void onComputeScroll() { } }; private boolean isPainting; public static interface OnSizeChangedListener { public void onSizeChanged(int w, int h, int oldw, int oldh); } public static interface OnComputeScrollListener { public void onComputeScroll(); } public MarkView(Context context) { super(context); } public MarkView(Context context, AttributeSet attrs) { super(context, attrs); } public MarkView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); onSizeChangedListener.onSizeChanged(w, h, oldw, oldh); } @Override public void computeScroll() { super.computeScroll(); if (ScrollSynchronizer.getInstance().amILocker(this)) { onComputeScrollListener.onComputeScroll(); } } public void setOnComputeScrollListener(final OnComputeScrollListener onComputeScrollListener) { this.onComputeScrollListener = onComputeScrollListener; } @Override protected void onDraw(final Canvas canvas) { //canvas.drawBitmap(border, this.eMatrix, null); super.onDraw(canvas); if (!drawable) { return; } final Matrix matrix = getImageMatrix(); matrix.getValues(utilValues); canvas.translate(utilValues[Matrix.MTRANS_X], utilValues[Matrix.MTRANS_Y]); canvas.scale(utilValues[Matrix.MSCALE_X], utilValues[Matrix.MSCALE_Y]); if (currentMark != null) { canvas.drawPath(currentMark.path, currentMarkPaint); } for (final Mark mark : marks) { if (mark != null) { canvas.drawPath(mark.path, SUCCESS_PATH_PAINT); } } } public boolean isPainting() { return isPainting; } public void setPainting(boolean isPainting) { this.isPainting = isPainting; } @Override public boolean onTouchEvent(final MotionEvent ev) { Log.d(LOG_TAG, "onTouchEvent"); final int action = ev.getAction(); if ((action == MotionEvent.ACTION_DOWN) || (action == MotionEvent.ACTION_MOVE)) { ScrollSynchronizer.getInstance().tryLock(this); } else if ((action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_OUTSIDE)) { ScrollSynchronizer.getInstance().tryUnlock(this); } else if (ev.getAction() == MotionEvent.ACTION_CANCEL) { ScrollSynchronizer.getInstance().tryUnlock(this); } if (ScrollSynchronizer.getInstance().amILocker(this)) { if (drawable && isPainting) { final float eventX = ev.getX(); final float eventY = ev.getY(); final Matrix matrix = getImageMatrix(); matrix.getValues(utilValues); final float pathX = (eventX - utilValues[Matrix.MTRANS_X]) / utilValues[Matrix.MSCALE_X]; final float pathY = (eventY - utilValues[Matrix.MTRANS_Y]) / utilValues[Matrix.MSCALE_Y]; if (action == MotionEvent.ACTION_DOWN) { currentMark = new Mark(); currentMark.path.moveTo(pathX, pathY); currentMark.points.add(new Point((int) pathX, (int) pathY)); } else if (action == MotionEvent.ACTION_MOVE) { if (currentMark != null) { currentMark.path.lineTo(pathX, pathY); currentMark.path.rMoveTo(0, 0); currentMark.points.add(new Point((int) pathX, (int) pathY)); } } else if (action == MotionEvent.ACTION_UP) { if (currentMark != null) { marks.add(currentMark); currentMark = null; // checkCurrentMark(); } } invalidate(); return true; } else { super.onTouchEvent(ev); return true; } } return false; } public void setOnSizeChangedListener(OnSizeChangedListener listener) { this.onSizeChangedListener = listener; } public void setCurrentMarkPaint(final Paint paint) { this.currentMarkPaint = paint; } public void removeLastMark() { if (marks != null && marks.size() > 0) { this.marks.remove(marks.size() - 1); } invalidate(); } public boolean isDrawable() { return drawable; } public void setDrawable(final boolean drawable) { this.drawable = drawable; } public void removeAllMarks() { marks.clear(); currentMark = null; invalidate(); } public Bitmap createPicture() { DisplayMetrics dm = getContext().getResources().getDisplayMetrics(); final Bitmap bitmap = Bitmap.createBitmap(dm.widthPixels, dm.heightPixels, ARGB_8888); final Canvas canvas = new Canvas(bitmap); setImageMatrix(eMatrix); draw(canvas); return bitmap; } public ArrayList<Mark> getMarks() { return marks; } public void setMarks(ArrayList<Mark> marks) { this.marks = marks; } }
/** * Copyright 2014 Nikita Koksharov, Nickolay Borbit * * 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.redisson.connection; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.redisson.MasterSlaveServersConfig; import org.redisson.misc.ReclosableLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lambdaworks.redis.RedisConnection; import com.lambdaworks.redis.RedisConnectionException; import com.lambdaworks.redis.codec.RedisCodec; import com.lambdaworks.redis.pubsub.RedisPubSubConnection; abstract class BaseLoadBalancer implements LoadBalancer { private final Logger log = LoggerFactory.getLogger(getClass()); private RedisCodec codec; private MasterSlaveServersConfig config; private final ReclosableLatch clientsEmpty = new ReclosableLatch(); final Queue<SubscribesConnectionEntry> clients = new ConcurrentLinkedQueue<SubscribesConnectionEntry>(); public void init(RedisCodec codec, MasterSlaveServersConfig config) { this.codec = codec; this.config = config; } public synchronized void add(SubscribesConnectionEntry entry) { clients.add(entry); clientsEmpty.open(); } public synchronized void unfreeze(String host, int port) { InetSocketAddress addr = new InetSocketAddress(host, port); for (SubscribesConnectionEntry connectionEntry : clients) { if (!connectionEntry.getClient().getAddr().equals(addr)) { continue; } connectionEntry.setFreezed(false); clientsEmpty.open(); return; } throw new IllegalStateException("Can't find " + addr + " in slaves!"); } public synchronized Collection<RedisPubSubConnection> freeze(String host, int port) { InetSocketAddress addr = new InetSocketAddress(host, port); for (SubscribesConnectionEntry connectionEntry : clients) { if (connectionEntry.isFreezed() || !connectionEntry.getClient().getAddr().equals(addr)) { continue; } log.debug("{} freezed", addr); connectionEntry.setFreezed(true); // close all connections while (true) { RedisConnection connection = connectionEntry.getConnections().poll(); if (connection == null) { break; } connection.close(); } // close all pub/sub connections while (true) { RedisPubSubConnection connection = connectionEntry.pollFreeSubscribeConnection(); if (connection == null) { break; } connection.close(); } boolean allFreezed = true; for (SubscribesConnectionEntry entry : clients) { if (!entry.isFreezed()) { allFreezed = false; break; } } if (allFreezed) { clientsEmpty.close(); } List<RedisPubSubConnection> list = new ArrayList<RedisPubSubConnection>(connectionEntry.getAllSubscribeConnections()); connectionEntry.getAllSubscribeConnections().clear(); return list; } return Collections.emptyList(); } @SuppressWarnings("unchecked") public RedisPubSubConnection nextPubSubConnection() { clientsEmpty.awaitUninterruptibly(); List<SubscribesConnectionEntry> clientsCopy = new ArrayList<SubscribesConnectionEntry>(clients); while (true) { if (clientsCopy.isEmpty()) { throw new RedisConnectionException("Slave subscribe-connection pool gets exhausted!"); } int index = getIndex(clientsCopy); SubscribesConnectionEntry entry = clientsCopy.get(index); if (entry.isFreezed() || !entry.getSubscribeConnectionsSemaphore().tryAcquire()) { clientsCopy.remove(index); } else { try { RedisPubSubConnection conn = entry.pollFreeSubscribeConnection(); if (conn != null) { return conn; } conn = entry.getClient().connectPubSub(codec); if (config.getPassword() != null) { conn.auth(config.getPassword()); } if (config.getDatabase() != 0) { conn.select(config.getDatabase()); } if (config.getClientName() != null) { conn.clientSetname(config.getClientName()); } entry.registerSubscribeConnection(conn); return conn; } catch (RedisConnectionException e) { entry.getSubscribeConnectionsSemaphore().release(); // TODO connection scoring log.warn("Can't connect to {}, trying next connection!", entry.getClient().getAddr()); clientsCopy.remove(index); } } } } public RedisConnection nextConnection() { clientsEmpty.awaitUninterruptibly(); List<SubscribesConnectionEntry> clientsCopy = new ArrayList<SubscribesConnectionEntry>(clients); while (true) { if (clientsCopy.isEmpty()) { throw new RedisConnectionException("Slave connection pool gets exhausted!"); } int index = getIndex(clientsCopy); SubscribesConnectionEntry entry = clientsCopy.get(index); if (entry.isFreezed() || !entry.getConnectionsSemaphore().tryAcquire()) { clientsCopy.remove(index); } else { RedisConnection conn = entry.getConnections().poll(); if (conn != null) { return conn; } try { conn = entry.getClient().connect(codec); if (config.getPassword() != null) { conn.auth(config.getPassword()); } if (config.getDatabase() != 0) { conn.select(config.getDatabase()); } if (config.getClientName() != null) { conn.clientSetname(config.getClientName()); } return conn; } catch (RedisConnectionException e) { entry.getConnectionsSemaphore().release(); // TODO connection scoring log.warn("Can't connect to {}, trying next connection!", entry.getClient().getAddr()); clientsCopy.remove(index); } } } } abstract int getIndex(List<SubscribesConnectionEntry> clientsCopy); public void returnSubscribeConnection(RedisPubSubConnection connection) { for (SubscribesConnectionEntry entry : clients) { if (entry.getClient().equals(connection.getRedisClient())) { if (entry.isFreezed()) { connection.close(); } else { entry.offerFreeSubscribeConnection(connection); } entry.getSubscribeConnectionsSemaphore().release(); break; } } } public void returnConnection(RedisConnection connection) { for (SubscribesConnectionEntry entry : clients) { if (entry.getClient().equals(connection.getRedisClient())) { if (entry.isFreezed()) { connection.close(); } else { entry.getConnections().add(connection); } entry.getConnectionsSemaphore().release(); break; } } } public void shutdown() { for (SubscribesConnectionEntry entry : clients) { entry.getClient().shutdown(); } } }
package Accounting.editor; /*Generated by MPS */ import jetbrains.mps.nodeEditor.DefaultNodeEditor; import jetbrains.mps.openapi.editor.cells.EditorCell; import jetbrains.mps.openapi.editor.EditorContext; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.nodeEditor.cells.EditorCell_Collection; import jetbrains.mps.nodeEditor.cells.EditorCell_Constant; import jetbrains.mps.openapi.editor.style.Style; import jetbrains.mps.editor.runtime.style.StyleImpl; import jetbrains.mps.editor.runtime.style.StyleAttributes; import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole; import jetbrains.mps.lang.editor.cellProviders.PropertyCellProvider; import jetbrains.mps.nodeEditor.EditorManager; import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.nodeEditor.cellMenu.DefaultChildSubstituteInfo; import jetbrains.mps.nodeEditor.cells.EditorCell_Indent; import jetbrains.mps.lang.editor.cellProviders.RefCellCellProvider; import jetbrains.mps.nodeEditor.InlineCellProvider; import jetbrains.mps.baseLanguage.closures.runtime.Wrappers; import de.slisson.mps.tables.runtime.cells.TableEditor; import jetbrains.mps.baseLanguage.closures.runtime._FunctionTypes; import de.slisson.mps.hacks.editor.EditorCacheHacks; import de.slisson.mps.tables.runtime.cells.ChildsTracker; import de.slisson.mps.tables.runtime.cells.PartialTableExtractor; import de.slisson.mps.tables.runtime.gridmodel.Grid; import java.util.List; import de.slisson.mps.tables.runtime.gridmodel.HeaderGrid; import java.util.ArrayList; import jetbrains.mps.internal.collections.runtime.ListSequence; import de.slisson.mps.tables.runtime.style.ITableStyleFactory; import de.slisson.mps.tables.runtime.gridmodel.IHeaderNodeInsertAction; import de.slisson.mps.tables.runtime.gridmodel.IHeaderNodeDeleteAction; import de.slisson.mps.tables.runtime.gridmodel.HeaderGridFactory; import de.slisson.mps.tables.runtime.gridmodel.Header; import de.slisson.mps.tables.runtime.gridmodel.EditorCellHeader; import de.slisson.mps.tables.runtime.gridmodel.StringHeaderReference; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.internal.collections.runtime.ISelector; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.smodel.action.SNodeFactoryOperations; import de.slisson.mps.tables.runtime.gridmodel.GridAdapter; import de.slisson.mps.tables.runtime.gridmodel.GridElementFactory; import de.slisson.mps.tables.runtime.gridmodel.IGridElement; import de.slisson.mps.tables.runtime.substitute.CellQuerySubstituteInfo; import de.slisson.mps.tables.runtime.cells.TableUtils; import jetbrains.mps.editor.runtime.cells.AbstractCellAction; import jetbrains.mps.openapi.editor.cells.CellAction; import org.apache.log4j.Logger; import jetbrains.mps.nodeEditor.cells.EditorCell_Error; import de.slisson.mps.tables.runtime.cells.PartialTableEditor; import de.slisson.mps.tables.runtime.gridmodel.EditorCellGridLeaf; import jetbrains.mps.nodeEditor.AbstractCellProvider; import jetbrains.mps.nodeEditor.cells.EditorCell_Property; import jetbrains.mps.nodeEditor.cells.ModelAccessor; import Accounting.behavior.InvoiceLine__BehaviorDescriptor; import jetbrains.mps.util.EqualUtil; import jetbrains.mps.openapi.editor.cells.CellActionType; import jetbrains.mps.editor.runtime.cells.EmptyCellAction; import Accounting.behavior.Invoice__BehaviorDescriptor; public class Invoice_Editor extends DefaultNodeEditor { public EditorCell createEditorCell(EditorContext editorContext, SNode node) { return this.createCollection_mbkewv_a(editorContext, node); } private EditorCell createCollection_mbkewv_a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createVertical(editorContext, node); editorCell.setCellId("Collection_mbkewv_a"); editorCell.setBig(true); editorCell.addEditorCell(this.createCollection_mbkewv_a0(editorContext, node)); editorCell.addEditorCell(this.createCollection_mbkewv_b0(editorContext, node)); editorCell.addEditorCell(this.createConstant_mbkewv_c0(editorContext, node)); return editorCell; } private EditorCell createCollection_mbkewv_a0(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createHorizontal(editorContext, node); editorCell.setCellId("Collection_mbkewv_a0"); editorCell.addEditorCell(this.createConstant_mbkewv_a0a(editorContext, node)); editorCell.addEditorCell(this.createConstant_mbkewv_b0a(editorContext, node)); editorCell.addEditorCell(this.createProperty_mbkewv_c0a(editorContext, node)); editorCell.addEditorCell(this.createConstant_mbkewv_d0a(editorContext, node)); editorCell.addEditorCell(this.createRefNode_mbkewv_e0a(editorContext, node)); return editorCell; } private EditorCell createConstant_mbkewv_a0a(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "invoice"); editorCell.setCellId("Constant_mbkewv_a0a"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createConstant_mbkewv_b0a(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "#"); editorCell.setCellId("Constant_mbkewv_b0a"); Style style = new StyleImpl(); style.set(StyleAttributes.PUNCTUATION_RIGHT, 0, true); editorCell.getStyle().putAll(style); editorCell.setDefaultText(""); return editorCell; } private EditorCell createProperty_mbkewv_c0a(EditorContext editorContext, SNode node) { CellProviderWithRole provider = new PropertyCellProvider(node, editorContext); provider.setRole("identifier"); provider.setNoTargetText("<no identifier>"); EditorCell editorCell; editorCell = provider.createEditorCell(editorContext); editorCell.setCellId("property_identifier"); editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo()); SNode attributeConcept = provider.getRoleAttribute(); Class attributeKind = provider.getRoleAttributeClass(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(editorContext); return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell); } else return editorCell; } private EditorCell createConstant_mbkewv_d0a(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "on"); editorCell.setCellId("Constant_mbkewv_d0a"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createRefNode_mbkewv_e0a(EditorContext editorContext, SNode node) { SingleRoleCellProvider provider = new Invoice_Editor.emittedOnSingleRoleHandler_mbkewv_e0a(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ec6e7L, "emittedOn"), editorContext); return provider.createCell(); } private class emittedOnSingleRoleHandler_mbkewv_e0a extends SingleRoleCellProvider { public emittedOnSingleRoleHandler_mbkewv_e0a(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) { super(ownerNode, containmentLink, context); } protected EditorCell createChildCell(SNode child) { EditorCell editorCell = super.createChildCell(child); installCellInfo(child, editorCell); return editorCell; } private void installCellInfo(SNode child, EditorCell editorCell) { editorCell.setSubstituteInfo(new DefaultChildSubstituteInfo(myOwnerNode, myContainmentLink.getDeclarationNode(), myEditorContext)); if (editorCell.getRole() == null) { editorCell.setRole("emittedOn"); } } @Override protected EditorCell createEmptyCell() { EditorCell editorCell = super.createEmptyCell(); editorCell.setCellId("empty_emittedOn"); installCellInfo(null, editorCell); return editorCell; } protected String getNoTargetText() { return "<no emittedOn>"; } } private EditorCell createCollection_mbkewv_b0(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createHorizontal(editorContext, node); editorCell.setCellId("Collection_mbkewv_b0"); Style style = new StyleImpl(); style.set(StyleAttributes.SELECTABLE, 0, false); editorCell.getStyle().putAll(style); editorCell.addEditorCell(this.createIndentCell_mbkewv_a1a(editorContext, node)); editorCell.addEditorCell(this.createCollection_mbkewv_b1a(editorContext, node)); return editorCell; } private EditorCell createIndentCell_mbkewv_a1a(EditorContext editorContext, SNode node) { EditorCell_Indent editorCell = new EditorCell_Indent(editorContext, node); return editorCell; } private EditorCell createCollection_mbkewv_b1a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createVertical(editorContext, node); editorCell.setCellId("Collection_mbkewv_b1a"); editorCell.addEditorCell(this.createCollection_mbkewv_a1b0(editorContext, node)); editorCell.addEditorCell(this.createConstant_mbkewv_b1b0(editorContext, node)); editorCell.addEditorCell(this.createTable_mbkewv_c1b0(editorContext, node)); return editorCell; } private EditorCell createCollection_mbkewv_a1b0(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createVertical(editorContext, node); editorCell.setCellId("Collection_mbkewv_a1b0"); Style style = new StyleImpl(); style.set(StyleAttributes.SELECTABLE, 0, false); editorCell.getStyle().putAll(style); editorCell.setGridLayout(true); editorCell.addEditorCell(this.createCollection_mbkewv_a0b1a(editorContext, node)); editorCell.addEditorCell(this.createCollection_mbkewv_b0b1a(editorContext, node)); return editorCell; } private EditorCell createCollection_mbkewv_a0b1a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createHorizontal(editorContext, node); editorCell.setCellId("Collection_mbkewv_a0b1a"); Style style = new StyleImpl(); style.set(StyleAttributes.SELECTABLE, 0, false); editorCell.getStyle().putAll(style); editorCell.addEditorCell(this.createConstant_mbkewv_a0a1b0(editorContext, node)); editorCell.addEditorCell(this.createRefCell_mbkewv_b0a1b0(editorContext, node)); return editorCell; } private EditorCell createConstant_mbkewv_a0a1b0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "emitter:"); editorCell.setCellId("Constant_mbkewv_a0a1b0"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createRefCell_mbkewv_b0a1b0(EditorContext editorContext, SNode node) { CellProviderWithRole provider = new RefCellCellProvider(node, editorContext); provider.setRole("emitter"); provider.setNoTargetText("<no emitter>"); EditorCell editorCell; provider.setAuxiliaryCellProvider(new Invoice_Editor._Inline_mbkewv_a1a0b1a()); editorCell = provider.createEditorCell(editorContext); if (editorCell.getRole() == null) { editorCell.setReferenceCell(true); editorCell.setRole("emitter"); } editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo()); SNode attributeConcept = provider.getRoleAttribute(); Class attributeKind = provider.getRoleAttributeClass(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(editorContext); return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell); } else return editorCell; } public static class _Inline_mbkewv_a1a0b1a extends InlineCellProvider { public _Inline_mbkewv_a1a0b1a() { super(); } public EditorCell createEditorCell(EditorContext editorContext) { return this.createEditorCell(editorContext, this.getSNode()); } public EditorCell createEditorCell(EditorContext editorContext, SNode node) { return this.createProperty_mbkewv_a0b0a1b0(editorContext, node); } private EditorCell createProperty_mbkewv_a0b0a1b0(EditorContext editorContext, SNode node) { CellProviderWithRole provider = new PropertyCellProvider(node, editorContext); provider.setRole("name"); provider.setNoTargetText("<no name>"); provider.setReadOnly(true); EditorCell editorCell; editorCell = provider.createEditorCell(editorContext); editorCell.setCellId("property_name"); editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo()); SNode attributeConcept = provider.getRoleAttribute(); Class attributeKind = provider.getRoleAttributeClass(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(editorContext); return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell); } else return editorCell; } } private EditorCell createCollection_mbkewv_b0b1a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createHorizontal(editorContext, node); editorCell.setCellId("Collection_mbkewv_b0b1a"); Style style = new StyleImpl(); style.set(StyleAttributes.SELECTABLE, 0, false); editorCell.getStyle().putAll(style); editorCell.addEditorCell(this.createConstant_mbkewv_a1a1b0(editorContext, node)); editorCell.addEditorCell(this.createRefCell_mbkewv_b1a1b0(editorContext, node)); return editorCell; } private EditorCell createConstant_mbkewv_a1a1b0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "client:"); editorCell.setCellId("Constant_mbkewv_a1a1b0"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createRefCell_mbkewv_b1a1b0(EditorContext editorContext, SNode node) { CellProviderWithRole provider = new RefCellCellProvider(node, editorContext); provider.setRole("client"); provider.setNoTargetText("<no client>"); EditorCell editorCell; provider.setAuxiliaryCellProvider(new Invoice_Editor._Inline_mbkewv_a1b0b1a()); editorCell = provider.createEditorCell(editorContext); if (editorCell.getRole() == null) { editorCell.setReferenceCell(true); editorCell.setRole("client"); } editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo()); SNode attributeConcept = provider.getRoleAttribute(); Class attributeKind = provider.getRoleAttributeClass(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(editorContext); return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell); } else return editorCell; } public static class _Inline_mbkewv_a1b0b1a extends InlineCellProvider { public _Inline_mbkewv_a1b0b1a() { super(); } public EditorCell createEditorCell(EditorContext editorContext) { return this.createEditorCell(editorContext, this.getSNode()); } public EditorCell createEditorCell(EditorContext editorContext, SNode node) { return this.createProperty_mbkewv_a0b1a1b0(editorContext, node); } private EditorCell createProperty_mbkewv_a0b1a1b0(EditorContext editorContext, SNode node) { CellProviderWithRole provider = new PropertyCellProvider(node, editorContext); provider.setRole("name"); provider.setNoTargetText("<no name>"); provider.setReadOnly(true); EditorCell editorCell; editorCell = provider.createEditorCell(editorContext); editorCell.setCellId("property_name_1"); editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo()); SNode attributeConcept = provider.getRoleAttribute(); Class attributeKind = provider.getRoleAttributeClass(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(editorContext); return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell); } else return editorCell; } } private EditorCell createConstant_mbkewv_b1b0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, ""); editorCell.setCellId("Constant_mbkewv_b1b0"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createTable_mbkewv_c1b0(final EditorContext editorContext, final SNode node) { final Wrappers._T<TableEditor> editorCell = new Wrappers._T<TableEditor>(null); _FunctionTypes._void_P0_E0 creator = new _FunctionTypes._void_P0_E0() { public void invoke() { EditorCacheHacks.noCaching(editorContext, new Runnable() { public void run() { try { ChildsTracker.pushNewInstance(); PartialTableExtractor.pushNewInstance(); Grid grid = new Grid(); // column headers { List<HeaderGrid> headerGrids = new ArrayList<HeaderGrid>(0); grid.setColumnHeaders(headerGrids); } // row headers { List<HeaderGrid> headerGrids = new ArrayList<HeaderGrid>(0); grid.setRowHeaders(headerGrids); } final Grid childGrid = createStaticVertical_mbkewv_a2b1a(editorContext, node); childGrid.setSpanX(Math.max(1, grid.getColumnHeadersSizeX())); childGrid.setSpanY(Math.max(1, grid.getRowHeadersSizeY())); grid.setElement(0, 0, childGrid); editorCell.value = new TableEditor(editorContext, node, grid); editorCell.value.setCellId("Table_mbkewv_c1b0"); editorCell.value.init(); } finally { PartialTableExtractor.popInstance(); ChildsTracker.popInstance(true); } } }); } }; creator.invoke(); return editorCell.value; } public Grid createStaticVertical_mbkewv_a2b1a(final EditorContext editorContext, final SNode node) { Grid grid = new Grid(); grid.setColumnHeaders(0, 0, createHeaderCollection_mbkewv_a0c1b0(editorContext, node)); List<Grid> childs = new ArrayList<Grid>(3); childs.add(createStaticHorizontal_mbkewv_a0c1b0(editorContext, node)); childs.add(createTableCell_mbkewv_b0c1b0(editorContext, node)); childs.add(createTableCellQuery_mbkewv_c0c1b0(editorContext, node)); int maxWidth = grid.getColumnHeadersSizeX(); for (Grid child : ListSequence.fromList(childs)) { maxWidth = Math.max(maxWidth, child.getSizeX()); } for (int y = 0; y < childs.size(); y++) { if (maxWidth > 0) { childs.get(y).setSpanX(maxWidth); } grid.setElement(0, y, childs.get(y)); } final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); grid.setStyle(style); return grid; } public HeaderGrid createHeaderCollection_mbkewv_a0c1b0(final EditorContext editorContext, final SNode node) { IHeaderNodeInsertAction insertAction = null; IHeaderNodeDeleteAction deleteAction = null; List<HeaderGrid> nodeList = new ArrayList<HeaderGrid>(); nodeList.add(createStaticHeader_mbkewv_a0a2b1a(editorContext, node)); nodeList.add(createStaticHeader_mbkewv_b0a2b1a(editorContext, node)); nodeList.add(createStaticHeader_mbkewv_c0a2b1a(editorContext, node)); nodeList.add(createStaticHeader_mbkewv_d0a2b1a(editorContext, node)); nodeList.add(createStaticHeader_mbkewv_e0a2b1a(editorContext, node)); return new HeaderGridFactory(editorContext, node, true).createFromHeaderGridList(nodeList); } public HeaderGrid createStaticHeader_mbkewv_a0a2b1a(final EditorContext editorContext, final SNode snode) { final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); final EditorCell_Constant cell = new EditorCell_Constant(editorContext, snode, "Description", false); Header header = new EditorCellHeader(new StringHeaderReference("Description"), cell); header.setLabel("Description"); header.setStyle(style); HeaderGrid grid = new HeaderGrid(); grid.setElement(0, 0, header); return grid; } public HeaderGrid createStaticHeader_mbkewv_b0a2b1a(final EditorContext editorContext, final SNode snode) { final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); final EditorCell_Constant cell = new EditorCell_Constant(editorContext, snode, "Amount", false); Header header = new EditorCellHeader(new StringHeaderReference("Amount"), cell); header.setLabel("Amount"); header.setStyle(style); HeaderGrid grid = new HeaderGrid(); grid.setElement(0, 0, header); return grid; } public HeaderGrid createStaticHeader_mbkewv_c0a2b1a(final EditorContext editorContext, final SNode snode) { final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); final EditorCell_Constant cell = new EditorCell_Constant(editorContext, snode, "VAT Rate", false); Header header = new EditorCellHeader(new StringHeaderReference("VAT Rate"), cell); header.setLabel("VAT Rate"); header.setStyle(style); HeaderGrid grid = new HeaderGrid(); grid.setElement(0, 0, header); return grid; } public HeaderGrid createStaticHeader_mbkewv_d0a2b1a(final EditorContext editorContext, final SNode snode) { final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); final EditorCell_Constant cell = new EditorCell_Constant(editorContext, snode, "VAT", false); Header header = new EditorCellHeader(new StringHeaderReference("VAT"), cell); header.setLabel("VAT"); header.setStyle(style); HeaderGrid grid = new HeaderGrid(); grid.setElement(0, 0, header); return grid; } public HeaderGrid createStaticHeader_mbkewv_e0a2b1a(final EditorContext editorContext, final SNode snode) { final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); final EditorCell_Constant cell = new EditorCell_Constant(editorContext, snode, "Total", false); Header header = new EditorCellHeader(new StringHeaderReference("Total"), cell); header.setLabel("Total"); header.setStyle(style); HeaderGrid grid = new HeaderGrid(); grid.setElement(0, 0, header); return grid; } public Grid createStaticHorizontal_mbkewv_a0c1b0(final EditorContext editorContext, final SNode node) { Grid grid = new Grid(); grid.setRowHeaders(0, 0, createHeadQuery_mbkewv_a0a2b1a(editorContext, node)); List<Grid> childs = new ArrayList<Grid>(1); childs.add(createTableCellQuery_mbkewv_a0a2b1a(editorContext, node)); int maxHeight = grid.getRowHeadersSizeY(); for (Grid child : ListSequence.fromList(childs)) { maxHeight = Math.max(maxHeight, child.getSizeY()); } for (int x = 0; x < childs.size(); x++) { if (maxHeight > 0) { childs.get(x).setSpanY(maxHeight); } grid.setElement(x, 0, childs.get(x)); } final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); grid.setStyle(style); return grid; } public HeaderGrid createHeadQuery_mbkewv_a0a2b1a(final EditorContext editorContext, final SNode node) { Object queryResult = new Object() { public Object query() { return ListSequence.fromList(SLinkOperations.getChildren(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ee0d4L, "lines"))).select(new ISelector<SNode, String>() { public String select(SNode it) { return Integer.toString(SNodeOperations.getIndexInParent(it) + 1); } }); } }.query(); IHeaderNodeInsertAction insertAction = new IHeaderNodeInsertAction() { public void insertNew(int index) { SNodeFactoryOperations.addNewChild(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ee0d4L, "lines"), SNodeFactoryOperations.asInstanceConcept(MetaAdapterFactory.getConcept(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db08aL, "Accounting.structure.InvoiceLine"))); } }; IHeaderNodeDeleteAction deleteAction = new IHeaderNodeDeleteAction() { public void delete(final int index) { if (ListSequence.fromList(SLinkOperations.getChildren(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ee0d4L, "lines"))).count() > 1) { ListSequence.fromList(SLinkOperations.getChildren(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ee0d4L, "lines"))).removeElementAt(index); } } }; HeaderGrid grid = new HeaderGridFactory(editorContext, node, false).createFromObject(queryResult, new StringHeaderReference("4989694486378673577"), insertAction, deleteAction, 0, new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }, "Foo"); return grid; } public Grid createTableCellQuery_mbkewv_a0a2b1a(final EditorContext editorContext, final SNode node) { final Grid grid = new Grid(); final GridAdapter gridAdapter = new GridAdapter(grid, editorContext, node); final int sizeX = new Object() { public int getSizeX() { return 5; } }.getSizeX(); final int sizeY = new Object() { public int getSizeY() { return ListSequence.fromList(SLinkOperations.getChildren(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ee0d4L, "lines"))).count(); } }.getSizeY(); try { editorContext.getCellFactory().pushCellContext(); editorContext.getCellFactory().addCellContextHints(); editorContext.getCellFactory().removeCellContextHints(); new Object() { public void loadElements() { for (int xi = 0; xi < sizeX; xi++) { for (int yi = 0; yi < sizeY; yi++) { final int x = xi; final int y = yi; // EditorCell Object queryResult_ = queryCellsSafely(node, x, y); grid.setElement(x, y, new GridElementFactory(editorContext, node, false, false, grid).create(queryResult_)); // set headers IGridElement currentGridElement = grid.getElement(x, y); // set substitute info if (currentGridElement instanceof Grid && !(((Grid) currentGridElement).isEmpty())) { Grid currentGrid = ((Grid) currentGridElement); for (int indexX = 0; indexX < currentGrid.getSizeX(); indexX++) { for (int indexY = 0; indexY < currentGrid.getSizeY(); indexY++) { IGridElement listElement = currentGrid.getElement(indexX, indexY); final int index = Math.max(indexX, indexY); listElement.setSubstituteInfo(new CellQuerySubstituteInfo(editorContext, node, (queryResult_ instanceof SNode ? ((SNode) queryResult_) : SNodeOperations.cast(TableUtils.getSNode(listElement, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept"))), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")) { public SNode substituteNode(SNode currentNode, SNode newValue) { return doSubstituteNode_mbkewv_a0a2b1a(node, x, y, index, editorContext, currentNode, newValue); } }); if (canCreate(x, y, index)) { listElement.setInsertBeforeAction(new AbstractCellAction() { public void execute(EditorContext p0) { createNode(x, y, index); } }); } if (canCreate(x, y, index + 1)) { listElement.setInsertAction(new AbstractCellAction() { public void execute(EditorContext p0) { createNode(x, y, index + 1); } }); } } } } else { gridAdapter.setSubstituteInfo(x, y, new CellQuerySubstituteInfo(editorContext, node, (queryResult_ instanceof SNode ? ((SNode) queryResult_) : SNodeOperations.cast(TableUtils.getSNode(currentGridElement, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept"))), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")) { public SNode substituteNode(SNode currentNode, SNode newValue) { return doSubstituteNode_mbkewv_a0a2b1a(node, x, y, 0, editorContext, currentNode, newValue); } }); if (canCreate(x, y, 0)) { currentGridElement = grid.getElement(x, y); CellAction insertAction = new AbstractCellAction() { public void execute(EditorContext p0) { createNode(x, y, 0); } }; currentGridElement.setInsertBeforeAction(insertAction); currentGridElement.setInsertAction(insertAction); } } // style final Object queryResult = queryResult_; grid.getElement(x, y).setStyle(new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(x, y)); } } } public boolean canCreate(int columnIndex, int rowIndex, int listIndex) { return true; } public SNode createNode(int columnIndex, int rowIndex, int listIndex) { return doSubstituteNode_mbkewv_a0a2b1a(node, columnIndex, rowIndex, listIndex, editorContext, null, null); } public Object queryCellsSafely(final SNode node, final int columnIndex, final int rowIndex) { try { return queryCells(node, columnIndex, rowIndex); } catch (Exception ex) { Logger.getLogger(getClass()).error("Failed to query cell [" + rowIndex + ", " + columnIndex + "]", ex); return new EditorCell_Error(editorContext, node, "!exception! for [" + rowIndex + ", " + columnIndex + "]:" + ex.getMessage()); } } private Object queryCells(final SNode node, final int columnIndex, final int rowIndex) { SNode line = ListSequence.fromList(SLinkOperations.getChildren(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db02fL, 0x453ef4b2e64ee0d4L, "lines"))).getElement(rowIndex); switch (columnIndex) { case 0: return new Invoice_Editor.CellCreateOperation_a0a0b0a0a0c1b0().create(editorContext, line); case 1: return new Invoice_Editor.CellCreateOperation_a0a1b0a0a0c1b0().create(editorContext, line); case 2: return new Invoice_Editor.CellCreateOperation_a0a2b0a0a0c1b0().create(editorContext, line); case 3: return new Invoice_Editor.CellCreateOperation_a0a3b0a0a0c1b0().create(editorContext, line); case 4: return new Invoice_Editor.CellCreateOperation_a0a4b0a0a0c1b0().create(editorContext, line); default: throw new RuntimeException("Invalid column index " + columnIndex); } } }.loadElements(); } finally { editorContext.getCellFactory().popCellContext(); } return grid; } public SNode doSubstituteNode_mbkewv_a0a2b1a(SNode node, int columnIndex, int rowIndex, int listIndex, EditorContext editorContext, SNode currentNode, SNode newValue) { currentNode = SNodeOperations.cast(currentNode, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")); newValue = SNodeOperations.cast(newValue, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")); return null; } public Grid createTableCell_mbkewv_b0c1b0(final EditorContext editorContext, final SNode node) { EditorCell cell = createCustom_mbkewv_a1a2b1a(editorContext, node); final Style style = new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(0, 0); Grid grid; if (cell instanceof PartialTableEditor) { grid = ((PartialTableEditor) cell).getGrid().clone(); } else { grid = new Grid(); EditorCellGridLeaf leaf = new EditorCellGridLeaf(cell); leaf.setStyle(style); grid.setElement(0, 0, leaf); } return grid; } private EditorCell createCustom_mbkewv_a1a2b1a(final EditorContext editorContext, final SNode node) { AbstractCellProvider provider = new _FunctionTypes._return_P0_E0<HorizontalLineCellProvider>() { public HorizontalLineCellProvider invoke() { return new HorizontalLineCellProvider(node, 2); } }.invoke(); EditorCell editorCell = provider.createEditorCell(editorContext); editorCell.setCellId("Custom_mbkewv_a1a2b1a"); return editorCell; } public Grid createTableCellQuery_mbkewv_c0c1b0(final EditorContext editorContext, final SNode node) { final Grid grid = new Grid(); final GridAdapter gridAdapter = new GridAdapter(grid, editorContext, node); final int sizeX = new Object() { public int getSizeX() { return 5; } }.getSizeX(); final int sizeY = new Object() { public int getSizeY() { return 1; } }.getSizeY(); try { editorContext.getCellFactory().pushCellContext(); editorContext.getCellFactory().addCellContextHints(); editorContext.getCellFactory().removeCellContextHints(); new Object() { public void loadElements() { for (int xi = 0; xi < sizeX; xi++) { for (int yi = 0; yi < sizeY; yi++) { final int x = xi; final int y = yi; // EditorCell Object queryResult_ = queryCellsSafely(node, x, y); grid.setElement(x, y, new GridElementFactory(editorContext, node, false, false, grid).create(queryResult_)); // set headers IGridElement currentGridElement = grid.getElement(x, y); // set substitute info if (currentGridElement instanceof Grid && !(((Grid) currentGridElement).isEmpty())) { Grid currentGrid = ((Grid) currentGridElement); for (int indexX = 0; indexX < currentGrid.getSizeX(); indexX++) { for (int indexY = 0; indexY < currentGrid.getSizeY(); indexY++) { IGridElement listElement = currentGrid.getElement(indexX, indexY); final int index = Math.max(indexX, indexY); listElement.setSubstituteInfo(new CellQuerySubstituteInfo(editorContext, node, (queryResult_ instanceof SNode ? ((SNode) queryResult_) : SNodeOperations.cast(TableUtils.getSNode(listElement, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept"))), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")) { public SNode substituteNode(SNode currentNode, SNode newValue) { return doSubstituteNode_mbkewv_c0c1b0(node, x, y, index, editorContext, currentNode, newValue); } }); if (canCreate(x, y, index)) { listElement.setInsertBeforeAction(new AbstractCellAction() { public void execute(EditorContext p0) { createNode(x, y, index); } }); } if (canCreate(x, y, index + 1)) { listElement.setInsertAction(new AbstractCellAction() { public void execute(EditorContext p0) { createNode(x, y, index + 1); } }); } } } } else { gridAdapter.setSubstituteInfo(x, y, new CellQuerySubstituteInfo(editorContext, node, (queryResult_ instanceof SNode ? ((SNode) queryResult_) : SNodeOperations.cast(TableUtils.getSNode(currentGridElement, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept"))), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")) { public SNode substituteNode(SNode currentNode, SNode newValue) { return doSubstituteNode_mbkewv_c0c1b0(node, x, y, 0, editorContext, currentNode, newValue); } }); if (canCreate(x, y, 0)) { currentGridElement = grid.getElement(x, y); CellAction insertAction = new AbstractCellAction() { public void execute(EditorContext p0) { createNode(x, y, 0); } }; currentGridElement.setInsertBeforeAction(insertAction); currentGridElement.setInsertAction(insertAction); } } // style final Object queryResult = queryResult_; grid.getElement(x, y).setStyle(new ITableStyleFactory() { public Style createStyle(final int columnIndex, final int rowIndex) { Style style = new StyleImpl(); return style; } }.createStyle(x, y)); } } } public boolean canCreate(int columnIndex, int rowIndex, int listIndex) { return true; } public SNode createNode(int columnIndex, int rowIndex, int listIndex) { return doSubstituteNode_mbkewv_c0c1b0(node, columnIndex, rowIndex, listIndex, editorContext, null, null); } public Object queryCellsSafely(final SNode node, final int columnIndex, final int rowIndex) { try { return queryCells(node, columnIndex, rowIndex); } catch (Exception ex) { Logger.getLogger(getClass()).error("Failed to query cell [" + rowIndex + ", " + columnIndex + "]", ex); return new EditorCell_Error(editorContext, node, "!exception! for [" + rowIndex + ", " + columnIndex + "]:" + ex.getMessage()); } } private Object queryCells(final SNode node, final int columnIndex, final int rowIndex) { switch (columnIndex) { case 0: return new Invoice_Editor.CellCreateOperation_a0a0a0a2a2b1a().create(editorContext, node); case 1: return new Invoice_Editor.CellCreateOperation_a0a1a0a2a2b1a().create(editorContext, node); case 2: return new Invoice_Editor.CellCreateOperation_a0a2a0a2a2b1a().create(editorContext, node); case 3: return new Invoice_Editor.CellCreateOperation_a0a3a0a2a2b1a().create(editorContext, node); case 4: return new Invoice_Editor.CellCreateOperation_a0a4a0a2a2b1a().create(editorContext, node); default: throw new RuntimeException("Invalid column index " + columnIndex); } } }.loadElements(); } finally { editorContext.getCellFactory().popCellContext(); } return grid; } public SNode doSubstituteNode_mbkewv_c0c1b0(SNode node, int columnIndex, int rowIndex, int listIndex, EditorContext editorContext, SNode currentNode, SNode newValue) { currentNode = SNodeOperations.cast(currentNode, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")); newValue = SNodeOperations.cast(newValue, MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept")); return null; } private EditorCell createConstant_mbkewv_c0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, ""); editorCell.setCellId("Constant_mbkewv_c0"); editorCell.setDefaultText(""); return editorCell; } public static class CellCreateOperation_a0a0b0a0a0c1b0 { public CellCreateOperation_a0a0b0a0a0c1b0() { } public EditorCell create(EditorContext editorContext, SNode node) { return createProperty_mbkewv_a0a0a0a1a0a0a2b1a(editorContext, node); } private EditorCell createProperty_mbkewv_a0a0a0a1a0a0a2b1a(EditorContext editorContext, SNode node) { CellProviderWithRole provider = new PropertyCellProvider(node, editorContext); provider.setRole("description"); provider.setNoTargetText("<no description>"); EditorCell editorCell; editorCell = provider.createEditorCell(editorContext); editorCell.setCellId("property_description"); editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo()); SNode attributeConcept = provider.getRoleAttribute(); Class attributeKind = provider.getRoleAttributeClass(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(editorContext); return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell); } else return editorCell; } } public static class CellCreateOperation_a0a1b0a0a0c1b0 { public CellCreateOperation_a0a1b0a0a0c1b0() { } public EditorCell create(EditorContext editorContext, SNode node) { return createCollection_mbkewv_a0a0a0b1a0a0a2b1a(editorContext, node); } private EditorCell createCollection_mbkewv_a0a0a0b1a0a0a2b1a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node); editorCell.setCellId("Collection_mbkewv_a0a0a0b1a0a0a2b1a"); editorCell.addEditorCell(this.createRefNode_mbkewv_a0a0a0a1b0a0a0c1b0(editorContext, node)); return editorCell; } private EditorCell createRefNode_mbkewv_a0a0a0a1b0a0a0c1b0(EditorContext editorContext, SNode node) { SingleRoleCellProvider provider = new Invoice_Editor.CellCreateOperation_a0a1b0a0a0c1b0.amountSingleRoleHandler_mbkewv_a0a0a0a1b0a0a0c1b0(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db08aL, 0x453ef4b2e64db1eeL, "amount"), editorContext); return provider.createCell(); } private class amountSingleRoleHandler_mbkewv_a0a0a0a1b0a0a0c1b0 extends SingleRoleCellProvider { public amountSingleRoleHandler_mbkewv_a0a0a0a1b0a0a0c1b0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) { super(ownerNode, containmentLink, context); } protected EditorCell createChildCell(SNode child) { EditorCell editorCell = super.createChildCell(child); installCellInfo(child, editorCell); return editorCell; } private void installCellInfo(SNode child, EditorCell editorCell) { editorCell.setSubstituteInfo(new DefaultChildSubstituteInfo(myOwnerNode, myContainmentLink.getDeclarationNode(), myEditorContext)); if (editorCell.getRole() == null) { editorCell.setRole("amount"); } } @Override protected EditorCell createEmptyCell() { EditorCell editorCell = super.createEmptyCell(); editorCell.setCellId("empty_amount"); installCellInfo(null, editorCell); return editorCell; } protected String getNoTargetText() { return "<no amount>"; } } } public static class CellCreateOperation_a0a2b0a0a0c1b0 { public CellCreateOperation_a0a2b0a0a0c1b0() { } public EditorCell create(EditorContext editorContext, SNode node) { return createCollection_mbkewv_a0a0a0c1a0a0a2b1a(editorContext, node); } private EditorCell createCollection_mbkewv_a0a0a0c1a0a0a2b1a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node); editorCell.setCellId("Collection_mbkewv_a0a0a0c1a0a0a2b1a"); editorCell.addEditorCell(this.createRefNode_mbkewv_a0a0a0a2b0a0a0c1b0(editorContext, node)); return editorCell; } private EditorCell createRefNode_mbkewv_a0a0a0a2b0a0a0c1b0(EditorContext editorContext, SNode node) { SingleRoleCellProvider provider = new Invoice_Editor.CellCreateOperation_a0a2b0a0a0c1b0.vatRateSingleRoleHandler_mbkewv_a0a0a0a2b0a0a0c1b0(node, MetaAdapterFactory.getContainmentLink(0x3511d2b0c9d74a02L, 0xa20bca10f21445c3L, 0x453ef4b2e64db08aL, 0x453ef4b2e64f0088L, "vatRate"), editorContext); return provider.createCell(); } private class vatRateSingleRoleHandler_mbkewv_a0a0a0a2b0a0a0c1b0 extends SingleRoleCellProvider { public vatRateSingleRoleHandler_mbkewv_a0a0a0a2b0a0a0c1b0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) { super(ownerNode, containmentLink, context); } protected EditorCell createChildCell(SNode child) { EditorCell editorCell = super.createChildCell(child); installCellInfo(child, editorCell); return editorCell; } private void installCellInfo(SNode child, EditorCell editorCell) { editorCell.setSubstituteInfo(new DefaultChildSubstituteInfo(myOwnerNode, myContainmentLink.getDeclarationNode(), myEditorContext)); if (editorCell.getRole() == null) { editorCell.setRole("vatRate"); } } @Override protected EditorCell createEmptyCell() { EditorCell editorCell = super.createEmptyCell(); editorCell.setCellId("empty_vatRate"); installCellInfo(null, editorCell); return editorCell; } protected String getNoTargetText() { return "<no vatRate>"; } } } public static class CellCreateOperation_a0a3b0a0a0c1b0 { public CellCreateOperation_a0a3b0a0a0c1b0() { } public EditorCell create(EditorContext editorContext, SNode node) { return createReadOnlyModelAccessor_mbkewv_a0a0a0d1a0a0a2b1a(editorContext, node); } private EditorCell createReadOnlyModelAccessor_mbkewv_a0a0a0d1a0a0a2b1a(final EditorContext editorContext, final SNode node) { EditorCell_Property editorCell = EditorCell_Property.create(editorContext, new ModelAccessor() { public String getText() { return "" + InvoiceLine__BehaviorDescriptor.vatAmount_id4kYXbbAlngZ.invoke(node); } public void setText(String s) { } public boolean isValidText(String s) { return EqualUtil.equals(s, getText()); } }, node); editorCell.setAction(CellActionType.DELETE, EmptyCellAction.getInstance()); editorCell.setAction(CellActionType.BACKSPACE, EmptyCellAction.getInstance()); editorCell.setCellId("ReadOnlyModelAccessor_mbkewv_a0a0a0d1a0a0a2b1a"); return editorCell; } } public static class CellCreateOperation_a0a4b0a0a0c1b0 { public CellCreateOperation_a0a4b0a0a0c1b0() { } public EditorCell create(EditorContext editorContext, SNode node) { return createReadOnlyModelAccessor_mbkewv_a0a0a0e1a0a0a2b1a(editorContext, node); } private EditorCell createReadOnlyModelAccessor_mbkewv_a0a0a0e1a0a0a2b1a(final EditorContext editorContext, final SNode node) { EditorCell_Property editorCell = EditorCell_Property.create(editorContext, new ModelAccessor() { public String getText() { return "" + InvoiceLine__BehaviorDescriptor.total_id4kYXbbAlvrI.invoke(node); } public void setText(String s) { } public boolean isValidText(String s) { return EqualUtil.equals(s, getText()); } }, node); editorCell.setAction(CellActionType.DELETE, EmptyCellAction.getInstance()); editorCell.setAction(CellActionType.BACKSPACE, EmptyCellAction.getInstance()); editorCell.setCellId("ReadOnlyModelAccessor_mbkewv_a0a0a0e1a0a0a2b1a"); return editorCell; } } public static class CellCreateOperation_a0a0a0a2a2b1a { public CellCreateOperation_a0a0a0a2a2b1a() { } public EditorCell create(EditorContext editorContext, SNode node) { return createConstant_mbkewv_a0a0a0a0a0c0c1b0(editorContext, node); } private EditorCell createConstant_mbkewv_a0a0a0a0a0c0c1b0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "Total"); editorCell.setCellId("Constant_mbkewv_a0a0a0a0a0c0c1b0"); editorCell.setDefaultText(""); return editorCell; } } public static class CellCreateOperation_a0a1a0a2a2b1a { public CellCreateOperation_a0a1a0a2a2b1a() { } public EditorCell create(EditorContext editorContext, SNode node) { return createReadOnlyModelAccessor_mbkewv_a0a0a0b0a0c0c1b0(editorContext, node); } private EditorCell createReadOnlyModelAccessor_mbkewv_a0a0a0b0a0c0c1b0(final EditorContext editorContext, final SNode node) { EditorCell_Property editorCell = EditorCell_Property.create(editorContext, new ModelAccessor() { public String getText() { return "" + Invoice__BehaviorDescriptor.totalAmount_id4kYXbbAm20u.invoke(node); } public void setText(String s) { } public boolean isValidText(String s) { return EqualUtil.equals(s, getText()); } }, node); editorCell.setAction(CellActionType.DELETE, EmptyCellAction.getInstance()); editorCell.setAction(CellActionType.BACKSPACE, EmptyCellAction.getInstance()); editorCell.setCellId("ReadOnlyModelAccessor_mbkewv_a0a0a0b0a0c0c1b0"); return editorCell; } } public static class CellCreateOperation_a0a2a0a2a2b1a { public CellCreateOperation_a0a2a0a2a2b1a() { } public EditorCell create(EditorContext editorContext, SNode node) { return createReadOnlyModelAccessor_mbkewv_a0a0a0c0a0c0c1b0(editorContext, node); } private EditorCell createReadOnlyModelAccessor_mbkewv_a0a0a0c0a0c0c1b0(final EditorContext editorContext, final SNode node) { EditorCell_Property editorCell = EditorCell_Property.create(editorContext, new ModelAccessor() { public String getText() { return "---"; } public void setText(String s) { } public boolean isValidText(String s) { return EqualUtil.equals(s, getText()); } }, node); editorCell.setAction(CellActionType.DELETE, EmptyCellAction.getInstance()); editorCell.setAction(CellActionType.BACKSPACE, EmptyCellAction.getInstance()); editorCell.setCellId("ReadOnlyModelAccessor_mbkewv_a0a0a0c0a0c0c1b0"); return editorCell; } } public static class CellCreateOperation_a0a3a0a2a2b1a { public CellCreateOperation_a0a3a0a2a2b1a() { } public EditorCell create(EditorContext editorContext, SNode node) { return createReadOnlyModelAccessor_mbkewv_a0a0a0d0a0c0c1b0(editorContext, node); } private EditorCell createReadOnlyModelAccessor_mbkewv_a0a0a0d0a0c0c1b0(final EditorContext editorContext, final SNode node) { EditorCell_Property editorCell = EditorCell_Property.create(editorContext, new ModelAccessor() { public String getText() { return "" + Invoice__BehaviorDescriptor.totalVATAmount_id4kYXbbAm59V.invoke(node); } public void setText(String s) { } public boolean isValidText(String s) { return EqualUtil.equals(s, getText()); } }, node); editorCell.setAction(CellActionType.DELETE, EmptyCellAction.getInstance()); editorCell.setAction(CellActionType.BACKSPACE, EmptyCellAction.getInstance()); editorCell.setCellId("ReadOnlyModelAccessor_mbkewv_a0a0a0d0a0c0c1b0"); return editorCell; } } public static class CellCreateOperation_a0a4a0a2a2b1a { public CellCreateOperation_a0a4a0a2a2b1a() { } public EditorCell create(EditorContext editorContext, SNode node) { return createReadOnlyModelAccessor_mbkewv_a0a0a0e0a0c0c1b0(editorContext, node); } private EditorCell createReadOnlyModelAccessor_mbkewv_a0a0a0e0a0c0c1b0(final EditorContext editorContext, final SNode node) { EditorCell_Property editorCell = EditorCell_Property.create(editorContext, new ModelAccessor() { public String getText() { return "" + Invoice__BehaviorDescriptor.total_id4kYXbbAm5Sy.invoke(node); } public void setText(String s) { } public boolean isValidText(String s) { return EqualUtil.equals(s, getText()); } }, node); editorCell.setAction(CellActionType.DELETE, EmptyCellAction.getInstance()); editorCell.setAction(CellActionType.BACKSPACE, EmptyCellAction.getInstance()); editorCell.setCellId("ReadOnlyModelAccessor_mbkewv_a0a0a0e0a0c0c1b0"); return editorCell; } } }
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.bazel.rules.genrule; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import com.google.common.base.Joiner; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * A unit test of the various kinds of label and "Make"-variable substitutions that are applied to * the genrule "cmd" attribute. * * <p>Some of these tests are similar to tests in LabelExpanderTest and MakeVariableExpanderTest, * but this test case exercises the composition of these various transformations. */ @RunWith(JUnit4.class) public final class GenRuleCommandSubstitutionTest extends BuildViewTestCase { private static final Pattern SETUP_COMMAND_PATTERN = Pattern.compile(".*/genrule-setup.sh;\\s+(?<command>.*)"); private String getGenruleCommand(String genrule) throws Exception { return ((SpawnAction) getGeneratingAction(getFilesToBuild(getConfiguredTarget(genrule)).toList().get(0))) .getArguments() .get(2); } private void assertExpansionEquals(String expected, String genrule) throws Exception { String command = getGenruleCommand(genrule); assertCommandEquals(expected, command); } private static void assertCommandEquals(String expected, String command) { // Ensure the command after the genrule setup is correct. Matcher m = SETUP_COMMAND_PATTERN.matcher(command); if (m.matches()) { command = m.group("command"); } assertWithMessage("Expected command to be \"" + expected + "\", but found \"" + command + "\"") .that(command) .isEqualTo(expected); } private void assertExpansionFails(String expectedErrorSuffix, String genrule) throws Exception { reporter.removeHandler(failFastHandler); // we expect errors eventCollector.clear(); getConfiguredTarget(genrule); assertContainsEvent(expectedErrorSuffix); } // Creates a BUILD file defining a genrule called "//test" with no srcs or // deps, one output and the specified command. private void genrule(String command) throws Exception { scratch.overwriteFile( "test/BUILD", // This is a horrible workaround for b/147306893: // somehow, duplicate events (same location, same message) // are being suppressed, so we must vary the location of the // genrule by inserting a unique number of newlines. new String(new char[seq++]).replace('\0', '\n'), "genrule(name = 'test',", " outs = ['out'],", " cmd = '" + command + "')"); // Since we're probably re-defining "//test": invalidatePackages(); } private int seq = 0; @Test public void testLocationSyntaxErrors() throws Exception { genrule("$(location )"); assertExpansionFails( "invalid label in $(location) expression: empty package-relative label", "//test"); genrule("$(location foo bar"); assertExpansionFails("unterminated variable reference", "//test"); genrule("$(location"); assertExpansionFails("unterminated variable reference", "//test"); genrule("$(locationz"); assertExpansionFails("unterminated variable reference", "//test"); genrule("$(locationz)"); assertExpansionFails("$(locationz) not defined", "//test"); genrule("$(locationz )"); assertExpansionFails("$(locationz) not defined", "//test"); genrule("$(locationz foo )"); assertExpansionFails("$(locationz) not defined", "//test"); } @Test public void testLocationOfLabelThatIsNotAPrerequsite() throws Exception { scratch.file( "test/BUILD", "exports_files(['exists'])", "genrule(name = 'test1',", " outs = ['test1.out'],", " cmd = '$(location :exists)')", "genrule(name = 'test2',", " outs = ['test2.out'],", " cmd = '$(location :doesnt_exist)')"); // $(location) of a non-prerequisite fails, even if the target exists: assertExpansionFails( "label '//test:exists' in $(location) expression is " + "not a declared prerequisite of this rule", "//test:test1"); assertExpansionFails( "label '//test:doesnt_exist' in $(location) expression is " + "not a declared prerequisite of this rule", "//test:test2"); } @Test public void testLocationOfMultiFileLabel() throws Exception { scratch.file( "deuce/BUILD", "genrule(name = 'deuce',", " outs = ['out.1', 'out.2'],", " cmd = ':')"); checkError( "test", "test1", "label '//deuce:deuce' in $(location) expression expands to more than one " + "file, please use $(locations //deuce:deuce) instead", "genrule(name = 'test1',", " tools = ['//deuce'],", " outs = ['test1.out'],", " cmd = '$(location //deuce)')"); } @Test public void testUnknownVariable() throws Exception { genrule("$(UNKNOWN)"); assertExpansionFails("$(UNKNOWN) not defined", "//test"); } @Test public void testLocationOfSourceLabel() throws Exception { scratch.file( "test1/BUILD", "genrule(name = 'test1',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(location //test1:src)')"); assertExpansionEquals("test1/src", "//test1"); scratch.file( "test2/BUILD", "genrule(name = 'test2',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(location src)')"); assertExpansionEquals("test2/src", "//test2"); scratch.file( "test3/BUILD", "genrule(name = 'test3',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(location :src)')"); assertExpansionEquals("test3/src", "//test3"); } @Test public void testLocationOfOutputLabel() throws Exception { String gendir = targetConfig.getMakeVariableDefault("GENDIR"); scratch.file( "test1/BUILD", "genrule(name = 'test1',", " outs = ['out'],", " cmd = '$(location //test1:out)')"); assertExpansionEquals(gendir + "/test1/out", "//test1"); scratch.file( "test2/BUILD", "genrule(name = 'test2',", " outs = ['out'],", " cmd = '$(location out)')"); assertExpansionEquals(gendir + "/test2/out", "//test2"); scratch.file( "test3/BUILD", "genrule(name = 'test3',", " outs = ['out'],", " cmd = '$(location out)')"); assertExpansionEquals(gendir + "/test3/out", "//test3"); } @Test public void testLocationsSyntaxErrors() throws Exception { genrule("$(locations )"); assertExpansionFails( "invalid label in $(locations) expression: empty package-relative label", "//test"); genrule("$(locations foo bar"); assertExpansionFails("unterminated variable reference", "//test"); genrule("$(locations"); assertExpansionFails("unterminated variable reference", "//test"); genrule("$(locationsz"); assertExpansionFails("unterminated variable reference", "//test"); genrule("$(locationsz)"); assertExpansionFails("$(locationsz) not defined", "//test"); genrule("$(locationsz )"); assertExpansionFails("$(locationsz) not defined", "//test"); genrule("$(locationsz foo )"); assertExpansionFails("$(locationsz) not defined", "//test"); } @Test public void testLocationsOfLabelThatIsNotAPrerequsite() throws Exception { scratch.file( "test/BUILD", "exports_files(['exists'])", "genrule(name = 'test1',", " outs = ['test1.out'],", " cmd = '$(locations :exists)')", "genrule(name = 'test2',", " outs = ['test2.out'],", " cmd = '$(locations :doesnt_exist)')"); // $(locations) of a non-prerequisite fails, even if the target exists: assertExpansionFails( "label '//test:exists' in $(locations) expression is " + "not a declared prerequisite of this rule", "//test:test1"); assertExpansionFails( "label '//test:doesnt_exist' in $(locations) expression is " + "not a declared prerequisite of this rule", "//test:test2"); } @Test public void testLocationsOfMultiFileLabel() throws Exception { String gendir = targetConfig.getMakeVariableDefault("GENDIR"); scratch.file( "test/BUILD", "genrule(name = 'x',", " srcs = ['src'],", " outs = ['out1', 'out2'],", " cmd = ':')", "genrule(name = 'y',", " srcs = ['x'],", " outs = ['out'],", " cmd = '$(locations x)')"); assertExpansionEquals(gendir + "/test/out1 " + gendir + "/test/out2", "//test:y"); } @Test public void testLocationLocationsAndLabel() throws Exception { String gendir = targetConfig.getMakeVariableDefault("GENDIR"); scratch.file( "test/BUILD", "genrule(name = 'x',", " srcs = ['src'],", " outs = ['out'],", " cmd = ':')", "genrule(name = 'y',", " srcs = ['src'],", " outs = ['out1', 'out2'],", " cmd = ':')", "genrule(name = 'r',", " srcs = ['x', 'y', 'z'],", " outs = ['res'],", " cmd = ' _ $(location x) _ $(locations y) _ ')"); String expected = "_ " + gendir + "/test/out _ " + gendir + "/test/out1 " + gendir + "/test/out2 _ "; assertExpansionEquals(expected, "//test:r"); } @Test public void testLocationsOfSourceLabel() throws Exception { scratch.file( "test1/BUILD", "genrule(name = 'test1',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(locations //test1:src)')"); assertExpansionEquals("test1/src", "//test1"); scratch.file( "test2/BUILD", "genrule(name = 'test2',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(locations src)')"); assertExpansionEquals("test2/src", "//test2"); scratch.file( "test3/BUILD", "genrule(name = 'test3',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(location :src)')"); assertExpansionEquals("test3/src", "//test3"); } @Test public void testLocationsOfOutputLabel() throws Exception { String gendir = targetConfig.getMakeVariableDefault("GENDIR"); scratch.file( "test1/BUILD", "genrule(name = 'test1',", " outs = ['out'],", " cmd = '$(locations //test1:out)')"); assertExpansionEquals(gendir + "/test1/out", "//test1"); scratch.file( "test2/BUILD", "genrule(name = 'test2',", " outs = ['out'],", " cmd = '$(locations out)')"); assertExpansionEquals(gendir + "/test2/out", "//test2"); scratch.file( "test3/BUILD", "genrule(name = 'test3',", " outs = ['out'],", " cmd = '$(locations out)')"); assertExpansionEquals(gendir + "/test3/out", "//test3"); } @Test public void testOuts() throws Exception { String expected = targetConfig.getMakeVariableDefault("GENDIR") + "/test/out"; scratch.file( "test/BUILD", "genrule(name = 'test',", " outs = ['out'],", " cmd = '$(OUTS) # $@')"); assertExpansionEquals(expected + " # " + expected, "//test"); } @Test public void testSrcs() throws Exception { String expected = "test/src"; scratch.file( "test/BUILD", "genrule(name = 'test',", " srcs = ['src'],", " outs = ['out'],", " cmd = '$(SRCS) # $<')"); assertExpansionEquals(expected + " # " + expected, "//test"); } @Test public void testDollarDollar() throws Exception { scratch.file( "test/BUILD", "genrule(name = 'test',", " outs = ['out'],", " cmd = '$$DOLLAR')"); assertExpansionEquals("$DOLLAR", "//test"); } @Test public void testDollarLessThanWithZeroInputs() throws Exception { scratch.file( "test/BUILD", "genrule(name = 'test',", " outs = ['out'],", " cmd = '$<')"); assertExpansionFails("variable '$<' : no input file", "//test"); } @Test public void testDollarLessThanWithMultipleInputs() throws Exception { scratch.file( "test/BUILD", "genrule(name = 'test',", " srcs = ['src1', 'src2'],", " outs = ['out'],", " cmd = '$<')"); assertExpansionFails("variable '$<' : more than one input file", "//test"); } @Test public void testDollarAtWithMultipleOutputs() throws Exception { scratch.file( "test/BUILD", "genrule(name = 'test',", " outs = ['out.1', 'out.2'],", " cmd = '$@')"); assertExpansionFails("variable '$@' : more than one output file", "//test"); } @Test public void testDollarAtWithZeroOutputs() throws Exception { scratch.file( "test/BUILD", "genrule(name = 'test',", " srcs = ['src1', 'src2'],", " outs = [],", " cmd = '$@')"); assertExpansionFails("Genrules without outputs don't make sense", "//test"); } @Test public void testShellVariables() throws Exception { genrule("for file in a b c;do echo $$file;done"); assertExpansionEquals("for file in a b c;do echo $file;done", "//test"); assertNoEvents(); genrule("$${file%:.*8}"); assertExpansionEquals("${file%:.*8}", "//test"); assertNoEvents(); genrule("$$(basename file)"); assertExpansionEquals("$(basename file)", "//test"); assertNoEvents(); genrule("$(basename file)"); assertExpansionFails("$(basename) not defined", "//test"); assertContainsEvent("$(basename) not defined"); } @Test public void heuristicLabelExpansion_singletonFilegroupInTools_expandsToFile() throws Exception { scratch.file( "foo/BUILD", "filegroup(name = 'fg', srcs = ['fg1.txt'])", "genrule(", " name = 'gen',", " outs = ['gen.out'],", " tools = [':fg'],", " heuristic_label_expansion = True,", " cmd = 'cp :fg $@',", ")"); useConfiguration("--experimental_enable_aggregating_middleman"); assertThat(getGenruleCommand("//foo:gen")).contains("foo/fg1.txt"); useConfiguration("--noexperimental_enable_aggregating_middleman"); assertThat(getGenruleCommand("//foo:gen")).contains("foo/fg1.txt"); } @Test public void heuristicLabelExpansion_emptyFilegroupInTools_fails() throws Exception { scratch.file( "foo/BUILD", "filegroup(name = 'fg', srcs = [])", "genrule(", " name = 'gen',", " outs = ['gen.out'],", " tools = [':fg'],", " heuristic_label_expansion = True,", " cmd = 'cp :fg $@',", ")"); useConfiguration("--experimental_enable_aggregating_middleman"); assertExpansionFails("expands to 0 files", "//foo:gen"); useConfiguration("--noexperimental_enable_aggregating_middleman"); assertExpansionFails("expands to 0 files", "//foo:gen"); } @Test public void heuristicLabelExpansion_multiFilegroupInTools_fails() throws Exception { scratch.file( "foo/BUILD", "filegroup(name = 'fg', srcs = ['fg1.txt', 'fg2.txt'])", "genrule(", " name = 'gen',", " outs = ['gen.out'],", " tools = [':fg'],", " heuristic_label_expansion = True,", " cmd = 'cp :fg $@',", ")"); useConfiguration("--experimental_enable_aggregating_middleman"); assertExpansionFails("expands to 2 files", "//foo:gen"); useConfiguration("--noexperimental_enable_aggregating_middleman"); assertExpansionFails("expands to 2 files", "//foo:gen"); } @Test public void testDollarFileFails() throws Exception { checkError( "test", "test", "'$file' syntax is not supported; use '$(file)' ", getBuildFileWithCommand("for file in a b c;do echo $file;done")); } @Test public void testDollarFile2Fails() throws Exception { checkError( "test", "test", "'${file%:.*8}' syntax is not supported; use '$(file%:.*8)' ", getBuildFileWithCommand("${file%:.*8}")); } private static String getBuildFileWithCommand(String command) { return Joiner.on("\n") .join( "genrule(name = 'test',", " outs = ['out'],", " cmd = '" + command + "')"); } }
/* * 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.cassandra.db.compaction; import org.apache.cassandra.db.lifecycle.LifecycleTransaction; import org.apache.cassandra.utils.concurrent.Refs; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.cassandra.config.KSMetaData; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.sstable.format.SSTableWriter; import org.apache.cassandra.locator.SimpleStrategy; import org.junit.BeforeClass; import org.junit.After; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.db.ArrayBackedSortedColumns; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.Keyspace; import org.apache.cassandra.db.Mutation; import org.apache.cassandra.dht.ByteOrderedPartitioner.BytesToken; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.io.sstable.*; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.utils.ByteBufferUtil; import com.google.common.collect.Iterables; public class AntiCompactionTest { private static final String KEYSPACE1 = "AntiCompactionTest"; private static final String CF = "Standard1"; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, SimpleStrategy.class, KSMetaData.optsWithRF(1), SchemaLoader.standardCFMD(KEYSPACE1, CF)); } @After public void truncateCF() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.truncateBlocking(); } @Test public void antiCompactOne() throws Exception { ColumnFamilyStore store = prepareColumnFamilyStore(); Collection<SSTableReader> sstables = store.getUnrepairedSSTables(); assertEquals(store.getSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("4".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); int repairedKeys = 0; int nonRepairedKeys = 0; try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { if (txn == null) throw new IllegalStateException(); long repairedAt = 1000; CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt); } assertEquals(2, store.getSSTables().size()); for (SSTableReader sstable : store.getSSTables()) { try (ISSTableScanner scanner = sstable.getScanner()) { while (scanner.hasNext()) { SSTableIdentityIterator row = (SSTableIdentityIterator) scanner.next(); if (sstable.isRepaired()) { assertTrue(range.contains(row.getKey().getToken())); repairedKeys++; } else { assertFalse(range.contains(row.getKey().getToken())); nonRepairedKeys++; } } } } for (SSTableReader sstable : store.getSSTables()) { assertFalse(sstable.isMarkedCompacted()); assertEquals(1, sstable.selfRef().globalCount()); } assertEquals(0, store.getTracker().getCompacting().size()); assertEquals(repairedKeys, 4); assertEquals(nonRepairedKeys, 6); } @Test public void antiCompactionSizeTest() throws InterruptedException, IOException { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF); cfs.disableAutoCompaction(); SSTableReader s = writeFile(cfs, 1000); cfs.addSSTable(s); long origSize = s.bytesOnDisk(); Range<Token> range = new Range<Token>(new BytesToken(ByteBufferUtil.bytes(0)), new BytesToken(ByteBufferUtil.bytes(500))); Collection<SSTableReader> sstables = cfs.getSSTables(); try (LifecycleTransaction txn = cfs.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(cfs, Arrays.asList(range), refs, txn, 12345); } long sum = 0; for (SSTableReader x : cfs.getSSTables()) sum += x.bytesOnDisk(); assertEquals(sum, cfs.metric.liveDiskSpaceUsed.getCount()); assertEquals(origSize, cfs.metric.liveDiskSpaceUsed.getCount(), 100000); } private SSTableReader writeFile(ColumnFamilyStore cfs, int count) { ArrayBackedSortedColumns cf = ArrayBackedSortedColumns.factory.create(cfs.metadata); for (int i = 0; i < count; i++) cf.addColumn(Util.column(String.valueOf(i), "a", 1)); File dir = cfs.directories.getDirectoryForNewSSTables(); String filename = cfs.getTempSSTablePath(dir); try (SSTableWriter writer = SSTableWriter.create(filename, 0, 0);) { for (int i = 0; i < count * 5; i++) writer.append(StorageService.getPartitioner().decorateKey(ByteBufferUtil.bytes(i)), cf); return writer.finish(true); } } public void generateSStable(ColumnFamilyStore store, String Suffix) { long timestamp = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { DecoratedKey key = Util.dk(Integer.toString(i) + "-" + Suffix); Mutation rm = new Mutation(KEYSPACE1, key.getKey()); for (int j = 0; j < 10; j++) rm.add("Standard1", Util.cellname(Integer.toString(j)), ByteBufferUtil.EMPTY_BYTE_BUFFER, timestamp, 0); rm.apply(); } store.forceBlockingFlush(); } @Test public void antiCompactTenSTC() throws Exception { antiCompactTen("SizeTieredCompactionStrategy"); } @Test public void antiCompactTenLC() throws Exception { antiCompactTen("LeveledCompactionStrategy"); } public void antiCompactTen(String compactionStrategy) throws Exception { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.setCompactionStrategyClass(compactionStrategy); store.disableAutoCompaction(); for (int table = 0; table < 10; table++) { generateSStable(store,Integer.toString(table)); } Collection<SSTableReader> sstables = store.getUnrepairedSSTables(); assertEquals(store.getSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("4".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); long repairedAt = 1000; try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt); } /* Anticompaction will be anti-compacting 10 SSTables but will be doing this two at a time so there will be no net change in the number of sstables */ assertEquals(10, store.getSSTables().size()); int repairedKeys = 0; int nonRepairedKeys = 0; for (SSTableReader sstable : store.getSSTables()) { try(ISSTableScanner scanner = sstable.getScanner()) { while (scanner.hasNext()) { SSTableIdentityIterator row = (SSTableIdentityIterator) scanner.next(); if (sstable.isRepaired()) { assertTrue(range.contains(row.getKey().getToken())); assertEquals(repairedAt, sstable.getSSTableMetadata().repairedAt); repairedKeys++; } else { assertFalse(range.contains(row.getKey().getToken())); assertEquals(ActiveRepairService.UNREPAIRED_SSTABLE, sstable.getSSTableMetadata().repairedAt); nonRepairedKeys++; } } } } assertEquals(repairedKeys, 40); assertEquals(nonRepairedKeys, 60); } @Test public void shouldMutateRepairedAt() throws InterruptedException, IOException { ColumnFamilyStore store = prepareColumnFamilyStore(); Collection<SSTableReader> sstables = store.getUnrepairedSSTables(); assertEquals(store.getSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("9999".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, 1); } assertThat(store.getSSTables().size(), is(1)); assertThat(Iterables.get(store.getSSTables(), 0).isRepaired(), is(true)); assertThat(Iterables.get(store.getSSTables(), 0).selfRef().globalCount(), is(1)); assertThat(store.getTracker().getCompacting().size(), is(0)); } @Test public void shouldSkipAntiCompactionForNonIntersectingRange() throws InterruptedException, IOException { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.disableAutoCompaction(); for (int table = 0; table < 10; table++) { generateSStable(store,Integer.toString(table)); } Collection<SSTableReader> sstables = store.getUnrepairedSSTables(); assertEquals(store.getSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("-1".getBytes()), new BytesToken("-10".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, 1); } assertThat(store.getSSTables().size(), is(10)); assertThat(Iterables.get(store.getSSTables(), 0).isRepaired(), is(false)); } private ColumnFamilyStore prepareColumnFamilyStore() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.disableAutoCompaction(); long timestamp = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { DecoratedKey key = Util.dk(Integer.toString(i)); Mutation rm = new Mutation(KEYSPACE1, key.getKey()); for (int j = 0; j < 10; j++) rm.add("Standard1", Util.cellname(Integer.toString(j)), ByteBufferUtil.EMPTY_BYTE_BUFFER, timestamp, 0); rm.apply(); } store.forceBlockingFlush(); return store; } @After public void truncateCfs() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.truncateBlocking(); } }
/* * 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.action.admin.cluster.snapshots.status; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.FailedNodeException; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.nodes.*; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.metadata.SnapshotId; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.snapshots.IndexShardSnapshotStatus; import org.elasticsearch.snapshots.SnapshotsService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; import java.util.List; import java.util.concurrent.atomic.AtomicReferenceArray; /** * Transport client that collects snapshot shard statuses from data nodes */ public class TransportNodesSnapshotsStatus extends TransportNodesOperationAction<TransportNodesSnapshotsStatus.Request, TransportNodesSnapshotsStatus.NodesSnapshotStatus, TransportNodesSnapshotsStatus.NodeRequest, TransportNodesSnapshotsStatus.NodeSnapshotStatus> { public static final String ACTION_NAME = SnapshotsStatusAction.NAME + "[nodes]"; private final SnapshotsService snapshotsService; @Inject public TransportNodesSnapshotsStatus(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, SnapshotsService snapshotsService, ActionFilters actionFilters) { super(settings, ACTION_NAME, clusterName, threadPool, clusterService, transportService, actionFilters); this.snapshotsService = snapshotsService; } @Override protected String executor() { return ThreadPool.Names.GENERIC; } @Override protected boolean transportCompress() { return true; // compress since the metadata can become large } @Override protected Request newRequest() { return new Request(); } @Override protected NodeRequest newNodeRequest() { return new NodeRequest(); } @Override protected NodeRequest newNodeRequest(String nodeId, Request request) { return new NodeRequest(nodeId, request); } @Override protected NodeSnapshotStatus newNodeResponse() { return new NodeSnapshotStatus(); } @Override protected NodesSnapshotStatus newResponse(Request request, AtomicReferenceArray responses) { final List<NodeSnapshotStatus> nodesList = Lists.newArrayList(); final List<FailedNodeException> failures = Lists.newArrayList(); for (int i = 0; i < responses.length(); i++) { Object resp = responses.get(i); if (resp instanceof NodeSnapshotStatus) { // will also filter out null response for unallocated ones nodesList.add((NodeSnapshotStatus) resp); } else if (resp instanceof FailedNodeException) { failures.add((FailedNodeException) resp); } else { logger.warn("unknown response type [{}], expected NodeSnapshotStatus or FailedNodeException", resp); } } return new NodesSnapshotStatus(clusterName, nodesList.toArray(new NodeSnapshotStatus[nodesList.size()]), failures.toArray(new FailedNodeException[failures.size()])); } @Override protected NodeSnapshotStatus nodeOperation(NodeRequest request) throws ElasticsearchException { ImmutableMap.Builder<SnapshotId, ImmutableMap<ShardId, SnapshotIndexShardStatus>> snapshotMapBuilder = ImmutableMap.builder(); try { String nodeId = clusterService.localNode().id(); for (SnapshotId snapshotId : request.snapshotIds) { ImmutableMap<ShardId, IndexShardSnapshotStatus> shardsStatus = snapshotsService.currentSnapshotShards(snapshotId); if (shardsStatus == null) { continue; } ImmutableMap.Builder<ShardId, SnapshotIndexShardStatus> shardMapBuilder = ImmutableMap.builder(); for (ImmutableMap.Entry<ShardId, IndexShardSnapshotStatus> shardEntry : shardsStatus.entrySet()) { SnapshotIndexShardStatus shardStatus; IndexShardSnapshotStatus.Stage stage = shardEntry.getValue().stage(); if (stage != IndexShardSnapshotStatus.Stage.DONE && stage != IndexShardSnapshotStatus.Stage.FAILURE) { // Store node id for the snapshots that are currently running. shardStatus = new SnapshotIndexShardStatus(shardEntry.getKey(), shardEntry.getValue(), nodeId); } else { shardStatus = new SnapshotIndexShardStatus(shardEntry.getKey(), shardEntry.getValue()); } shardMapBuilder.put(shardEntry.getKey(), shardStatus); } snapshotMapBuilder.put(snapshotId, shardMapBuilder.build()); } return new NodeSnapshotStatus(clusterService.localNode(), snapshotMapBuilder.build()); } catch (Exception e) { throw new ElasticsearchException("failed to load metadata", e); } } @Override protected boolean accumulateExceptions() { return true; } static class Request extends NodesOperationRequest<Request> { private SnapshotId[] snapshotIds; public Request() { } public Request(ActionRequest request, String[] nodesIds) { super(request, nodesIds); } public Request snapshotIds(SnapshotId[] snapshotIds) { this.snapshotIds = snapshotIds; return this; } @Override public void readFrom(StreamInput in) throws IOException { // This operation is never executed remotely throw new UnsupportedOperationException("shouldn't be here"); } @Override public void writeTo(StreamOutput out) throws IOException { // This operation is never executed remotely throw new UnsupportedOperationException("shouldn't be here"); } } public static class NodesSnapshotStatus extends NodesOperationResponse<NodeSnapshotStatus> { private FailedNodeException[] failures; NodesSnapshotStatus() { } public NodesSnapshotStatus(ClusterName clusterName, NodeSnapshotStatus[] nodes, FailedNodeException[] failures) { super(clusterName, nodes); this.failures = failures; } public FailedNodeException[] failures() { return failures; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); nodes = new NodeSnapshotStatus[in.readVInt()]; for (int i = 0; i < nodes.length; i++) { nodes[i] = new NodeSnapshotStatus(); nodes[i].readFrom(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(nodes.length); for (NodeSnapshotStatus response : nodes) { response.writeTo(out); } } } static class NodeRequest extends NodeOperationRequest { private SnapshotId[] snapshotIds; NodeRequest() { } NodeRequest(String nodeId, TransportNodesSnapshotsStatus.Request request) { super(request, nodeId); snapshotIds = request.snapshotIds; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); int n = in.readVInt(); snapshotIds = new SnapshotId[n]; for (int i = 0; i < n; i++) { snapshotIds[i] = SnapshotId.readSnapshotId(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (snapshotIds != null) { out.writeVInt(snapshotIds.length); for (int i = 0; i < snapshotIds.length; i++) { snapshotIds[i].writeTo(out); } } else { out.writeVInt(0); } } } public static class NodeSnapshotStatus extends NodeOperationResponse { private ImmutableMap<SnapshotId, ImmutableMap<ShardId, SnapshotIndexShardStatus>> status; NodeSnapshotStatus() { } public NodeSnapshotStatus(DiscoveryNode node, ImmutableMap<SnapshotId, ImmutableMap<ShardId, SnapshotIndexShardStatus>> status) { super(node); this.status = status; } public ImmutableMap<SnapshotId, ImmutableMap<ShardId, SnapshotIndexShardStatus>> status() { return status; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); int numberOfSnapshots = in.readVInt(); ImmutableMap.Builder<SnapshotId, ImmutableMap<ShardId, SnapshotIndexShardStatus>> snapshotMapBuilder = ImmutableMap.builder(); for (int i = 0; i < numberOfSnapshots; i++) { SnapshotId snapshotId = SnapshotId.readSnapshotId(in); ImmutableMap.Builder<ShardId, SnapshotIndexShardStatus> shardMapBuilder = ImmutableMap.builder(); int numberOfShards = in.readVInt(); for (int j = 0; j < numberOfShards; j++) { ShardId shardId = ShardId.readShardId(in); SnapshotIndexShardStatus status = SnapshotIndexShardStatus.readShardSnapshotStatus(in); shardMapBuilder.put(shardId, status); } snapshotMapBuilder.put(snapshotId, shardMapBuilder.build()); } status = snapshotMapBuilder.build(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (status != null) { out.writeVInt(status.size()); for (ImmutableMap.Entry<SnapshotId, ImmutableMap<ShardId, SnapshotIndexShardStatus>> entry : status.entrySet()) { entry.getKey().writeTo(out); out.writeVInt(entry.getValue().size()); for (ImmutableMap.Entry<ShardId, SnapshotIndexShardStatus> shardEntry : entry.getValue().entrySet()) { shardEntry.getKey().writeTo(out); shardEntry.getValue().writeTo(out); } } } else { out.writeVInt(0); } } } }
package danie.gmhserver; /** * Created by danie on 3/12/2017. */ import android.Manifest; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.telephony.SmsManager; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; /** * Created by ty on 3/10/2017. */ public class SmsSender { private static final int MY_PERMISSIONS_SEND_SMS = 123; private static final int MY_PERMISSIONS_RECEIVE_SMS = 321;; private static final int MAX_SMS_LENGTH = 130; //Made shorter to comply to added headers on some phones Context mContext; String phone; String message; public SmsSender(Context context) { mContext = context; phone = ""; message = ""; } public SmsSender(Context context, String aPhone){ mContext = context; phone = aPhone; message = ""; } public SmsSender(Context context, String aPhone, String aMessage) { mContext = context; phone = aPhone; message = aMessage; } public void setPhone(String aPhone) { phone = aPhone; } public void setMessage(String aMessage) { message = aMessage; } public void sendSMS(String message) { String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0, new Intent(DELIVERED), 0); //---when the SMS has been sent--- mContext.registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(mContext, "SMS sent", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(mContext, "Generic failure", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(mContext, "No service", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(mContext, "Null PDU", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(mContext, "Radio off", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(SENT)); //---when the SMS has been delivered--- mContext.registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(mContext, "SMS delivered", Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: Toast.makeText(mContext, "SMS not delivered", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(DELIVERED)); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phone, null, message, sentPI, deliveredPI); } private void requestSMSPermission() { if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, Manifest.permission.SEND_SMS)) { } else { ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_SEND_SMS); } } else { sendSMS(message); } if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, Manifest.permission.RECEIVE_SMS)) { } else { ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.RECEIVE_SMS}, MY_PERMISSIONS_RECEIVE_SMS); } } } //@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_SEND_SMS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted sendSMS(message); } else { // permission denied } break; } } } public void sendDirections(String request){ Log.d("Status", "SENDING"); ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; boolean isConnected = isWiFi && (activeNetwork != null && activeNetwork.isConnectedOrConnecting()); Log.d("Connection", Boolean.toString(isConnected)); if(!isConnected){ message = "NO SERVICE"; Log.d("Message", message); requestSMSPermission(); return; } DirectionSet ds = new DirectionSet(request); Log.d("URL", ds.getUrl()); try { ds.fetchDirections(); } catch (IOException e) { e.printStackTrace(); return; } catch (JSONException e) { e.printStackTrace(); return; } if(!ds.isValid()) { message = "INVALID"; Log.d("Message", message); requestSMSPermission(); return; } ArrayList<Direction> directions = ds.getDirections(); //Construct giant string that contains directions //Each direction is divided by || //Each component of the direction is divided by ^^ String all = ""; for(Direction direction : directions){ Direction.Coordinate start = direction.getStart(); Direction.Coordinate end = direction.getEnd(); String instruction = direction.getInstruction(); all += (start.lat + "^^" + start.lng + "^^" + end.lat + "^^" + end.lng + "^^" + instruction + "||"); } int queryLength = (int) Math.ceil(all.length() / ((double) MAX_SMS_LENGTH)); ArrayList<String> allSMS = new ArrayList<String>(); int index = 0; int count = 1; while (index < all.length()) { allSMS.add("<" + count + "/" + queryLength + ">" + all.substring(index, Math.min(index + MAX_SMS_LENGTH,all.length()))); index += MAX_SMS_LENGTH; count++; } for(String SMS : allSMS) { message = SMS; Log.d("Message", message); requestSMSPermission(); } } }
package com.felhr.usbserial; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbRequest; import android.util.Log; /* * Werner Wolfrum (w.wolfrum@wolfrum-elektronik.de) */ @Deprecated public class XdcVcpSerialDevice extends UsbSerialDevice { private static final String CLASS_ID = XdcVcpSerialDevice.class.getSimpleName(); private static final int XDCVCP_IFC_ENABLE = 0x00; private static final int XDCVCP_SET_BAUDDIV = 0x01; private static final int XDCVCP_SET_LINE_CTL = 0x03; private static final int XDCVCP_GET_LINE_CTL = 0x04; private static final int XDCVCP_SET_MHS = 0x07; private static final int XDCVCP_SET_BAUDRATE = 0x1E; private static final int XDCVCP_SET_FLOW = 0x13; private static final int XDCVCP_SET_XON = 0x09; private static final int XDCVCP_SET_XOFF = 0x0A; private static final int XDCVCP_SET_CHARS = 0x19; private static final int XDCVCP_REQTYPE_HOST2DEVICE = 0x41; private static final int XDCVCP_REQTYPE_DEVICE2HOST = 0xC1; /*** * Default Serial Configuration * Baud rate: 115200 * Data bits: 8 * Stop bits: 1 * Parity: None * Flow Control: Off */ private static final int XDCVCP_UART_ENABLE = 0x0001; private static final int XDCVCP_UART_DISABLE = 0x0000; private static final int XDCVCP_LINE_CTL_DEFAULT = 0x0800; private static final int XDCVCP_MHS_DEFAULT = 0x0000; private static final int XDCVCP_MHS_DTR = 0x0001; private static final int XDCVCP_MHS_RTS = 0x0010; private static final int XDCVCP_MHS_ALL = 0x0011; private static final int XDCVCP_XON = 0x0000; private static final int XDCVCP_XOFF = 0x0000; private static final int DEFAULT_BAUDRATE = 115200; private UsbInterface mInterface; private UsbEndpoint inEndpoint; private UsbEndpoint outEndpoint; private UsbRequest requestIN; public XdcVcpSerialDevice(UsbDevice device, UsbDeviceConnection connection) { this(device, connection, -1); } public XdcVcpSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { super(device, connection); mInterface = device.getInterface(iface >= 0 ? iface : 0); } @Override public boolean open() { initSerialBuffer(); // Restart the working thread and writeThread if it has been killed before and get and claim interface restartWorkingThread(); restartWriteThread(); if(connection.claimInterface(mInterface, true)) { Log.i(CLASS_ID, "Interface succesfully claimed"); }else { Log.i(CLASS_ID, "Interface could not be claimed"); return false; } // Assign endpoints int numberEndpoints = mInterface.getEndpointCount(); for(int i=0;i<=numberEndpoints-1;i++) { UsbEndpoint endpoint = mInterface.getEndpoint(i); if(endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK && endpoint.getDirection() == UsbConstants.USB_DIR_IN) { inEndpoint = endpoint; }else { outEndpoint = endpoint; } } // Default Setup if(setControlCommand(XDCVCP_IFC_ENABLE, XDCVCP_UART_ENABLE, null) < 0) return false; setBaudRate(DEFAULT_BAUDRATE); if(setControlCommand(XDCVCP_SET_LINE_CTL, XDCVCP_LINE_CTL_DEFAULT,null) < 0) return false; setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF); if(setControlCommand(XDCVCP_SET_MHS, XDCVCP_MHS_DEFAULT, null) < 0) return false; // Initialize UsbRequest requestIN = new UsbRequest(); requestIN.initialize(connection, inEndpoint); // Pass references to the threads setThreadsParams(requestIN, outEndpoint); return true; } @Override public void close() { setControlCommand(XDCVCP_IFC_ENABLE, XDCVCP_UART_DISABLE, null); killWorkingThread(); killWriteThread(); connection.releaseInterface(mInterface); } @Override public boolean syncOpen() { return false; } @Override public void syncClose() { } @Override public void setBaudRate(int baudRate) { byte[] data = new byte[] { (byte) (baudRate & 0xff), (byte) (baudRate >> 8 & 0xff), (byte) (baudRate >> 16 & 0xff), (byte) (baudRate >> 24 & 0xff) }; setControlCommand(XDCVCP_SET_BAUDRATE, 0, data); } @Override public void setDataBits(int dataBits) { byte[] data = getCTL(); switch(dataBits) { case UsbSerialInterface.DATA_BITS_5: data[1] = 5; break; case UsbSerialInterface.DATA_BITS_6: data[1] = 6; break; case UsbSerialInterface.DATA_BITS_7: data[1] = 7; break; case UsbSerialInterface.DATA_BITS_8: data[1] = 8; break; default: return; } byte wValue = (byte) ((data[1] << 8) | (data[0] & 0xFF)); setControlCommand(XDCVCP_SET_LINE_CTL, wValue, null); } @Override public void setStopBits(int stopBits) { byte[] data = getCTL(); switch(stopBits) { case UsbSerialInterface.STOP_BITS_1: data[0] &= ~1; data[0] &= ~(1 << 1); break; case UsbSerialInterface.STOP_BITS_15: data[0] |= 1; data[0] &= ~(1 << 1) ; break; case UsbSerialInterface.STOP_BITS_2: data[0] &= ~1; data[0] |= (1 << 1); break; default: return; } byte wValue = (byte) ((data[1] << 8) | (data[0] & 0xFF)); setControlCommand(XDCVCP_SET_LINE_CTL, wValue, null); } @Override public void setParity(int parity) { byte[] data = getCTL(); switch(parity) { case UsbSerialInterface.PARITY_NONE: data[0] &= ~(1 << 4); data[0] &= ~(1 << 5); data[0] &= ~(1 << 6); data[0] &= ~(1 << 7); break; case UsbSerialInterface.PARITY_ODD: data[0] |= (1 << 4); data[0] &= ~(1 << 5); data[0] &= ~(1 << 6); data[0] &= ~(1 << 7); break; case UsbSerialInterface.PARITY_EVEN: data[0] &= ~(1 << 4); data[0] |= (1 << 5); data[0] &= ~(1 << 6); data[0] &= ~(1 << 7); break; case UsbSerialInterface.PARITY_MARK: data[0] |= (1 << 4); data[0] |= (1 << 5); data[0] &= ~(1 << 6); data[0] &= ~(1 << 7); break; case UsbSerialInterface.PARITY_SPACE: data[0] &= ~(1 << 4); data[0] &= ~(1 << 5); data[0] |= (1 << 6); data[0] &= ~(1 << 7); break; default: return; } byte wValue = (byte) ((data[1] << 8) | (data[0] & 0xFF)); setControlCommand(XDCVCP_SET_LINE_CTL, wValue, null); } @Override public void setFlowControl(int flowControl) { switch(flowControl) { case UsbSerialInterface.FLOW_CONTROL_OFF: byte[] dataOff = new byte[]{ (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00 }; setControlCommand(XDCVCP_SET_FLOW, 0, dataOff); break; case UsbSerialInterface.FLOW_CONTROL_RTS_CTS: byte[] dataRTSCTS = new byte[]{ (byte) 0x09, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00 }; setControlCommand(XDCVCP_SET_FLOW, 0, dataRTSCTS); break; case UsbSerialInterface.FLOW_CONTROL_DSR_DTR: byte[] dataDSRDTR = new byte[]{ (byte) 0x12, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00 }; setControlCommand(XDCVCP_SET_FLOW, 0, dataDSRDTR); break; case UsbSerialInterface.FLOW_CONTROL_XON_XOFF: byte[] dataXONXOFF = new byte[]{ (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x43, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00 }; byte[] dataChars = new byte[]{ (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x11, (byte) 0x13 }; setControlCommand(XDCVCP_SET_CHARS, 0, dataChars); setControlCommand(XDCVCP_SET_FLOW, 0, dataXONXOFF); break; default: return; } } @Override public void setRTS(boolean state) { //TODO } @Override public void setDTR(boolean state) { //TODO } @Override public void getCTS(UsbCTSCallback ctsCallback) { //TODO } @Override public void getDSR(UsbDSRCallback dsrCallback) { //TODO } @Override public void getBreak(UsbBreakCallback breakCallback) { //TODO } @Override public void getFrame(UsbFrameCallback frameCallback) { //TODO } @Override public void getOverrun(UsbOverrunCallback overrunCallback) { //TODO } @Override public void getParity(UsbParityCallback parityCallback) { //TODO } private int setControlCommand(int request, int value, byte[] data) { int dataLength = 0; if(data != null) { dataLength = data.length; } int response = connection.controlTransfer(XDCVCP_REQTYPE_HOST2DEVICE, request, value, mInterface.getId(), data, dataLength, USB_TIMEOUT); Log.i(CLASS_ID,"Control Transfer Response: " + String.valueOf(response)); return response; } private byte[] getCTL() { byte[] data = new byte[2]; int response = connection.controlTransfer(XDCVCP_REQTYPE_DEVICE2HOST, XDCVCP_GET_LINE_CTL, 0, mInterface.getId(), data, data.length, USB_TIMEOUT ); Log.i(CLASS_ID,"Control Transfer Response: " + String.valueOf(response)); return data; } }
package me.nithanim.longbuffer; import java.nio.ByteOrder; public abstract class AbstractBuffer implements Buffer { protected long readerIndex; protected long writerIndex; @Override public long readerIndex() { return readerIndex; } @Override public void readerIndex(long index) { readerIndex = index; } @Override public long writerIndex() { return writerIndex; } @Override public void writerIndex(long index) { writerIndex = index; } /** * If the ByteOrder is the same it returns "this". Otherwise * a new Buffer with the specified ByteOrder is created. * * @param order * @return */ @Override public Buffer order(ByteOrder order) { return BufferUtil.ensureByteOrder(this, order); } @Override public byte getByte(long index) { ensureReadable(index, Byte.SIZE/8); return _getByte(index); } @Override public short getShort(long index) { ensureReadable(index, Short.SIZE/8); return _getShort(index); } @Override public int getInt(long index) { ensureReadable(index, Integer.SIZE/8); return _getInt(index); } @Override public long getUnsignedInt(long index) { return getLong(index) & 0xFFFFFFFF; } @Override public long getLong(long index) { ensureReadable(index, Long.SIZE/8); return _getLong(index); } @Override public float getFloat(long index) { ensureReadable(index, Float.SIZE/8); return _getFloat(index); } @Override public double getDouble(long index) { ensureReadable(index, Double.SIZE/8); return _getDouble(index); } @Override public byte readByte() { long i = readerIndex; byte v = getByte(i); readerIndex += Byte.SIZE/8; return v; } @Override public short readShort() { long i = readerIndex; short v = getShort(i); readerIndex += Short.SIZE/8; return v; } @Override public int readInt() { long i = readerIndex; int v = getInt(i); readerIndex += Integer.SIZE/8; return v; } @Override public long readUnsignedInt() { return readInt() & 0xFFFFFFFFL; } @Override public long readLong() { long i = readerIndex; long v = getLong(i); readerIndex += Long.SIZE/8; return v; } @Override public float readFloat() { long i = readerIndex; float v = getFloat(i); readerIndex += Float.SIZE/8; return v; } @Override public double readDouble() { long i = readerIndex; double v = getDouble(i); readerIndex += Double.SIZE/8; return v; } @Override public Buffer writeByte(byte value) { setByte(writerIndex, value); writerIndex += Byte.SIZE/8; return this; } @Override public Buffer writeShort(short value) { setShort(writerIndex, value); writerIndex += Short.SIZE/8; return this; } @Override public Buffer writeInt(int value) { setInt(writerIndex, value); writerIndex += Integer.SIZE/8; return this; } @Override public Buffer writeLong(long value) { setLong(writerIndex, value); writerIndex += Long.SIZE/8; return this; } @Override public Buffer writeFloat(float value) { setFloat(writerIndex, value); writerIndex += Float.SIZE/8; return this; } @Override public Buffer writeDouble(double value) { setDouble(writerIndex, value); writerIndex += Double.SIZE/8; return this; } @Override public Buffer setByte(long index, byte value) { ensureWriteable(index, Byte.SIZE/8); _setByte(index, value); return this; } @Override public Buffer setShort(long index, short value) { ensureWriteable(index, Short.SIZE/8); _setShort(index, value); return this; } @Override public Buffer setInt(long index, int value) { ensureWriteable(index, Integer.SIZE/8); _setInt(index, value); return this; } @Override public Buffer setLong(long index, long value) { ensureWriteable(index, Long.SIZE/8); _setLong(index, value); return this; } @Override public Buffer setFloat(long index, float value) { ensureWriteable(index, Float.SIZE/8); _setFloat(index, value); return this; } @Override public Buffer setDouble(long index, double value) { ensureWriteable(index, Double.SIZE/8); _setDouble(index, value); return this; } protected abstract byte _getByte(long index); protected abstract short _getShort(long index); protected abstract int _getInt(long index); protected abstract long _getLong(long index); protected abstract float _getFloat(long index); protected abstract double _getDouble(long index); protected abstract Buffer _setByte(long index, byte value); protected abstract Buffer _setShort(long index, short value); protected abstract Buffer _setInt(long index, int value); protected abstract Buffer _setLong(long index, long value); protected abstract Buffer _setFloat(long index, float value); protected abstract Buffer _setDouble(long index, double value); protected void ensureWriteable(long length) { ensureReadable(writerIndex, length); } protected abstract void ensureWriteable(long index, long length); protected void ensureReadable(long length) { ensureReadable(readerIndex, length); } protected abstract void ensureReadable(long index, long length); /** * Creates a view of a part of this buffer. In other words: * Creates a new Buffer which acts as a window for only the * specified part of the underlying buffer. It cannot be read * or written outside of this range. * * @param index * @param length * @return */ @Override public Buffer slice(long index, long length) { return new ViewBuffer(this, index, length); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('<').append(getClass().getSimpleName()); sb.append('(').append("rIdx: ").append(readerIndex()); sb.append(", wIdx: ").append(writerIndex()); sb.append(", cap: ").append(capacity()); sb.append(')').append('>'); return sb.toString(); } @Override public boolean equals(Object obj) { return BufferUtil.equals(this, obj); } }
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package leap.core; import leap.core.sys.DefaultSysSecurity; import leap.core.sys.SysContext; import leap.lang.Classes; import leap.lang.Exceptions; import leap.lang.Factory; import leap.lang.annotation.Internal; import leap.lang.logging.Log; import leap.lang.logging.LogFactory; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; @Internal public class AppContextInitializer { private static final Log log = LogFactory.get(AppContextInitializer.class); private static ThreadLocal<AppConfig> initialAppConfig; private static boolean initializing; private static boolean testing; private static boolean instrumentDisabled; private static String basePackage; private static AppClassLoaderGetter classLoaderGetter = Factory.tryNewInstance(AppClassLoaderGetter.class); public static String getBasePackage() { return basePackage; } public static void setBasePackage(String basePackage) { AppContextInitializer.basePackage = basePackage; } public static void setInstrumentDisabled(boolean disabled) { instrumentDisabled = disabled; } public static boolean isTesting() { return testing; } public static void markTesting() { testing = true; } public static AppConfig getInitialConfig() { return null == initialAppConfig ? null : initialAppConfig.get(); } public static AppContext newStandalone() { return initStandalone(null, null, true); } public static void initStandalone() { initStandalone(null, null, true); } public static void initStandalone(Map<String, String> props) { initStandalone(null, props, true); } public static void initStandalone(BeanFactory externalAppFactory) { initStandalone(externalAppFactory, null, true); } protected static ClassLoader getClassLoader() { ClassLoader current = Classes.getClassLoader(AppContextInitializer.class); return null == classLoaderGetter ? current : classLoaderGetter.getClassLoader(current); } protected static synchronized AppContext initStandalone(BeanFactory externalAppFactory, Map<String, String> props, boolean createNew) { if (initializing) { return null; } if (!createNew && AppContext.tryGetCurrent() != null) { throw new IllegalStateException("App context already initialized"); } AppConfig config = null; try { initializing = true; initialAppConfig = new InheritableThreadLocal<>(); log.debug("Starting standalone app..."); AppConfigSource cs = Factory.newInstance(AppConfigSource.class); config = cs.loadConfig(null, props); initialAppConfig.set(config); ClassLoader ctxCl = Thread.currentThread().getContextClassLoader(); AppClassLoader appCl = null; if (!instrumentDisabled) { ClassLoader parent = getClassLoader(); appCl = AppClassLoader.init(parent); Thread.currentThread().setContextClassLoader(appCl); appCl.load(config); } try { BeanFactoryInternal factory = createStandaloneAppFactory(config, externalAppFactory); //register beans cs.registerBeans(config, factory); AppContext context = new AppContext("app", config, factory, null); initSysContext(context, config); AppContext.setStandalone(context); RequestContext.setStandalone(new StandaloneRequestContext()); factory.load(context); onInited(context); log.debug("Standalone app started!!!\n\n"); return context; } finally { if (null != appCl) { appCl.done(); Thread.currentThread().setContextClassLoader(ctxCl); } } } finally { initialAppConfig.remove(); initialAppConfig = null; initializing = false; if (null != config) { AppResources.destroy(config); } } } public static synchronized void initExternal(Object externalContext, String name, Function<AppConfig, BeanFactory> newBeanFactory, Consumer<AppContext> onAppContextCreated, Consumer<AppContext> onAppContextinited, Map<String, String> initProperties) { if (initializing) { return; } if (AppContext.tryGetCurrent() != null) { throw new IllegalStateException("App context already initialized"); } AppConfig config = null; try { initializing = true; initialAppConfig = new InheritableThreadLocal<>(); //log.info("Initializing app context"); AppConfigSource cs = Factory.newInstance(AppConfigSource.class); config = cs.loadConfig(externalContext, initProperties); initialAppConfig.set(config); ClassLoader ctxCl = Thread.currentThread().getContextClassLoader(); AppClassLoader appCl = null; if (!instrumentDisabled) { ClassLoader parent = getClassLoader(); appCl = AppClassLoader.init(parent); Thread.currentThread().setContextClassLoader(appCl); appCl.load(config); } try { BeanFactory factory = newBeanFactory.apply(config); //register bean cs.registerBeans(config, factory); AppContext context = new AppContext(name, config, factory, externalContext); initSysContext(context, config); AppContext.setCurrent(context); onAppContextCreated.accept(context); onInited(context); onAppContextinited.accept(context); } finally { if (null != appCl) { appCl.done(); Thread.currentThread().setContextClassLoader(ctxCl); } } } finally { initialAppConfig.remove(); initialAppConfig = null; initializing = false; if (null != config) { AppResources.destroy(config); } } } protected static BeanFactoryInternal createStandaloneAppFactory(AppConfig config, BeanFactory externalAppFactory) { BeanFactoryInternal factory = Factory.newInstance(BeanFactoryInternal.class); factory.init(config, externalAppFactory); return factory; } protected static void initSysContext(AppContext appContext, AppConfig config) { appContext.setAttribute(SysContext.SYS_CONTEXT_ATTRIBUTE_KEY, new SysContext(new DefaultSysSecurity(config))); } protected static void onInited(AppContext context) { try { context.postInit(); for (AppContextInitializable bean : context.getBeanFactory().getBeans(AppContextInitializable.class)) { bean.postInit(context); } context.getBeanFactory().postInit(context); } catch (Throwable e) { Exceptions.uncheckAndThrow(e); } } private AppContextInitializer() { } }
package db; import db.util.JsfUtil; import db.util.PaginationHelper; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @Named("personnelController") @SessionScoped public class PersonnelController implements Serializable { private Personnel current; private DataModel items = null; @EJB private db.PersonnelFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public PersonnelController() { } public Personnel getSelected() { if (current == null) { current = new Personnel(); selectedItemIndex = -1; } return current; } private PersonnelFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Personnel) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Personnel(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonnelCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Personnel) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonnelUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Personnel) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonnelDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } public Personnel getPersonnel(java.lang.String id) { return ejbFacade.find(id); } @FacesConverter(forClass = Personnel.class) public static class PersonnelControllerConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } PersonnelController controller = (PersonnelController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "personnelController"); return controller.getPersonnel(getKey(value)); } java.lang.String getKey(String value) { java.lang.String key; key = value; return key; } String getStringKey(java.lang.String value) { StringBuilder sb = new StringBuilder(); sb.append(value); return sb.toString(); } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Personnel) { Personnel o = (Personnel) object; return getStringKey(o.getPersID()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Personnel.class.getName()); } } } }
package com.planet_ink.coffee_mud.Abilities.Songs; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2022 Bo Zimmerman 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. */ public class Dance_Square extends Dance { @Override public String ID() { return "Dance_Square"; } private final static String localizedName = CMLib.lang().L("Square"); @Override public String name() { return localizedName; } @Override public int abstractQuality() { return Ability.QUALITY_MALICIOUS; } @Override protected boolean skipStandardDanceInvoke() { return true; } @Override protected String danceOf() { return name()+" Dance"; } @Override protected boolean HAS_QUANTITATIVE_ASPECT() { return false; } @Override public int castingQuality(final MOB mob, final Physical target) { if(mob!=null) { if(mob.isMonster()) return Ability.QUALITY_INDIFFERENT; } return super.castingQuality(mob,target); } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if(msg.amISource(invoker()) &&(affected!=invoker()) &&(msg.sourceMinor()==CMMsg.TYP_SPEAK) &&(msg.sourceMessage()!=null) &&(msg.sourceMessage().length()>0)) { final String cmd=CMStrings.getSayFromMessage(msg.sourceMessage()); if(cmd!=null) { final MOB M=(MOB)affected; final CMMsg omsg=CMClass.getMsg(invoker(),affected,null,CMMsg.MSG_ORDER,null); if(CMLib.flags().canBeHeardMovingBy(invoker(),M) &&CMLib.flags().canBeSeenBy(invoker(),M) &&(M.location()==invoker().location()) &&(M.location().okMessage(M, omsg))) { M.location().send(M, omsg); if(omsg.sourceMinor()==CMMsg.TYP_ORDER) { final CMObject O=CMLib.english().findCommand(M,CMParms.parse(cmd)); if((O!=null)&&((!(O instanceof Command))||(((Command)O).canBeOrdered()))) M.enqueCommand(CMParms.parse(cmd),MUDCmdProcessor.METAFLAG_FORCED|MUDCmdProcessor.METAFLAG_ORDER,0); } } } } super.executeMsg(myHost,msg); } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { timeOut=0; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if((!auto)&&(!CMLib.flags().isAliveAwakeMobile(mob,false))) return false; final boolean success=proficiencyCheck(mob,0,auto); final int newDepth = this.calculateNewSongDepth(mob); final boolean redance = mob.fetchEffect(ID())!=null; unDanceAll(mob,null,false,false); // because ALWAYS removing myself, depth needs pre-calculating. if(success) { invoker=mob; originRoom=mob.location(); final int oldDepth = this.danceDepth; commonRoomSet=getInvokerScopeRoomSet(newDepth); this.danceDepth = newDepth; String str=auto?L("^SThe @x1 begins!^?",danceOf()):L("^S<S-NAME> begin(s) to dance the @x1.^?",danceOf()); if((!auto) && (redance)) { if(newDepth > oldDepth) str=L("^S<S-NAME> extend(s) the @x1`s range.^?",danceOf()); else str=L("^S<S-NAME> start(s) the @x1 over again.^?",danceOf()); } final Set<MOB> friends=mob.getGroupMembers(new HashSet<MOB>()); for(int v=0;v<commonRoomSet.size();v++) { final Room R=commonRoomSet.get(v); final String msgStr=getCorrectMsgString(R,str,v); final CMMsg msg=CMClass.getMsg(mob,null,this,somanticCastCode(mob,null,auto),msgStr); if(R.okMessage(mob,msg)) { R.send(mob,msg); invoker=mob; final Dance newOne=(Dance)this.copyOf(); newOne.invokerManaCost=-1; for(int i=0;i<R.numInhabitants();i++) { final MOB follower=R.fetchInhabitant(i); final Room R2=follower.location(); // malicious dances must not affect the invoker! int affectType=CMMsg.MSG_CAST_SOMANTIC_SPELL; if((!friends.contains(follower))&&(follower!=mob)) affectType=affectType|CMMsg.MASK_MALICIOUS; if(auto) affectType=affectType|CMMsg.MASK_ALWAYS; final Dance effectD = (Dance)follower.fetchEffect(this.ID()); if(effectD!=null) effectD.danceDepth = this.danceDepth; else if(CMLib.flags().canBeSeenBy(invoker,follower)) { CMMsg msg2=CMClass.getMsg(mob,follower,this,affectType,null); final CMMsg msg3=msg2; if((!friends.contains(follower))&&(follower!=mob)) msg2=CMClass.getMsg(mob,follower,this,CMMsg.MSK_CAST_MALICIOUS_SOMANTIC|CMMsg.TYP_MIND|(auto?CMMsg.MASK_ALWAYS:0),null); if((R.okMessage(mob,msg2))&&(R.okMessage(mob,msg3))) { R2.send(follower,msg2); if(msg2.value()<=0) { R2.send(follower,msg3); if(msg3.value()<=0) { if(follower!=mob) follower.addEffect((Ability)newOne.copyOf()); else follower.addEffect(newOne); } } } } } mob.location().recoverRoomStats(); } } } else mob.location().show(mob,null,CMMsg.MSG_NOISE,L("<S-NAME> make(s) a false step.")); return success; } }
/* $Id: RobotsManager.java 988245 2010-08-23 18:39:35Z kwright $ */ /** * 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.manifoldcf.crawler.connectors.webcrawler; import java.util.*; import java.io.*; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.authorities.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.CacheKeyFactory; import org.apache.manifoldcf.crawler.system.ManifoldCF; import org.apache.manifoldcf.crawler.system.Logging; /** This class manages the database table into which we write robots.txt files for hosts. The data resides in the database, * as well as in cache (up to a certain point). The result is that there is a memory limited, database-backed repository * of robots files that we can draw on. * * <br><br> * <b>robotsdata</b> * <table border="1" cellpadding="3" cellspacing="0"> * <tr class="TableHeadingColor"> * <th>Field</th><th>Type</th><th>Description&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th> * <tr><td>hostname</td><td>VARCHAR(255)</td><td>Primary Key</td></tr> * <tr><td>robotsdata</td><td>BIGINT</td><td></td></tr> * <tr><td>expirationtime</td><td>BLOB</td><td></td></tr> * </table> * <br><br> * */ public class RobotsManager extends org.apache.manifoldcf.core.database.BaseTable { public static final String _rcsid = "@(#)$Id: RobotsManager.java 988245 2010-08-23 18:39:35Z kwright $"; // Robots cache class. Only one needed. protected static RobotsCacheClass robotsCacheClass = new RobotsCacheClass(); // Database fields protected final static String hostField = "hostname"; protected final static String robotsField = "robotsdata"; protected final static String expirationField = "expirationtime"; // Cache manager. This handle is set up during the constructor. ICacheManager cacheManager; /** Constructor. Note that one robotsmanager handle is only useful within a specific thread context, * so the calling connector object logic must recreate the handle whenever the thread context changes. *@param tc is the thread context. *@param database is the database handle. */ public RobotsManager(IThreadContext tc, IDBInterface database) throws ManifoldCFException { super(database,"robotsdata"); cacheManager = CacheManagerFactory.make(tc); } /** Install the manager. */ public void install() throws ManifoldCFException { // Standard practice: outer loop on install methods, no transactions while (true) { Map existing = getTableSchema(null,null); if (existing == null) { // Install the table. HashMap map = new HashMap(); map.put(hostField,new ColumnDescription("VARCHAR(255)",true,false,null,null,false)); map.put(expirationField,new ColumnDescription("BIGINT",false,false,null,null,false)); map.put(robotsField,new ColumnDescription("BLOB",false,true,null,null,false)); performCreate(map,null); } else { // Upgrade code, if needed, goes here } // Handle indexes, if needed break; } } /** Uninstall the manager. */ public void deinstall() throws ManifoldCFException { performDrop(null); } /** Read robots.txt data from the cache or from the database. *@param hostName is the host for which the data is desired. *@param currentTime is the time of the check. *@return null if the record needs to be fetched, true if fetch is allowed. */ public Boolean checkFetchAllowed(String userAgent, String hostName, long currentTime, String pathString, IVersionActivity activities) throws ManifoldCFException { // Build description objects HostDescription[] objectDescriptions = new HostDescription[1]; StringSetBuffer ssb = new StringSetBuffer(); ssb.add(getRobotsKey(hostName)); objectDescriptions[0] = new HostDescription(hostName,new StringSet(ssb)); HostExecutor exec = new HostExecutor(this,activities,objectDescriptions[0]); cacheManager.findObjectsAndExecute(objectDescriptions,null,exec,getTransactionID()); // We do the expiration check here, rather than in the query, so that caching // is possible. RobotsData rd = exec.getResults(); if (rd == null || rd.getExpirationTime() <= currentTime) return null; return new Boolean(rd.isFetchAllowed(userAgent,pathString)); } /** Write robots.txt, replacing any existing row. *@param hostName is the host. *@param expirationTime is the time this data should expire. *@param data is the robots data stream. May be null. */ public void writeRobotsData(String hostName, long expirationTime, InputStream data) throws ManifoldCFException, IOException { TempFileInput tfi = null; try { if (data != null) { try { tfi = new TempFileInput(data); } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) throw e; throw new IOException("Fetch failed: "+e.getMessage()); } } StringSetBuffer ssb = new StringSetBuffer(); ssb.add(getRobotsKey(hostName)); StringSet cacheKeys = new StringSet(ssb); ICacheHandle ch = cacheManager.enterCache(null,cacheKeys,getTransactionID()); try { beginTransaction(); try { // See whether the instance exists ArrayList params = new ArrayList(); params.add(hostName); IResultSet set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+ hostField+"=?",params,null,null); HashMap values = new HashMap(); values.put(expirationField,new Long(expirationTime)); if (tfi != null) values.put(robotsField,tfi); if (set.getRowCount() > 0) { // Update params.clear(); params.add(hostName); performUpdate(values," WHERE "+hostField+"=?",params,null); } else { // Insert values.put(hostField,hostName); // We only need the general key because this is new. performInsert(values,null); } cacheManager.invalidateKeys(ch); } catch (ManifoldCFException e) { signalRollback(); throw e; } catch (Error e) { signalRollback(); throw e; } finally { endTransaction(); } } finally { cacheManager.leaveCache(ch); } } finally { if (tfi != null) tfi.discard(); } } // Protected methods and classes /** Construct a key which represents an individual host name. *@param hostName is the name of the connector. *@return the cache key. */ protected static String getRobotsKey(String hostName) { return "ROBOTS_"+hostName; } /** Read robots data, if it exists. *@return null if the data doesn't exist at all. Return robots data if it does. */ protected RobotsData readRobotsData(String hostName, IVersionActivity activities) throws ManifoldCFException { try { ArrayList list = new ArrayList(); list.add(hostName); IResultSet set = performQuery("SELECT "+robotsField+","+expirationField+" FROM "+getTableName()+ " WHERE "+hostField+"=?",list,null,null); if (set.getRowCount() == 0) return null; if (set.getRowCount() > 1) throw new ManifoldCFException("Unexpected number of robotsdata rows matching '"+hostName+"': "+Integer.toString(set.getRowCount())); IResultRow row = set.getRow(0); long expiration = ((Long)row.getValue(expirationField)).longValue(); BinaryInput bi = (BinaryInput)row.getValue(robotsField); if (bi == null) return new RobotsData(null,expiration,hostName,activities); try { InputStream is = bi.getStream(); return new RobotsData(is,expiration,hostName,activities); } finally { bi.discard(); } } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (IOException e) { throw new ManifoldCFException("IO error reading robots data for "+hostName+": "+e.getMessage(),e); } } /** Convert a string from the robots file into a readable form that does NOT contain NUL characters (since postgresql does not accept those). */ protected static String makeReadable(String inputString) { StringBuilder sb = new StringBuilder(); int i = 0; while (i < inputString.length()) { char y = inputString.charAt(i++); if (y >= ' ') sb.append(y); else { sb.append('^'); sb.append((char)(y + '@')); } } return sb.toString(); } /** This is a cached data item. */ protected static class RobotsData { protected long expiration; protected ArrayList records = null; /** Constructor. */ public RobotsData(InputStream is, long expiration, String hostName, IVersionActivity activities) throws IOException, ManifoldCFException { this.expiration = expiration; if (is == null) { records = null; return; } Reader r = new InputStreamReader(is,"utf-8"); try { BufferedReader br = new BufferedReader(r); try { parseRobotsTxt(br,hostName,activities); } finally { br.close(); } } finally { r.close(); } } /** Check if fetch is allowed */ public boolean isFetchAllowed(String userAgent, String pathString) { if (records == null) return true; boolean wasDisallowed = false; boolean wasAllowed = false; // First matching user-agent takes precedence, according to the following chunk of spec: // "These name tokens are used in User-agent lines in /robots.txt to // identify to which specific robots the record applies. The robot // must obey the first record in /robots.txt that contains a User- // Agent line whose value contains the name token of the robot as a // substring. The name comparisons are case-insensitive. If no such // record exists, it should obey the first record with a User-agent // line with a "*" value, if present. If no record satisfied either // condition, or no records are present at all, access is unlimited." boolean sawAgent = false; String userAgentUpper = userAgent.toUpperCase(); int i = 0; while (i < records.size()) { Record r = (Record)records.get(i++); if (r.isAgentMatch(userAgentUpper,false)) { if (r.isDisallowed(pathString)) wasDisallowed = true; if (r.isAllowed(pathString)) wasAllowed = true; sawAgent = true; break; } } if (sawAgent == false) { i = 0; while (i < records.size()) { Record r = (Record)records.get(i++); if (r.isAgentMatch("*",true)) { if (r.isDisallowed(pathString)) wasDisallowed = true; if (r.isAllowed(pathString)) wasAllowed = true; sawAgent = true; break; } } } if (sawAgent == false) return true; // Allowed always overrides disallowed if (wasAllowed) return true; if (wasDisallowed) return false; // No match -> crawl allowed return true; } /** Get expiration */ public long getExpirationTime() { return expiration; } /** Parse the robots.txt file using a reader. * Is NOT expected to close the stream. */ protected void parseRobotsTxt(BufferedReader r, String hostName, IVersionActivity activities) throws IOException, ManifoldCFException { boolean parseCompleted = false; boolean robotsWasHtml = false; boolean foundErrors = false; String description = null; long startParseTime = System.currentTimeMillis(); try { records = new ArrayList(); Record record = null; boolean seenAction = false; while (true) { String x = r.readLine(); if (x == null) break; int numSignPos = x.indexOf("#"); if (numSignPos != -1) x = x.substring(0,numSignPos); String lowercaseLine = x.toLowerCase().trim(); if (lowercaseLine.startsWith("user-agent:")) { if (seenAction) { records.add(record); record = null; seenAction = false; } if (record == null) record = new Record(); String agentName = x.substring("User-agent:".length()).trim(); record.addAgent(agentName); } else if (lowercaseLine.startsWith("user-agent")) { if (seenAction) { records.add(record); record = null; seenAction = false; } if (record == null) record = new Record(); String agentName = x.substring("User-agent".length()).trim(); record.addAgent(agentName); } else if (lowercaseLine.startsWith("disallow:")) { if (record == null) { description = "Disallow without User-agent"; Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description); foundErrors = true; } else { String disallowPath = x.substring("Disallow:".length()).trim(); // The spec says that a blank disallow means let everything through. if (disallowPath.length() > 0) record.addDisallow(disallowPath); seenAction = true; } } else if (lowercaseLine.startsWith("disallow")) { if (record == null) { description = "Disallow without User-agent"; Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description); foundErrors = true; } else { String disallowPath = x.substring("Disallow".length()).trim(); // The spec says that a blank disallow means let everything through. if (disallowPath.length() > 0) record.addDisallow(disallowPath); seenAction = true; } } else if (lowercaseLine.startsWith("allow:")) { if (record == null) { description = "Allow without User-agent"; Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description); foundErrors = true; } else { String allowPath = x.substring("Allow:".length()).trim(); // The spec says that a blank disallow means let everything through. if (allowPath.length() > 0) record.addAllow(allowPath); seenAction = true; } } else if (lowercaseLine.startsWith("allow")) { if (record == null) { description = "Allow without User-agent"; Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description); foundErrors = true; } else { String allowPath = x.substring("Allow".length()).trim(); // The spec says that a blank disallow means let everything through. if (allowPath.length() > 0) record.addAllow(allowPath); seenAction = true; } } else if (lowercaseLine.startsWith("crawl-delay:")) { // We don't complain about this, but right now we don't listen to it either. } else if (lowercaseLine.startsWith("crawl-delay")) { // We don't complain about this, but right now we don't listen to it either. } else { // If it's not just a blank line, complain if (x.trim().length() > 0) { String problemLine = makeReadable(x); description = "Unknown robots.txt line: '"+problemLine+"'"; Logging.connectors.warn("Web: Unknown robots.txt line from '"+hostName+"': '"+problemLine+"'"); if (x.indexOf("<html") != -1 || x.indexOf("<HTML") != -1) { // Looks like some kind of an html file, probably as a result of a redirection, so just abort as if we have a page error robotsWasHtml = true; parseCompleted = true; break; } foundErrors = true; } } } if (record != null) records.add(record); parseCompleted = true; } finally { // Log the fact that we attempted to parse robots.txt, as well as what happened // These are the following situations we will report: // (1) INCOMPLETE - Parsing did not complete - if the stream was interrupted // (2) HTML - Robots was html - if the robots data seemed to be html // (3) ERRORS - Robots had errors - if the robots data was accepted but had errors in it // (4) SUCCESS - Robots parsed successfully - if the robots data was parsed without problem String status; if (parseCompleted) { if (robotsWasHtml) { status = "HTML"; description = "Robots file contained HTML, skipped"; } else { if (foundErrors) { status = "ERRORS"; // description should already be set } else { status = "SUCCESS"; description = null; } } } else { status = "INCOMPLETE"; description = "Parsing was interrupted"; } activities.recordActivity(new Long(startParseTime),WebcrawlerConnector.ACTIVITY_ROBOTSPARSE, null,hostName,status,description,null); } } } /** Check if path matches specification */ protected static boolean doesPathMatch(String path, String spec) { // For robots 1.0, this function would do just this: // return path.startsWith(spec); // However, we implement the "google bot" spec, which allows wildcard matches that are, in fact, regular-expression-like in some ways. // The "specification" can be found here: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=40367 return doesPathMatch(path,0,spec,0); } /** Recursive method for matching specification to path. */ protected static boolean doesPathMatch(String path, int pathIndex, String spec, int specIndex) { while (true) { if (specIndex == spec.length()) // Hit the end of the specification! We're done. return true; char specChar = spec.charAt(specIndex++); if (specChar == '*') { // Found a specification wildcard. // Eat up all the '*' characters at this position - otherwise each additional one increments the exponent of how long this can take, // making denial-of-service via robots parsing a possibility. while (specIndex < spec.length()) { if (spec.charAt(specIndex) != '*') break; specIndex++; } // It represents zero or more characters, so we must recursively try for a match against all remaining characters in the path string. while (true) { boolean match = doesPathMatch(path,pathIndex,spec,specIndex); if (match) return true; if (path.length() == pathIndex) // Nothing further to try, and no match return false; pathIndex++; // Try again } } else if (specChar == '$' && specIndex == spec.length()) { // Found a specification end-of-path character. // (It can only be legitimately the last character of the specification.) return pathIndex == path.length(); } if (pathIndex == path.length()) // Hit the end of the path! (but not the end of the specification!) return false; if (path.charAt(pathIndex) != specChar) return false; // On to the next match pathIndex++; } } /** This is the object description for a robots host object. * This is the key that is used to look up cached data. */ protected static class HostDescription extends org.apache.manifoldcf.core.cachemanager.BaseDescription { protected String hostName; protected String criticalSectionName; protected StringSet cacheKeys; public HostDescription(String hostName, StringSet invKeys) { super("robotscache"); this.hostName = hostName; criticalSectionName = getClass().getName()+"-"+hostName; cacheKeys = invKeys; } public String getHostName() { return hostName; } public int hashCode() { return hostName.hashCode(); } public boolean equals(Object o) { if (!(o instanceof HostDescription)) return false; HostDescription d = (HostDescription)o; return d.hostName.equals(hostName); } public String getCriticalSectionName() { return criticalSectionName; } /** Get the cache keys for an object (which may or may not exist yet in * the cache). This method is called in order for cache manager to throw the correct locks. * @return the object's cache keys, or null if the object should not * be cached. */ public StringSet getObjectKeys() { return cacheKeys; } /** Get the object class for an object. The object class is used to determine * the group of objects treated in the same LRU manner. * @return the newly created object's object class, or null if there is no * such class, and LRU behavior is not desired. */ public ICacheClass getObjectClass() { return robotsCacheClass; } } /** Cache class for robots. * An instance of this class describes the cache class for robots data caching. There's * only ever a need for one, so that will be created statically. */ protected static class RobotsCacheClass implements ICacheClass { /** Get the name of the object class. * This determines the set of objects that are treated in the same * LRU pool. *@return the class name. */ public String getClassName() { // We count all the robot data, so this is a constant string. return "ROBOTSCLASS"; } /** Get the maximum LRU count of the object class. *@return the maximum number of the objects of the particular class * allowed. */ public int getMaxLRUCount() { // Hardwired for the moment; 2000 robots data records will be cached, // and no more. return 2000; } } /** This is the executor object for locating robots host objects. * This object furnishes the operations the cache manager needs to rebuild objects that it needs that are * not in the cache at the moment. */ protected static class HostExecutor extends org.apache.manifoldcf.core.cachemanager.ExecutorBase { // Member variables protected RobotsManager thisManager; protected RobotsData returnValue; protected HostDescription thisHost; protected IVersionActivity activities; /** Constructor. *@param manager is the RobotsManager class instance. *@param objectDescription is the desired object description. */ public HostExecutor(RobotsManager manager, IVersionActivity activities, HostDescription objectDescription) { super(); thisManager = manager; this.activities = activities; thisHost = objectDescription; returnValue = null; } /** Get the result. *@return the looked-up or read cached instance. */ public RobotsData getResults() { return returnValue; } /** Create a set of new objects to operate on and cache. This method is called only * if the specified object(s) are NOT available in the cache. The specified objects * should be created and returned; if they are not created, it means that the * execution cannot proceed, and the execute() method will not be called. * @param objectDescriptions is the set of unique identifier of the object. * @return the newly created objects to cache, or null, if any object cannot be created. * The order of the returned objects must correspond to the order of the object descriptinos. */ public Object[] create(ICacheDescription[] objectDescriptions) throws ManifoldCFException { // I'm not expecting multiple values to be request, so it's OK to walk through the objects // and do a request at a time. RobotsData[] rval = new RobotsData[objectDescriptions.length]; int i = 0; while (i < rval.length) { HostDescription desc = (HostDescription)objectDescriptions[i]; // I need to cache both the data and the expiration date, and pick up both when I // do the query. This is because I don't want to cache based on request time, since that // would screw up everything! rval[i] = thisManager.readRobotsData(desc.getHostName(),activities); i++; } return rval; } /** Notify the implementing class of the existence of a cached version of the * object. The object is passed to this method so that the execute() method below * will have it available to operate on. This method is also called for all objects * that are freshly created as well. * @param objectDescription is the unique identifier of the object. * @param cachedObject is the cached object. */ public void exists(ICacheDescription objectDescription, Object cachedObject) throws ManifoldCFException { // Cast what came in as what it really is HostDescription objectDesc = (HostDescription)objectDescription; RobotsData robotsData = (RobotsData)cachedObject; if (objectDesc.equals(thisHost)) returnValue = robotsData; } /** Perform the desired operation. This method is called after either createGetObject() * or exists() is called for every requested object. */ public void execute() throws ManifoldCFException { // Does nothing; we only want to fetch objects in this cacher. } } /** This class represents a record in a robots.txt file. It contains one or * more user-agents, and one or more disallows. */ protected static class Record { protected ArrayList userAgents = new ArrayList(); protected ArrayList disallows = new ArrayList(); protected ArrayList allows = new ArrayList(); /** Constructor. */ public Record() { } /** Add a user-agent. */ public void addAgent(String agentName) { userAgents.add(agentName); } /** Add a disallow. */ public void addDisallow(String disallowPath) { disallows.add(disallowPath); } /** Add an allow. */ public void addAllow(String allowPath) { allows.add(allowPath); } /** See if user-agent matches. */ public boolean isAgentMatch(String agentNameUpper, boolean exactMatch) { int i = 0; while (i < userAgents.size()) { String agent = ((String)userAgents.get(i++)).toUpperCase(); if (exactMatch && agent.trim().equals(agentNameUpper)) return true; if (!exactMatch && agentNameUpper.indexOf(agent) != -1) return true; } return false; } /** See if path is disallowed. Only called if user-agent has already * matched. (This checks if there's an explicit match with one of the * Disallows clauses.) */ public boolean isDisallowed(String path) { int i = 0; while (i < disallows.size()) { String disallow = (String)disallows.get(i++); if (doesPathMatch(path,disallow)) return true; } return false; } /** See if path is allowed. Only called if user-agent has already * matched. (This checks if there's an explicit match with one of the * Allows clauses). */ public boolean isAllowed(String path) { int i = 0; while (i < allows.size()) { String allow = (String)allows.get(i++); if (doesPathMatch(path,allow)) return true; } return false; } } }
/** * Copyright (c) 2004-2005, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Los Angeles 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 jintgen.gen; import cck.text.Printer; import cck.text.StringUtil; import cck.util.Option; import jintgen.gen.disassembler.DGUtil; import jintgen.isdl.*; import jintgen.types.TypeRef; import jintgen.jigir.JIGIRTypeEnv; import java.io.IOException; import java.util.*; /** * The <code>ClassGenerator</code> class generates a set of classes that represent instructions in an * architecture. It will generate an outer class <code>Instr</code> that contains as inner classes, the * individual instructions contained in the architecture description. * * @author Ben L. Titzer */ public class InstrIRGenerator extends Generator { LinkedList<String> hashMapImport; protected final Option.Str CLASS_FILE = options.newOption("class-template", "Instr.java", "This option specifies the name of the file that contains a template for generating the " + "instruction classes."); public void generate() throws Exception { properties.setProperty("instr", className("Instr")); properties.setProperty("addr", className("AddrMode")); properties.setProperty("addrvisitor", className("AddrModeVisitor")); properties.setProperty("operand", className("Operand")); properties.setProperty("opvisitor", className("OperandVisitor")); properties.setProperty("visitor", className("InstrVisitor")); properties.setProperty("builder", className("InstrBuilder")); properties.setProperty("symbol", className("Symbol")); hashMapImport = new LinkedList<String>(); hashMapImport.add("java.util.HashMap"); generateOperandClasses(); generateVisitor(); generateInstrClasses(); generateEnumerations(); generateBuilder(); generateAddrModeClasses(); } //========================================================================================= // CODE TO EMIT VISITOR CLASS //========================================================================================= private void generateVisitor() throws IOException { setPrinter(newInterfacePrinter("visitor", null, null, tr("The <code>$visitor</code> interface allows user code that implements " + "the interface to easily dispatch on the type of an instruction without casting using " + "the visitor pattern."))); for (InstrDecl d : arch.instructions ) emitVisitMethod(d); p.endblock(); close(); } private void emitVisitMethod(InstrDecl d) { println("public void visit($instr.$1 i);", d.innerClassName); } //========================================================================================= // CODE TO EMIT INSTR CLASSES //========================================================================================= private void generateInstrClasses() throws IOException { LinkedList<String> imports = new LinkedList<String>(); imports.add("avrora.arch.AbstractArchitecture"); imports.add("avrora.arch.AbstractInstr"); LinkedList<String> impl = new LinkedList<String>(); impl.add("AbstractInstr"); setPrinter(newAbstractClassPrinter("instr", imports, null, impl, tr("The <code>$instr</code> class is a container (almost a namespace) for " + "all of the instructions in this architecture. Each inner class represents an instruction " + "in the architecture and also extends the outer class."))); generateJavaDoc("The <code>accept()</code> method accepts an instruction visitor and " + "calls the appropriate <code>visit()</code> method for this instruction.\n" + "@param v the instruction visitor to accept"); println("public abstract void accept($visitor v);"); generateJavaDoc("The <code>accept()</code> method accepts an addressing mode visitor " + "and calls the appropriate <code>visit_*()</code> method for this instruction's addressing " + "mode.\n" + "@param v the addressing mode visitor to accept"); startblock("public void accept($addrvisitor v)"); println("// the default implementation of accept() is empty"); endblock(); generateJavaDoc("The <code>toString()</code> method converts this instruction to a string " + "representation. For instructions with operands, this method will render the operands " + "in the appropriate syntax as declared in the architecture description.\n" + "@return a string representation of this instruction"); startblock("public String toString()"); println("// the default implementation of toString() simply returns the name"); println("return name;"); endblock(); generateJavaDoc("The <code>name</code> field stores a reference to the name of the instruction as a " + "string."); println("public final String name;"); generateJavaDoc("The <code>size</code> field stores the size of the instruction in bytes."); println("public final int size;"); generateJavaDoc("The <code>getSize()</code> method returns the size of this instruction in bytes."); startblock("public int getSize()"); println("return size;"); endblock(); println(""); generateJavaDoc("The <code>getName()</code> method returns the name of this instruction."); startblock("public String getName()"); println("return name;"); endblock(); println(""); generateJavaDoc("The <code>getArchitecture()</code> method returns the architecture of this instruction."); startblock("public AbstractArchitecture getArchitecture()"); println("return null;"); endblock(); println(""); generateJavaDoc(tr("The default constructor for the <code>$instr</code> class accepts a " + "string name and a size for each instruction.\n" + "@param name the string name of the instruction\n" + "@param size the size of the instruction in bytes")); startblock("protected $instr(String name, int size)"); println("this.name = name;"); println("this.size = size;"); endblock(); println(""); generateSuperClasses(); for (InstrDecl d : arch.instructions) emitClass(d); endblock(); close(); } private void generateSuperClasses() { HashSet<AddrModeDecl> usedAddrs = new HashSet<AddrModeDecl>(); HashSet<AddrModeSetDecl> usedSets = new HashSet<AddrModeSetDecl>(); // only generate the classes that are used directly by instructions for(InstrDecl d: arch.instructions) { if ( d.addrMode.ref != null ) { AddrModeSetDecl as = arch.getAddressingModeSet(d.addrMode.ref.image); if ( as != null ) usedSets.add(as); else { AddrModeDecl am = arch.getAddressingMode(d.addrMode.ref.image); if ( am != null ) usedAddrs.add(am); } } } for (AddrModeDecl d : usedAddrs) emitAddrInstrClass(d); for (AddrModeSetDecl d : usedSets) emitAddrSetClass(d); } private void emitAddrInstrClass(AddrModeDecl d) { startblock("public abstract static class $1_Instr extends $instr", d.name); for (AddrModeDecl.Operand o : d.operands) println("public final $operand.$1 $2;", o.typeRef, o.name); startblock("protected $1_Instr(String name, int size, $addr.$1 am)", d.name); println("super(name, size);"); initFields("this.$1 = am.$1;", d.operands); endblock(); // emit the accept method for the addressing mode visitor startblock("public void accept($addrvisitor v)"); print("v.visit_$1", d.name); printParams(nameList("this", d.operands)); println(";"); endblock(); startblock("public String toString()"); print("return name"); emitRenderer(d.getProperty("syntax"), d.operands); println(";"); endblock(); endblock(); println(""); } private void emitAddrSetClass(AddrModeSetDecl d) { startblock("public abstract static class $1_Instr extends $instr", d.name); println("public final $addr.$1 am;", d.name); for (AddrModeDecl.Operand o : d.unionOperands) println("public final $operand $1;", o.name); startblock("protected $1_Instr(String name, int size, $addr.$1 am)", d.name); println("super(name, size);"); println("this.am = am;", d.name); initFields("this.$1 = am.get_$1();", d.unionOperands); endblock(); // emit the accept method for the addressing mode visitor startblock("public void accept($addrvisitor v)"); println("am.accept(this, v);"); endblock(); // emit the toString() method startblock("public String toString()"); println("return name+am.toString();"); endblock(); endblock(); println(""); } private void emitClass(InstrDecl d) { String cName = d.getInnerClassName(); cName = StringUtil.trimquotes(cName.toUpperCase()); boolean hasSuper = d.addrMode.localDecl == null; String sup = hasSuper ? addrModeName(d) + "_Instr" : tr("$instr"); startblock("public static class $1 extends $2", cName, sup); emitFields(d, hasSuper); emitConstructor(cName, d, hasSuper); println("public void accept($visitor v) { v.visit(this); }"); if ( !hasSuper ) { if ( DGUtil.addrModeClassExists(d) ) { startblock("public void accept($addrvisitor v)"); print("v.visit_$1", addrModeName(d)); printParams(nameList("this", d.getOperands())); println(";"); endblock(); } startblock("public String toString()"); print("return name"); emitRenderer(d.getProperty("syntax"), d.getOperands()); println(";"); endblock(); } endblock(); println(""); } private void emitFields(InstrDecl d, boolean hasSuper) { // emit the declaration of the fields if ( !hasSuper ) { for (AddrModeDecl.Operand o : d.getOperands()) println("public final $operand.$1 $2;", o.typeRef, o.name); } } private void emitConstructor(String cName, InstrDecl d, boolean hasSuper) { // emit the declaration of the constructor if ( DGUtil.addrModeClassExists(d) ) { startblock("$1(int size, $addr.$2 am)", cName, addrModeName(d)); } else { startblock("$1(int size)", cName, addrModeName(d)); } if ( hasSuper ) { println("super($1, size, am);", d.name); } else { println("super($1, size);", d.name); initFields("this.$1 = am.$1;", d.getOperands()); } endblock(); } private void initFields(String format, List<AddrModeDecl.Operand> list) { for (AddrModeDecl.Operand o : list) { String n = o.name.image; println(format, n); } } private String addrModeName(InstrDecl d) { if ( d.addrMode.localDecl != null ) return javaName(d.name.image); else return d.addrMode.ref.image; } //========================================================================================= // CODE TO EMIT SYMBOL SETS //========================================================================================= private void generateEnumerations() throws IOException { setPrinter(newClassPrinter("symbol", hashMapImport, null, null, tr("The <code>$symbol</code> class represents a symbol (or an enumeration as " + "declared in the instruction set description) relevant to the instruction set architecture. " + "For example register names, status bit names, etc are given here. This class provides a " + "type-safe enumeration for such symbolic names."))); generateEnumHeader(); for ( EnumDecl d : arch.enums ) { generateEnumClass(d); } endblock(); close(); } private void generateEnumHeader() { println("public final String symbol;"); println("public final int value;"); println(""); println("$symbol(String sym, int v) { symbol = sym; value = v; }"); println("public int getValue() { return value; }"); println("public int getEncodingValue() { return value; }"); println(""); } private void generateEnumClass(EnumDecl d) { SymbolMapping m = d.map; String n = m.name.image; properties.setProperty("enum", n); if ( d instanceof EnumDecl.Subset ) { // this enumeration is a subset of another enumeration, but with possibly different // encoding EnumDecl.Subset sd = (EnumDecl.Subset)d; startblock("public static class $enum extends $1", javaType(sd.parentRef)); println("public final int encoding;"); println("public int getEncodingValue() { return encoding; }"); println("private static HashMap set = new HashMap();"); startblock("private static $enum new$enum(String n, int v, int ev)"); println("$enum obj = new $enum(n, v, ev);"); println("set.put(n, obj);"); println("return obj;"); endblock(); println("$enum(String sym, int v, int ev) { super(sym, v); encoding = ev; }"); for ( SymbolMapping.Entry e : m.getEntries() ) { String en = e.name; String EN = en.toUpperCase(); SymbolMapping.Entry se = sd.getParent().map.get(e.name); println("public static final $enum "+EN+" = new"+n+"(\""+en+"\", "+se.value+", "+e.value+");"); } } else { // this enumeration is NOT a subset of another enumeration startblock("public static class $1 extends $symbol", n); println("private static HashMap set = new HashMap();"); startblock("private static $enum new$enum(String n, int v)"); println("$enum obj = new $enum(n, v);"); println("set.put(n, obj);"); println("return obj;"); endblock(); println("$enum(String sym, int v) { super(sym, v); }"); for ( SymbolMapping.Entry e : m.getEntries() ) { String en = e.name; String EN = en.toUpperCase(); println("public static final $enum "+EN+" = new"+n+"(\""+en+"\", "+e.value+");"); } } endblock(); println(""); genGetMethod(); println(""); } private void genGetMethod() { startblock("public static $enum get_$enum(String name)"); println("return ($enum)$enum.set.get(name);"); endblock(); } //========================================================================================= // CODE TO EMIT OPERAND TYPES //========================================================================================= private void generateOperandClasses() throws IOException { setPrinter(newAbstractClassPrinter("operand", hashMapImport, null, null, tr("The <code>$operand</code> interface represents operands that are allowed to " + "instructions in this architecture. Inner classes of this interface enumerate the possible " + "operand types to instructions and their constructors allow for dynamic checking of " + "correctness constraints as expressed in the instruction set description."))); int cntr = 1; for ( OperandTypeDecl d : arch.operandTypes ) { println("public static final byte $1_val = $2;", d.name, cntr++); } generateJavaDoc("The <code>op_type</code> field stores a code that determines the type of " + "the operand. This code can be used to dispatch on the type of the operand by switching " + "on the code."); println("public final byte op_type;"); generateJavaDoc("The <code>accept()</code> method implements the visitor pattern for operand " + "types, allowing a user to double-dispatch on the type of an operand."); p.println(tr("public abstract void accept($opvisitor v);")); generateJavaDoc("The default constructor for the <code>$operand</code> class simply stores the " + "type of the operand in a final field."); startblock("protected $operand(byte t)"); println("op_type = t;"); endblock(); generateJavaDoc(tr("The <code>$operand.Int</code> class is the super class of operands that can " + "take on integer values. It implements rendering the operand as an integer literal.")); startblock("abstract static class Int extends $operand"); println("public final int value;"); startblock("Int(byte t, int val)"); println("super(t);"); println("this.value = val;"); endblock(); startblock("public String toString()"); println("return Integer.toString(value);"); endblock(); endblock(); println(""); generateJavaDoc(tr("The <code>$operand.Sym</code> class is the super class of operands that can " + "take on symbolic (enumerated) values. It implements rendering the operand as " + "the name of the corresponding enumeration type.")); startblock("abstract static class Sym extends $operand"); println("public final $symbol value;"); startblock("Sym(byte t, $symbol sym)"); println("super(t);"); println("if ( sym == null ) throw new Error();"); println("this.value = sym;"); endblock(); startblock("public String toString()"); println("return value.symbol;"); endblock(); endblock(); println(""); generateJavaDoc(tr("The <code>$operand.Addr</code> class is the super class of operands that represent " + "an address. It implements rendering the operand as a hexadecimal number.")); startblock("abstract static class Addr extends $operand"); println("public final int value;"); startblock("Addr(byte t, int addr)"); println("super(t);"); println("this.value = addr;"); endblock(); startblock("public String toString()"); println("String hs = Integer.toHexString(value);"); println("StringBuffer buf = new StringBuffer(\"0x\");"); println("for ( int cntr = hs.length(); cntr < 4; cntr++ ) buf.append('0');"); println("buf.append(hs);"); println("return buf.toString();"); endblock(); endblock(); println(""); generateJavaDoc(tr("The <code>$operand.Rel</code> class is the super class of operands that represent " + "an address that is computed relative to the program counter. It implements rendering " + "the operand as the PC plus an offset.")); startblock("abstract static class Rel extends $operand"); println("public final int value;"); println("public final int relative;"); startblock("Rel(byte t, int addr, int rel)"); println("super(t);"); println("this.value = addr;"); println("this.relative = rel;"); endblock(); startblock("public String toString()"); println("if ( relative >= 0 ) return \".+\"+relative;"); println("else return \".\"+relative;"); endblock(); endblock(); println(""); for ( OperandTypeDecl d : arch.operandTypes ) generateOperandType(d); endblock(); close(); // generate visitor class Printer vprinter = newInterfacePrinter("opvisitor", hashMapImport, null, tr("The <code>$opvisitor</code> interface allows clients to use the Visitor pattern to " + "resolve the types of operands to instructions.")); // generate the visit methods explicitly declared operand types for ( OperandTypeDecl d : arch.operandTypes ) vprinter.println(tr("public void visit($operand.$1 o);", d.name)); vprinter.endblock(); vprinter.close(); } private void generateOperandType(OperandTypeDecl d) { String otname = d.name.image; // generate visit method inside visitor if ( d.isValue() ) { OperandTypeDecl.Value vd = (OperandTypeDecl.Value)d; startblock("public static class $1 extends $2", otname, operandSuperClass(vd)); generateSimpleType(vd); } else if ( d.isCompound() ) { startblock("public static class $1 extends $operand", otname); generateCompoundType((OperandTypeDecl.Compound)d); } // generate accept method in operand class startblock("public void accept($opvisitor v)"); println("v.visit(this);"); endblock(); endblock(); println(""); } private String operandSuperClass(OperandTypeDecl.Value d) { EnumDecl ed = arch.getEnum(d.typeRef.getTypeConName()); if ( ed != null ) return "Sym"; else { if ( d.isRelative() ) return "Rel"; if ( d.isAddress() ) return "Addr"; return "Int"; } } private void generateSimpleType(OperandTypeDecl.Value d) { EnumDecl ed = arch.getEnum(d.typeRef.getTypeConName()); properties.setProperty("oname", d.name.image); properties.setProperty("kind", d.typeRef.getTypeConName()); if ( ed != null ) { startblock("$oname(String s)"); println("super($oname_val, $symbol.get_$kind(s));"); endblock(); startblock("$oname($symbol.$kind sym)"); println("super($oname_val, sym);"); endblock(); } else { println("public static final int low = "+d.low+ ';'); println("public static final int high = "+d.high+ ';'); if ( d.isRelative() ) { JIGIRTypeEnv.TYPE_addr a = ((JIGIRTypeEnv.TYPE_addr)d.typeRef.getType()); startblock("$oname(int pc, int rel)"); int align = a.getAlign(); if ( align > 1 ) println("super($oname_val, pc + $1 + $1 * rel, $builder.checkValue(rel, low, high));", align); else println("super($oname_val, pc + 1 + rel, $builder.checkValue(rel, low, high));"); } else if ( d.isAddress() ) { JIGIRTypeEnv.TYPE_addr a = ((JIGIRTypeEnv.TYPE_addr)d.typeRef.getType()); startblock("$oname(int addr)"); int align = a.getAlign(); if ( align > 1 ) println("super($oname_val, $1 * $builder.checkValue(addr, low, high));", align); else println("super($oname_val, $builder.checkValue(addr, low, high));"); } else { startblock("$oname(int val)"); println("super($oname_val, $builder.checkValue(val, low, high));"); } endblock(); } } private void generateCompoundType(OperandTypeDecl.Compound d) { // generate fields of compound operand emitOperandFields(d.subOperands); // emit the constructor print("public $1", d.name.image); printParams(nameTypeList(d.subOperands)); startblock(" "); properties.setProperty("oname", d.name.image); println("super($oname_val);"); initFields("this.$1 = $1;", d.subOperands); endblock(); } //========================================================================================= // CODE TO EMIT OTHER STUFF //========================================================================================= private void generateBuilder() throws IOException { setPrinter(newAbstractClassPrinter("builder", hashMapImport, null, null, null)); println("public abstract $instr build(int size, $addr am);"); println("static final HashMap builders = new HashMap();"); startblock("static $builder add(String name, $builder b)"); println("builders.put(name, b);"); println("return b;"); endblock(); for ( InstrDecl d : arch.instructions ) { startblock("public static class $1_builder extends $builder", d.innerClassName); startblock("public $instr build(int size, $addr am)"); if ( DGUtil.addrModeClassExists(d)) println("return new $instr.$1(size, ($addr.$2)am);", d.innerClassName, addrModeName(d)); else println("return new $instr.$1(size);", d.innerClassName); endblock(); endblock(); } for ( InstrDecl d : arch.instructions ) { println("public static final $builder $1 = add($2, new $1_builder());", d.innerClassName, d.name); } startblock("public static int checkValue(int val, int low, int high)"); startblock("if ( val < low || val > high )"); println("throw new Error();"); endblock(); println("return val;"); endblock(); endblock(); close(); } void generateAddrModeClasses() throws IOException { setPrinter(newInterfacePrinter("addr", hashMapImport, null, tr("The <code>$addr</code> class represents an addressing mode for this architecture. An " + "addressing mode fixes the number and type of operands, the syntax, and the encoding format " + "of the instruction."))); println("public void accept($instr i, $addrvisitor v);"); for ( AddrModeSetDecl as : arch.addrSets ) { startblock("public interface $1 extends $addr", as.name); for ( AddrModeDecl.Operand o : as.unionOperands ) println("public $operand get_$1();", o.name); endblock(); } List<AddrModeDecl> list = new LinkedList<AddrModeDecl>(); for ( AddrModeDecl am : arch.addrModes ) list.add(am); for ( InstrDecl id : arch.instructions ) { // for each addressing mode declared locally if ( id.addrMode.localDecl != null && DGUtil.addrModeClassExists(id) ) list.add(id.addrMode.localDecl); } for ( AddrModeDecl am : list ) emitAddrMode(am); endblock(); close(); emitAddrModeVisitor(list); } private void emitAddrModeVisitor(List<AddrModeDecl> list) throws IOException { setPrinter(newInterfacePrinter("addrvisitor", hashMapImport, null, tr("The <code>$addrvisitor</code> interface implements the visitor pattern for addressing modes."))); for ( AddrModeDecl am : list ) { print("public void visit_$1", javaName(am.name.image)); printParams(nameTypeList("$instr", "i", am.operands)); println(";"); } endblock(); close(); } private void emitAddrMode(AddrModeDecl am) { String amName = javaName(am.name.image); beginList("public static class $1 implements ", amName); print("$addr"); for ( AddrModeSetDecl as : am.sets ) print(as.name.image); endList(" "); // generate fields startblock(); emitOperandFields(am.operands); // generate constructor print("public $1", amName); printParams(nameTypeList(am.operands)); // generate field writes startblock(" "); initFields("this.$1 = $1;", am.operands); endblock(); // generate accept method startblock("public void accept($instr i, $addrvisitor v)"); print("v.visit_$1", amName); printParams(nameList("i", am.operands)); println(";"); endblock(); startblock("public String toString()"); print("return \"\""); emitRenderer(am.getProperty("syntax"), am.operands); println(";"); endblock(); for ( AddrModeDecl.Operand o : am.operands ) { OperandTypeDecl d = o.getOperandType(); println("public $operand get_$2() { return $2; }", d.name, o.name); } endblock(); } private void emitOperandFields(List<AddrModeDecl.Operand> list) { List<String> ntl = nameTypeList(list); for ( String str : ntl ) println("public final "+str+ ';'); } private void emitRenderer(Property syntax, List<AddrModeDecl.Operand> list) { if ( syntax != null && syntax.type.isBasedOn("String")) { String format = StringUtil.trimquotes(syntax.value.image); int max = format.length(); StringBuffer buf = new StringBuffer(); buf.append(' '); for ( int pos = 0; pos < max; pos++ ) { char ch = format.charAt(pos); StringBuffer var = new StringBuffer(); if ( ch == '%' ) { for ( pos++; pos < max; pos++) { char vch = format.charAt(pos); if ( !Character.isLetterOrDigit(vch) && vch != '.' ) { pos--; break; } var.append(vch); } print("+"); print(StringUtil.quote(buf)); print("+"); print(var.toString()); buf = new StringBuffer(); } else { buf.append(ch); } } if ( buf.length() > 0 ) { print("+"); print(StringUtil.quote(buf)); } } else { String sep = "' '"; for ( AddrModeDecl.Operand o : list ) { print(" + $1 + $2", sep, o.name); sep = "\", \""; } } } protected String javaType(TypeRef tr) { return renderType(tr); } }
package eu.geoknow.generator.graphs; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import javax.ws.rs.NotFoundException; import org.apache.log4j.Logger; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hp.hpl.jena.sparql.vocabulary.FOAF; import com.hp.hpl.jena.vocabulary.DCTerms; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.ontos.ldiw.vocabulary.ACL; import com.ontos.ldiw.vocabulary.LDIWO; import com.ontos.ldiw.vocabulary.SD; import com.ontos.ldiw.vocabulary.VOID; import eu.geoknow.generator.common.MediaType; import eu.geoknow.generator.common.Queries; import eu.geoknow.generator.configuration.FrameworkConfiguration; import eu.geoknow.generator.exceptions.InformationMissingException; import eu.geoknow.generator.exceptions.ResourceNotFoundException; import eu.geoknow.generator.exceptions.SPARQLEndpointException; import eu.geoknow.generator.graphs.beans.AccessControl; import eu.geoknow.generator.graphs.beans.Contribution; import eu.geoknow.generator.graphs.beans.Graph; import eu.geoknow.generator.graphs.beans.NamedGraph; import eu.geoknow.generator.rdf.RdfStoreManagerImpl; import eu.geoknow.generator.users.FrameworkUserManager; import eu.geoknow.generator.users.UserManager; import eu.geoknow.generator.users.UserManager.GraphPermissions; /** * Manager for creating, retrieving and updating graphs. It is mainly used by @GraphsService, but * can also be used by all classes. * * @author Jonas * */ public class GraphsManager { private static final Logger log = Logger.getLogger(GraphsManager.class); private static GraphsManager instance; private static FrameworkConfiguration frameworkConfig; private static UserManager storeAdmin; private static RdfStoreManagerImpl systemAdmin; private static FrameworkUserManager fuManager; private static String graphsGraph; public static synchronized GraphsManager getInstance() { if (instance == null) instance = new GraphsManager(); return instance; } public GraphsManager() { try { frameworkConfig = FrameworkConfiguration.getInstance(); // systemAdmin for graph creation (SPARQL-Level); storeAdmin for setting permissions (Store // System-Level) systemAdmin = frameworkConfig.getSystemRdfStoreManager(); storeAdmin = frameworkConfig.getRdfStoreUserManager(); // FrameworkUserManager has the power to manage User fuManager = frameworkConfig.getFrameworkUserManager(); graphsGraph = FrameworkConfiguration.getInstance().getSettingsGraph(); } catch (IOException e) { log.error(e); e.printStackTrace(); } catch (InformationMissingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * will only update the metadata * * @param newNamedGraph * @return * @throws SPARQLEndpointException */ public NamedGraph addContribution(Contribution contribution) throws SPARQLEndpointException { int triples = Queries.countGraphTriples(contribution.getNamedGraph(), systemAdmin); log.debug(contribution.getDate()); // "2005-07-14T03:18:56+0100"^^xsd:dateTime List<String> sources = contribution.getSource(); // Check if the source is a URI String sourcesTriples = ""; for (String source : sources) { try { new URL(source); source = "<" + source + ">"; } catch (MalformedURLException e) { source = "\"" + source + "\""; } sourcesTriples += "?graph <" + DCTerms.source.getURI() + "> " + source + " . "; } String query = " WITH <" + graphsGraph + "> " + "DELETE { ?graph <" + DCTerms.modified.getURI() + "> ?m ." + "?graph <" + VOID.triples.getURI() + "> ?t . " + "} INSERT { ?graph <" + DCTerms.modified.getURI() + "> \"" + contribution.getDate() + "\" ." + "?graph <" + VOID.triples.getURI() + "> " + triples + " . " + "?graph <" + DCTerms.contributor.getURI() + "> <" + contribution.getContributor() + "> . " + sourcesTriples + " } WHERE { <" + contribution.getNamedGraph() + "> <" + SD.graph.getURI() + "> ?graph" + " . OPTIONAL{ ?graph <" + DCTerms.modified.getURI() + "> ?m .?graph <" + VOID.triples.getURI() + "> ?t .}}"; log.debug(query); try { String result = systemAdmin.execute(query, MediaType.SPARQL_JSON_RESPONSE_FORMAT); log.debug(result); } catch (Exception e) { e.printStackTrace(); throw new SPARQLEndpointException(e.getMessage()); } return getNamedGraphByUri(contribution.getNamedGraph()); } public NamedGraph getNamedGraphByUri(String uri) { String query = "SELECT distinct ?label ?description ?owner ?publicAccess ?created ?modified ?contributor ?source ?triples where {Graph <" + graphsGraph + "> {" + "?graph <" + SD.name.getURI() + "> <" + uri + "> ." + "\n" // + "?graph <" + DCTerms.identifier.getURI() + "> \"" + id + "\"^^<"+ // XSD.xstring.getURI() + "> ." + "\n" + "?graph <" + ACL.owner.getURI() + "> ?owner ." + "\n" + "?graph <" + SD.graph.getURI() + "> ?metadata ." + "\n" + "OPTIONAL {?graph <" + LDIWO.access.getURI() + "> ?access ." + "\n" // public access information + "?access <" + ACL.agentClass.getURI() + "> <" + FOAF.Agent.getURI() + "> . " + "\n" + "?access <" + ACL.mode.getURI() + "> ?publicAccess .} " + "\n" // metadatagraph + "?metadata <" + RDF.type.getURI() + "> <" + SD.Graph.getURI() + ">." + "\n" + "?metadata <" + RDFS.label.getURI() + "> ?label ." + "\n" + "?metadata <" + DCTerms.description.getURI() + "> ?description ." + "\n" + "?metadata <" + DCTerms.created.getURI() + "> ?created ." + "\n" + "OPTIONAL { ?metadata <" + VOID.triples.getURI() + "> ?triples ." + "\n" + "?metadata <" + DCTerms.contributor.getURI() + "> ?contributor ." + "\n" + "?metadata <" + DCTerms.source.getURI() + "> ?source ." + "\n" + "?metadata <" + DCTerms.modified.getURI() + "> ?modified ." + "\n" + "} }}"; // String delegatesQuery = // "SELECT distinct ?delegate where {GRAPH <" + graphsGraph + "> {" + "\n" + "<" // + frameworkConfig.getDefaultDataset() + "> <" + SD.namedGraph.getURI() + "> ?graph ." // + "\n" + "?graph <" + DCTerms.identifier.getURI() + "> \"" + id + "\"^^<" // + XSD.xstring.getURI() + "> ." + "\n" + "?graph <" + ACL.delegates.getURI() // + "> ?delegate ." + "\n" + "}}"; // // String accessQuery = // "SELECT distinct ?mode ?user where {GRAPH <" + graphsGraph + "> {" + "\n" + "<" // + frameworkConfig.getDefaultDataset() + "> <" + SD.namedGraph.getURI() + "> ?graph ." // + "\n" + "?graph <" + DCTerms.identifier.getURI() + "> \"" + id + "\"^^<" // + XSD.xstring.getURI() + "> ." + "\n" + "?graph ldiw:access ?access ." + "\n" // + "?access <" + ACL.mode.getURI() + "> ?mode . " + "\n" + "?access <" // + ACL.agent.getURI() + "> ?user . " + "\n" + "}}"; log.debug(query); String result; NamedGraph graph = new NamedGraph(); Graph graphMeta = new Graph(); AccessControl graphAccess = new AccessControl(); // fetch graph data without accessinformation try { result = systemAdmin.execute(query, "application/sparql-results+json"); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(result); Iterator<JsonNode> bindingsIter = rootNode.path("results").path("bindings").elements(); if (!bindingsIter.hasNext()) throw new ResourceNotFoundException("Graph with uri " + uri + " not found"); while (bindingsIter.hasNext()) { JsonNode bindNode = bindingsIter.next(); // graph.setId(id); graph.setUri(bindNode.path("uri").path("value").textValue()); graph.setOwner(bindNode.path("owner").path("value").textValue()); graphMeta.setLabel(bindNode.path("label").path("value").textValue()); graphMeta.setDescription(bindNode.path("description").path("value").textValue()); graphMeta.setCreated(bindNode.path("created").path("value").textValue()); graphMeta.setModified(bindNode.path("modified").path("value").textValue()); graphMeta.setTriples(bindNode.path("triples").path("value").asInt()); if (bindNode.path("contributor").path("value").textValue() != null && !bindNode.path("contributor").path("value").textValue().isEmpty()) { if (!graphMeta.getContributor().contains( bindNode.path("contributor").path("value").textValue())) graphMeta.getContributor().add(bindNode.path("contributor").path("value").textValue()); } if (bindNode.path("source").path("value").textValue() != null && !bindNode.path("source").path("value").textValue().isEmpty()) { if (!graphMeta.getSource().contains(bindNode.path("source").path("value").textValue())) graphMeta.getSource().add(bindNode.path("source").path("value").textValue()); } if (bindNode.path("publicAccess").path("value").textValue() != null && !bindNode.path("publicAccess").path("value").textValue().isEmpty()) { graphAccess.setPublicAccess(bindNode.path("publicAccess").path("value").textValue() .replace(ACL.NS + "#", "")); } else { graphAccess.setPublicAccess(GraphPermissions.NO); } } } catch (Exception e) { e.printStackTrace(); throw new NotFoundException(); } // fetch access information // try { // result = systemAdmin.execute(prefix + accessQuery, "application/sparql-results+json"); // ObjectMapper mapper = new ObjectMapper(); // JsonNode rootNode = mapper.readTree(result); // Iterator<JsonNode> bindingsIter = rootNode.path("results").path("bindings").elements(); // graphAccess.setReadPermissionUsers(new ArrayList<String>()); // graphAccess.setWritePermissionUsers(new ArrayList<String>()); // while (bindingsIter.hasNext()) { // JsonNode bindNode = bindingsIter.next(); // graphAccess.addPermissionUser( // bindNode.path("mode").path("value").textValue().replace(ACL.NS + "#", ""), bindNode // .path("user").path("value").textValue()); // // } // // } catch (Exception e) { // // e.printStackTrace(); // throw new NotFoundException(); // } graph.setGraph(graphMeta); graph.setAccessControl(graphAccess); return graph; } }
package ca.uhn.fhir.model.dstu3.composite; /* * #%L * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0) * %% * Copyright (C) 2014 - 2015 University Health Network * %% * 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. * #L% */ import java.util.List; import org.hl7.fhir.instance.model.api.IIdType; import ca.uhn.fhir.model.api.ICompositeDatatype; import ca.uhn.fhir.model.api.IElement; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.DatatypeDef; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.SimpleSetter; import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.StringDt; /** * HAPI/FHIR <b>ResourceReferenceDt</b> Datatype * (A reference from one resource to another) * * <p> * <b>Definition:</b> * A reference from one resource to another * </p> * * <p> * <b>Requirements:</b> * * </p> */ @DatatypeDef(name="ResourceReferenceDt") public class ResourceReferenceDt extends BaseResourceReferenceDt implements ICompositeDatatype { /** * Constructor */ public ResourceReferenceDt() { // nothing } /** * Constructor which creates a resource reference containing the actual resource in question. * <p> * <b> When using this in a server:</b> Generally if this is serialized, it will be serialized as a contained * resource, so this should not be used if the intent is not to actually supply the referenced resource. This is not * a hard-and-fast rule however, as the server can be configured to not serialized this resource, or to load an ID * and contain even if this constructor is not used. * </p> * * @param theResource * The resource instance */ @SimpleSetter() public ResourceReferenceDt(IResource theResource) { super(theResource); } /** * Constructor which accepts a reference directly (this can be an ID, a partial/relative URL or a complete/absolute * URL) * * @param theId * The reference itself */ public ResourceReferenceDt(String theId) { setReference(new IdDt(theId)); } /** * Constructor which accepts a reference directly (this can be an ID, a partial/relative URL or a complete/absolute * URL) * * @param theResourceId * The reference itself */ public ResourceReferenceDt(IdDt theResourceId) { setReference(theResourceId); } /** * Constructor which accepts a reference directly (this can be an ID, a partial/relative URL or a complete/absolute * URL) * * @param theResourceId * The reference itself */ public ResourceReferenceDt(IIdType theResourceId) { setReference(theResourceId); } @Child(name="reference", type=IdDt.class, order=0, min=0, max=1) @Description( shortDefinition="Relative, internal or absolute URL reference", formalDefinition="A reference to a location at which the other resource is found. The reference may a relative reference, in which case it is relative to the service base URL, or an absolute URL that resolves to the location where the resource is found. The reference may be version specific or not. If the reference is not to a FHIR RESTful server, then it should be assumed to be version specific. Internal fragment references (start with '#') refer to contained resources" ) private IdDt myReference; @Child(name="display", type=StringDt.class, order=1, min=0, max=1) @Description( shortDefinition="Text alternative for the resource", formalDefinition="Plain text narrative that identifies the resource in addition to the resource reference" ) private StringDt myDisplay; @Override public boolean isEmpty() { return super.isBaseEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty( myReference, myDisplay); } @Override public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) { return ca.uhn.fhir.util.ElementUtil.allPopulatedChildElements(theType, myReference, myDisplay); } /** * Gets the value(s) for <b>reference</b> (Relative, internal or absolute URL reference). * creating it if it does * not exist. Will not return <code>null</code>. * * <p> * <b>Definition:</b> * A reference to a location at which the other resource is found. The reference may a relative reference, in which case it is relative to the service base URL, or an absolute URL that resolves to the location where the resource is found. The reference may be version specific or not. If the reference is not to a FHIR RESTful server, then it should be assumed to be version specific. Internal fragment references (start with '#') refer to contained resources * </p> */ public IdDt getReference() { if (myReference == null) { myReference = new IdDt(); } return myReference; } @Override public IdDt getReferenceElement() { return getReference(); } /** * Sets the value(s) for <b>reference</b> (Relative, internal or absolute URL reference) * * <p> * <b>Definition:</b> * A reference to a location at which the other resource is found. The reference may a relative reference, in which case it is relative to the service base URL, or an absolute URL that resolves to the location where the resource is found. The reference may be version specific or not. If the reference is not to a FHIR RESTful server, then it should be assumed to be version specific. Internal fragment references (start with '#') refer to contained resources * </p> */ public ResourceReferenceDt setReference(IdDt theValue) { myReference = theValue; return this; } /** * Sets the value for <b>reference</b> (Relative, internal or absolute URL reference) * * <p> * <b>Definition:</b> * A reference to a location at which the other resource is found. The reference may a relative reference, in which case it is relative to the service base URL, or an absolute URL that resolves to the location where the resource is found. The reference may be version specific or not. If the reference is not to a FHIR RESTful server, then it should be assumed to be version specific. Internal fragment references (start with '#') refer to contained resources * </p> */ public ResourceReferenceDt setReference( String theId) { myReference = new IdDt(theId); return this; } /** * Gets the value(s) for <b>display</b> (Text alternative for the resource). * creating it if it does * not exist. Will not return <code>null</code>. * * <p> * <b>Definition:</b> * Plain text narrative that identifies the resource in addition to the resource reference * </p> */ public StringDt getDisplay() { if (myDisplay == null) { myDisplay = new StringDt(); } return myDisplay; } /** * Sets the value(s) for <b>display</b> (Text alternative for the resource) * * <p> * <b>Definition:</b> * Plain text narrative that identifies the resource in addition to the resource reference * </p> */ public ResourceReferenceDt setDisplay(StringDt theValue) { myDisplay = theValue; return this; } /** * Sets the value for <b>display</b> (Text alternative for the resource) * * <p> * <b>Definition:</b> * Plain text narrative that identifies the resource in addition to the resource reference * </p> */ public ResourceReferenceDt setDisplay( String theString) { myDisplay = new StringDt(theString); return this; } @Override public StringDt getDisplayElement() { return getDisplay(); } }
/* * The MIT License * * Copyright (c) 2009 The Broad Institute * * 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 picard.sam.markduplicates; import htsjdk.samtools.SAMReadGroupRecord; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.metrics.MetricsFile; import htsjdk.samtools.util.CloserUtil; import htsjdk.samtools.util.Histogram; import htsjdk.samtools.util.IOUtil; import htsjdk.samtools.util.Log; import htsjdk.samtools.util.PeekableIterator; import htsjdk.samtools.util.ProgressLogger; import htsjdk.samtools.util.SequenceUtil; import htsjdk.samtools.util.SortingCollection; import htsjdk.samtools.util.StringUtil; import picard.PicardException; import picard.cmdline.CommandLineProgramProperties; import picard.cmdline.Option; import picard.cmdline.StandardOptionDefinitions; import picard.cmdline.programgroups.Metrics; import picard.sam.DuplicationMetrics; import picard.sam.markduplicates.util.AbstractOpticalDuplicateFinderCommandLineProgram; import picard.sam.util.PhysicalLocationShort; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.*; import static java.lang.Math.pow; /** * <p>Attempts to estimate library complexity from sequence alone. Does so by sorting all reads * by the first N bases (5 by default) of each read and then comparing reads with the first * N bases identical to each other for duplicates. Reads are considered to be duplicates if * they match each other with no gaps and an overall mismatch rate less than or equal to * MAX_DIFF_RATE (0.03 by default).</p> * <p/> * <p>Reads of poor quality are filtered out so as to provide a more accurate estimate. The filtering * removes reads with any no-calls in the first N bases or with a mean base quality lower than * MIN_MEAN_QUALITY across either the first or second read.</p> * <p/> * <p>The algorithm attempts to detect optical duplicates separately from PCR duplicates and excludes * these in the calculation of library size. Also, since there is no alignment to screen out technical * reads one further filter is applied on the data. After examining all reads a Histogram is built of * [#reads in duplicate set -> #of duplicate sets]; all bins that contain exactly one duplicate set are * then removed from the Histogram as outliers before library size is estimated.</p> * * @author Tim Fennell */ @CommandLineProgramProperties( usage = EstimateLibraryComplexity.USAGE_SUMMARY + EstimateLibraryComplexity.USAGE_DETAILS, usageShort = EstimateLibraryComplexity.USAGE_SUMMARY, programGroup = Metrics.class ) public class EstimateLibraryComplexity extends AbstractOpticalDuplicateFinderCommandLineProgram { static final String USAGE_SUMMARY = "Estimates the numbers of unique molecules in a sequencing library. "; static final String USAGE_DETAILS = "<p>This tool outputs quality metrics for a sequencing library preparation." + "Library complexity refers to the number of unique DNA fragments present in a given library. Reductions in complexity " + "resulting from PCR amplification during library preparation will ultimately compromise downstream analyses " + "via an elevation in the number of duplicate reads. PCR-associated duplication artifacts can result from: inadequate amounts " + "of starting material (genomic DNA, cDNA, etc.), losses during cleanups, and size selection issues. " + "Duplicate reads can also arise from optical duplicates resulting from sequencing-machine optical sensor artifacts.</p> " + "<p>This tool attempts to estimate library complexity from sequence of read pairs alone. Reads are sorted by the first N bases " + "(5 by default) of the first read and then the first N bases of the second read of a pair. Read pairs are considered to " + "be duplicates if they match each other with no gaps and an overall mismatch rate less than or equal to MAX_DIFF_RATE " + "(0.03 by default). Reads of poor quality are filtered out to provide a more accurate estimate. The filtering removes reads" + " with any poor quality bases as defined by a read's MIN_MEAN_QUALITY (20 is the default value) across either the first or " + "second read. Unpaired reads are ignored in this computation.</p> " + "" + "<p>The algorithm attempts to detect optical duplicates separately from PCR duplicates and excludes these in the calculation " + "of library size. Also, since there is no alignment information used in this algorithm, an additional filter is applied to " + "the data as follows. After examining all reads, a histogram is built in which the number of reads in a duplicate set is " + "compared with the number of of duplicate sets. All bins that contain exactly one duplicate set are then removed from the " + "histogram as outliers prior to the library size estimation. </p>" + "<h4>Usage example:</h4>" + "<pre>" + "java -jar picard.jar EstimateLibraryComplexity \\<br />" + " I=input.bam \\<br />" + " O=est_lib_complex_metrics.txt" + "</pre>" + "Please see the documentation for the companion " + "<a href='https://broadinstitute.github.io/picard/command-line-overview.html#MarkDuplicates'>MarkDuplicates</a> tool." + "<hr />"; @Option(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "One or more files to combine and " + "estimate library complexity from. Reads can be mapped or unmapped.") public List<File> INPUT; @Option(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "Output file to writes per-library metrics to.") public File OUTPUT; @Option(doc = "The minimum number of bases at the starts of reads that must be identical for reads to " + "be grouped together for duplicate detection. In effect total_reads / 4^max_id_bases reads will " + "be compared at a time, so lower numbers will produce more accurate results but consume " + "exponentially more memory and CPU.") public int MIN_IDENTICAL_BASES = 5; @Option(doc = "The maximum rate of differences between two reads to call them identical.") public double MAX_DIFF_RATE = 0.03; @Option(doc = "The minimum mean quality of the bases in a read pair for the read to be analyzed. Reads with " + "lower average quality are filtered out and not considered in any calculations.") public int MIN_MEAN_QUALITY = 20; @Option(doc = "Do not process self-similar groups that are this many times over the mean expected group size. " + "I.e. if the input contains 10m read pairs and MIN_IDENTICAL_BASES is set to 5, then the mean expected " + "group size would be approximately 10 reads.") public int MAX_GROUP_RATIO = 500; @Option(doc = "Barcode SAM tag (ex. BC for 10X Genomics)", optional = true) public String BARCODE_TAG = null; @Option(doc = "Read one barcode SAM tag (ex. BX for 10X Genomics)", optional = true) public String READ_ONE_BARCODE_TAG = null; @Option(doc = "Read two barcode SAM tag (ex. BX for 10X Genomics)", optional = true) public String READ_TWO_BARCODE_TAG = null; @Option(doc = "The maximum number of bases to consider when comparing reads (0 means no maximum).", optional = true) public int MAX_READ_LENGTH = 0; @Option(doc = "Minimum number group count. On a per-library basis, we count the number of groups of duplicates " + "that have a particular size. Omit from consideration any count that is less than this value. For " + "example, if we see only one group of duplicates with size 500, we omit it from the metric calculations if " + "MIN_GROUP_COUNT is set to two. Setting this to two may help remove technical artifacts from the library " + "size calculation, for example, adapter dimers.", optional = true) public int MIN_GROUP_COUNT = 2; private final Log log = Log.getInstance(EstimateLibraryComplexity.class); @Override protected String[] customCommandLineValidation() { final List<String> errorMsgs = new ArrayList<String>(); if (0 < MAX_READ_LENGTH && MAX_READ_LENGTH < MIN_IDENTICAL_BASES) { errorMsgs.add("MAX_READ_LENGTH must be greater than MIN_IDENTICAL_BASES"); } if (MIN_IDENTICAL_BASES <= 0) { errorMsgs.add("MIN_IDENTICAL_BASES must be greater than 0"); } return errorMsgs.isEmpty() ? super.customCommandLineValidation() : errorMsgs.toArray(new String[errorMsgs.size()]); } /** * Little class to hold the sequence of a pair of reads and tile location information. */ static class PairedReadSequence extends PhysicalLocationShort { //just for rough estimate size of reads, does not affect the fundamental operation of the algorithm static final int NUMBER_BASES_IN_READ = 150; short readGroup = -1; boolean qualityOk = true; byte[] read1; byte[] read2; short libraryId; // Hashes corresponding to read1 and read2 int[] hashes1; int[] hashes2; // Possible candidates for this PairedReadSequence Set<PairedReadSequence> dupCandidates; public static int getSizeInBytes() { // rough guess at memory footprint, summary size of all fields return 16 + 4 + (2 * 4) + 1 + 2 * (24 + 8 + NUMBER_BASES_IN_READ) + 2 + (2 * (24 + 8)) + 8 + 4; } public short getReadGroup() { return this.readGroup; } public void setReadGroup(final short readGroup) { this.readGroup = readGroup; } public short getLibraryId() { return this.libraryId; } public void setLibraryId(final short libraryId) { this.libraryId = libraryId; } public static SortingCollection.Codec<PairedReadSequence> getCodec() { return new PairedReadCodec(); } void initHashes(int maxReadLength, int hashLength, int skippedBases) { dupCandidates = new HashSet<>(); hashes1 = getHashes(read1, maxReadLength, hashLength, skippedBases); hashes2 = getHashes(read2, maxReadLength, hashLength, skippedBases); } // Split read by (MAX_DIFF_RATE * read.length + 1) parts and hash each part private int[] getHashes(byte[] read, int maxReadLength, int hashLength, int skippedBases) { int maxLengthWithoutHead = maxReadLength - skippedBases; int hashNum = (Math.min(read.length - skippedBases, maxLengthWithoutHead)) / hashLength; int[] hashValues = new int[hashNum]; for (int i = 0; i < hashNum; ++i) { int st = skippedBases + i * hashLength; int end = st + hashLength; // use custom hash to avoid using System.arraycopy hashValues[i] = 1; for (int j = st; j < end; ++j) { hashValues[i] = 31 * hashValues[i] + read[j]; } } return hashValues; } } static class PairedReadSequenceWithBarcodes extends PairedReadSequence { int barcode; // primary barcode for this read (and pair) int readOneBarcode; // read one barcode, 0 if not present int readTwoBarcode; // read two barcode, 0 if not present or not paired public PairedReadSequenceWithBarcodes() { super(); } public PairedReadSequenceWithBarcodes(final PairedReadSequence val) { if (null == val) throw new PicardException("val was null"); this.readGroup = val.getReadGroup(); this.tile = val.getTile(); this.x = val.getX(); this.y = val.getY(); this.qualityOk = val.qualityOk; this.read1 = val.read1.clone(); this.read2 = val.read2.clone(); this.libraryId = val.getLibraryId(); } public static int getSizeInBytes() { return PairedReadSequence.getSizeInBytes() + (3 * 4); // rough guess at memory footprint } } /** * Codec class for writing and read PairedReadSequence objects. */ static class PairedReadCodec implements SortingCollection.Codec<PairedReadSequence> { protected DataOutputStream out; protected DataInputStream in; public void setOutputStream(final OutputStream out) { this.out = new DataOutputStream(out); } public void setInputStream(final InputStream in) { this.in = new DataInputStream(in); } public void encode(final PairedReadSequence val) { try { this.out.writeShort(val.readGroup); this.out.writeShort(val.tile); this.out.writeShort(val.x); this.out.writeShort(val.y); this.out.writeInt(val.read1.length); this.out.write(val.read1); this.out.writeInt(val.read2.length); this.out.write(val.read2); } catch (final IOException ioe) { throw new PicardException("Error write out read pair.", ioe); } } public PairedReadSequence decode() { try { final PairedReadSequence val = new PairedReadSequence(); try { val.readGroup = this.in.readShort(); } catch (final EOFException eof) { return null; } val.tile = this.in.readShort(); val.x = this.in.readShort(); val.y = this.in.readShort(); int length = this.in.readInt(); val.read1 = new byte[length]; if (this.in.read(val.read1) != length) { throw new PicardException("Could not read " + length + " bytes from temporary file."); } length = this.in.readInt(); val.read2 = new byte[length]; if (this.in.read(val.read2) != length) { throw new PicardException("Could not read " + length + " bytes from temporary file."); } return val; } catch (final IOException ioe) { throw new PicardException("Exception reading read pair.", ioe); } } @Override public SortingCollection.Codec<PairedReadSequence> clone() { return new PairedReadCodec(); } } /** * Codec class for writing and read PairedReadSequence objects. */ static class PairedReadWithBarcodesCodec extends PairedReadCodec { @Override public void encode(final PairedReadSequence val) { if (!(val instanceof PairedReadSequenceWithBarcodes)) { throw new PicardException("Val was not a PairedReadSequenceWithBarcodes"); } final PairedReadSequenceWithBarcodes data = (PairedReadSequenceWithBarcodes) val; super.encode(val); try { this.out.writeInt(data.barcode); this.out.writeInt(data.readOneBarcode); this.out.writeInt(data.readTwoBarcode); } catch (final IOException ioe) { throw new PicardException("Error write out read pair.", ioe); } } @Override public PairedReadSequence decode() { try { final PairedReadSequence parentVal = super.decode(); if (null == parentVal) return null; // EOF final PairedReadSequenceWithBarcodes val = new PairedReadSequenceWithBarcodes(parentVal); val.barcode = this.in.readInt(); val.readOneBarcode = this.in.readInt(); val.readTwoBarcode = this.in.readInt(); return val; } catch (final IOException ioe) { throw new PicardException("Exception reading read pair.", ioe); } } @Override public SortingCollection.Codec<PairedReadSequence> clone() { return new PairedReadWithBarcodesCodec(); } } /** * Comparator that orders read pairs on the first N bases of both reads. * There is no tie-breaking, so any sort is stable, not total. */ private class PairedReadComparator implements Comparator<PairedReadSequence> { final int BASES = EstimateLibraryComplexity.this.MIN_IDENTICAL_BASES; public int compare(final PairedReadSequence lhs, final PairedReadSequence rhs) { // First compare the first N bases of the first read for (int i = 0; i < BASES; ++i) { final int retval = lhs.read1[i] - rhs.read1[i]; if (retval != 0) return retval; } // Then compare the first N bases of the second read for (int i = 0; i < BASES; ++i) { final int retval = lhs.read2[i] - rhs.read2[i]; if (retval != 0) return retval; } return 0; } } public int getBarcodeValue(final SAMRecord record) { return getReadBarcodeValue(record, BARCODE_TAG); } public static int getReadBarcodeValue(final SAMRecord record, final String tag) { if (null == tag) return 0; final String attr = record.getStringAttribute(tag); if (null == attr) return 0; else return attr.hashCode(); } private int getReadOneBarcodeValue(final SAMRecord record) { return getReadBarcodeValue(record, READ_ONE_BARCODE_TAG); } private int getReadTwoBarcodeValue(final SAMRecord record) { return getReadBarcodeValue(record, READ_TWO_BARCODE_TAG); } /** Stock main method. */ public static void main(final String[] args) { new EstimateLibraryComplexity().instanceMainWithExit(args); } public EstimateLibraryComplexity() { final int sizeInBytes; if (null != BARCODE_TAG || null != READ_ONE_BARCODE_TAG || null != READ_TWO_BARCODE_TAG) { sizeInBytes = PairedReadSequenceWithBarcodes.getSizeInBytes(); } else { sizeInBytes = PairedReadSequence.getSizeInBytes(); } MAX_RECORDS_IN_RAM = (int) (Runtime.getRuntime().maxMemory() / sizeInBytes) / 2; } /** * Method that does most of the work. Reads through the input BAM file and extracts the * read sequences of each read pair and sorts them via a SortingCollection. Then traverses * the sorted reads and looks at small groups at a time to find duplicates. */ @Override protected int doWork() { for (final File f : INPUT) IOUtil.assertFileIsReadable(f); log.info("Will store " + MAX_RECORDS_IN_RAM + " read pairs in memory before sorting."); final List<SAMReadGroupRecord> readGroups = new ArrayList<SAMReadGroupRecord>(); final SortingCollection<PairedReadSequence> sorter; final boolean useBarcodes = (null != BARCODE_TAG || null != READ_ONE_BARCODE_TAG || null != READ_TWO_BARCODE_TAG); if (!useBarcodes) { sorter = SortingCollection.newInstance(PairedReadSequence.class, new PairedReadCodec(), new PairedReadComparator(), MAX_RECORDS_IN_RAM, TMP_DIR); } else { sorter = SortingCollection.newInstance(PairedReadSequence.class, new PairedReadWithBarcodesCodec(), new PairedReadComparator(), MAX_RECORDS_IN_RAM, TMP_DIR); } // Loop through the input files and pick out the read sequences etc. final ProgressLogger progress = new ProgressLogger(log, (int) 1e6, "Read"); for (final File f : INPUT) { final Map<String, PairedReadSequence> pendingByName = new HashMap<String, PairedReadSequence>(); final SamReader in = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(f); readGroups.addAll(in.getFileHeader().getReadGroups()); for (final SAMRecord rec : in) { if (!rec.getReadPairedFlag()) continue; if (!rec.getFirstOfPairFlag() && !rec.getSecondOfPairFlag()) { continue; } if (rec.isSecondaryOrSupplementary()) continue; PairedReadSequence prs = pendingByName.remove(rec.getReadName()); if (prs == null) { // Make a new paired read object and add RG and physical location information to it prs = useBarcodes ? new PairedReadSequenceWithBarcodes() : new PairedReadSequence(); if (opticalDuplicateFinder.addLocationInformation(rec.getReadName(), prs)) { final SAMReadGroupRecord rg = rec.getReadGroup(); if (rg != null) prs.setReadGroup((short) readGroups.indexOf(rg)); } pendingByName.put(rec.getReadName(), prs); } // Read passes quality check if both ends meet the mean quality criteria final boolean passesQualityCheck = passesQualityCheck(rec.getReadBases(), rec.getBaseQualities(), MIN_IDENTICAL_BASES, MIN_MEAN_QUALITY); prs.qualityOk = prs.qualityOk && passesQualityCheck; // Get the bases and restore them to their original orientation if necessary final byte[] bases = rec.getReadBases(); if (rec.getReadNegativeStrandFlag()) SequenceUtil.reverseComplement(bases); final PairedReadSequenceWithBarcodes prsWithBarcodes = (useBarcodes) ? (PairedReadSequenceWithBarcodes) prs : null; if (rec.getFirstOfPairFlag()) { prs.read1 = bases; if (useBarcodes) { prsWithBarcodes.barcode = getBarcodeValue(rec); prsWithBarcodes.readOneBarcode = getReadOneBarcodeValue(rec); } } else { prs.read2 = bases; if (useBarcodes) { prsWithBarcodes.readTwoBarcode = getReadTwoBarcodeValue(rec); } } if (prs.read1 != null && prs.read2 != null && prs.qualityOk) { sorter.add(prs); } progress.record(rec); } CloserUtil.close(in); } log.info(String.format("Finished reading - read %d records - moving on to scanning for duplicates.", progress.getCount())); // Now go through the sorted reads and attempt to find duplicates final PeekableIterator<PairedReadSequence> iterator = new PeekableIterator<PairedReadSequence>(sorter.iterator()); final Map<String, Histogram<Integer>> duplicationHistosByLibrary = new HashMap<String, Histogram<Integer>>(); final Map<String, Histogram<Integer>> opticalHistosByLibrary = new HashMap<String, Histogram<Integer>>(); int groupsProcessed = 0; long lastLogTime = System.currentTimeMillis(); final int meanGroupSize = (int) (Math.max(1, (progress.getCount() / 2) / (int) pow(4, MIN_IDENTICAL_BASES * 2))); ElcDuplicatesFinderResolver algorithmResolver = new ElcDuplicatesFinderResolver( MAX_DIFF_RATE, MAX_READ_LENGTH, MIN_IDENTICAL_BASES, useBarcodes, opticalDuplicateFinder ); while (iterator.hasNext()) { // Get the next group and split it apart by library final List<PairedReadSequence> group = getNextGroup(iterator); if (group.size() > meanGroupSize * MAX_GROUP_RATIO) { final PairedReadSequence prs = group.get(0); log.warn("Omitting group with over " + MAX_GROUP_RATIO + " times the expected mean number of read pairs. " + "Mean=" + meanGroupSize + ", Actual=" + group.size() + ". Prefixes: " + StringUtil.bytesToString(prs.read1, 0, MIN_IDENTICAL_BASES) + " / " + StringUtil.bytesToString(prs.read2, 0, MIN_IDENTICAL_BASES)); } else { final Map<String, List<PairedReadSequence>> sequencesByLibrary = splitByLibrary(group, readGroups); // Now process the reads by library for (final Map.Entry<String, List<PairedReadSequence>> entry : sequencesByLibrary.entrySet()) { final String library = entry.getKey(); final List<PairedReadSequence> seqs = entry.getValue(); Histogram<Integer> duplicationHisto = duplicationHistosByLibrary.get(library); Histogram<Integer> opticalHisto = opticalHistosByLibrary.get(library); if (duplicationHisto == null) { duplicationHisto = new Histogram<>("duplication_group_count", library); opticalHisto = new Histogram<>("duplication_group_count", "optical_duplicates"); duplicationHistosByLibrary.put(library, duplicationHisto); opticalHistosByLibrary.put(library, opticalHisto); } algorithmResolver.resolveAndSearch(seqs, duplicationHisto, opticalHisto); } ++groupsProcessed; if (lastLogTime < System.currentTimeMillis() - 60000) { log.info("Processed " + groupsProcessed + " groups."); lastLogTime = System.currentTimeMillis(); } } } iterator.close(); sorter.cleanup(); final MetricsFile<DuplicationMetrics, Integer> file = getMetricsFile(); for (final String library : duplicationHistosByLibrary.keySet()) { final Histogram<Integer> duplicationHisto = duplicationHistosByLibrary.get(library); final Histogram<Integer> opticalHisto = opticalHistosByLibrary.get(library); final DuplicationMetrics metrics = new DuplicationMetrics(); metrics.LIBRARY = library; // Filter out any bins that have fewer than MIN_GROUP_COUNT entries in them and calculate derived metrics for (final Integer bin : duplicationHisto.keySet()) { final double duplicateGroups = duplicationHisto.get(bin).getValue(); final double opticalDuplicates = opticalHisto.get(bin) == null ? 0 : opticalHisto.get(bin).getValue(); if (duplicateGroups >= MIN_GROUP_COUNT) { metrics.READ_PAIRS_EXAMINED += (bin * duplicateGroups); metrics.READ_PAIR_DUPLICATES += ((bin - 1) * duplicateGroups); metrics.READ_PAIR_OPTICAL_DUPLICATES += opticalDuplicates; } } metrics.calculateDerivedFields(); file.addMetric(metrics); file.addHistogram(duplicationHisto); } file.write(OUTPUT); return 0; } /** * Pulls out of the iterator the next group of reads that can be compared to each other to * identify duplicates. */ List<PairedReadSequence> getNextGroup(final PeekableIterator<PairedReadSequence> iterator) { final List<PairedReadSequence> group = new ArrayList<PairedReadSequence>(); final PairedReadSequence first = iterator.next(); group.add(first); outer: while (iterator.hasNext()) { final PairedReadSequence next = iterator.peek(); for (int i = 0; i < MIN_IDENTICAL_BASES; ++i) { if (first.read1[i] != next.read1[i] || first.read2[i] != next.read2[i]) break outer; } group.add(iterator.next()); } return group; } /** * Takes a list of PairedReadSequence objects and splits them into lists by library. */ Map<String, List<PairedReadSequence>> splitByLibrary(final List<PairedReadSequence> input, final List<SAMReadGroupRecord> rgs) { final Map<String, List<PairedReadSequence>> out = new HashMap<>(); for (final PairedReadSequence seq : input) { String library; if (seq.getReadGroup() != -1) { library = rgs.get(seq.getReadGroup()).getLibrary(); if (library == null) library = "Unknown"; } else { library = "Unknown"; } List<PairedReadSequence> librarySeqs = out.get(library); if (librarySeqs == null) { librarySeqs = new ArrayList<>(); out.put(library, librarySeqs); } librarySeqs.add(seq); } return out; } /** * Checks that the average quality over the entire read is >= min, and that the first N bases do * not contain any no-calls. */ boolean passesQualityCheck(final byte[] bases, final byte[] quals, final int seedLength, final int minQuality) { if (bases.length < seedLength) return false; for (int i = 0; i < seedLength; ++i) { if (SequenceUtil.isNoCall(bases[i])) return false; } final int maxReadLength = (MAX_READ_LENGTH <= 0) ? Integer.MAX_VALUE : MAX_READ_LENGTH; final int readLength = Math.min(bases.length, maxReadLength); int total = 0; for (int i = 0; i < readLength; i++) total += quals[i]; return total / readLength >= minQuality; } }
/* * Copyright 2015-2017 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 com.funtl.framework.paypal.api.payments; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import java.util.List; import com.funtl.framework.paypal.base.rest.APIContext; import com.funtl.framework.paypal.base.rest.HttpMethod; import com.funtl.framework.paypal.base.rest.PayPalRESTException; import com.funtl.framework.paypal.base.rest.PayPalResource; import com.funtl.framework.paypal.base.rest.RESTUtil; @Getter @Setter @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) public class Authorization extends PayPalResource { /** * ID of the authorization transaction. */ private String id; /** * Amount being authorized. */ private Amount amount; /** * Specifies the payment mode of the transaction. */ private String paymentMode; /** * State of the authorization. */ private String state; /** * Reason code, `AUTHORIZATION`, for a transaction state of `pending`. */ private String reasonCode; /** * [DEPRECATED] Reason code for the transaction state being Pending.Obsolete. use reason_code field instead. */ private String pendingReason; /** * The level of seller protection in force for the transaction. Only supported when the `payment_method` is set to `paypal`. Allowed values:<br> `ELIGIBLE`- Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received.<br> `PARTIALLY_ELIGIBLE`- Merchant is protected by PayPal's Seller Protection Policy for Item Not Received or Unauthorized Payments. Refer to `protection_eligibility_type` for specifics. <br> `INELIGIBLE`- Merchant is not protected under the Seller Protection Policy. */ private String protectionEligibility; /** * The kind of seller protection in force for the transaction. This property is returned only when the `protection_eligibility` property is set to `ELIGIBLE`or `PARTIALLY_ELIGIBLE`. Only supported when the `payment_method` is set to `paypal`. Allowed values:<br> `ITEM_NOT_RECEIVED_ELIGIBLE`- Sellers are protected against claims for items not received.<br> `UNAUTHORIZED_PAYMENT_ELIGIBLE`- Sellers are protected against claims for unauthorized payments.<br> One or both of the allowed values can be returned. */ private String protectionEligibilityType; /** * Fraud Management Filter (FMF) details applied for the payment that could result in accept, deny, or pending action. Returned in a payment response only if the merchant has enabled FMF in the profile settings and one of the fraud filters was triggered based on those settings. See [Fraud Management Filters Summary](https://developer.paypal.com/docs/classic/fmf/integration-guide/FMFSummary/) for more information. */ private FmfDetails fmfDetails; /** * ID of the Payment resource that this transaction is based on. */ private String parentPayment; /** * Authorization expiration time and date as defined in [RFC 3339 Section 5.6](http://tools.ietf.org/html/rfc3339#section-5.6). */ private String validUntil; /** * Time of authorization as defined in [RFC 3339 Section 5.6](http://tools.ietf.org/html/rfc3339#section-5.6). */ private String createTime; /** * Time that the resource was last updated. */ private String updateTime; /** * Identifier to the purchase or transaction unit corresponding to this authorization transaction. */ private String referenceId; /** * Receipt id is 16 digit number payment identification number returned for guest users to identify the payment. */ private String receiptId; /** * */ private List<Links> links; /** * Default Constructor */ public Authorization() { } /** * Parameterized Constructor */ public Authorization(Amount amount) { this.amount = amount; } /** * Shows details for an authorization, by ID. * * @param accessToken Access Token used for the API call. * @param authorizationId String * @return Authorization * @throws PayPalRESTException * @deprecated Please use {@link #get(APIContext, String)} instead. */ public static Authorization get(String accessToken, String authorizationId) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); return get(apiContext, authorizationId); } /** * Shows details for an authorization, by ID. * * @param apiContext {@link APIContext} used for the API call. * @param authorizationId String * @return Authorization * @throws PayPalRESTException */ public static Authorization get(APIContext apiContext, String authorizationId) throws PayPalRESTException { if (authorizationId == null) { throw new IllegalArgumentException("authorizationId cannot be null"); } Object[] parameters = new Object[]{authorizationId}; String pattern = "v1/payments/authorization/{0}"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; return configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, Authorization.class); } /** * Captures and processes an authorization, by ID. To use this call, the original payment call must specify an intent of `authorize`. * * @param accessToken Access Token used for the API call. * @param capture Capture * @return Capture * @throws PayPalRESTException * @deprecated Please use {@link #capture(APIContext, Capture)} instead. */ public Capture capture(String accessToken, Capture capture) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); return capture(apiContext, capture); } /** * Captures and processes an authorization, by ID. To use this call, the original payment call must specify an intent of `authorize`. * * @param apiContext {@link APIContext} used for the API call. * @param capture Capture * @return Capture * @throws PayPalRESTException */ public Capture capture(APIContext apiContext, Capture capture) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } if (capture == null) { throw new IllegalArgumentException("capture cannot be null"); } Object[] parameters = new Object[]{this.getId()}; String pattern = "v1/payments/authorization/{0}/capture"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = capture.toJSON(); return configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Capture.class); } /** * Voids, or cancels, an authorization, by ID. You cannot void a fully captured authorization. * * @param accessToken Access Token used for the API call. * @return Authorization * @throws PayPalRESTException * @deprecated Please use {@link #doVoid(APIContext)} instead. */ public Authorization doVoid(String accessToken) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); return doVoid(apiContext); } /** * Voids, or cancels, an authorization, by ID. You cannot void a fully captured authorization. * * @param apiContext {@link APIContext} used for the API call. * @return Authorization * @throws PayPalRESTException */ public Authorization doVoid(APIContext apiContext) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } Object[] parameters = new Object[]{this.getId()}; String pattern = "v1/payments/authorization/{0}/void"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; return configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Authorization.class); } /** * Reauthorizes a PayPal account payment, by authorization ID. To ensure that funds are still available, reauthorize a payment after the initial three-day honor period. Supports only the `amount` request parameter. * * @param accessToken Access Token used for the API call. * @return Authorization * @throws PayPalRESTException * @deprecated Please use {@link #reauthorize(APIContext)} instead. */ public Authorization reauthorize(String accessToken) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); return reauthorize(apiContext); } /** * Reauthorizes a PayPal account payment, by authorization ID. To ensure that funds are still available, reauthorize a payment after the initial three-day honor period. Supports only the `amount` request parameter. * * @param apiContext {@link APIContext} used for the API call. * @return Authorization * @throws PayPalRESTException */ public Authorization reauthorize(APIContext apiContext) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } Object[] parameters = new Object[]{this.getId()}; String pattern = "v1/payments/authorization/{0}/reauthorize"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = this.toJSON(); return configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Authorization.class); } }
package org.java_websocket.server; import org.java_websocket.*; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshakeBuilder; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add * functionality/purpose to the server. * */ public abstract class WebSocketServer extends WebSocketAdapter implements Runnable { public static int DECODERS = Runtime.getRuntime().availableProcessors(); /** * Holds the list of active WebSocket connections. "Active" means WebSocket * handshake is complete and socket can be written to, or read from. */ private final Collection<WebSocket> connections; /** * The port number that this WebSocket server should listen on. Default is * WebSocket.DEFAULT_PORT. */ private final InetSocketAddress address; /** * The socket channel for this WebSocket server. */ private ServerSocketChannel server; /** * The 'Selector' used to get event keys from the underlying socket. */ private Selector selector; /** * The Draft of the WebSocket protocol the Server is adhering to. */ private List<Draft> drafts; private Thread selectorthread; private volatile AtomicBoolean isclosed = new AtomicBoolean( false ); private List<WebSocketWorker> decoders; private List<WebSocketImpl> iqueue; private BlockingQueue<ByteBuffer> buffers; private int queueinvokes = 0; private AtomicInteger queuesize = new AtomicInteger( 0 ); private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); /** * Creates a WebSocketServer that will attempt to * listen on port <var>WebSocket.DEFAULT_PORT</var>. * * @see #WebSocketServer(java.net.InetSocketAddress, int, java.util.List, java.util.Collection) more details here */ public WebSocketServer() throws UnknownHostException { this( new InetSocketAddress( WebSocket.DEFAULT_PORT ), DECODERS, null ); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>. * * @see #WebSocketServer(java.net.InetSocketAddress, int, java.util.List, java.util.Collection) more details here */ public WebSocketServer( InetSocketAddress address ) { this( address, DECODERS, null ); } /** * @see #WebSocketServer(java.net.InetSocketAddress, int, java.util.List, java.util.Collection) more details here */ public WebSocketServer( InetSocketAddress address , int decoders ) { this( address, decoders, null ); } /** * @see #WebSocketServer(java.net.InetSocketAddress, int, java.util.List, java.util.Collection) more details here */ public WebSocketServer( InetSocketAddress address , List<Draft> drafts ) { this( address, DECODERS, drafts ); } /** * @see #WebSocketServer(java.net.InetSocketAddress, int, java.util.List, java.util.Collection) more details here */ public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts ) { this( address, decodercount, drafts, new HashSet<WebSocket>() ); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>, * and comply with <tt>Draft</tt> version <var>draft</var>. * * @param address * The address (host:port) this server should listen on. * @param decodercount * The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts * The versions of the WebSocket protocol that this server * instance should comply to. Clients that use an other protocol version will be rejected. * * @param connectionscontainer * Allows to specify a collection that will be used to store the websockets in. <br> * If you plan to often iterate through the currently connected websockets you may want to use a collection that does not require synchronization like a {@link java.util.concurrent.CopyOnWriteArraySet}. In that case make sure that you overload {@link #removeConnection(org.java_websocket.WebSocket)} and {@link #addConnection(org.java_websocket.WebSocket)}.<br> * By default a {@link java.util.HashSet} will be used. * * @see #removeConnection(org.java_websocket.WebSocket) for more control over syncronized operation * @see <a href="https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts" > more about drafts */ public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts , Collection<WebSocket> connectionscontainer ) { if( address == null || decodercount < 1 || connectionscontainer == null ) { throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder" ); } if( drafts == null ) this.drafts = Collections.emptyList(); else this.drafts = drafts; this.address = address; this.connections = connectionscontainer; iqueue = new LinkedList<WebSocketImpl>(); decoders = new ArrayList<WebSocketWorker>( decodercount ); buffers = new LinkedBlockingQueue<ByteBuffer>(); for( int i = 0 ; i < decodercount ; i++ ) { WebSocketWorker ex = new WebSocketWorker(); decoders.add( ex ); ex.start(); } } /** * Starts the server selectorthread that binds to the currently set port number and * listeners for WebSocket connection requests. Creates a fixed thread pool with the size {@link WebSocketServer#DECODERS}<br> * May only be called once. * * Alternatively you can call {@link WebSocketServer#run()} directly. * * @throws IllegalStateException */ public void start() { if( selectorthread != null ) throw new IllegalStateException( getClass().getName() + " can only be started once." ); new Thread( this ).start();; } /** * Closes all connected clients sockets, then closes the underlying * ServerSocketChannel, effectively killing the server socket selectorthread, * freeing the port the server was bound to and stops all internal workerthreads. * * If this method is called before the server is started it will never start. * * @param timeout * Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking.<br> * * @throws java.io.IOException * When {@link java.nio.channels.ServerSocketChannel}.close throws an IOException * @throws InterruptedException */ public void stop( int timeout ) throws InterruptedException { if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections return; } List<WebSocket> socketsToClose = null; // copy the connections in a list (prevent callback deadlocks) synchronized ( connections ) { socketsToClose = new ArrayList<WebSocket>( connections ); } for( WebSocket ws : socketsToClose ) { ws.close( CloseFrame.GOING_AWAY ); } synchronized ( this ) { if( selectorthread != null ) { if( Thread.currentThread() != selectorthread ) { } if( selectorthread != Thread.currentThread() ) { if( socketsToClose.size() > 0 ) selectorthread.join( timeout );// isclosed will tell the selectorthread to go down after the last connection was closed selectorthread.interrupt();// in case the selectorthread did not terminate in time we send the interrupt selectorthread.join(); } } } } public void stop() throws IOException , InterruptedException { stop( 0 ); } /** * Returns a WebSocket[] of currently connected clients. * Its iterators will be failfast and its not judicious * to modify it. * * @return The currently connected clients. */ public Collection<WebSocket> connections() { return this.connections; } public InetSocketAddress getAddress() { return this.address; } /** * Gets the port number that this server listens on. * * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if( port == 0 && server != null ) { port = server.socket().getLocalPort(); } return port; } public List<Draft> getDraft() { return Collections.unmodifiableList( drafts ); } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { synchronized ( this ) { if( selectorthread != null ) throw new IllegalStateException( getClass().getName() + " can only be started once." ); selectorthread = Thread.currentThread(); if( isclosed.get() ) { return; } } selectorthread.setName( "WebsocketSelector" + selectorthread.getId() ); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); ServerSocket socket = server.socket(); socket.setReceiveBufferSize( WebSocketImpl.RCVBUF ); socket.bind( address ); selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { handleFatal( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocketImpl conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); if( !key.isValid() ) { // Object o = key.attachment(); continue; } if( key.isAcceptable() ) { if( !onConnect( key ) ) { key.cancel(); continue; } SocketChannel channel = server.accept(); channel.configureBlocking( false ); WebSocketImpl w = wsf.createWebSocket( this, drafts, channel.socket() ); w.key = channel.register( selector, SelectionKey.OP_READ, w ); w.channel = wsf.wrapChannel( channel, w.key ); i.remove(); allocateBuffers( w ); continue; } if( key.isReadable() ) { conn = (WebSocketImpl) key.attachment(); ByteBuffer buf = takeBuffer(); try { if( SocketChannelIOHelper.read( buf, conn, conn.channel ) ) { if( buf.hasRemaining() ) { conn.inQueue.put( buf ); queue( conn ); i.remove(); if( conn.channel instanceof WrappedByteChannel ) { if( ( (WrappedByteChannel) conn.channel ).isNeedRead() ) { iqueue.add( conn ); } } } else pushBuffer( buf ); } else { pushBuffer( buf ); } } catch ( IOException e ) { pushBuffer( buf ); throw e; } } if( key.isWritable() ) { conn = (WebSocketImpl) key.attachment(); if( SocketChannelIOHelper.batch( conn, conn.channel ) ) { if( key.isValid() ) key.interestOps( SelectionKey.OP_READ ); } } } while ( !iqueue.isEmpty() ) { conn = iqueue.remove( 0 ); WrappedByteChannel c = ( (WrappedByteChannel) conn.channel ); ByteBuffer buf = takeBuffer(); try { if( SocketChannelIOHelper.readMore( buf, conn, c ) ) iqueue.add( conn ); if( buf.hasRemaining() ) { conn.inQueue.put( buf ); queue( conn ); } else { pushBuffer( buf ); } } catch ( IOException e ) { pushBuffer( buf ); throw e; } } } catch ( CancelledKeyException e ) { // an other thread may cancel the key } catch ( ClosedByInterruptException e ) { return; // do the same stuff as when InterruptedException is thrown } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( key, conn, ex ); } catch ( InterruptedException e ) { return;// FIXME controlled shutdown (e.g. take care of buffermanagement) } } } catch ( RuntimeException e ) { // should hopefully never occur handleFatal( null, e ); } finally { if( decoders != null ) { for( WebSocketWorker w : decoders ) { w.interrupt(); } } if( server != null ) { try { server.close(); } catch ( IOException e ) { onError( null, e ); } } } } protected void allocateBuffers( WebSocket c ) throws InterruptedException { if( queuesize.get() >= 2 * decoders.size() + 1 ) { return; } queuesize.incrementAndGet(); buffers.put( createBuffer() ); } protected void releaseBuffers( WebSocket c ) throws InterruptedException { // queuesize.decrementAndGet(); // takeBuffer(); } public ByteBuffer createBuffer() { return ByteBuffer.allocate( WebSocketImpl.RCVBUF ); } private void queue( WebSocketImpl ws ) throws InterruptedException { if( ws.workerThread == null ) { ws.workerThread = decoders.get( queueinvokes % decoders.size() ); queueinvokes++; } ws.workerThread.put( ws ); } private ByteBuffer takeBuffer() throws InterruptedException { return buffers.take(); } private void pushBuffer( ByteBuffer buf ) throws InterruptedException { if( buffers.size() > queuesize.intValue() ) return; buffers.put( buf ); } private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) { // onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); } else if( key != null ) { SelectableChannel channel = key.channel(); if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException try { channel.close(); } catch ( IOException e ) { // there is nothing that must be done here } if( WebSocketImpl.DEBUG ) System.out.println( "Connection closed because of" + ex ); } } } private void handleFatal( WebSocket conn, Exception e ) { onError( conn, e ); try { stop(); } catch ( IOException e1 ) { onError( null, e1 ); } catch ( InterruptedException e1 ) { Thread.currentThread().interrupt(); onError( null, e1 ); } } /** * Gets the XML string that should be returned if a client requests a Flash * security policy. * * The default implementation allows access from all remote domains, but * only on the port that this WebSocketServer is listening on. * * This is specifically implemented for gitime's WebSocket client for Flash: * http://github.com/gimite/web-socket-js * * @return An XML String that comforms to Flash's security policy. You MUST * not include the null char at the end, it is appended automatically. */ protected String getFlashSecurityPolicy() { return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"" + getPort() + "\" /></cross-domain-policy>"; } @Override public final void onWebsocketMessage( WebSocket conn, String message ) { onMessage( conn, message ); } @Override @Deprecated public/*final*/void onWebsocketMessageFragment( WebSocket conn, Framedata frame ) {// onFragment should be overloaded instead onFragment( conn, frame ); } @Override public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) { onMessage( conn, blob ); } @Override public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) { if( addConnection( conn ) ) { onOpen( conn, (ClientHandshake) handshake ); } } @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { selector.wakeup(); try { if( removeConnection( conn ) ) { onClose( conn, code, reason, remote ); } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } /** * This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized * <p> * {@link #WebSocketServer(java.net.InetSocketAddress, int, java.util.List, java.util.Collection)} allows to specify a collection which will be used to store current connections in.<br> * Depending on the type on the connection, modifications of that collection may have to be synchronized. **/ protected boolean removeConnection( WebSocket ws ) { boolean removed; synchronized ( connections ) { removed = this.connections.remove( ws ); assert ( removed ); } if( isclosed.get() && connections.size() == 0 ) { selectorthread.interrupt(); } return removed; } @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException { return super.onWebsocketHandshakeReceivedAsServer( conn, draft, request ); } /** @see #removeConnection(org.java_websocket.WebSocket) */ protected boolean addConnection( WebSocket ws ) { if( !isclosed.get() ) { synchronized ( connections ) { boolean succ = this.connections.add( ws ); assert ( succ ); return succ; } } else { // This case will happen when a new connection gets ready while the server is already stopping. ws.close( CloseFrame.GOING_AWAY ); return true;// for consistency sake we will make sure that both onOpen will be called } } /** * @param conn * may be null if the error does not belong to a single connection */ @Override public final void onWebsocketError( WebSocket conn, Exception ex ) { onError( conn, ex ); } @Override public final void onWriteDemand( WebSocket w ) { WebSocketImpl conn = (WebSocketImpl) w; try { conn.key.interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE ); } catch ( CancelledKeyException e ) { // the thread which cancels key is responsible for possible cleanup conn.outQueue.clear(); } selector.wakeup(); } @Override public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) { onCloseInitiated( conn, code, reason ); } @Override public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) { onClosing( conn, code, reason, remote ); } public void onCloseInitiated( WebSocket conn, int code, String reason ) { } public void onClosing( WebSocket conn, int code, String reason, boolean remote ) { } public final void setWebSocketFactory( WebSocketServerFactory wsf ) { this.wsf = wsf; } public final WebSocketFactory getWebSocketFactory() { return wsf; } /** * Returns whether a new connection shall be accepted or not.<br> * Therefore method is well suited to implement some kind of connection limitation.<br> * * @see {@link #onOpen(org.java_websocket.WebSocket, org.java_websocket.handshake.ClientHandshake)}, {@link #onWebsocketHandshakeReceivedAsServer(org.java_websocket.WebSocket, org.java_websocket.drafts.Draft, org.java_websocket.handshake.ClientHandshake)} **/ protected boolean onConnect( SelectionKey key ) { return true; } private Socket getSocket( WebSocket conn ) { WebSocketImpl impl = (WebSocketImpl) conn; return ( (SocketChannel) impl.key.channel() ).socket(); } @Override public InetSocketAddress getLocalSocketAddress( WebSocket conn ) { return (InetSocketAddress) getSocket( conn ).getLocalSocketAddress(); } @Override public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { return (InetSocketAddress) getSocket( conn ).getRemoteSocketAddress(); } /** Called after an opening handshake has been performed and the given websocket is ready to be written on. */ public abstract void onOpen( WebSocket conn, ClientHandshake handshake ); /** * Called after the websocket connection has been closed. * * @param code * The codes can be looked up here: {@link org.java_websocket.framing.CloseFrame} * @param reason * Additional information string * @param remote * Returns whether or not the closing of the connection was initiated by the remote host. **/ public abstract void onClose( WebSocket conn, int code, String reason, boolean remote ); /** * Callback for string messages received from the remote host * * @see #onMessage(org.java_websocket.WebSocket, java.nio.ByteBuffer) **/ public abstract void onMessage( WebSocket conn, String message ); /** * Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(org.java_websocket.WebSocket, int, String, boolean)} will be called additionally.<br> * This method will be called primarily because of IO or protocol errors.<br> * If the given exception is an RuntimeException that probably means that you encountered a bug.<br> * * @param con * Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound. **/ public abstract void onError( WebSocket conn, Exception ex ); /** * Callback for binary messages received from the remote host * * @see #onMessage(org.java_websocket.WebSocket, String) **/ public void onMessage( WebSocket conn, ByteBuffer message ) { } /** * @see org.java_websocket.WebSocket#sendFragmentedFrame(org.java_websocket.framing.Framedata.Opcode, java.nio.ByteBuffer, boolean) */ public void onFragment( WebSocket conn, Framedata fragment ) { } public class WebSocketWorker extends Thread { private BlockingQueue<WebSocketImpl> iqueue; public WebSocketWorker() { iqueue = new LinkedBlockingQueue<WebSocketImpl>(); setName( "WebSocketWorker-" + getId() ); setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException( Thread t, Throwable e ) { getDefaultUncaughtExceptionHandler().uncaughtException( t, e ); } } ); } public void put( WebSocketImpl ws ) throws InterruptedException { iqueue.put( ws ); } @Override public void run() { WebSocketImpl ws = null; try { while ( true ) { ByteBuffer buf = null; ws = iqueue.take(); buf = ws.inQueue.poll(); assert ( buf != null ); try { ws.decode( buf ); } finally { pushBuffer( buf ); } } } catch ( InterruptedException e ) { } catch ( RuntimeException e ) { handleFatal( ws, e ); } } } public interface WebSocketServerFactory extends WebSocketFactory { @Override public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d, Socket s); public WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> drafts, Socket s); /** * Allows to wrap the Socketchannel( key.channel() ) to insert a protocol layer( like ssl or proxy authentication) beyond the ws layer. * * @param key * a SelectionKey of an open SocketChannel. * @return The channel on which the read and write operations will be performed.<br> */ public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException; } }
package org.bouncycastle.bcpg; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Vector; import org.bouncycastle.util.StringList; import org.bouncycastle.util.Strings; /** * reader for Base64 armored objects - read the headers and then start returning * bytes when the data is reached. An IOException is thrown if the CRC check * fails. */ public class ArmoredInputStream extends InputStream { /* * set up the decoding table. */ private static final byte[] decodingTable; static { decodingTable = new byte[128]; for (int i = 'A'; i <= 'Z'; i++) { decodingTable[i] = (byte)(i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { decodingTable[i] = (byte)(i - 'a' + 26); } for (int i = '0'; i <= '9'; i++) { decodingTable[i] = (byte)(i - '0' + 52); } decodingTable['+'] = 62; decodingTable['/'] = 63; } /** * decode the base 64 encoded input data. * * @return the offset the data starts in out. */ private int decode( int in0, int in1, int in2, int in3, int[] out) throws EOFException { int b1, b2, b3, b4; if (in3 < 0) { throw new EOFException("unexpected end of file in armored stream."); } if (in2 == '=') { b1 = decodingTable[in0] &0xff; b2 = decodingTable[in1] & 0xff; out[2] = ((b1 << 2) | (b2 >> 4)) & 0xff; return 2; } else if (in3 == '=') { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; out[1] = ((b1 << 2) | (b2 >> 4)) & 0xff; out[2] = ((b2 << 4) | (b3 >> 2)) & 0xff; return 1; } else { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; b4 = decodingTable[in3]; out[0] = ((b1 << 2) | (b2 >> 4)) & 0xff; out[1] = ((b2 << 4) | (b3 >> 2)) & 0xff; out[2] = ((b3 << 6) | b4) & 0xff; return 0; } } InputStream in; boolean start = true; int[] outBuf = new int[3]; int bufPtr = 3; CRC24 crc = new CRC24(); boolean crcFound = false; boolean hasHeaders = true; String header = null; boolean newLineFound = false; boolean clearText = false; boolean restart = false; StringList headerList= Strings.newList(); int lastC = 0; boolean isEndOfStream; /** * Create a stream for reading a PGP armoured message, parsing up to a header * and then reading the data that follows. * * @param in */ public ArmoredInputStream( InputStream in) throws IOException { this(in, true); } /** * Create an armoured input stream which will assume the data starts * straight away, or parse for headers first depending on the value of * hasHeaders. * * @param in * @param hasHeaders true if headers are to be looked for, false otherwise. */ public ArmoredInputStream( InputStream in, boolean hasHeaders) throws IOException { this.in = in; this.hasHeaders = hasHeaders; if (hasHeaders) { parseHeaders(); } start = false; } public int available() throws IOException { return in.available(); } private boolean parseHeaders() throws IOException { header = null; int c; int last = 0; boolean headerFound = false; headerList = Strings.newList(); // // if restart we already have a header // if (restart) { headerFound = true; } else { while ((c = in.read()) >= 0) { if (c == '-' && (last == 0 || last == '\n' || last == '\r')) { headerFound = true; break; } last = c; } } if (headerFound) { StringBuffer buf = new StringBuffer("-"); boolean eolReached = false; boolean crLf = false; if (restart) // we've had to look ahead two '-' { buf.append('-'); } while ((c = in.read()) >= 0) { if (last == '\r' && c == '\n') { crLf = true; } if (eolReached && (last != '\r' && c == '\n')) { break; } if (eolReached && c == '\r') { break; } if (c == '\r' || (last != '\r' && c == '\n')) { String line = buf.toString(); if (line.trim().length() == 0) { break; } headerList.add(line); buf.setLength(0); } if (c != '\n' && c != '\r') { buf.append((char)c); eolReached = false; } else { if (c == '\r' || (last != '\r' && c == '\n')) { eolReached = true; } } last = c; } if (crLf) { in.read(); // skip last \n } } if (headerList.size() > 0) { header = headerList.get(0); } clearText = "-----BEGIN PGP SIGNED MESSAGE-----".equals(header); newLineFound = true; return headerFound; } /** * @return true if we are inside the clear text section of a PGP * signed message. */ public boolean isClearText() { return clearText; } /** * @return true if the stream is actually at end of file. */ public boolean isEndOfStream() { return isEndOfStream; } /** * Return the armor header line (if there is one) * @return the armor header line, null if none present. */ public String getArmorHeaderLine() { return header; } /** * Return the armor headers (the lines after the armor header line), * @return an array of armor headers, null if there aren't any. */ public String[] getArmorHeaders() { if (headerList.size() <= 1) { return null; } return headerList.toStringArray(1, headerList.size()); } private int readIgnoreSpace() throws IOException { int c = in.read(); while (c == ' ' || c == '\t') { c = in.read(); } return c; } public int read() throws IOException { int c; if (start) { if (hasHeaders) { parseHeaders(); } crc.reset(); start = false; } if (clearText) { c = in.read(); if (c == '\r' || (c == '\n' && lastC != '\r')) { newLineFound = true; } else if (newLineFound && c == '-') { c = in.read(); if (c == '-') // a header, not dash escaped { clearText = false; start = true; restart = true; } else // a space - must be a dash escape { c = in.read(); } newLineFound = false; } else { if (c != '\n' && lastC != '\r') { newLineFound = false; } } lastC = c; if (c < 0) { isEndOfStream = true; } return c; } if (bufPtr > 2 || crcFound) { c = readIgnoreSpace(); if (c == '\r' || c == '\n') { c = readIgnoreSpace(); while (c == '\n' || c == '\r') { c = readIgnoreSpace(); } if (c < 0) // EOF { isEndOfStream = true; return -1; } if (c == '=') // crc reached { bufPtr = decode(readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), outBuf); if (bufPtr == 0) { int i = ((outBuf[0] & 0xff) << 16) | ((outBuf[1] & 0xff) << 8) | (outBuf[2] & 0xff); crcFound = true; if (i != crc.getValue()) { throw new IOException("crc check failed in armored message."); } return read(); } else { throw new IOException("no crc found in armored message."); } } else if (c == '-') // end of record reached { while ((c = in.read()) >= 0) { if (c == '\n' || c == '\r') { break; } } if (!crcFound) { throw new IOException("crc check not found."); } crcFound = false; start = true; bufPtr = 3; if (c < 0) { isEndOfStream = true; } return -1; } else // data { bufPtr = decode(c, readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), outBuf); } } else { if (c >= 0) { bufPtr = decode(c, readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), outBuf); } else { isEndOfStream = true; return -1; } } } c = outBuf[bufPtr++]; crc.update(c); return c; } public void close() throws IOException { in.close(); } }
/* * Copyright 2000-2015 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.javadoc; import com.intellij.analysis.AnalysisScope; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.*; import com.intellij.execution.filters.RegexpFilter; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessTerminatedListener; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.BrowserUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.ex.PathUtilEx; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.util.PathsList; import com.intellij.util.containers.HashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; import javax.swing.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * @author Eugene Zhuravlev * Date: Apr 24, 2004 */ public class JavadocConfiguration implements ModuleRunProfile, JDOMExternalizable{ public String OUTPUT_DIRECTORY; public String OPTION_SCOPE = PsiKeyword.PROTECTED; public boolean OPTION_HIERARCHY = true; public boolean OPTION_NAVIGATOR = true; public boolean OPTION_INDEX = true; public boolean OPTION_SEPARATE_INDEX = true; public boolean OPTION_DOCUMENT_TAG_USE = false; public boolean OPTION_DOCUMENT_TAG_AUTHOR = false; public boolean OPTION_DOCUMENT_TAG_VERSION = false; public boolean OPTION_DOCUMENT_TAG_DEPRECATED = true; public boolean OPTION_DEPRECATED_LIST = true; public String OTHER_OPTIONS = ""; public String HEAP_SIZE; public String LOCALE; public boolean OPEN_IN_BROWSER = true; private final Project myProject; private AnalysisScope myGenerationScope; private static final Logger LOGGER = Logger.getInstance("#" + JavadocConfiguration.class.getName()); public boolean OPTION_INCLUDE_LIBS = false; public boolean OPTION_LINK_TO_JDK_DOCS = false; public void setGenerationScope(AnalysisScope generationScope) { myGenerationScope = generationScope; } public JavadocConfiguration(Project project) { myProject = project; } public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException { return new MyJavaCommandLineState(myProject, myGenerationScope, env); } public String getName() { return JavadocBundle.message("javadoc.settings.title"); } public void checkConfiguration() throws RuntimeConfigurationException { if (myGenerationScope == null) { throw new RuntimeConfigurationError(JavadocBundle.message("javadoc.settings.not.specified")); } } public JavadocConfigurable createConfigurable() { return new JavadocConfigurable(this); } public Icon getIcon() { return null; } @NotNull public Module[] getModules() { return Module.EMPTY_ARRAY; } public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); } public void writeExternal(Element element) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, element); } public boolean sdkHasJavadocUrls() { return getSdk(myProject).getRootProvider().getFiles(JavadocOrderRootType.getInstance()).length > 0; } public static Sdk getSdk(@NotNull Project project) { return PathUtilEx.getAnyJdk(project); } private class MyJavaCommandLineState extends CommandLineState { private final AnalysisScope myGenerationOptions; private final Project myProject; @NonNls private static final String INDEX_HTML = "index.html"; public MyJavaCommandLineState(Project project, AnalysisScope generationOptions, ExecutionEnvironment env) { super(env); myGenerationOptions = generationOptions; myProject = project; addConsoleFilters(new RegexpFilter(project, "$FILE_PATH$:$LINE$:[^\\^]+\\^"), new RegexpFilter(project, "$FILE_PATH$:$LINE$: warning - .+$")); } protected GeneralCommandLine createCommandLine() throws ExecutionException { final GeneralCommandLine cmdLine = new GeneralCommandLine(); final Sdk jdk = getSdk(myProject); setupExeParams(jdk, cmdLine); setupProgramParameters(jdk, cmdLine); return cmdLine; } private void setupExeParams(final Sdk jdk, GeneralCommandLine cmdLine) throws ExecutionException { final String jdkPath = jdk != null && jdk.getSdkType() instanceof JavaSdkType ? ((JavaSdkType)jdk.getSdkType()).getBinPath(jdk) : null; if (jdkPath == null) { throw new CantRunException(JavadocBundle.message("javadoc.generate.no.jdk.path")); } JavaSdkVersion version = JavaSdk.getInstance().getVersion(jdk); if (HEAP_SIZE != null && HEAP_SIZE.trim().length() != 0) { if (version == null || version.isAtLeast(JavaSdkVersion.JDK_1_2)) { cmdLine.getParametersList().prepend("-J-Xmx" + HEAP_SIZE + "m"); } else { cmdLine.getParametersList().prepend("-J-mx" + HEAP_SIZE + "m"); } } cmdLine.setWorkDirectory((File)null); @NonNls final String javadocExecutableName = File.separator + (SystemInfo.isWindows ? "javadoc.exe" : "javadoc"); @NonNls String exePath = jdkPath.replace('/', File.separatorChar) + javadocExecutableName; if (new File(exePath).exists()) { cmdLine.setExePath(exePath); } else { //try to use wrapper jdk exePath = new File(jdkPath).getParent().replace('/', File.separatorChar) + javadocExecutableName; if (!new File(exePath).exists()){ final File parent = new File(System.getProperty("java.home")).getParentFile(); //try system jre exePath = parent.getPath() + File.separator + "bin" + javadocExecutableName; if (!new File(exePath).exists()){ throw new CantRunException(JavadocBundle.message("javadoc.generate.no.jdk.path")); } } cmdLine.setExePath(exePath); } } private void setupProgramParameters(final Sdk jdk, final GeneralCommandLine cmdLine) throws CantRunException { @NonNls final ParametersList parameters = cmdLine.getParametersList(); if (LOCALE != null && LOCALE.length() > 0) { parameters.add("-locale"); parameters.add(LOCALE); } if (OPTION_SCOPE != null) { parameters.add("-" + OPTION_SCOPE); } if (!OPTION_HIERARCHY) { parameters.add("-notree"); } if (!OPTION_NAVIGATOR) { parameters.add("-nonavbar"); } if (!OPTION_INDEX) { parameters.add("-noindex"); } else if (OPTION_SEPARATE_INDEX) { parameters.add("-splitindex"); } if (OPTION_DOCUMENT_TAG_USE) { parameters.add("-use"); } if (OPTION_DOCUMENT_TAG_AUTHOR) { parameters.add("-author"); } if (OPTION_DOCUMENT_TAG_VERSION) { parameters.add("-version"); } if (!OPTION_DOCUMENT_TAG_DEPRECATED) { parameters.add("-nodeprecated"); } else if (!OPTION_DEPRECATED_LIST) { parameters.add("-nodeprecatedlist"); } parameters.addParametersString(OTHER_OPTIONS); final Set<Module> modules = new LinkedHashSet<Module>(); try { final File sourcePathTempFile = FileUtil.createTempFile("javadoc", "args.txt", true); parameters.add("@" + sourcePathTempFile.getCanonicalPath()); final PrintWriter writer = new PrintWriter(new FileWriter(sourcePathTempFile)); try { final Collection<String> packages = new HashSet<String>(); final Collection<String> sources = new HashSet<String>(); final Runnable findRunnable = new Runnable() { public void run() { final int scopeType = myGenerationOptions.getScopeType(); final boolean usePackageNotation = scopeType == AnalysisScope.MODULE || scopeType == AnalysisScope.MODULES || scopeType == AnalysisScope.PROJECT || scopeType == AnalysisScope.DIRECTORY; myGenerationOptions.accept(new MyContentIterator(myProject, packages, sources, modules, usePackageNotation)); } }; if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRunnable, "Search for sources to generate javadoc in...", true, myProject)) { return; } if (packages.size() + sources.size() == 0) { throw new CantRunException(JavadocBundle.message("javadoc.generate.no.classes.in.selected.packages.error")); } for (String aPackage : packages) { writer.println(aPackage); } //http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#runningjavadoc for (String source : sources) { writer.println(StringUtil.wrapWithDoubleQuote(source)); } writer.println("-sourcepath"); OrderEnumerator enumerator = OrderEnumerator.orderEntries(myProject); if (!OPTION_INCLUDE_LIBS) { enumerator = enumerator.withoutSdk().withoutLibraries(); } final PathsList pathsList = enumerator.getSourcePathsList(); final List<VirtualFile> files = pathsList.getRootDirs(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); final StringBuilder sourcePath = new StringBuilder(); boolean start = true; for (VirtualFile file : files) { if (!myGenerationOptions.isIncludeTestSource() && fileIndex.isInTestSourceContent(file)) continue; if (start) { start = false; } else { sourcePath.append(File.pathSeparator); } sourcePath.append(file.getPath()); } writer.println(StringUtil.wrapWithDoubleQuote(sourcePath.toString())); } finally { writer.close(); } } catch (IOException e) { LOGGER.error(e); } if (OPTION_LINK_TO_JDK_DOCS) { VirtualFile[] docUrls = jdk.getRootProvider().getFiles(JavadocOrderRootType.getInstance()); for (VirtualFile docUrl : docUrls) { parameters.add("-link"); parameters.add(VfsUtil.toUri(docUrl).toString()); } } final PathsList classPath; final OrderEnumerator orderEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules); if (jdk.getSdkType() instanceof JavaSdk) { classPath = orderEnumerator.withoutSdk().withoutModuleSourceEntries().getPathsList(); } else { //libraries are included into jdk classPath = orderEnumerator.withoutModuleSourceEntries().getPathsList(); } final String classPathString = classPath.getPathsString(); if (classPathString.length() > 0) { parameters.add("-classpath"); parameters.add(classPathString); } if (OUTPUT_DIRECTORY != null) { parameters.add("-d"); parameters.add(OUTPUT_DIRECTORY.replace('/', File.separatorChar)); } } @NotNull protected OSProcessHandler startProcess() throws ExecutionException { final OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine()); ProcessTerminatedListener.attach(handler, myProject, JavadocBundle.message("javadoc.generate.exited")); handler.addProcessListener(new ProcessAdapter() { public void processTerminated(ProcessEvent event) { if (OPEN_IN_BROWSER) { File url = new File(OUTPUT_DIRECTORY, INDEX_HTML); if (url.exists() && event.getExitCode() == 0) { BrowserUtil.browse(url); } } } }); return handler; } } private static class MyContentIterator extends PsiRecursiveElementWalkingVisitor { private final PsiManager myPsiManager; private final Collection<String> myPackages; private final Collection<String> mySourceFiles; private final Set<Module> myModules; private final boolean myUsePackageNotation; public MyContentIterator(Project project, Collection<String> packages, Collection<String> sources, Set<Module> modules, boolean canUsePackageNotation) { myModules = modules; myUsePackageNotation = canUsePackageNotation; myPsiManager = PsiManager.getInstance(project); myPackages = packages; mySourceFiles = sources; } @Override public void visitFile(PsiFile file) { final VirtualFile fileOrDir = file.getVirtualFile(); if (fileOrDir == null) return; if (!fileOrDir.isInLocalFileSystem()) return; final Module module = ModuleUtilCore.findModuleForFile(fileOrDir, myPsiManager.getProject()); if (module != null) { myModules.add(module); } if (file instanceof PsiJavaFile) { final PsiJavaFile javaFile = (PsiJavaFile)file; final String packageName = javaFile.getPackageName(); if (containsPackagePrefix(module, packageName) || (packageName.length() == 0 && !(javaFile instanceof ServerPageFile)) || !myUsePackageNotation) { mySourceFiles.add(FileUtil.toSystemIndependentName(fileOrDir.getPath())); } else { myPackages.add(packageName); } } } private static boolean containsPackagePrefix(Module module, String packageFQName) { if (module == null) return false; for (ContentEntry contentEntry : ModuleRootManager.getInstance(module).getContentEntries()) { for (SourceFolder sourceFolder : contentEntry.getSourceFolders(JavaModuleSourceRootTypes.SOURCES)) { final String packagePrefix = sourceFolder.getPackagePrefix(); final int prefixLength = packagePrefix.length(); if (prefixLength > 0 && packageFQName.startsWith(packagePrefix)) { return true; } } } return false; } } }
/** * 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.drill.exec.physical.impl.join; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Iterator; import java.util.List; import org.apache.drill.categories.OperatorTest; import org.apache.drill.categories.SlowTest; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.util.FileUtils; import org.apache.drill.common.util.TestTools; import org.apache.drill.exec.client.DrillClient; import org.apache.drill.exec.expr.fn.FunctionImplementationRegistry; import org.apache.drill.exec.ops.FragmentContext; import org.apache.drill.exec.physical.PhysicalPlan; import org.apache.drill.exec.physical.base.FragmentRoot; import org.apache.drill.exec.physical.impl.ImplCreator; import org.apache.drill.exec.physical.impl.SimpleRootExec; import org.apache.drill.exec.planner.PhysicalPlanReader; import org.apache.drill.exec.planner.PhysicalPlanReaderTestFactory; import org.apache.drill.exec.pop.PopUnitTestBase; import org.apache.drill.exec.proto.BitControl.PlanFragment; import org.apache.drill.exec.record.RecordBatchLoader; import org.apache.drill.exec.record.VectorWrapper; import org.apache.drill.exec.rpc.user.QueryDataBatch; import org.apache.drill.exec.rpc.UserClientConnection; import org.apache.drill.exec.server.Drillbit; import org.apache.drill.exec.server.DrillbitContext; import org.apache.drill.exec.server.RemoteServiceSet; import org.apache.drill.exec.vector.ValueVector; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestRule; import com.google.common.base.Charsets; import com.google.common.io.Files; import mockit.Injectable; @Category({SlowTest.class, OperatorTest.class}) public class TestHashJoin extends PopUnitTestBase { //private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestMergeJoin.class); @Rule public final TestRule TIMEOUT = TestTools.getTimeoutRule(100000); private final DrillConfig c = DrillConfig.create(); private void testHJMockScanCommon(final DrillbitContext bitContext, UserClientConnection connection, String physicalPlan, int expectedRows) throws Throwable { mockDrillbitContext(bitContext); final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(c); final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile(physicalPlan), Charsets.UTF_8)); final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c); final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry); final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next())); int totalRecordCount = 0; while (exec.next()) { totalRecordCount += exec.getRecordCount(); } exec.close(); assertEquals(expectedRows, totalRecordCount); System.out.println("Total Record Count: " + totalRecordCount); if (context.getFailureCause() != null) { throw context.getFailureCause(); } assertTrue(!context.isFailed()); } @Test public void multiBatchEqualityJoin(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable { testHJMockScanCommon(bitContext, connection, "/join/hash_join_multi_batch.json", 200000); } @Test public void multiBatchRightOuterJoin(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable { testHJMockScanCommon(bitContext, connection, "/join/hj_right_outer_multi_batch.json", 100000); } @Test public void multiBatchLeftOuterJoin(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable { testHJMockScanCommon(bitContext, connection, "/join/hj_left_outer_multi_batch.json", 100000); } @Test public void simpleEqualityJoin() throws Throwable { // Function checks hash join with single equality condition try (RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet(); Drillbit bit = new Drillbit(CONFIG, serviceSet); DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator())) { // run query. bit.run(); client.connect(); List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/join/hash_join.json"), Charsets.UTF_8) .replace("#{TEST_FILE_1}", FileUtils.getResourceAsFile("/build_side_input.json").toURI().toString()) .replace("#{TEST_FILE_2}", FileUtils.getResourceAsFile("/probe_side_input.json").toURI().toString())); RecordBatchLoader batchLoader = new RecordBatchLoader(bit.getContext().getAllocator()); QueryDataBatch batch = results.get(1); assertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData())); Iterator<VectorWrapper<?>> itr = batchLoader.iterator(); // Just test the join key long colA[] = {1, 1, 2, 2, 1, 1}; // Check the output of decimal9 ValueVector.Accessor intAccessor1 = itr.next().getValueVector().getAccessor(); for (int i = 0; i < intAccessor1.getValueCount(); i++) { assertEquals(intAccessor1.getObject(i), colA[i]); } assertEquals(6, intAccessor1.getValueCount()); batchLoader.clear(); for (QueryDataBatch result : results) { result.release(); } } } @Test public void hjWithExchange(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable { // Function tests with hash join with exchanges try (final RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet(); final Drillbit bit = new Drillbit(CONFIG, serviceSet); final DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator())) { // run query. bit.run(); client.connect(); final List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/join/hj_exchanges.json"), Charsets.UTF_8)); int count = 0; for (final QueryDataBatch b : results) { if (b.getHeader().getRowCount() != 0) { count += b.getHeader().getRowCount(); } b.release(); } System.out.println("Total records: " + count); assertEquals(25, count); } } @Test public void multipleConditionJoin(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable { // Function tests hash join with multiple join conditions try (final RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet(); final Drillbit bit = new Drillbit(CONFIG, serviceSet); final DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator())) { // run query. bit.run(); client.connect(); final List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/join/hj_multi_condition_join.json"), Charsets.UTF_8) .replace("#{TEST_FILE_1}", FileUtils.getResourceAsFile("/build_side_input.json").toURI().toString()) .replace("#{TEST_FILE_2}", FileUtils.getResourceAsFile("/probe_side_input.json").toURI().toString())); final RecordBatchLoader batchLoader = new RecordBatchLoader(bit.getContext().getAllocator()); final QueryDataBatch batch = results.get(1); assertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData())); final Iterator<VectorWrapper<?>> itr = batchLoader.iterator(); // Just test the join key final long colA[] = {1, 2, 1}; final long colC[] = {100, 200, 500}; // Check the output of decimal9 final ValueVector.Accessor intAccessor1 = itr.next().getValueVector().getAccessor(); final ValueVector.Accessor intAccessor2 = itr.next().getValueVector().getAccessor(); for (int i = 0; i < intAccessor1.getValueCount(); i++) { assertEquals(intAccessor1.getObject(i), colA[i]); assertEquals(intAccessor2.getObject(i), colC[i]); } assertEquals(3, intAccessor1.getValueCount()); batchLoader.clear(); for (final QueryDataBatch result : results) { result.release(); } } } @Test public void hjWithExchange1(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable { // Another test for hash join with exchanges try (final RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet(); final Drillbit bit = new Drillbit(CONFIG, serviceSet); final DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator())) { // run query. bit.run(); client.connect(); final List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/join/hj_exchanges1.json"), Charsets.UTF_8)); int count = 0; for (final QueryDataBatch b : results) { if (b.getHeader().getRowCount() != 0) { count += b.getHeader().getRowCount(); } b.release(); } System.out.println("Total records: " + count); assertEquals(272, count); } } @Test public void testHashJoinExprInCondition() throws Exception { final RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet(); try (final Drillbit bit1 = new Drillbit(CONFIG, serviceSet); final DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator());) { bit1.run(); client.connect(); final List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/join/hashJoinExpr.json"), Charsets.UTF_8)); int count = 0; for (final QueryDataBatch b : results) { if (b.getHeader().getRowCount() != 0) { count += b.getHeader().getRowCount(); } b.release(); } assertEquals(10, count); } } }
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.identitymanagement.model; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.identitymanagement.AmazonIdentityManagement#putGroupPolicy(PutGroupPolicyRequest) PutGroupPolicy operation}. * <p> * Adds (or updates) a policy document associated with the specified group. For information about policies, refer to <a * href="http://docs.amazonwebservices.com/IAM/latest/UserGuide/index.html?PoliciesOverview.html"> Overview of Policies </a> in <i>Using AWS Identity * and Access Management</i> . * </p> * <p> * For information about limits on the number of policies you can associate with a group, see <a * href="http://docs.amazonwebservices.com/IAM/latest/UserGuide/index.html?LimitationsOnEntities.html"> Limitations on IAM Entities </a> in <i>Using AWS * Identity and Access Management</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use POST rather than GET when calling PutGroupPolicy. For information about setting up * signatures and authorization through the API, go to Signing AWS API Requests in the AWS General Reference. For general information about using the * Query API with IAM, go to Making Query Requests in Using IAM. * </p> * * @see com.amazonaws.services.identitymanagement.AmazonIdentityManagement#putGroupPolicy(PutGroupPolicyRequest) */ public class PutGroupPolicyRequest extends AmazonWebServiceRequest { /** * Name of the group to associate the policy with. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> */ private String groupName; /** * Name of the policy document. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> */ private String policyName; /** * The policy document. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 131072<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> */ private String policyDocument; /** * Default constructor for a new PutGroupPolicyRequest object. Callers should use the * setter or fluent setter (with...) methods to initialize this object after creating it. */ public PutGroupPolicyRequest() {} /** * Constructs a new PutGroupPolicyRequest object. * Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param groupName Name of the group to associate the policy with. * @param policyName Name of the policy document. * @param policyDocument The policy document. */ public PutGroupPolicyRequest(String groupName, String policyName, String policyDocument) { this.groupName = groupName; this.policyName = policyName; this.policyDocument = policyDocument; } /** * Name of the group to associate the policy with. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @return Name of the group to associate the policy with. */ public String getGroupName() { return groupName; } /** * Name of the group to associate the policy with. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param groupName Name of the group to associate the policy with. */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * Name of the group to associate the policy with. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param groupName Name of the group to associate the policy with. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutGroupPolicyRequest withGroupName(String groupName) { this.groupName = groupName; return this; } /** * Name of the policy document. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @return Name of the policy document. */ public String getPolicyName() { return policyName; } /** * Name of the policy document. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param policyName Name of the policy document. */ public void setPolicyName(String policyName) { this.policyName = policyName; } /** * Name of the policy document. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param policyName Name of the policy document. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutGroupPolicyRequest withPolicyName(String policyName) { this.policyName = policyName; return this; } /** * The policy document. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 131072<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> * * @return The policy document. */ public String getPolicyDocument() { return policyDocument; } /** * The policy document. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 131072<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> * * @param policyDocument The policy document. */ public void setPolicyDocument(String policyDocument) { this.policyDocument = policyDocument; } /** * The policy document. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 131072<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> * * @param policyDocument The policy document. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutGroupPolicyRequest withPolicyDocument(String policyDocument) { this.policyDocument = policyDocument; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (groupName != null) sb.append("GroupName: " + groupName + ", "); if (policyName != null) sb.append("PolicyName: " + policyName + ", "); if (policyDocument != null) sb.append("PolicyDocument: " + policyDocument + ", "); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGroupName() == null) ? 0 : getGroupName().hashCode()); hashCode = prime * hashCode + ((getPolicyName() == null) ? 0 : getPolicyName().hashCode()); hashCode = prime * hashCode + ((getPolicyDocument() == null) ? 0 : getPolicyDocument().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PutGroupPolicyRequest == false) return false; PutGroupPolicyRequest other = (PutGroupPolicyRequest)obj; if (other.getGroupName() == null ^ this.getGroupName() == null) return false; if (other.getGroupName() != null && other.getGroupName().equals(this.getGroupName()) == false) return false; if (other.getPolicyName() == null ^ this.getPolicyName() == null) return false; if (other.getPolicyName() != null && other.getPolicyName().equals(this.getPolicyName()) == false) return false; if (other.getPolicyDocument() == null ^ this.getPolicyDocument() == null) return false; if (other.getPolicyDocument() != null && other.getPolicyDocument().equals(this.getPolicyDocument()) == false) return false; return true; } }
package fr.jmini.asciidoctorj.testcases; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.asciidoctor.OptionsBuilder; import org.asciidoctor.ast.Cell; import org.asciidoctor.ast.Column; import org.asciidoctor.ast.Document; import org.asciidoctor.ast.Row; import org.asciidoctor.ast.Table; public class TableBorderGridNoneTestCase implements AdocTestCase { public static final String ASCIIDOC = "" + "[grid=rows]\n" + "|===\n" + "|Name of Column 1 |Name of Column 2 |Name of Column 3\n" + "\n" + "|Cell in column 1, row 1\n" + "|Cell in column 2, row 1\n" + "|Cell in column 3, row 1\n" + "\n" + "|Cell in column 1, row 2\n" + "|Cell in column 2, row 2\n" + "|Cell in column 3, row 2\n" + "|==="; @Override public String getAdocInput() { return ASCIIDOC; } @Override public Map<String, Object> getInputOptions() { return OptionsBuilder.options() .asMap(); } // tag::expected-html[] public static final String EXPECTED_HTML = "" + "<table class=\"tableblock frame-all grid-rows spread\">\n" + "<colgroup>\n" + "<col style=\"width: 33.3333%;\" />\n" + "<col style=\"width: 33.3333%;\" />\n" + "<col style=\"width: 33.3334%;\" />\n" + "</colgroup>\n" + "<thead>\n" + "<tr>\n" + "<th class=\"tableblock halign-left valign-top\">Name of Column 1</th>\n" + "<th class=\"tableblock halign-left valign-top\">Name of Column 2</th>\n" + "<th class=\"tableblock halign-left valign-top\">Name of Column 3</th>\n" + "</tr>\n" + "</thead>\n" + "<tbody>\n" + "<tr>\n" + "<td class=\"tableblock halign-left valign-top\"><p class=\"tableblock\">Cell in column 1, row 1</p></td>\n" + "<td class=\"tableblock halign-left valign-top\"><p class=\"tableblock\">Cell in column 2, row 1</p></td>\n" + "<td class=\"tableblock halign-left valign-top\"><p class=\"tableblock\">Cell in column 3, row 1</p></td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"tableblock halign-left valign-top\"><p class=\"tableblock\">Cell in column 1, row 2</p></td>\n" + "<td class=\"tableblock halign-left valign-top\"><p class=\"tableblock\">Cell in column 2, row 2</p></td>\n" + "<td class=\"tableblock halign-left valign-top\"><p class=\"tableblock\">Cell in column 3, row 2</p></td>\n" + "</tr>\n" + "</tbody>\n" + "</table>"; // end::expected-html[] @Override public String getHtmlOutput() { return EXPECTED_HTML; } @Override // tag::assert-code[] public void checkAst(Document astDocument) { Document document1 = astDocument; assertThat(document1.getId()).isNull(); assertThat(document1.getNodeName()).isEqualTo("document"); assertThat(document1.getParent()).isNull(); assertThat(document1.getContext()).isEqualTo("document"); assertThat(document1.getDocument()).isSameAs(document1); assertThat(document1.isInline()).isFalse(); assertThat(document1.isBlock()).isTrue(); assertThat(document1.getAttributes()).containsEntry("doctype", "article") .containsEntry("example-caption", "Example") .containsEntry("figure-caption", "Figure") .containsEntry("filetype", "html") .containsEntry("notitle", "") .containsEntry("prewrap", "") .containsEntry("table-caption", "Table"); assertThat(document1.getRoles()).isNullOrEmpty(); assertThat(document1.isReftext()).isFalse(); assertThat(document1.getReftext()).isNull(); assertThat(document1.getCaption()).isNull(); assertThat(document1.getTitle()).isNull(); assertThat(document1.getStyle()).isNull(); assertThat(document1.getLevel()).isEqualTo(0); assertThat(document1.getContentModel()).isEqualTo("compound"); assertThat(document1.getSourceLocation()).isNull(); assertThat(document1.getSubstitutions()).isNullOrEmpty(); assertThat(document1.getBlocks()).hasSize(1); Table table1 = (Table) document1.getBlocks() .get(0); assertThat(table1.getId()).isNull(); assertThat(table1.getNodeName()).isEqualTo("table"); assertThat(table1.getParent()).isSameAs(document1); assertThat(table1.getContext()).isEqualTo("table"); assertThat(table1.getDocument()).isSameAs(document1); assertThat(table1.isInline()).isFalse(); assertThat(table1.isBlock()).isTrue(); assertThat(table1.getAttributes()).containsEntry("colcount", 3L) .containsEntry("grid", "rows") .containsEntry("header-option", "") .containsEntry("options", "header") .containsEntry("rowcount", 3L) .containsEntry("style", "table") .containsEntry("tablepcwidth", 100L); assertThat(table1.getRoles()).isNullOrEmpty(); assertThat(table1.isReftext()).isFalse(); assertThat(table1.getReftext()).isNull(); assertThat(table1.getCaption()).isNull(); assertThat(table1.getTitle()).isNull(); assertThat(table1.getStyle()).isEqualTo("table"); assertThat(table1.getLevel()).isEqualTo(0); assertThat(table1.getContentModel()).isEqualTo("compound"); assertThat(table1.getSourceLocation()).isNull(); assertThat(table1.getSubstitutions()).isNullOrEmpty(); assertThat(table1.getBlocks()).isNullOrEmpty(); assertThat(table1.hasHeaderOption()).isTrue(); assertThat(table1.getColumns()).hasSize(3); Column column1 = (Column) table1.getColumns() .get(0); assertThat(column1.getId()).isNull(); assertThat(column1.getNodeName()).isEqualTo("column"); assertThat(column1.getParent()).isSameAs(table1); assertThat(column1.getContext()).isEqualTo("column"); assertThat(column1.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { column1.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { column1.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(column1.getAttributes()).containsEntry("colnumber", 1L) .containsEntry("colpcwidth", 33.3333) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(column1.getRoles()).isNullOrEmpty(); assertThat(column1.isReftext()).isFalse(); assertThat(column1.getReftext()).isNull(); assertThat(column1.getStyle()).isNull(); assertThat(column1.getTable()).isSameAs(table1); assertThat(column1.getColumnNumber()).isEqualTo(1); assertThat(column1.getWidth()).isEqualTo(1); assertThat(column1.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(column1.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); Column column2 = (Column) table1.getColumns() .get(1); assertThat(column2.getId()).isNull(); assertThat(column2.getNodeName()).isEqualTo("column"); assertThat(column2.getParent()).isSameAs(table1); assertThat(column2.getContext()).isEqualTo("column"); assertThat(column2.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { column2.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { column2.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(column2.getAttributes()).containsEntry("colnumber", 2L) .containsEntry("colpcwidth", 33.3333) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(column2.getRoles()).isNullOrEmpty(); assertThat(column2.isReftext()).isFalse(); assertThat(column2.getReftext()).isNull(); assertThat(column2.getStyle()).isNull(); assertThat(column2.getTable()).isSameAs(table1); assertThat(column2.getColumnNumber()).isEqualTo(2); assertThat(column2.getWidth()).isEqualTo(1); assertThat(column2.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(column2.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); Column column3 = (Column) table1.getColumns() .get(2); assertThat(column3.getId()).isNull(); assertThat(column3.getNodeName()).isEqualTo("column"); assertThat(column3.getParent()).isSameAs(table1); assertThat(column3.getContext()).isEqualTo("column"); assertThat(column3.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { column3.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { column3.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(column3.getAttributes()).containsEntry("colnumber", 3L) .containsEntry("colpcwidth", 33.3334) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(column3.getRoles()).isNullOrEmpty(); assertThat(column3.isReftext()).isFalse(); assertThat(column3.getReftext()).isNull(); assertThat(column3.getStyle()).isNull(); assertThat(column3.getTable()).isSameAs(table1); assertThat(column3.getColumnNumber()).isEqualTo(3); assertThat(column3.getWidth()).isEqualTo(1); assertThat(column3.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(column3.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(table1.getHeader()).hasSize(1); Row row1 = (Row) table1.getHeader() .get(0); assertThat(row1.getCells()).hasSize(3); Cell cell1 = (Cell) row1.getCells() .get(0); assertThat(cell1.getId()).isNull(); assertThat(cell1.getNodeName()).isEqualTo("cell"); assertThat(cell1.getParent()).isSameAs(column1); assertThat(cell1.getContext()).isEqualTo("cell"); assertThat(cell1.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell1.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell1.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell1.getAttributes()).containsEntry("colnumber", 1L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell1.getRoles()).isNullOrEmpty(); assertThat(cell1.isReftext()).isFalse(); assertThat(cell1.getReftext()).isNull(); assertThat(cell1.getColumn()).isSameAs(column1); assertThat(cell1.getColspan()).isEqualTo(0); assertThat(cell1.getRowspan()).isEqualTo(0); assertThat(cell1.getText()).isEqualTo("Name of Column 1"); assertThat(cell1.getSource()).isEqualTo("Name of Column 1"); assertThat(cell1.getStyle()).isNull(); assertThat(cell1.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell1.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell1.getInnerDocument()).isNull(); Cell cell2 = (Cell) row1.getCells() .get(1); assertThat(cell2.getId()).isNull(); assertThat(cell2.getNodeName()).isEqualTo("cell"); assertThat(cell2.getParent()).isSameAs(column2); assertThat(cell2.getContext()).isEqualTo("cell"); assertThat(cell2.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell2.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell2.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell2.getAttributes()).containsEntry("colnumber", 2L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell2.getRoles()).isNullOrEmpty(); assertThat(cell2.isReftext()).isFalse(); assertThat(cell2.getReftext()).isNull(); assertThat(cell2.getColumn()).isSameAs(column2); assertThat(cell2.getColspan()).isEqualTo(0); assertThat(cell2.getRowspan()).isEqualTo(0); assertThat(cell2.getText()).isEqualTo("Name of Column 2"); assertThat(cell2.getSource()).isEqualTo("Name of Column 2"); assertThat(cell2.getStyle()).isNull(); assertThat(cell2.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell2.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell2.getInnerDocument()).isNull(); Cell cell3 = (Cell) row1.getCells() .get(2); assertThat(cell3.getId()).isNull(); assertThat(cell3.getNodeName()).isEqualTo("cell"); assertThat(cell3.getParent()).isSameAs(column3); assertThat(cell3.getContext()).isEqualTo("cell"); assertThat(cell3.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell3.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell3.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell3.getAttributes()).containsEntry("colnumber", 3L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell3.getRoles()).isNullOrEmpty(); assertThat(cell3.isReftext()).isFalse(); assertThat(cell3.getReftext()).isNull(); assertThat(cell3.getColumn()).isSameAs(column3); assertThat(cell3.getColspan()).isEqualTo(0); assertThat(cell3.getRowspan()).isEqualTo(0); assertThat(cell3.getText()).isEqualTo("Name of Column 3"); assertThat(cell3.getSource()).isEqualTo("Name of Column 3"); assertThat(cell3.getStyle()).isNull(); assertThat(cell3.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell3.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell3.getInnerDocument()).isNull(); assertThat(table1.getFooter()).isNullOrEmpty(); assertThat(table1.getBody()).hasSize(2); Row row2 = (Row) table1.getBody() .get(0); assertThat(row2.getCells()).hasSize(3); Cell cell4 = (Cell) row2.getCells() .get(0); assertThat(cell4.getId()).isNull(); assertThat(cell4.getNodeName()).isEqualTo("cell"); assertThat(cell4.getParent()).isSameAs(column1); assertThat(cell4.getContext()).isEqualTo("cell"); assertThat(cell4.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell4.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell4.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell4.getAttributes()).containsEntry("colnumber", 1L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell4.getRoles()).isNullOrEmpty(); assertThat(cell4.isReftext()).isFalse(); assertThat(cell4.getReftext()).isNull(); assertThat(cell4.getColumn()).isSameAs(column1); assertThat(cell4.getColspan()).isEqualTo(0); assertThat(cell4.getRowspan()).isEqualTo(0); assertThat(cell4.getText()).isEqualTo("Cell in column 1, row 1"); assertThat(cell4.getSource()).isEqualTo("Cell in column 1, row 1"); assertThat(cell4.getStyle()).isNull(); assertThat(cell4.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell4.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell4.getInnerDocument()).isNull(); Cell cell5 = (Cell) row2.getCells() .get(1); assertThat(cell5.getId()).isNull(); assertThat(cell5.getNodeName()).isEqualTo("cell"); assertThat(cell5.getParent()).isSameAs(column2); assertThat(cell5.getContext()).isEqualTo("cell"); assertThat(cell5.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell5.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell5.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell5.getAttributes()).containsEntry("colnumber", 2L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell5.getRoles()).isNullOrEmpty(); assertThat(cell5.isReftext()).isFalse(); assertThat(cell5.getReftext()).isNull(); assertThat(cell5.getColumn()).isSameAs(column2); assertThat(cell5.getColspan()).isEqualTo(0); assertThat(cell5.getRowspan()).isEqualTo(0); assertThat(cell5.getText()).isEqualTo("Cell in column 2, row 1"); assertThat(cell5.getSource()).isEqualTo("Cell in column 2, row 1"); assertThat(cell5.getStyle()).isNull(); assertThat(cell5.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell5.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell5.getInnerDocument()).isNull(); Cell cell6 = (Cell) row2.getCells() .get(2); assertThat(cell6.getId()).isNull(); assertThat(cell6.getNodeName()).isEqualTo("cell"); assertThat(cell6.getParent()).isSameAs(column3); assertThat(cell6.getContext()).isEqualTo("cell"); assertThat(cell6.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell6.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell6.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell6.getAttributes()).containsEntry("colnumber", 3L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell6.getRoles()).isNullOrEmpty(); assertThat(cell6.isReftext()).isFalse(); assertThat(cell6.getReftext()).isNull(); assertThat(cell6.getColumn()).isSameAs(column3); assertThat(cell6.getColspan()).isEqualTo(0); assertThat(cell6.getRowspan()).isEqualTo(0); assertThat(cell6.getText()).isEqualTo("Cell in column 3, row 1"); assertThat(cell6.getSource()).isEqualTo("Cell in column 3, row 1"); assertThat(cell6.getStyle()).isNull(); assertThat(cell6.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell6.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell6.getInnerDocument()).isNull(); Row row3 = (Row) table1.getBody() .get(1); assertThat(row3.getCells()).hasSize(3); Cell cell7 = (Cell) row3.getCells() .get(0); assertThat(cell7.getId()).isNull(); assertThat(cell7.getNodeName()).isEqualTo("cell"); assertThat(cell7.getParent()).isSameAs(column1); assertThat(cell7.getContext()).isEqualTo("cell"); assertThat(cell7.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell7.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell7.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell7.getAttributes()).containsEntry("colnumber", 1L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell7.getRoles()).isNullOrEmpty(); assertThat(cell7.isReftext()).isFalse(); assertThat(cell7.getReftext()).isNull(); assertThat(cell7.getColumn()).isSameAs(column1); assertThat(cell7.getColspan()).isEqualTo(0); assertThat(cell7.getRowspan()).isEqualTo(0); assertThat(cell7.getText()).isEqualTo("Cell in column 1, row 2"); assertThat(cell7.getSource()).isEqualTo("Cell in column 1, row 2"); assertThat(cell7.getStyle()).isNull(); assertThat(cell7.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell7.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell7.getInnerDocument()).isNull(); Cell cell8 = (Cell) row3.getCells() .get(1); assertThat(cell8.getId()).isNull(); assertThat(cell8.getNodeName()).isEqualTo("cell"); assertThat(cell8.getParent()).isSameAs(column2); assertThat(cell8.getContext()).isEqualTo("cell"); assertThat(cell8.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell8.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell8.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell8.getAttributes()).containsEntry("colnumber", 2L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell8.getRoles()).isNullOrEmpty(); assertThat(cell8.isReftext()).isFalse(); assertThat(cell8.getReftext()).isNull(); assertThat(cell8.getColumn()).isSameAs(column2); assertThat(cell8.getColspan()).isEqualTo(0); assertThat(cell8.getRowspan()).isEqualTo(0); assertThat(cell8.getText()).isEqualTo("Cell in column 2, row 2"); assertThat(cell8.getSource()).isEqualTo("Cell in column 2, row 2"); assertThat(cell8.getStyle()).isNull(); assertThat(cell8.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell8.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell8.getInnerDocument()).isNull(); Cell cell9 = (Cell) row3.getCells() .get(2); assertThat(cell9.getId()).isNull(); assertThat(cell9.getNodeName()).isEqualTo("cell"); assertThat(cell9.getParent()).isSameAs(column3); assertThat(cell9.getContext()).isEqualTo("cell"); assertThat(cell9.getDocument()).isSameAs(document1); assertThatThrownBy(() -> { cell9.isInline(); }).hasMessageContaining("NotImplementedError"); assertThatThrownBy(() -> { cell9.isBlock(); }).hasMessageContaining("NotImplementedError"); assertThat(cell9.getAttributes()).containsEntry("colnumber", 3L) .containsEntry("halign", "left") .containsEntry("valign", "top") .containsEntry("width", 1L); assertThat(cell9.getRoles()).isNullOrEmpty(); assertThat(cell9.isReftext()).isFalse(); assertThat(cell9.getReftext()).isNull(); assertThat(cell9.getColumn()).isSameAs(column3); assertThat(cell9.getColspan()).isEqualTo(0); assertThat(cell9.getRowspan()).isEqualTo(0); assertThat(cell9.getText()).isEqualTo("Cell in column 3, row 2"); assertThat(cell9.getSource()).isEqualTo("Cell in column 3, row 2"); assertThat(cell9.getStyle()).isNull(); assertThat(cell9.getHorizontalAlignment()).isEqualTo(Table.HorizontalAlignment.LEFT); assertThat(cell9.getVerticalAlignment()).isEqualTo(Table.VerticalAlignment.TOP); assertThat(cell9.getInnerDocument()).isNull(); assertThat(table1.getFrame()).isEqualTo("all"); assertThat(table1.getGrid()).isEqualTo("rows"); assertThat(document1.getStructuredDoctitle()).isNull(); assertThat(document1.getDoctitle()).isNull(); assertThat(document1.getOptions()).containsEntry("header_footer", false); } // end::assert-code[] @Override // tag::mock-code[] public Document createMock() { Document mockDocument1 = mock(Document.class); when(mockDocument1.getId()).thenReturn(null); when(mockDocument1.getNodeName()).thenReturn("document"); when(mockDocument1.getParent()).thenReturn(null); when(mockDocument1.getContext()).thenReturn("document"); when(mockDocument1.getDocument()).thenReturn(mockDocument1); when(mockDocument1.isInline()).thenReturn(false); when(mockDocument1.isBlock()).thenReturn(true); Map<String, Object> map1 = new HashMap<>(); map1.put("doctype", "article"); map1.put("example-caption", "Example"); map1.put("figure-caption", "Figure"); map1.put("filetype", "html"); map1.put("notitle", ""); map1.put("prewrap", ""); map1.put("table-caption", "Table"); when(mockDocument1.getAttributes()).thenReturn(map1); when(mockDocument1.getRoles()).thenReturn(Collections.emptyList()); when(mockDocument1.isReftext()).thenReturn(false); when(mockDocument1.getReftext()).thenReturn(null); when(mockDocument1.getCaption()).thenReturn(null); when(mockDocument1.getTitle()).thenReturn(null); when(mockDocument1.getStyle()).thenReturn(null); when(mockDocument1.getLevel()).thenReturn(0); when(mockDocument1.getContentModel()).thenReturn("compound"); when(mockDocument1.getSourceLocation()).thenReturn(null); when(mockDocument1.getSubstitutions()).thenReturn(Collections.emptyList()); Table mockTable1 = mock(Table.class); when(mockTable1.getId()).thenReturn(null); when(mockTable1.getNodeName()).thenReturn("table"); when(mockTable1.getParent()).thenReturn(mockDocument1); when(mockTable1.getContext()).thenReturn("table"); when(mockTable1.getDocument()).thenReturn(mockDocument1); when(mockTable1.isInline()).thenReturn(false); when(mockTable1.isBlock()).thenReturn(true); Map<String, Object> map2 = new HashMap<>(); map2.put("colcount", 3L); map2.put("grid", "rows"); map2.put("header-option", ""); map2.put("options", "header"); map2.put("rowcount", 3L); map2.put("style", "table"); map2.put("tablepcwidth", 100L); when(mockTable1.getAttributes()).thenReturn(map2); when(mockTable1.getRoles()).thenReturn(Collections.emptyList()); when(mockTable1.isReftext()).thenReturn(false); when(mockTable1.getReftext()).thenReturn(null); when(mockTable1.getCaption()).thenReturn(null); when(mockTable1.getTitle()).thenReturn(null); when(mockTable1.getStyle()).thenReturn("table"); when(mockTable1.getLevel()).thenReturn(0); when(mockTable1.getContentModel()).thenReturn("compound"); when(mockTable1.getSourceLocation()).thenReturn(null); when(mockTable1.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockTable1.getBlocks()).thenReturn(Collections.emptyList()); when(mockTable1.hasHeaderOption()).thenReturn(true); Column mockColumn1 = mock(Column.class); when(mockColumn1.getId()).thenReturn(null); when(mockColumn1.getNodeName()).thenReturn("column"); when(mockColumn1.getParent()).thenReturn(mockTable1); when(mockColumn1.getContext()).thenReturn("column"); when(mockColumn1.getDocument()).thenReturn(mockDocument1); when(mockColumn1.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockColumn1.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map3 = new HashMap<>(); map3.put("colnumber", 1L); map3.put("colpcwidth", 33.3333); map3.put("halign", "left"); map3.put("valign", "top"); map3.put("width", 1L); when(mockColumn1.getAttributes()).thenReturn(map3); when(mockColumn1.getRoles()).thenReturn(Collections.emptyList()); when(mockColumn1.isReftext()).thenReturn(false); when(mockColumn1.getReftext()).thenReturn(null); when(mockColumn1.getStyle()).thenReturn(null); when(mockColumn1.getTable()).thenReturn(mockTable1); when(mockColumn1.getColumnNumber()).thenReturn(1); when(mockColumn1.getWidth()).thenReturn(1); when(mockColumn1.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockColumn1.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); Column mockColumn2 = mock(Column.class); when(mockColumn2.getId()).thenReturn(null); when(mockColumn2.getNodeName()).thenReturn("column"); when(mockColumn2.getParent()).thenReturn(mockTable1); when(mockColumn2.getContext()).thenReturn("column"); when(mockColumn2.getDocument()).thenReturn(mockDocument1); when(mockColumn2.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockColumn2.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map4 = new HashMap<>(); map4.put("colnumber", 2L); map4.put("colpcwidth", 33.3333); map4.put("halign", "left"); map4.put("valign", "top"); map4.put("width", 1L); when(mockColumn2.getAttributes()).thenReturn(map4); when(mockColumn2.getRoles()).thenReturn(Collections.emptyList()); when(mockColumn2.isReftext()).thenReturn(false); when(mockColumn2.getReftext()).thenReturn(null); when(mockColumn2.getStyle()).thenReturn(null); when(mockColumn2.getTable()).thenReturn(mockTable1); when(mockColumn2.getColumnNumber()).thenReturn(2); when(mockColumn2.getWidth()).thenReturn(1); when(mockColumn2.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockColumn2.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); Column mockColumn3 = mock(Column.class); when(mockColumn3.getId()).thenReturn(null); when(mockColumn3.getNodeName()).thenReturn("column"); when(mockColumn3.getParent()).thenReturn(mockTable1); when(mockColumn3.getContext()).thenReturn("column"); when(mockColumn3.getDocument()).thenReturn(mockDocument1); when(mockColumn3.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockColumn3.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map5 = new HashMap<>(); map5.put("colnumber", 3L); map5.put("colpcwidth", 33.3334); map5.put("halign", "left"); map5.put("valign", "top"); map5.put("width", 1L); when(mockColumn3.getAttributes()).thenReturn(map5); when(mockColumn3.getRoles()).thenReturn(Collections.emptyList()); when(mockColumn3.isReftext()).thenReturn(false); when(mockColumn3.getReftext()).thenReturn(null); when(mockColumn3.getStyle()).thenReturn(null); when(mockColumn3.getTable()).thenReturn(mockTable1); when(mockColumn3.getColumnNumber()).thenReturn(3); when(mockColumn3.getWidth()).thenReturn(1); when(mockColumn3.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockColumn3.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockTable1.getColumns()).thenReturn(Arrays.asList(mockColumn1, mockColumn2, mockColumn3)); Row mockRow1 = mock(Row.class); Cell mockCell1 = mock(Cell.class); when(mockCell1.getId()).thenReturn(null); when(mockCell1.getNodeName()).thenReturn("cell"); when(mockCell1.getParent()).thenReturn(mockColumn1); when(mockCell1.getContext()).thenReturn("cell"); when(mockCell1.getDocument()).thenReturn(mockDocument1); when(mockCell1.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell1.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map6 = new HashMap<>(); map6.put("colnumber", 1L); map6.put("halign", "left"); map6.put("valign", "top"); map6.put("width", 1L); when(mockCell1.getAttributes()).thenReturn(map6); when(mockCell1.getRoles()).thenReturn(Collections.emptyList()); when(mockCell1.isReftext()).thenReturn(false); when(mockCell1.getReftext()).thenReturn(null); when(mockCell1.getColumn()).thenReturn(mockColumn1); when(mockCell1.getColspan()).thenReturn(0); when(mockCell1.getRowspan()).thenReturn(0); when(mockCell1.getText()).thenReturn("Name of Column 1"); when(mockCell1.getSource()).thenReturn("Name of Column 1"); when(mockCell1.getStyle()).thenReturn(null); when(mockCell1.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell1.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell1.getInnerDocument()).thenReturn(null); Cell mockCell2 = mock(Cell.class); when(mockCell2.getId()).thenReturn(null); when(mockCell2.getNodeName()).thenReturn("cell"); when(mockCell2.getParent()).thenReturn(mockColumn2); when(mockCell2.getContext()).thenReturn("cell"); when(mockCell2.getDocument()).thenReturn(mockDocument1); when(mockCell2.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell2.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map7 = new HashMap<>(); map7.put("colnumber", 2L); map7.put("halign", "left"); map7.put("valign", "top"); map7.put("width", 1L); when(mockCell2.getAttributes()).thenReturn(map7); when(mockCell2.getRoles()).thenReturn(Collections.emptyList()); when(mockCell2.isReftext()).thenReturn(false); when(mockCell2.getReftext()).thenReturn(null); when(mockCell2.getColumn()).thenReturn(mockColumn2); when(mockCell2.getColspan()).thenReturn(0); when(mockCell2.getRowspan()).thenReturn(0); when(mockCell2.getText()).thenReturn("Name of Column 2"); when(mockCell2.getSource()).thenReturn("Name of Column 2"); when(mockCell2.getStyle()).thenReturn(null); when(mockCell2.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell2.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell2.getInnerDocument()).thenReturn(null); Cell mockCell3 = mock(Cell.class); when(mockCell3.getId()).thenReturn(null); when(mockCell3.getNodeName()).thenReturn("cell"); when(mockCell3.getParent()).thenReturn(mockColumn3); when(mockCell3.getContext()).thenReturn("cell"); when(mockCell3.getDocument()).thenReturn(mockDocument1); when(mockCell3.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell3.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map8 = new HashMap<>(); map8.put("colnumber", 3L); map8.put("halign", "left"); map8.put("valign", "top"); map8.put("width", 1L); when(mockCell3.getAttributes()).thenReturn(map8); when(mockCell3.getRoles()).thenReturn(Collections.emptyList()); when(mockCell3.isReftext()).thenReturn(false); when(mockCell3.getReftext()).thenReturn(null); when(mockCell3.getColumn()).thenReturn(mockColumn3); when(mockCell3.getColspan()).thenReturn(0); when(mockCell3.getRowspan()).thenReturn(0); when(mockCell3.getText()).thenReturn("Name of Column 3"); when(mockCell3.getSource()).thenReturn("Name of Column 3"); when(mockCell3.getStyle()).thenReturn(null); when(mockCell3.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell3.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell3.getInnerDocument()).thenReturn(null); when(mockRow1.getCells()).thenReturn(Arrays.asList(mockCell1, mockCell2, mockCell3)); when(mockTable1.getHeader()).thenReturn(Collections.singletonList(mockRow1)); when(mockTable1.getFooter()).thenReturn(Collections.emptyList()); Row mockRow2 = mock(Row.class); Cell mockCell4 = mock(Cell.class); when(mockCell4.getId()).thenReturn(null); when(mockCell4.getNodeName()).thenReturn("cell"); when(mockCell4.getParent()).thenReturn(mockColumn1); when(mockCell4.getContext()).thenReturn("cell"); when(mockCell4.getDocument()).thenReturn(mockDocument1); when(mockCell4.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell4.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map9 = new HashMap<>(); map9.put("colnumber", 1L); map9.put("halign", "left"); map9.put("valign", "top"); map9.put("width", 1L); when(mockCell4.getAttributes()).thenReturn(map9); when(mockCell4.getRoles()).thenReturn(Collections.emptyList()); when(mockCell4.isReftext()).thenReturn(false); when(mockCell4.getReftext()).thenReturn(null); when(mockCell4.getColumn()).thenReturn(mockColumn1); when(mockCell4.getColspan()).thenReturn(0); when(mockCell4.getRowspan()).thenReturn(0); when(mockCell4.getText()).thenReturn("Cell in column 1, row 1"); when(mockCell4.getSource()).thenReturn("Cell in column 1, row 1"); when(mockCell4.getStyle()).thenReturn(null); when(mockCell4.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell4.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell4.getInnerDocument()).thenReturn(null); Cell mockCell5 = mock(Cell.class); when(mockCell5.getId()).thenReturn(null); when(mockCell5.getNodeName()).thenReturn("cell"); when(mockCell5.getParent()).thenReturn(mockColumn2); when(mockCell5.getContext()).thenReturn("cell"); when(mockCell5.getDocument()).thenReturn(mockDocument1); when(mockCell5.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell5.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map10 = new HashMap<>(); map10.put("colnumber", 2L); map10.put("halign", "left"); map10.put("valign", "top"); map10.put("width", 1L); when(mockCell5.getAttributes()).thenReturn(map10); when(mockCell5.getRoles()).thenReturn(Collections.emptyList()); when(mockCell5.isReftext()).thenReturn(false); when(mockCell5.getReftext()).thenReturn(null); when(mockCell5.getColumn()).thenReturn(mockColumn2); when(mockCell5.getColspan()).thenReturn(0); when(mockCell5.getRowspan()).thenReturn(0); when(mockCell5.getText()).thenReturn("Cell in column 2, row 1"); when(mockCell5.getSource()).thenReturn("Cell in column 2, row 1"); when(mockCell5.getStyle()).thenReturn(null); when(mockCell5.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell5.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell5.getInnerDocument()).thenReturn(null); Cell mockCell6 = mock(Cell.class); when(mockCell6.getId()).thenReturn(null); when(mockCell6.getNodeName()).thenReturn("cell"); when(mockCell6.getParent()).thenReturn(mockColumn3); when(mockCell6.getContext()).thenReturn("cell"); when(mockCell6.getDocument()).thenReturn(mockDocument1); when(mockCell6.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell6.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map11 = new HashMap<>(); map11.put("colnumber", 3L); map11.put("halign", "left"); map11.put("valign", "top"); map11.put("width", 1L); when(mockCell6.getAttributes()).thenReturn(map11); when(mockCell6.getRoles()).thenReturn(Collections.emptyList()); when(mockCell6.isReftext()).thenReturn(false); when(mockCell6.getReftext()).thenReturn(null); when(mockCell6.getColumn()).thenReturn(mockColumn3); when(mockCell6.getColspan()).thenReturn(0); when(mockCell6.getRowspan()).thenReturn(0); when(mockCell6.getText()).thenReturn("Cell in column 3, row 1"); when(mockCell6.getSource()).thenReturn("Cell in column 3, row 1"); when(mockCell6.getStyle()).thenReturn(null); when(mockCell6.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell6.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell6.getInnerDocument()).thenReturn(null); when(mockRow2.getCells()).thenReturn(Arrays.asList(mockCell4, mockCell5, mockCell6)); Row mockRow3 = mock(Row.class); Cell mockCell7 = mock(Cell.class); when(mockCell7.getId()).thenReturn(null); when(mockCell7.getNodeName()).thenReturn("cell"); when(mockCell7.getParent()).thenReturn(mockColumn1); when(mockCell7.getContext()).thenReturn("cell"); when(mockCell7.getDocument()).thenReturn(mockDocument1); when(mockCell7.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell7.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map12 = new HashMap<>(); map12.put("colnumber", 1L); map12.put("halign", "left"); map12.put("valign", "top"); map12.put("width", 1L); when(mockCell7.getAttributes()).thenReturn(map12); when(mockCell7.getRoles()).thenReturn(Collections.emptyList()); when(mockCell7.isReftext()).thenReturn(false); when(mockCell7.getReftext()).thenReturn(null); when(mockCell7.getColumn()).thenReturn(mockColumn1); when(mockCell7.getColspan()).thenReturn(0); when(mockCell7.getRowspan()).thenReturn(0); when(mockCell7.getText()).thenReturn("Cell in column 1, row 2"); when(mockCell7.getSource()).thenReturn("Cell in column 1, row 2"); when(mockCell7.getStyle()).thenReturn(null); when(mockCell7.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell7.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell7.getInnerDocument()).thenReturn(null); Cell mockCell8 = mock(Cell.class); when(mockCell8.getId()).thenReturn(null); when(mockCell8.getNodeName()).thenReturn("cell"); when(mockCell8.getParent()).thenReturn(mockColumn2); when(mockCell8.getContext()).thenReturn("cell"); when(mockCell8.getDocument()).thenReturn(mockDocument1); when(mockCell8.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell8.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map13 = new HashMap<>(); map13.put("colnumber", 2L); map13.put("halign", "left"); map13.put("valign", "top"); map13.put("width", 1L); when(mockCell8.getAttributes()).thenReturn(map13); when(mockCell8.getRoles()).thenReturn(Collections.emptyList()); when(mockCell8.isReftext()).thenReturn(false); when(mockCell8.getReftext()).thenReturn(null); when(mockCell8.getColumn()).thenReturn(mockColumn2); when(mockCell8.getColspan()).thenReturn(0); when(mockCell8.getRowspan()).thenReturn(0); when(mockCell8.getText()).thenReturn("Cell in column 2, row 2"); when(mockCell8.getSource()).thenReturn("Cell in column 2, row 2"); when(mockCell8.getStyle()).thenReturn(null); when(mockCell8.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell8.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell8.getInnerDocument()).thenReturn(null); Cell mockCell9 = mock(Cell.class); when(mockCell9.getId()).thenReturn(null); when(mockCell9.getNodeName()).thenReturn("cell"); when(mockCell9.getParent()).thenReturn(mockColumn3); when(mockCell9.getContext()).thenReturn("cell"); when(mockCell9.getDocument()).thenReturn(mockDocument1); when(mockCell9.isInline()).thenThrow(new UnsupportedOperationException("NotImplementedError")); when(mockCell9.isBlock()).thenThrow(new UnsupportedOperationException("NotImplementedError")); Map<String, Object> map14 = new HashMap<>(); map14.put("colnumber", 3L); map14.put("halign", "left"); map14.put("valign", "top"); map14.put("width", 1L); when(mockCell9.getAttributes()).thenReturn(map14); when(mockCell9.getRoles()).thenReturn(Collections.emptyList()); when(mockCell9.isReftext()).thenReturn(false); when(mockCell9.getReftext()).thenReturn(null); when(mockCell9.getColumn()).thenReturn(mockColumn3); when(mockCell9.getColspan()).thenReturn(0); when(mockCell9.getRowspan()).thenReturn(0); when(mockCell9.getText()).thenReturn("Cell in column 3, row 2"); when(mockCell9.getSource()).thenReturn("Cell in column 3, row 2"); when(mockCell9.getStyle()).thenReturn(null); when(mockCell9.getHorizontalAlignment()).thenReturn(Table.HorizontalAlignment.LEFT); when(mockCell9.getVerticalAlignment()).thenReturn(Table.VerticalAlignment.TOP); when(mockCell9.getInnerDocument()).thenReturn(null); when(mockRow3.getCells()).thenReturn(Arrays.asList(mockCell7, mockCell8, mockCell9)); when(mockTable1.getBody()).thenReturn(Arrays.asList(mockRow2, mockRow3)); when(mockTable1.getFrame()).thenReturn("all"); when(mockTable1.getGrid()).thenReturn("rows"); when(mockDocument1.getBlocks()).thenReturn(Collections.singletonList(mockTable1)); when(mockDocument1.getStructuredDoctitle()).thenReturn(null); when(mockDocument1.getDoctitle()).thenReturn(null); Map<Object, Object> map15 = new HashMap<>(); map15.put("attributes", "{}"); map15.put("header_footer", false); when(mockDocument1.getOptions()).thenReturn(map15); return mockDocument1; } // end::mock-code[] }
package apoc.export.cypher; import apoc.graph.Graphs; import apoc.util.TestUtil; import apoc.util.Util; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.test.TestGraphDatabaseFactory; import java.io.File; import java.io.FileNotFoundException; import java.util.*; import static apoc.export.util.ExportFormat.CYPHER_SHELL; import static apoc.export.util.ExportFormat.NEO4J_SHELL; import static apoc.export.util.ExportFormat.PLAIN_FORMAT; import static apoc.util.MapUtil.map; import static org.junit.Assert.assertEquals; /** * @author mh * @since 22.05.16 */ public class ExportCypherTest { private static final String EXPECTED_NODES = String.format("BEGIN%n" + "CREATE (:`Foo`:`UNIQUE IMPORT LABEL` {`name`:\"foo\", `UNIQUE IMPORT ID`:0});%n" + "CREATE (:`Bar` {`age`:42, `name`:\"bar\"});%n" + "CREATE (:`Bar`:`UNIQUE IMPORT LABEL` {`age`:12, `UNIQUE IMPORT ID`:2});%n" + "COMMIT%n"); private static final String EXPECTED_NODES_MERGE = String.format("BEGIN%n" + "MERGE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`:0}) SET n.`name`=\"foo\", n:`Foo`;%n" + "MERGE (n:`Bar`{`name`:\"bar\"}) SET n.`age`=42;%n" + "MERGE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`:2}) SET n.`age`=12, n:`Bar`;%n" + "COMMIT%n"); private static final String EXPECTED_NODES_MERGE_ON_CREATE_SET = EXPECTED_NODES_MERGE.replaceAll(" SET ", " ON CREATE SET "); private static final String EXPECTED_NODES_EMPTY = String.format("BEGIN%n" + "COMMIT%n"); private static final String EXPECTED_SCHEMA = String.format("BEGIN%n" + "CREATE INDEX ON :`Foo`(`name`);%n" + "CREATE CONSTRAINT ON (node:`Bar`) ASSERT node.`name` IS UNIQUE;%n" + "CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT node.`UNIQUE IMPORT ID` IS UNIQUE;%n" + "COMMIT%n" + "SCHEMA AWAIT%n"); private static final String EXPECTED_SCHEMA_EMPTY = String.format("BEGIN%n" + "COMMIT%n" + "SCHEMA AWAIT%n"); private static final String EXPECTED_INDEXES_AWAIT = String.format("CALL db.awaitIndex(':`Foo`(`name`)');%n" + "CALL db.awaitIndex(':`Bar`(`name`)');%n"); private static final String EXPECTED_RELATIONSHIPS = String.format("BEGIN%n" + "MATCH (n1:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`:0}), (n2:`Bar`{`name`:\"bar\"}) CREATE (n1)-[r:`KNOWS` {`since`:2016}]->(n2);%n" + "COMMIT%n"); private static final String EXPECTED_RELATIONSHIPS_MERGE = String.format("BEGIN%n" + "MATCH (n1:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`:0}), (n2:`Bar`{`name`:\"bar\"}) MERGE (n1)-[r:`KNOWS`]->(n2) SET r.`since`=2016;%n" + "COMMIT%n"); private static final String EXPECTED_RELATIONSHIPS_MERGE_ON_CREATE_SET = EXPECTED_RELATIONSHIPS_MERGE.replaceAll(" SET ", " ON CREATE SET "); private static final String EXPECTED_CLEAN_UP = String.format("BEGIN%n" + "MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`;%n" + "COMMIT%n" + "BEGIN%n" + "DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT node.`UNIQUE IMPORT ID` IS UNIQUE;%n" + "COMMIT%n"); private static final String EXPECTED_CLEAN_UP_EMPTY = String.format("BEGIN%n" + "COMMIT%n" + "BEGIN%n" + "COMMIT%n"); private static final String EXPECTED_ONLY_SCHEMA_NEO4J_SHELL = String.format("BEGIN%n" + "CREATE INDEX ON :`Foo`(`name`);%n" + "CREATE CONSTRAINT ON (node:`Bar`) ASSERT node.`name` IS UNIQUE;%n" + "COMMIT%n" + "SCHEMA AWAIT%n"); private static final String EXPECTED_NEO4J_SHELL = EXPECTED_NODES + EXPECTED_SCHEMA + EXPECTED_RELATIONSHIPS + EXPECTED_CLEAN_UP; private static final String EXPECTED_CYPHER_SHELL = EXPECTED_NEO4J_SHELL .replace(NEO4J_SHELL.begin(), CYPHER_SHELL.begin()) .replace(NEO4J_SHELL.commit(),CYPHER_SHELL.commit()) .replace(NEO4J_SHELL.schemaAwait(), EXPECTED_INDEXES_AWAIT) .replace(NEO4J_SHELL.schemaAwait(),CYPHER_SHELL.schemaAwait()); private static final String EXPECTED_PLAIN = EXPECTED_NEO4J_SHELL .replace(NEO4J_SHELL.begin(), PLAIN_FORMAT.begin()).replace(NEO4J_SHELL.commit(), PLAIN_FORMAT.commit()) .replace(NEO4J_SHELL.schemaAwait(), PLAIN_FORMAT.schemaAwait()); private static final String EXPECTED_NEO4J_MERGE = EXPECTED_NODES_MERGE + EXPECTED_SCHEMA + EXPECTED_RELATIONSHIPS_MERGE + EXPECTED_CLEAN_UP; private static final String EXPECTED_ONLY_SCHEMA_CYPHER_SHELL = EXPECTED_ONLY_SCHEMA_NEO4J_SHELL.replace(NEO4J_SHELL.begin(), CYPHER_SHELL.begin()) .replace(NEO4J_SHELL.commit(), CYPHER_SHELL.commit()).replace(NEO4J_SHELL.schemaAwait(), CYPHER_SHELL.schemaAwait()) + EXPECTED_INDEXES_AWAIT; private static final Map<String, Object> exportConfig = Collections.singletonMap("separateFiles", true); private static GraphDatabaseService db; private static File directory = new File("target/import"); static { //noinspection ResultOfMethodCallIgnored directory.mkdirs(); } @BeforeClass public static void setUp() throws Exception { db = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig(GraphDatabaseSettings.load_csv_file_url_root, directory.getAbsolutePath()) .setConfig("apoc.export.file.enabled", "true").newGraphDatabase(); TestUtil.registerProcedure(db, ExportCypher.class, Graphs.class); db.execute("CREATE INDEX ON :Foo(name)").close(); db.execute("CREATE CONSTRAINT ON (b:Bar) ASSERT b.name IS UNIQUE").close(); db.execute("CREATE (f:Foo {name:'foo'})-[:KNOWS {since:2016}]->(b:Bar {name:'bar',age:42}),(c:Bar {age:12})").close(); } @AfterClass public static void tearDown() { db.shutdown(); } // -- Whole file test -- // @Test public void testExportAllCypherDefault() throws Exception { File output = new File(directory, "all.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.all({file},null)", map("file", output.getAbsolutePath()), (r) -> assertResults(output, r, "database")); assertEquals(EXPECTED_NEO4J_SHELL, readFile(output)); } @Test public void testExportAllCypherForCypherShell() throws Exception { File output = new File(directory, "all.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.all({file},{config})", map("file", output.getAbsolutePath(), "config", Util.map("format", "cypher-shell")), (r) -> assertResults(output, r, "database")); assertEquals(EXPECTED_CYPHER_SHELL, readFile(output)); } @Test public void testExportQueryCypherForNeo4j() throws Exception { File output = new File(directory, "all.cypher"); String query = "MATCH (n) OPTIONAL MATCH p = (n)-[r]-(m) RETURN n,r,m"; TestUtil.testCall(db, "CALL apoc.export.cypher.query({query},{file},{config})", map("file", output.getAbsolutePath(), "query", query, "config", Util.map("format", "neo4j-shell")), (r) -> { }); assertEquals(EXPECTED_NEO4J_SHELL, readFile(output)); } public static String readFile(File output) throws FileNotFoundException { return new Scanner(output).useDelimiter("\\Z").next() + String.format("%n"); } @Test public void testExportGraphCypher() throws Exception { File output = new File(directory, "graph.cypher"); TestUtil.testCall(db, "CALL apoc.graph.fromDB('test',{}) yield graph " + "CALL apoc.export.cypher.graph(graph, {file},null) " + "YIELD nodes, relationships, properties, file, source,format, time " + "RETURN *", map("file", output.getAbsolutePath()), (r) -> assertResults(output, r, "graph")); assertEquals(EXPECTED_NEO4J_SHELL, readFile(output)); } // -- Separate files tests -- // @Test public void testExportAllCypherNodes() throws Exception { File output = new File(directory, "all.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.all({file},{exportConfig})", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "database")); assertEquals(EXPECTED_NODES, readFile(new File(directory, "all.nodes.cypher"))); } @Test public void testExportAllCypherRelationships() throws Exception { File output = new File(directory, "all.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.all({file},{exportConfig})", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "database")); assertEquals(EXPECTED_RELATIONSHIPS, readFile(new File(directory, "all.relationships.cypher"))); } @Test public void testExportAllCypherSchema() throws Exception { File output = new File(directory, "all.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.all({file},{exportConfig})", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "database")); assertEquals(EXPECTED_SCHEMA, readFile(new File(directory, "all.schema.cypher"))); } @Test public void testExportAllCypherCleanUp() throws Exception { File output = new File(directory, "all.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.all({file},{exportConfig})", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "database")); assertEquals(EXPECTED_CLEAN_UP, readFile(new File(directory, "all.cleanup.cypher"))); } @Test public void testExportGraphCypherNodes() throws Exception { File output = new File(directory, "graph.cypher"); TestUtil.testCall(db, "CALL apoc.graph.fromDB('test',{}) yield graph " + "CALL apoc.export.cypher.graph(graph, {file},{exportConfig}) " + "YIELD nodes, relationships, properties, file, source,format, time " + "RETURN *", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "graph")); assertEquals(EXPECTED_NODES, readFile(new File(directory, "graph.nodes.cypher"))); } @Test public void testExportGraphCypherRelationships() throws Exception { File output = new File(directory, "graph.cypher"); TestUtil.testCall(db, "CALL apoc.graph.fromDB('test',{}) yield graph " + "CALL apoc.export.cypher.graph(graph, {file},{exportConfig}) " + "YIELD nodes, relationships, properties, file, source,format, time " + "RETURN *", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "graph")); assertEquals(EXPECTED_RELATIONSHIPS, readFile(new File(directory, "graph.relationships.cypher"))); } @Test public void testExportGraphCypherSchema() throws Exception { File output = new File(directory, "graph.cypher"); TestUtil.testCall(db, "CALL apoc.graph.fromDB('test',{}) yield graph " + "CALL apoc.export.cypher.graph(graph, {file},{exportConfig}) " + "YIELD nodes, relationships, properties, file, source,format, time " + "RETURN *", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "graph")); assertEquals(EXPECTED_SCHEMA, readFile(new File(directory, "graph.schema.cypher"))); } @Test public void testExportGraphCypherCleanUp() throws Exception { File output = new File(directory, "graph.cypher"); TestUtil.testCall(db, "CALL apoc.graph.fromDB('test',{}) yield graph " + "CALL apoc.export.cypher.graph(graph, {file},{exportConfig}) " + "YIELD nodes, relationships, properties, file, source,format, time " + "RETURN *", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> assertResults(output, r, "graph")); assertEquals(EXPECTED_CLEAN_UP, readFile(new File(directory, "graph.cleanup.cypher"))); } private void assertResults(File output, Map<String, Object> r, final String source) { assertEquals(3L, r.get("nodes")); assertEquals(1L, r.get("relationships")); assertEquals(5L, r.get("properties")); assertEquals(output.getAbsolutePath(), r.get("file")); assertEquals(source + ": nodes(3), rels(1)", r.get("source")); assertEquals("cypher", r.get("format")); assertEquals(true, ((long) r.get("time")) >= 0); } @Test public void testExportQueryCypherPlainFormat() throws Exception { File output = new File(directory, "all.cypher"); String query = "MATCH (n) OPTIONAL MATCH p = (n)-[r]-(m) RETURN n,r,m"; TestUtil.testCall(db, "CALL apoc.export.cypher.query({query},{file},{config})", map("file", output.getAbsolutePath(), "query", query, "config", Util.map("format", "plain")), (r) -> { }); assertEquals(EXPECTED_PLAIN, readFile(output)); } @Test public void testExportQueryCypherFormatUpdateAll() throws Exception { File output = new File(directory, "all.cypher"); String query = "MATCH (n) OPTIONAL MATCH p = (n)-[r]-(m) RETURN n,r,m"; TestUtil.testCall(db, "CALL apoc.export.cypher.query({query},{file},{config})", map("file", output.getAbsolutePath(), "query", query, "config", Util.map("format", "neo4j-shell","cypherFormat","updateAll")), (r) -> { }); assertEquals(EXPECTED_NEO4J_MERGE, readFile(output)); } @Test public void testExportQueryCypherFormatAddStructure() throws Exception { File output = new File(directory, "all.cypher"); String query = "MATCH (n) OPTIONAL MATCH p = (n)-[r]-(m) RETURN n,r,m"; TestUtil.testCall(db, "CALL apoc.export.cypher.query({query},{file},{config})", map("file", output.getAbsolutePath(), "query", query, "config", Util.map("format", "neo4j-shell","cypherFormat","addStructure")), (r) -> { }); assertEquals(EXPECTED_NODES_MERGE_ON_CREATE_SET + EXPECTED_SCHEMA_EMPTY + EXPECTED_RELATIONSHIPS + EXPECTED_CLEAN_UP_EMPTY, readFile(output)); } @Test public void testExportQueryCypherFormatUpdateStructure() throws Exception { File output = new File(directory, "all.cypher"); String query = "MATCH (n) OPTIONAL MATCH p = (n)-[r]-(m) RETURN n,r,m"; TestUtil.testCall(db, "CALL apoc.export.cypher.query({query},{file},{config})", map("file", output.getAbsolutePath(), "query", query, "config", Util.map("format", "neo4j-shell","cypherFormat","updateStructure")), (r) -> { }); assertEquals(EXPECTED_NODES_EMPTY + EXPECTED_SCHEMA_EMPTY + EXPECTED_RELATIONSHIPS_MERGE_ON_CREATE_SET + EXPECTED_CLEAN_UP_EMPTY, readFile(output)); } @Test public void testExportSchemaCypher() throws Exception { File output = new File(directory, "onlySchema.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.schema({file},{exportConfig})", map("file", output.getAbsolutePath(), "exportConfig", exportConfig), (r) -> {}); assertEquals(EXPECTED_ONLY_SCHEMA_NEO4J_SHELL, readFile(new File(directory, "onlySchema.cypher"))); } @Test public void testExportSchemaCypherShell() throws Exception { File output = new File(directory, "onlySchema.cypher"); TestUtil.testCall(db, "CALL apoc.export.cypher.schema({file},{exportConfig})", map("file", output.getAbsolutePath(), "exportConfig", Util.map("format", "cypher-shell")), (r) -> {}); assertEquals(EXPECTED_ONLY_SCHEMA_CYPHER_SHELL, readFile(new File(directory, "onlySchema.cypher"))); } }
package com.srs.tetris.game; import com.srs.tetris.game.piecegen.PieceGenerator; import com.srs.tetris.player.DirectPlayer; import com.srs.tetris.player.Player; import com.srs.tetris.replay.Replay; import com.srs.tetris.replay.ReplayGenerator; import java.time.Instant; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Queue; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class Game { private GameSettings settings; private PieceGenerator pieceGenerator; private Executor listenerExecutor; private Player player; private GameBoard board; private Piece piece; private Queue<PieceType> nextPieces; private PieceType swapPiece; private Input lastInput; private Input input; private long totalPieces; private long completedLines; private long level; private long score; private long lastFrame; private long dropInterval; private long dropDelay; private long pieceMoveDelay; private long pieceManualDownDelay; private boolean pieceSwapped; private List<GameListener> listeners = new ArrayList<>(); public enum Status { New, InProgress, Complete, Cancelled, Error } private volatile Status status = Status.New; private Throwable error; private Instant startTime; private Instant endTime; private ReplayGenerator replayGenerator; public Game(GameSettings settings) { this.settings = settings; this.player = settings.getPlayer(); this.pieceGenerator = settings.getPieceGenerator(); this.listenerExecutor = settings.getListenerExecutor(); } public void init() { // Validate the game settings. validate(); // Initialize the player. player.init(this); // Set up the game. setupGame(); } public void run() { if (status != Status.New) { throw new IllegalStateException("Cannot run a game that is not new."); } status = Status.InProgress; startTime = Instant.now(); // Start the replay if necessary. startReplay(); try { notifyListeners((listener) -> listener.onGameStart()); // Drop the first piece. dropNextPiece(); while (!isGameOver()) { long frame = System.currentTimeMillis(); long interval = frame - lastFrame; lastFrame = frame; // Get the input state from the player. updateInput(); // Update the game state. updateGame(interval); notifyListeners((listener) -> listener.onFrame()); // Sleep until the next frame. sleep(settings.getFrameInterval()); } } catch (Throwable throwable) { status = Status.Error; error = throwable; throw throwable; } finally { endTime = Instant.now(); notifyListeners((listener) -> listener.onGameOver()); } } private void startReplay() { // Create the replay generator. if (settings.isGenerateReplay()) { // Add the replay generator in first position so it always receives events first. // Otherwise other listeners that try to do something with the replay on game over // won't be dealing with the finished product. listeners.add(0, replayGenerator = new ReplayGenerator(this)); } } private void validate() { if (settings.getInputMode() == GameSettings.InputMode.Direct && !(player instanceof DirectPlayer)) { throw new IllegalStateException("Invalid player for direct input mode"); } } private void setupGame() { // Create the empty game board. board = new GameBoard(settings.getWidth(), settings.getHeight()); // Create a random next piece, and drop it. nextPieces = new ArrayDeque<>(); fillNextPieces(); // Set the time for the last frame. lastFrame = System.currentTimeMillis(); // Assume empty input at the beginning of the game. lastInput = new Input(); input = new Input(); // Calculate the starting level. updateLevel(); } private void updateInput() { // Get input from the player. if (player instanceof DirectPlayer && settings.getInputMode() == GameSettings.InputMode.Direct) { // This is a direct player and we are in direct input mode, so get it directly. DirectInput move = ((DirectPlayer) player).directInput(); lastInput = new Input(); input = new Input(); if (move != null) { if (!move.isSwap()) { // The move is for the current piece. Move it to the correct location and drop it. piece = piece.moveTo(move.getX(), move.getY(), move.getOrientation()); input.setDrop(true); assert board.canPlace(piece) : "Invalid move, could not place on board"; } else { // The move is a swap. input.setSwap(true); } } } else { // Otherwise, it's just a normal input player. lastInput = input; input = player.input(); } } private void updateGame(long interval) { // See if the piece needs to be swapped. updatePieceSwap(); // See if the piece needs to move left or right. updatePieceMoveLeftRight(interval); // See if the piece needs to rotate. updatePieceRotate(); // Check if the current piece needs to move down. updatePieceDrop(interval); } private void updatePieceSwap() { if (input.isSwap() && !pieceSwapped) { // Swap out the current piece PieceType current = piece.getType(); piece = swapPiece != null ? new Piece(swapPiece) : null; swapPiece = current; // Don't allow it to be swapped again until they place this one. pieceSwapped = true; if (piece == null) { // If there was no piece already in the swap position, just drop the next piece. dropNextPiece(); } else { // Otherwise, move the piece up to the top of the board. movePieceToTopCenter(); Piece started = this.piece; notifyListeners((listener) -> listener.onPieceStart(started)); } } } private void updatePieceMoveLeftRight(long interval) { if (!input.isLeft() && !input.isRight()) { // If no buttons are pressed reset the piece move delay to allow the piece to move again immediately. pieceMoveDelay = 0; } else { // Otherwise, if they are holding an arrow only move the piece after the piece delay expires. pieceMoveDelay -= interval; if (pieceMoveDelay <= 0) { boolean moved = false; if (input.isLeft() && board.canPlace(piece.moveLeft())) { piece = piece.moveLeft(); moved = true; } if (input.isRight() && board.canPlace(piece.moveRight())) { piece = piece.moveRight(); moved = true; } // Reset the delay for the next move. if (moved) { pieceMoveDelay = settings.getPieceMoveInterval(); } } } } private void updatePieceRotate() { if (!lastInput.isRotateLeft() && input.isRotateLeft()) { Piece rotated = adjustPieceAfterRotation(piece.rotateLeft()); if (rotated != null) { piece = rotated; } } if (!lastInput.isRotateRight() && input.isRotateRight()) { Piece rotated = adjustPieceAfterRotation(piece.rotateRight()); if (rotated != null) { piece = rotated; } } } private Piece adjustPieceAfterRotation(Piece piece) { Piece original = piece; if (!board.canPlace(piece)) { piece = original.moveLeft(); if (!board.canPlace(piece)) { piece = original.moveRight(); if (!board.canPlace(piece)) { piece = original.moveLeft().moveLeft(); if (!board.canPlace(piece)) { piece = original.moveRight().moveRight(); if (!board.canPlace(piece)) { piece = original.moveDown(); if (!board.canPlace(piece)) { piece = original.moveDown().moveDown(); if (!board.canPlace(piece)) { piece = original.moveUp(); if (!board.canPlace(piece)) { return null; } } } } } } } } return piece; } private void updatePieceDrop(long interval) { boolean moveDown = false; // Check for a manual move down. if (!input.isDown()) { // If they aren't holding down, reset the delay so the piece can be manually moved down immediately. pieceManualDownDelay = 0; } else { // If they are holding down, only allow the piece to go down if the delay expires. pieceManualDownDelay -= interval; if (pieceManualDownDelay <= 0) { // The delay expired, so move it down. moveDown = true; // Reset the manual delay until it moves down again. pieceManualDownDelay = settings.getPieceManualDownInterval(); } } // Check if the automatic drop delay is expired. dropDelay -= interval; if (dropDelay <= 0) { // The delay epired, so move it down. moveDown = true; } if (moveDown) { // They are pressing down or enough time has passed that the piece should move. if (!movePieceDown()) { // The piece is already at the bottom or is blocked. So place it. placePiece(); } // Reset the delay for the next drop. dropDelay = dropInterval; } if (!lastInput.isDrop() && input.isDrop()) { // They pressed the drop button, so move it all the way down and then place it. while (movePieceDown()); placePiece(); } } private void dropNextPiece() { // Place the next piece at the top of the game board. piece = new Piece(nextPieces.remove()); movePieceToTopCenter(); // If the new piece is blocked, the game is over. if (!board.canPlace(piece)) { status = Status.Complete; } // Create the next next piece. fillNextPieces(); // Reset the drop delay dropDelay = dropInterval; // Keep track of the total pieces played. totalPieces++; // Notify listeners that the piece is starting. Piece started = piece; notifyListeners((listener) -> listener.onPieceStart(started)); } private void fillNextPieces() { // Fill up the next pieces queue. while (nextPieces.size() < settings.getNextPieceCount()) { nextPieces.add(pieceGenerator.generate()); } } private void placePiece() { // Place the piece on the board and remove completed lines. board.place(piece); // Notify listeners that the piece just landed. Piece landed = piece; notifyListeners((listener) -> listener.onPieceLand(landed)); // Update the score. score += computeScoreDeltaForPiece(); // Check for complete lines. checkCompleteLines(); // Drop the next piece. dropNextPiece(); // Allow the piece to be swapped out again. pieceSwapped = false; } private void movePieceToTopCenter() { // Find the center of the piece, taking into account empty columns. double center = piece.getBoard().getWidth() / 2.0; int x = 0; while (piece.getBoard().isColumnEmpty(x++)) { center += 0.5; } x = piece.getBoard().getWidth() - 1; while (piece.getBoard().isColumnEmpty(x--)) { center -= 0.5; } // Find the top of the piece, taking into account empty rows. int top = 0; while (piece.getBoard().isLineEmpty(top)) { top++; } // Place the piece at the top center of the board, taking into account the empty space. piece = piece.moveTo((int) Math.round(board.getWidth() / 2.0 - center), -top); } private boolean movePieceDown() { if (board.canPlace(piece.moveDown())) { // Move the piece down. piece = piece.moveDown(); return true; } else { // The piece couldn't move. return false; } } private void checkCompleteLines() { // Remove the completed lines from the board. int lines = board.removeCompleteLines(); if (lines > 0) { // If lines were complete, update the score. completedLines += lines; score += computeScoreDeltaForLines(lines); // Update the current level. updateLevel(); // Notify listeners. notifyListeners(listener -> listener.onLinesComplete()); if (settings.getMaxLines() > 0 && completedLines > settings.getMaxLines()) { status = Status.Complete; } // If there is supposed to be a line complete delay wait now (typically to allow for animation). sleep(settings.getLineCompleteDelay()); } } private void updateLevel() { // Update the level based on the number of lines completed. level = completedLines / settings.getLinesPerLevel(); // Update the drop interval (faster with every level). dropInterval = (long) (settings.getStartingDropInterval() / ((level * settings.getLevelAccelerator()) + 1)); if (dropInterval < settings.getMinDropInterval()) { dropInterval = settings.getMinDropInterval(); } } private long computeScoreDeltaForPiece() { // This is the original NES scoring system. return (level + 1) * 5; } private long computeScoreDeltaForLines(int lines) { assert lines >= 1 && lines <= 4 : "Unexpected number of completed lines: " + lines; // This is the original NES scoring system. int[] multipliers = {40, 100, 300, 1200}; return multipliers[lines - 1] * (level + 1); } public boolean isGameOver() { return status != Status.New && status != Status.InProgress; } private void sleep(long interval) { try { if (interval > 0) { TimeUnit.MILLISECONDS.sleep(interval); } if (Thread.interrupted()) { cancel(); } } catch (InterruptedException e) { throw new RuntimeException(e); } } public void cancel() { status = Status.Cancelled; } private void notifyListeners(Consumer<? super GameListener> consumer) { listenerExecutor.execute(() -> listeners.forEach(consumer)); } public void addListener(GameListener listener) { listeners.add(listener); } public GameSettings getSettings() { return settings; } public Player getPlayer() { return player; } public GameBoard getBoard() { return board; } public Piece getPiece() { return piece; } public Collection<PieceType> getNextPieces() { return nextPieces; } public PieceType getSwapPiece() { return swapPiece; } public boolean isPieceSwapped() { return pieceSwapped; } public long getScore() { return score; } public long getLevel() { return level; } public long getCompletedLines() { return completedLines; } public long getTotalPieces() { return totalPieces; } public Status getStatus() { return status; } public Throwable getError() { return error; } public Instant getStartTime() { return startTime; } public Instant getEndTime() { return endTime; } public Replay getReplay() { return replayGenerator != null ? replayGenerator.getReplay() : null; } }
/* * Copyright (c) 2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient; import static org.asynchttpclient.Dsl.*; import static org.testng.Assert.*; import java.io.IOException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.asynchttpclient.filter.FilterContext; import org.asynchttpclient.filter.FilterException; import org.asynchttpclient.filter.ResponseFilter; import org.eclipse.jetty.server.handler.AbstractHandler; import org.testng.annotations.Test; public class PostRedirectGetTest extends AbstractBasicTest { // ------------------------------------------------------ Test Configuration @Override public AbstractHandler configureHandler() throws Exception { return new PostRedirectGetHandler(); } // ------------------------------------------------------------ Test Methods @Test(groups = { "standalone", "post_redirect_get" }) public void postRedirectGet302Test() throws Exception { doTestPositive(302); } @Test(groups = { "standalone", "post_redirect_get" }) public void postRedirectGet302StrictTest() throws Exception { doTestNegative(302, true); } @Test(groups = { "standalone", "post_redirect_get" }) public void postRedirectGet303Test() throws Exception { doTestPositive(303); } @Test(groups = { "standalone", "post_redirect_get" }) public void postRedirectGet301Test() throws Exception { doTestPositive(301); } @Test(groups = { "standalone", "post_redirect_get" }) public void postRedirectGet307Test() throws Exception { doTestNegative(307, false); } // --------------------------------------------------------- Private Methods private void doTestNegative(final int status, boolean strict) throws Exception { ResponseFilter responseFilter = new ResponseFilter() { @Override public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException { // pass on the x-expect-get and remove the x-redirect // headers if found in the response ctx.getResponseHeaders().getHeaders().get("x-expect-post"); ctx.getRequest().getHeaders().add("x-expect-post", "true"); ctx.getRequest().getHeaders().remove("x-redirect"); return ctx; } }; try (AsyncHttpClient p = asyncHttpClient(config().setFollowRedirect(true).setStrict302Handling(strict).addResponseFilter(responseFilter))) { Request request = post(getTargetUrl()).addFormParam("q", "a b").addHeader("x-redirect", +status + "@" + "http://localhost:" + port1 + "/foo/bar/baz").addHeader("x-negative", "true").build(); Future<Integer> responseFuture = p.executeRequest(request, new AsyncCompletionHandler<Integer>() { @Override public Integer onCompleted(Response response) throws Exception { return response.getStatusCode(); } @Override public void onThrowable(Throwable t) { t.printStackTrace(); fail("Unexpected exception: " + t.getMessage(), t); } }); int statusCode = responseFuture.get(); assertEquals(statusCode, 200); } } private void doTestPositive(final int status) throws Exception { ResponseFilter responseFilter = new ResponseFilter() { @Override public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException { // pass on the x-expect-get and remove the x-redirect // headers if found in the response ctx.getResponseHeaders().getHeaders().get("x-expect-get"); ctx.getRequest().getHeaders().add("x-expect-get", "true"); ctx.getRequest().getHeaders().remove("x-redirect"); return ctx; } }; try (AsyncHttpClient p = asyncHttpClient(config().setFollowRedirect(true).addResponseFilter(responseFilter))) { Request request = post(getTargetUrl()).addFormParam("q", "a b").addHeader("x-redirect", +status + "@" + "http://localhost:" + port1 + "/foo/bar/baz").build(); Future<Integer> responseFuture = p.executeRequest(request, new AsyncCompletionHandler<Integer>() { @Override public Integer onCompleted(Response response) throws Exception { return response.getStatusCode(); } @Override public void onThrowable(Throwable t) { t.printStackTrace(); fail("Unexpected exception: " + t.getMessage(), t); } }); int statusCode = responseFuture.get(); assertEquals(statusCode, 200); } } // ---------------------------------------------------------- Nested Classes public static class PostRedirectGetHandler extends AbstractHandler { final AtomicInteger counter = new AtomicInteger(); @Override public void handle(String pathInContext, org.eclipse.jetty.server.Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { final boolean expectGet = (httpRequest.getHeader("x-expect-get") != null); final boolean expectPost = (httpRequest.getHeader("x-expect-post") != null); if (expectGet) { final String method = request.getMethod(); if (!"GET".equals(method)) { httpResponse.sendError(500, "Incorrect method. Expected GET, received " + method); return; } httpResponse.setStatus(200); httpResponse.getOutputStream().write("OK".getBytes()); httpResponse.getOutputStream().flush(); return; } else if (expectPost) { final String method = request.getMethod(); if (!"POST".equals(method)) { httpResponse.sendError(500, "Incorrect method. Expected POST, received " + method); return; } httpResponse.setStatus(200); httpResponse.getOutputStream().write("OK".getBytes()); httpResponse.getOutputStream().flush(); return; } String header = httpRequest.getHeader("x-redirect"); if (header != null) { // format for header is <status code>|<location url> String[] parts = header.split("@"); int redirectCode; try { redirectCode = Integer.parseInt(parts[0]); } catch (Exception ex) { ex.printStackTrace(); httpResponse.sendError(500, "Unable to parse redirect code"); return; } httpResponse.setStatus(redirectCode); if (httpRequest.getHeader("x-negative") == null) { httpResponse.addHeader("x-expect-get", "true"); } else { httpResponse.addHeader("x-expect-post", "true"); } httpResponse.setContentLength(0); httpResponse.addHeader("Location", parts[1] + counter.getAndIncrement()); httpResponse.getOutputStream().flush(); return; } httpResponse.sendError(500); httpResponse.getOutputStream().flush(); httpResponse.getOutputStream().close(); } } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.equity.portfoliotheory; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.Validate; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.equity.capm.CAPMFromRegressionCalculator; import com.opengamma.analytics.financial.timeseries.returns.TimeSeriesReturnCalculator; import com.opengamma.analytics.financial.timeseries.returns.TimeSeriesReturnCalculatorFactory; import com.opengamma.analytics.math.regression.LeastSquaresRegressionResult; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.core.value.MarketDataRequirementNames; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.OpenGammaExecutionContext; import com.opengamma.financial.analytics.timeseries.DateConstraint; import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesBundle; import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesFunctionUtils; import com.opengamma.id.ExternalId; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolutionResult; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolver; import com.opengamma.timeseries.DoubleTimeSeries; /** * */ @Deprecated public class CAPMFromRegressionModelFunction extends AbstractFunction.NonCompiledInvoker { private static final double DAYS_IN_YEAR = 365.25; private static final CAPMFromRegressionCalculator CAPM_REGRESSION_MODEL = new CAPMFromRegressionCalculator(); private static final ComputationTargetType TYPE = ComputationTargetType.POSITION.or(ComputationTargetType.PORTFOLIO_NODE); private static final ExternalId MARKET_QUOTE_TICKER = ExternalSchemes.syntheticSecurityId("SPX"); private static final ExternalId RISK_FREE_RATE_TICKER = ExternalSchemes.syntheticSecurityId("USDLIBORP3M"); private final String _resolutionKey; public CAPMFromRegressionModelFunction(final String resolutionKey) { Validate.notNull(resolutionKey, "resolution key"); _resolutionKey = resolutionKey; } // TODO need to have a schedule for the price series @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final HistoricalTimeSeriesSource timeSeriesSource = OpenGammaExecutionContext.getHistoricalTimeSeriesSource(executionContext); DoubleTimeSeries<?> assetPnL = null; double assetFairValue = 0; final HistoricalTimeSeriesBundle timeSeries = new HistoricalTimeSeriesBundle(); for (final ComputedValue input : inputs.getAllValues()) { if (ValueRequirementNames.PNL_SERIES.equals(input.getSpecification().getValueName())) { assetPnL = (DoubleTimeSeries<?>) inputs.getValue(ValueRequirementNames.PNL_SERIES); // TODO replace with return series when portfolio weights are in } else if (ValueRequirementNames.FAIR_VALUE.equals(input.getSpecification().getValueName())) { assetFairValue = (Double) inputs.getValue(ValueRequirementNames.FAIR_VALUE); } else if (ValueRequirementNames.HISTORICAL_TIME_SERIES.equals(input.getSpecification().getValueName())) { final HistoricalTimeSeries ts = (HistoricalTimeSeries) input.getValue(); timeSeries.add(input.getSpecification().getProperty(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY), timeSeriesSource.getExternalIdBundle(ts.getUniqueId()), ts); } } if (assetPnL == null) { throw new OpenGammaRuntimeException("Could not get P&L series"); } final ComputationTargetSpecification targetSpec = target.toSpecification(); final ValueRequirement desiredValue = desiredValues.iterator().next(); final ValueProperties constraints = desiredValue.getConstraints(); final HistoricalTimeSeries marketTimeSeries = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, MARKET_QUOTE_TICKER); final HistoricalTimeSeries riskFreeTimeSeries = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, RISK_FREE_RATE_TICKER); final TimeSeriesReturnCalculator returnCalculator = getReturnCalculator(constraints.getValues(ValuePropertyNames.RETURN_CALCULATOR)); DoubleTimeSeries<?> marketReturn = returnCalculator.evaluate(marketTimeSeries.getTimeSeries()); final DoubleTimeSeries<?> riskFreeTS = riskFreeTimeSeries.getTimeSeries().divide(100 * DAYS_IN_YEAR); marketReturn = marketReturn.subtract(riskFreeTS); DoubleTimeSeries<?> assetReturn = assetPnL.divide(assetFairValue); assetReturn = assetReturn.subtract(riskFreeTS); assetReturn = assetReturn.intersectionFirstValue(marketReturn); marketReturn = marketReturn.intersectionFirstValue(assetReturn); final LeastSquaresRegressionResult regression = CAPM_REGRESSION_MODEL.evaluate(assetReturn, marketReturn); final double alpha = regression.getBetas()[0]; final double alphaPValue = regression.getPValues()[0]; final double alphaTStat = regression.getTStatistics()[0]; final double alphaResidual = regression.getResiduals()[0]; final double alphaStdError = regression.getStandardErrorOfBetas()[0]; final ValueProperties resultProperties = getResultProperties(desiredValues.iterator().next()); final Set<ComputedValue> result = new HashSet<>(); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ADJUSTED_R_SQUARED, targetSpec, resultProperties), regression.getAdjustedRSquared())); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA, targetSpec, resultProperties), alpha)); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA, targetSpec, resultProperties), regression.getBetas()[1])); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_MEAN_SQUARE_ERROR, targetSpec, resultProperties), regression.getMeanSquareError())); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA_PVALUES, targetSpec, resultProperties), alphaPValue)); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA_PVALUES, targetSpec, resultProperties), regression.getPValues()[1])); result.add( new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_R_SQUARED, targetSpec, resultProperties), regression.getRSquared())); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA_RESIDUALS, targetSpec, resultProperties), alphaResidual)); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA_RESIDUALS, targetSpec, resultProperties), regression.getResiduals()[1])); result.add( new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_STANDARD_ERROR_OF_ALPHA, targetSpec, resultProperties), alphaStdError)); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_STANDARD_ERROR_OF_BETA, targetSpec, resultProperties), regression.getStandardErrorOfBetas()[1])); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA_TSTATS, targetSpec, resultProperties), alphaTStat)); result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA_TSTATS, targetSpec, resultProperties), regression.getTStatistics()[1])); return result; } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> samplingPeriods = constraints.getValues(ValuePropertyNames.SAMPLING_PERIOD); if (samplingPeriods == null || samplingPeriods.size() != 1) { return null; } final String samplingPeriod = samplingPeriods.iterator().next(); final Set<String> scheduleCalculatorName = constraints.getValues(ValuePropertyNames.SCHEDULE_CALCULATOR); if (scheduleCalculatorName == null || scheduleCalculatorName.size() != 1) { return null; } final Set<String> samplingFunctionName = constraints.getValues(ValuePropertyNames.SAMPLING_FUNCTION); if (samplingFunctionName == null || samplingFunctionName.size() != 1) { return null; } final Set<String> returnCalculatorName = constraints.getValues(ValuePropertyNames.RETURN_CALCULATOR); if (returnCalculatorName == null || returnCalculatorName.size() != 1) { return null; } final Set<ValueRequirement> requirements = new HashSet<>(); requirements.add(new ValueRequirement(ValueRequirementNames.PNL_SERIES, target.toSpecification(), ValueProperties.builder() .withAny(ValuePropertyNames.CURRENCY) .with(ValuePropertyNames.SAMPLING_PERIOD, samplingPeriod) .with(ValuePropertyNames.SCHEDULE_CALCULATOR, scheduleCalculatorName.iterator().next()) .with(ValuePropertyNames.SAMPLING_FUNCTION, samplingFunctionName.iterator().next()) .with(ValuePropertyNames.RETURN_CALCULATOR, returnCalculatorName.iterator().next()).get())); requirements.add(new ValueRequirement(ValueRequirementNames.FAIR_VALUE, target.toSpecification())); final HistoricalTimeSeriesResolver resolver = OpenGammaCompilationContext.getHistoricalTimeSeriesResolver(context); final HistoricalTimeSeriesResolutionResult marketTimeSeries = resolver.resolve(MARKET_QUOTE_TICKER.toBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, _resolutionKey); if (marketTimeSeries == null) { return null; } requirements.add(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(marketTimeSeries, MarketDataRequirementNames.MARKET_VALUE, DateConstraint.VALUATION_TIME.minus(samplingPeriod), true, DateConstraint.VALUATION_TIME, true)); final HistoricalTimeSeriesResolutionResult riskFreeTimeSeries = resolver.resolve(RISK_FREE_RATE_TICKER.toBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, _resolutionKey); if (riskFreeTimeSeries == null) { return null; } requirements.add(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(riskFreeTimeSeries, MarketDataRequirementNames.MARKET_VALUE, DateConstraint.VALUATION_TIME.minus(samplingPeriod), true, DateConstraint.VALUATION_TIME, true)); return requirements; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties resultProperties = getResultProperties(); final Set<ValueSpecification> results = new HashSet<>(); final ComputationTargetSpecification targetSpec = target.toSpecification(); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ADJUSTED_R_SQUARED, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_MEAN_SQUARE_ERROR, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA_PVALUES, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA_PVALUES, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_R_SQUARED, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA_RESIDUALS, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA_RESIDUALS, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_STANDARD_ERROR_OF_ALPHA, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_STANDARD_ERROR_OF_BETA, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_ALPHA_TSTATS, targetSpec, resultProperties)); results.add(new ValueSpecification(ValueRequirementNames.CAPM_REGRESSION_BETA_TSTATS, targetSpec, resultProperties)); return results; } private ValueProperties getResultProperties() { return createValueProperties() .withAny(ValuePropertyNames.SAMPLING_PERIOD) .withAny(ValuePropertyNames.SCHEDULE_CALCULATOR) .withAny(ValuePropertyNames.SAMPLING_FUNCTION) .withAny(ValuePropertyNames.RETURN_CALCULATOR).get(); } private ValueProperties getResultProperties(final ValueRequirement desiredValue) { return createValueProperties() .with(ValuePropertyNames.SAMPLING_PERIOD, desiredValue.getConstraint(ValuePropertyNames.SAMPLING_PERIOD)) .with(ValuePropertyNames.SCHEDULE_CALCULATOR, desiredValue.getConstraint(ValuePropertyNames.SCHEDULE_CALCULATOR)) .with(ValuePropertyNames.SAMPLING_FUNCTION, desiredValue.getConstraint(ValuePropertyNames.SAMPLING_FUNCTION)) .with(ValuePropertyNames.RETURN_CALCULATOR, desiredValue.getConstraint(ValuePropertyNames.RETURN_CALCULATOR)).get(); } private TimeSeriesReturnCalculator getReturnCalculator(final Set<String> returnCalculatorNames) { if (returnCalculatorNames == null || returnCalculatorNames.isEmpty() || returnCalculatorNames.size() != 1) { throw new OpenGammaRuntimeException("Missing or non-unique return calculator name: " + returnCalculatorNames); } return TimeSeriesReturnCalculatorFactory.getReturnCalculator(returnCalculatorNames.iterator().next()); } @Override public ComputationTargetType getTargetType() { return TYPE; } }
/* * $Id: JPointDemo.java,v 1.2 2006/01/19 14:45:49 luca Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt.demo; import gov.noaa.pmel.sgt.JPane; import gov.noaa.pmel.sgt.Layer; import gov.noaa.pmel.sgt.PlainAxis; import gov.noaa.pmel.sgt.LineKey; import gov.noaa.pmel.sgt.LinearTransform; import gov.noaa.pmel.sgt.Graph; import gov.noaa.pmel.sgt.CartesianGraph; import gov.noaa.pmel.sgt.SGLabel; import gov.noaa.pmel.sgt.PointAttribute; import gov.noaa.pmel.sgt.LineCartesianRenderer; import gov.noaa.pmel.sgt.StackedLayout; import gov.noaa.pmel.sgt.Axis; import gov.noaa.pmel.sgt.swing.JClassTree; import gov.noaa.pmel.sgt.Logo; import gov.noaa.pmel.sgt.dm.Collection; import gov.noaa.pmel.util.Point2D; import gov.noaa.pmel.util.Range2D; import gov.noaa.pmel.util.Dimension2D; import java.awt.*; import javax.swing.*; import it.unitn.ing.rista.util.Misc; /** * Example demonstrating the creation of a simple * graph of many points. * * @author Donald Denbo * @version $Revision: 1.2 $, $Date: 2006/01/19 14:45:49 $ * @since 2.0 */ public class JPointDemo extends JApplet { JButton tree_; JButton space_; JPane mainPane_; public void init() { setLayout(new BorderLayout(0,0)); setSize(553,438); add(makeGraph(), BorderLayout.CENTER); } public static void main(String[] args) { JPointDemo pd = new JPointDemo(); JFrame frame = new JFrame("Point Demo"); JPanel button = new JPanel(); JPane graph; button.setLayout(new FlowLayout()); pd.tree_ = new JButton("Tree View"); MyAction myAction = pd. new MyAction(); pd.tree_.addActionListener(myAction); button.add(pd.tree_); pd.space_ = new JButton("Add Mark"); pd.space_.addActionListener(myAction); button.add(pd.space_); frame.getContentPane().setLayout(new BorderLayout()); frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent event) { JFrame fr = (JFrame)event.getSource(); fr.setVisible(false); fr.dispose(); System.exit(0); } }); frame.setSize(553,438); graph = pd.makeGraph(); graph.setBatch(true); frame.getContentPane().add(graph, BorderLayout.CENTER); frame.getContentPane().add(button, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); graph.setBatch(false); } JPane makeGraph() { /* * This example creates a very simple plot from * scratch (not using one of the sgt.awt classes) * to display a Collection of points. */ /* * Create a Pane, place in the center of the Applet * and set the layout to be StackedLayout. */ mainPane_ = new JPane("Point Plot Demo", new Dimension(553,438)); mainPane_.setLayout(new StackedLayout()); mainPane_.setBackground(Color.white); /* * Create a Collection of points using the TestData class. */ Range2D xrange, yrange; TestData td; Collection col; xrange = new Range2D(50.0, 150., 10.0); yrange = new Range2D(-20.0, 20.0, 5.0); td = new TestData(xrange, yrange, 50); col = td.getCollection(); /* * xsize, ysize are the width and height in physical units * of the Layer graphics region. * * xstart, xend are the start and end points for the X axis * ystart, yend are the start and end points for the Y axis */ double xsize = 4.0; double xstart = 0.6; double xend = 3.5; double ysize = 3.0; double ystart = 0.6; double yend = 2.75; /* * Create the layer and add it to the Pane. */ Layer layer; layer = new Layer("Layer 1", new Dimension2D(xsize, ysize)); mainPane_.add(layer); /* * create and add image as a Logo to the layer */ Image img = this.getToolkit().getImage(getClass().getResource("ncBrowse48.gif")); // // wait for image to be loaded // if(img != null) { MediaTracker mt = new MediaTracker(this); try { mt.addImage(img, 0); mt.waitForAll(); if(mt.isErrorAny()) System.err.println("JPointDemo: Error loading image"); } catch (InterruptedException e) {} } Logo logo = new Logo(new Point2D.Double(0.0, 0.0), Logo.BOTTOM, Logo.LEFT); logo.setId("ncBrowse logo"); logo.setImage(img); layer.addChild(logo); /* * Create a CartesianGraph and transforms. */ CartesianGraph graph; LinearTransform xt, yt; graph = new CartesianGraph("Point Graph"); layer.setGraph(graph); xt = new LinearTransform(xstart, xend, xrange.start, xrange.end); yt = new LinearTransform(ystart, yend, yrange.start, yrange.end); graph.setXTransform(xt); graph.setYTransform(yt); /* * Create the bottom axis, set its range in user units * and its origin. Add the axis to the graph. */ PlainAxis xbot; String xLabel = "X Label"; xbot = new PlainAxis("Botton Axis"); xbot.setRangeU(xrange); xbot.setLocationU(new Point2D.Double(xrange.start, yrange.start)); Font xbfont = new Font("Helvetica", Font.ITALIC, 14); xbot.setLabelFont(xbfont); SGLabel xtitle = new SGLabel("xaxis title", xLabel, new Point2D.Double(0.0, 0.0)); Font xtfont = new Font("Helvetica", Font.PLAIN, 14); xtitle.setFont(xtfont); xtitle.setHeightP(0.2); xbot.setTitle(xtitle); graph.addXAxis(xbot); /* * Create the left axis, set its range in user units * and its origin. Add the axis to the graph. */ PlainAxis yleft; String yLabel = "Y Label"; yleft = new PlainAxis("Left Axis"); yleft.setRangeU(yrange); yleft.setLocationU(new Point2D.Double(xrange.start, yrange.start)); yleft.setLabelFont(xbfont); SGLabel ytitle = new SGLabel("yaxis title", yLabel, new Point2D.Double(0.0, 0.0)); Font ytfont = new Font("Helvetica", Font.PLAIN, 14); ytitle.setFont(ytfont); ytitle.setHeightP(0.2); yleft.setTitle(ytitle); graph.addYAxis(yleft); /* * Create a PointAttribute for the display of the * Collection of points. The points will be red with * the label at the NE corner and in blue. */ PointAttribute pattr; pattr = new PointAttribute(20, Color.red); pattr.setLabelPosition(PointAttribute.NE); Font pfont = new Font("Helvetica", Font.PLAIN, 12); pattr.setLabelFont(pfont); pattr.setLabelColor(Color.blue); pattr.setLabelHeightP(0.1); pattr.setDrawLabel(true); /* * Associate the attribute and the point Collection * with the graph. */ graph.setData(col, pattr); return mainPane_; } void tree_actionPerformed(java.awt.event.ActionEvent e) { JClassTree ct = new JClassTree(); ct.setModal(false); ct.setJPane(mainPane_); ct.show(); } class MyAction implements java.awt.event.ActionListener { public void actionPerformed(java.awt.event.ActionEvent event) { Object obj = event.getSource(); if(obj == space_) { System.out.println(" <<Mark>>"); } if(obj == tree_) tree_actionPerformed(event); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.protocol.java.config.gui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.apache.jmeter.config.Argument; import org.apache.jmeter.config.Arguments; import org.apache.jmeter.config.gui.AbstractConfigGui; import org.apache.jmeter.config.gui.ArgumentsPanel; import org.apache.jmeter.gui.util.HorizontalPanel; import org.apache.jmeter.protocol.java.config.JavaConfig; import org.apache.jmeter.protocol.java.sampler.JavaSampler; import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.PropertyIterator; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.reflect.ClassFinder; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * The <code>JavaConfigGui</code> class provides the user interface for the * {@link JavaConfig} object. * */ public class JavaConfigGui extends AbstractConfigGui implements ActionListener { private static final long serialVersionUID = 240L; /** Logging */ private static final Logger log = LoggingManager.getLoggerForClass(); /** A combo box allowing the user to choose a test class. */ private JComboBox classnameCombo; /** * Indicates whether or not the name of this component should be displayed * as part of the GUI. If true, this is a standalone component. If false, it * is embedded in some other component. */ private boolean displayName = true; /** A panel allowing the user to set arguments for this test. */ private ArgumentsPanel argsPanel; /** * Create a new JavaConfigGui as a standalone component. */ public JavaConfigGui() { this(true); } /** * Create a new JavaConfigGui as either a standalone or an embedded * component. * * @param displayNameField * tells whether the component name should be displayed with the * GUI. If true, this is a standalone component. If false, this * component is embedded in some other component. */ public JavaConfigGui(boolean displayNameField) { this.displayName = displayNameField; init(); } /** {@inheritDoc} */ @Override public String getLabelResource() { return "java_request_defaults"; // $NON-NLS-1$ } /** * Initialize the GUI components and layout. */ private void init() {// called from ctor, so must not be overridable setLayout(new BorderLayout(0, 5)); if (displayName) { setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); } JPanel classnameRequestPanel = new JPanel(new BorderLayout(0, 5)); classnameRequestPanel.add(createClassnamePanel(), BorderLayout.NORTH); classnameRequestPanel.add(createParameterPanel(), BorderLayout.CENTER); add(classnameRequestPanel, BorderLayout.CENTER); } /** * Create a panel with GUI components allowing the user to select a test * class. * * @return a panel containing the relevant components */ private JPanel createClassnamePanel() { List<String> possibleClasses = new ArrayList<String>(); try { // Find all the classes which implement the JavaSamplerClient // interface. possibleClasses = ClassFinder.findClassesThatExtend(JMeterUtils.getSearchPaths(), new Class[] { JavaSamplerClient.class }); // Remove the JavaConfig class from the list since it only // implements the interface for error conditions. possibleClasses.remove(JavaSampler.class.getName() + "$ErrorSamplerClient"); } catch (Exception e) { log.debug("Exception getting interfaces.", e); } JLabel label = new JLabel(JMeterUtils.getResString("protocol_java_classname")); // $NON-NLS-1$ classnameCombo = new JComboBox(possibleClasses.toArray()); classnameCombo.addActionListener(this); classnameCombo.setEditable(false); label.setLabelFor(classnameCombo); HorizontalPanel panel = new HorizontalPanel(); panel.add(label); panel.add(classnameCombo); return panel; } /** * Handle action events for this component. This method currently handles * events for the classname combo box. * * @param evt * the ActionEvent to be handled */ @Override public void actionPerformed(ActionEvent evt) { if (evt.getSource() == classnameCombo) { String className = ((String) classnameCombo.getSelectedItem()).trim(); try { JavaSamplerClient client = (JavaSamplerClient) Class.forName(className, true, Thread.currentThread().getContextClassLoader()).newInstance(); Arguments currArgs = new Arguments(); argsPanel.modifyTestElement(currArgs); Map<String, String> currArgsMap = currArgs.getArgumentsAsMap(); Arguments newArgs = new Arguments(); Arguments testParams = null; try { testParams = client.getDefaultParameters(); } catch (AbstractMethodError e) { log.warn("JavaSamplerClient doesn't implement " + "getDefaultParameters. Default parameters won't " + "be shown. Please update your client class: " + className); } if (testParams != null) { PropertyIterator i = testParams.getArguments().iterator(); while (i.hasNext()) { Argument arg = (Argument) i.next().getObjectValue(); String name = arg.getName(); String value = arg.getValue(); // If a user has set parameters in one test, and then // selects a different test which supports the same // parameters, those parameters should have the same // values that they did in the original test. if (currArgsMap.containsKey(name)) { String newVal = currArgsMap.get(name); if (newVal != null && newVal.length() > 0) { value = newVal; } } newArgs.addArgument(name, value); } } argsPanel.configure(newArgs); } catch (Exception e) { log.error("Error getting argument list for " + className, e); } } } /** * Create a panel containing components allowing the user to provide * arguments to be passed to the test class instance. * * @return a panel containing the relevant components */ private JPanel createParameterPanel() { argsPanel = new ArgumentsPanel(JMeterUtils.getResString("paramtable")); // $NON-NLS-1$ return argsPanel; } /** {@inheritDoc} */ @Override public void configure(TestElement config) { super.configure(config); argsPanel.configure((Arguments) config.getProperty(JavaSampler.ARGUMENTS).getObjectValue()); String className = config.getPropertyAsString(JavaSampler.CLASSNAME); if(checkContainsClassName(classnameCombo.getModel(), className)) { classnameCombo.setSelectedItem(className); } else { log.error("Error setting class:'"+className+"' in JavaSampler "+getName()+", check for a missing jar in your jmeter 'search_paths' and 'plugin_dependency_paths' properties"); } } /** * Check combo contains className * @param model ComboBoxModel * @param className String class name * @return boolean */ private static final boolean checkContainsClassName(ComboBoxModel model, String className) { int size = model.getSize(); Set<String> set = new HashSet<String>(size); for (int i = 0; i < size; i++) { set.add((String)model.getElementAt(i)); } return set.contains(className); } /** {@inheritDoc} */ @Override public TestElement createTestElement() { JavaConfig config = new JavaConfig(); modifyTestElement(config); return config; } /** {@inheritDoc} */ @Override public void modifyTestElement(TestElement config) { configureTestElement(config); ((JavaConfig) config).setArguments((Arguments) argsPanel.createTestElement()); ((JavaConfig) config).setClassname(String.valueOf(classnameCombo.getSelectedItem())); } /* (non-Javadoc) * @see org.apache.jmeter.gui.AbstractJMeterGuiComponent#clearGui() */ @Override public void clearGui() { super.clearGui(); this.displayName = true; argsPanel.clearGui(); classnameCombo.setSelectedIndex(0); } }
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.devtools.jpa.eclipselink.conv.ojb; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ojb.broker.metadata.ClassDescriptor; import org.apache.ojb.broker.metadata.CollectionDescriptor; import org.apache.ojb.broker.metadata.ConnectionDescriptorXmlHandler; import org.apache.ojb.broker.metadata.ConnectionRepository; import org.apache.ojb.broker.metadata.DescriptorRepository; import org.apache.ojb.broker.metadata.FieldDescriptor; import org.apache.ojb.broker.metadata.MetadataException; import org.apache.ojb.broker.metadata.ObjectReferenceDescriptor; import org.apache.ojb.broker.metadata.RepositoryXmlHandler; import org.apache.ojb.broker.util.ClassHelper; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class OjbUtil { private static final Log LOG = LogFactory.getLog(OjbUtil.class); private OjbUtil() { throw new UnsupportedOperationException("do not call"); } /** * Starting with a root class, get the entire tree of mapped objects including collections and references. * Cycles are correctly handled. * * @param rootClass the top level class to start with. * @return a collection of classes to process */ public static Collection<String> getMappedTree(String rootClass, Collection<DescriptorRepository> descriptorRepositories) { final Set<String> processed = new HashSet<String>(); getMappedTree(rootClass, descriptorRepositories, processed); return processed; } private static void getMappedTree(String rootClass, Collection<DescriptorRepository> descriptorRepositories, Set<String> processed) { if (processed.contains(rootClass)) { return; } processed.add(rootClass); final ClassDescriptor cd = findClassDescriptor(rootClass, descriptorRepositories); if (cd != null) { final Collection<ObjectReferenceDescriptor> ords = cd.getObjectReferenceDescriptors(); if (ords != null) { for (ObjectReferenceDescriptor ord : ords) { getMappedTree(ord.getItemClassName(), descriptorRepositories, processed); } } final Collection<CollectionDescriptor> clds = cd.getCollectionDescriptors(); if (clds != null) { for (ObjectReferenceDescriptor cld : clds) { getMappedTree(cld.getItemClassName(), descriptorRepositories, processed); } } } else { LOG.warn("ClassDescriptor not found for " + rootClass); } } public static boolean isMappedColumn(String clazz, String fieldName, Collection<DescriptorRepository> descriptorRepositories) { final ClassDescriptor cd = findClassDescriptor(clazz, descriptorRepositories); if (cd != null) { return cd.getFieldDescriptorByName(fieldName) != null || cd.getObjectReferenceDescriptorByName(fieldName) != null || cd.getCollectionDescriptorByName(fieldName) != null; } return false; } public static Collection<DescriptorRepository> getDescriptorRepositories(Collection<String> ojbFiles) throws Exception { final Collection<DescriptorRepository> drs = new ArrayList<DescriptorRepository>(); //first parse & get all of the mapped classes for (String file : ojbFiles) { DescriptorRepository repository = OjbUtil.readDescriptorRepository(file); if ( repository != null ) { drs.add(repository); } } return drs; } public static ClassDescriptor findClassDescriptor(String clazz, Collection<DescriptorRepository> descriptorRepositories) { for (DescriptorRepository dr : descriptorRepositories) { ClassDescriptor cd = (ClassDescriptor) dr.getDescriptorTable().get(clazz); if (cd != null) { //handle extends. don't return class descriptor for extent classes if (cd.getExtentClassNames() == null || cd.getExtentClassNames().isEmpty()) { return cd; } } } return null; } public static FieldDescriptor findFieldDescriptor(String clazz, String fieldName, Collection<DescriptorRepository> descriptorRepositories) { final ClassDescriptor cd = findClassDescriptor(clazz, descriptorRepositories); return cd != null ? cd.getFieldDescriptorByName(fieldName) : null; } public static ObjectReferenceDescriptor findObjectReferenceDescriptor(String clazz, String fieldName, Collection<DescriptorRepository> descriptorRepositories) { final ClassDescriptor cd = findClassDescriptor(clazz, descriptorRepositories); return cd != null ? cd.getObjectReferenceDescriptorByName(fieldName) : null; } public static CollectionDescriptor findCollectionDescriptor(String clazz, String fieldName, Collection<DescriptorRepository> descriptorRepositories) { final ClassDescriptor cd = findClassDescriptor(clazz, descriptorRepositories); return cd != null ? cd.getCollectionDescriptorByName(fieldName) : null; } public static Collection<String> getPrimaryKeyNames(String clazz, Collection<DescriptorRepository> descriptorRepositories) { final Collection<String> pks = new ArrayList<String>(); final ClassDescriptor cd = OjbUtil.findClassDescriptor(clazz, descriptorRepositories); for(FieldDescriptor pk : cd.getPkFields()) { pks.add(pk.getAttributeName()); } return pks; } /** * Parses a repository file and populates an ojb datastructure representing the file. * @param filename the file to parse * @return a DescriptorRepository or null */ public static DescriptorRepository readDescriptorRepository(String filename) { LOG.info( "Processing Repository: " + filename); try { return (DescriptorRepository) buildRepository(filename, DescriptorRepository.class); } catch (Exception e) { LOG.error("Unable to process descriptor repository: " + filename); LOG.error( e.getMessage() ); // Explicitly not logging the exception - it has already been dumped by earlier logging } return null; } /** * Gets all the mapped classes */ public static Set<String> mappedClasses(Collection<DescriptorRepository> descriptors) throws Exception { final Set<String> mappedClasses = new HashSet<String>(); for (DescriptorRepository dr : descriptors) { for (Map.Entry<String, ClassDescriptor> entry : ((Map<String, ClassDescriptor>) dr.getDescriptorTable()).entrySet()) { final Collection<String> extents = entry.getValue().getExtentClassNames(); if (extents != null && !extents.isEmpty()) { mappedClasses.addAll(extents); } else { mappedClasses.add(entry.getKey()); } } } return mappedClasses; } /** * Gets all the super classes & stopping when the super class matches a package prefix */ public static Set<String> getSuperClasses(String clazzName, String packagePrefixToStop) throws Exception { final Set<String> superClasses = new HashSet<String>(); Class<?> clazz = Class.forName(clazzName); for (Class<?> sc = clazz.getSuperclass(); sc != null && sc != Object.class && !sc.getName().startsWith(packagePrefixToStop);) { superClasses.add(sc.getName()); sc = sc.getSuperclass(); } return superClasses; } private static Object buildRepository(String repositoryFileName, Class targetRepository) throws IOException, ParserConfigurationException, SAXException { URL url = buildURL(repositoryFileName); String pathName = url.toExternalForm(); LOG.debug("Building repository from :" + pathName); InputSource source = new InputSource(pathName); URLConnection conn = url.openConnection(); conn.setUseCaches(false); conn.connect(); InputStream i = conn.getInputStream(); source.setByteStream(i); try { return readMetadataFromXML(source, targetRepository); } finally { try { i.close(); } catch (IOException x) { LOG.warn("unable to close repository input stream [" + x.getMessage() + "]", x); } } } private static Object readMetadataFromXML(InputSource source, Class target) throws ParserConfigurationException, SAXException, IOException { // get a xml reader instance: SAXParserFactory factory = SAXParserFactory.newInstance(); LOG.debug("RepositoryPersistor using SAXParserFactory : " + factory.getClass().getName()); SAXParser p = factory.newSAXParser(); XMLReader reader = p.getXMLReader(); Object result; if (DescriptorRepository.class.equals(target)) { // create an empty repository: DescriptorRepository repository = new DescriptorRepository(); // create handler for building the repository structure org.xml.sax.ContentHandler handler = new RepositoryXmlHandler(repository); // tell parser to use our handler: reader.setContentHandler(handler); reader.parse(source); result = repository; } else if (ConnectionRepository.class.equals(target)) { // create an empty repository: ConnectionRepository repository = new ConnectionRepository(); // create handler for building the repository structure org.xml.sax.ContentHandler handler = new ConnectionDescriptorXmlHandler(repository); // tell parser to use our handler: reader.setContentHandler(handler); reader.parse(source); //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs"); result = repository; } else throw new MetadataException("Could not build a repository instance for '" + target + "', using source " + source); return result; } private static URL buildURL(String repositoryFileName) throws MalformedURLException { //j2ee compliant lookup of resources URL url = ClassHelper.getResource(repositoryFileName); // don't be too strict: if resource is not on the classpath, try ordinary file lookup if (url == null) { try { url = new File(repositoryFileName).toURL(); } catch (MalformedURLException ignore) { } } if (url != null) { LOG.info("OJB Descriptor Repository: " + url); } else { throw new MalformedURLException("did not find resource " + repositoryFileName); } return url; } }
// Copyright 2008-2009 Thiago H. de Paula Figueiredo // // 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 br.com.arsmachina.controller.impl; import java.util.ArrayList; import java.util.List; import org.easymock.EasyMock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import br.com.arsmachina.controller.impl.SpringControllerImpl; import br.com.arsmachina.dao.DAO; /** * Test class for {@link SpringControllerImpl}. * * @author Thiago H. de Paula Figueiredo */ public class SpringControllerImplTest { final static String ANOTHER_OBJECT = "another"; final static String OBJECT = "persistent"; final static Integer ID = 1; private DAO<String, Integer> dao; private SpringControllerImpl<String, Integer> controller; @SuppressWarnings( { "unused", "unchecked" }) @BeforeMethod private void setUp() { dao = EasyMock.createMock(DAO.class); controller = new DummyGenericController(dao); } /** * Tests {@link SpringControllerImpl#GenericControllerImpl(DAO)}. */ @Test public void constructor() { boolean ok = false; try { new DummyGenericController(null); } catch (IllegalArgumentException e) { ok = true; } assert ok; new DummyGenericController(dao); } /** * Tests {@link SpringControllerImpl#save(Object)}. */ @Test public void save() { dao.save(OBJECT); EasyMock.replay(dao); controller.save(OBJECT); EasyMock.verify(dao); } /** * Tests {@link SpringControllerImpl#save(Object)}. */ @Test public void update() { EasyMock.expect(dao.update(OBJECT)).andReturn(ANOTHER_OBJECT); EasyMock.replay(dao); final String returned = controller.update(OBJECT); EasyMock.verify(dao); assert returned == ANOTHER_OBJECT; } /** * Tests {@link GenericControllerImpl#delete(<K>))}. */ @Test public void delete_id() { dao.delete(ID); EasyMock.replay(dao); controller.delete(ID); EasyMock.verify(dao); } /** * Tests {@link GenericControllerImpl#delete(<T>))}. */ @Test public void delete() { dao.delete(OBJECT); EasyMock.replay(dao); controller.delete(OBJECT); EasyMock.verify(dao); } /** * Tests {@link GenericControllerImpl#findAll())}. */ @Test public void findAll() { List<String> list = new ArrayList<String>(); EasyMock.expect(dao.findAll()).andReturn(list); EasyMock.replay(dao); final List<String> returned = controller.findAll(); EasyMock.verify(dao); assert list == returned; } /** * Tests {@link GenericControllerImpl#evict(<T>))}. */ @Test public void evict() { dao.evict(OBJECT); EasyMock.replay(dao); controller.evict(OBJECT); EasyMock.verify(dao); } /** * Tests {@link GenericControllerImpl#findById(<K>))}. */ @Test public void findById() { EasyMock.expect(dao.findById(ID)).andReturn(OBJECT); EasyMock.replay(dao); final String result = controller.findById(ID); EasyMock.verify(dao); assert result == OBJECT; } /** * Tests {@link GenericControllerImpl#findAll(int, int, String, boolean)))}. */ @Test public void findAll_paginated() { List<String> list = new ArrayList<String>(); EasyMock.expect(dao.findAll(1, 1)).andReturn(list); EasyMock.replay(dao); final List<String> returned = controller.findAll(1, 1); EasyMock.verify(dao); assert list == returned; } /** * Tests {@link SpringControllerImpl#saveOrUpdate(Object)}. */ @Test public void saveOrUpdate() { // at first, we test with a persistent object EasyMock.expect(dao.isPersistent(OBJECT)).andReturn(true); EasyMock.expect(dao.update(OBJECT)).andReturn(ANOTHER_OBJECT); EasyMock.replay(dao); String returned = controller.saveOrUpdate(OBJECT); EasyMock.verify(dao); assert returned == ANOTHER_OBJECT; // at last, we test with a non-persistent object EasyMock.reset(dao); EasyMock.expect(dao.isPersistent(OBJECT)).andReturn(false); dao.save(OBJECT); EasyMock.replay(dao); returned = controller.saveOrUpdate(OBJECT); EasyMock.verify(dao); assert returned == OBJECT; } final private static class DummyGenericController extends SpringControllerImpl<String, Integer> { /** * @param dao */ @SuppressWarnings("unchecked") public DummyGenericController(DAO dao) { super(dao); } } }
/* * Copyright 2012-2015 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.boot.autoconfigure.security.oauth2.resource; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration; import org.springframework.util.StringUtils; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Configuration properties for OAuth2 Resources. * * @author Dave Syer * @since 1.3.0 */ @ConfigurationProperties("security.oauth2.resource") public class ResourceServerProperties implements Validator, BeanFactoryAware { @JsonIgnore private final String clientId; @JsonIgnore private final String clientSecret; @JsonIgnore private ListableBeanFactory beanFactory; private String serviceId = "resource"; /** * Identifier of the resource. */ private String id; /** * URI of the user endpoint. */ private String userInfoUri; /** * URI of the token decoding endpoint. */ private String tokenInfoUri; /** * Use the token info, can be set to false to use the user info. */ private boolean preferTokenInfo = true; /** * The token type to send when using the userInfoUri. */ private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE; private Jwt jwt = new Jwt(); public ResourceServerProperties() { this(null, null); } public ResourceServerProperties(String clientId, String clientSecret) { this.clientId = clientId; this.clientSecret = clientSecret; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } public String getResourceId() { return this.id; } public String getServiceId() { return this.serviceId; } public void setServiceId(String serviceId) { this.serviceId = serviceId; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUserInfoUri() { return this.userInfoUri; } public void setUserInfoUri(String userInfoUri) { this.userInfoUri = userInfoUri; } public String getTokenInfoUri() { return this.tokenInfoUri; } public void setTokenInfoUri(String tokenInfoUri) { this.tokenInfoUri = tokenInfoUri; } public boolean isPreferTokenInfo() { return this.preferTokenInfo; } public void setPreferTokenInfo(boolean preferTokenInfo) { this.preferTokenInfo = preferTokenInfo; } public String getTokenType() { return this.tokenType; } public void setTokenType(String tokenType) { this.tokenType = tokenType; } public Jwt getJwt() { return this.jwt; } public void setJwt(Jwt jwt) { this.jwt = jwt; } public String getClientId() { return this.clientId; } public String getClientSecret() { return this.clientSecret; } @Override public boolean supports(Class<?> clazz) { return ResourceServerProperties.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { if (countBeans(AuthorizationServerEndpointsConfiguration.class) > 0) { // If we are an authorization server we don't need remote resource token // services return; } if (countBeans(ResourceServerTokenServicesConfiguration.class) == 0) { // If we are not a resource server or an SSO client we don't need remote // resource token services return; } ResourceServerProperties resource = (ResourceServerProperties) target; if (StringUtils.hasText(this.clientId)) { if (!StringUtils.hasText(this.clientSecret)) { if (!StringUtils.hasText(resource.getUserInfoUri())) { errors.rejectValue("userInfoUri", "missing.userInfoUri", "Missing userInfoUri (no client secret available)"); } } else { if (isPreferTokenInfo() && !StringUtils.hasText(resource.getTokenInfoUri())) { if (StringUtils.hasText(getJwt().getKeyUri()) || StringUtils.hasText(getJwt().getKeyValue())) { // It's a JWT decoder return; } if (!StringUtils.hasText(resource.getUserInfoUri())) { errors.rejectValue("tokenInfoUri", "missing.tokenInfoUri", "Missing tokenInfoUri and userInfoUri and there is no " + "JWT verifier key"); } } } } } private int countBeans(Class<?> type) { return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, type, true, false).length; } public class Jwt { /** * The verification key of the JWT token. Can either be a symmetric secret or * PEM-encoded RSA public key. If the value is not available, you can set the URI * instead. */ private String keyValue; /** * The URI of the JWT token. Can be set if the value is not available and the key * is public. */ private String keyUri; public String getKeyValue() { return this.keyValue; } public void setKeyValue(String keyValue) { this.keyValue = keyValue; } public void setKeyUri(String keyUri) { this.keyUri = keyUri; } public String getKeyUri() { if (this.keyUri != null) { return this.keyUri; } if (ResourceServerProperties.this.userInfoUri != null && ResourceServerProperties.this.userInfoUri.endsWith("/userinfo")) { return ResourceServerProperties.this.userInfoUri.replace("/userinfo", "/token_key"); } if (ResourceServerProperties.this.tokenInfoUri != null && ResourceServerProperties.this.tokenInfoUri .endsWith("/check_token")) { return ResourceServerProperties.this.userInfoUri.replace("/check_token", "/token_key"); } return null; } } }
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.transport.http.bridge; import static java.util.Collections.unmodifiableMap; import static java.util.Collections.unmodifiableSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.kaazing.gateway.transport.http.HttpCookie; import org.kaazing.gateway.transport.http.HttpVersion; public abstract class HttpStartMessage extends HttpMessage { private static final Map<String, List<String>> EMPTY_HEADERS = Collections.<String, List<String>>emptyMap(); private static final Set<String> EMPTY_HEADER_NAMES = Collections.<String>emptySet(); private static final List<String> EMPTY_HEADER = Collections.<String>emptyList(); private static final Set<HttpCookie> EMPTY_COOKIES = Collections.<HttpCookie>emptySet(); private Set<HttpCookie> cookies; private Map<String, List<String>> headers; private HttpVersion version; private HttpContentMessage content; private boolean contentLengthImplicit; public HttpStartMessage() { content = null; } @Override public boolean isComplete() { return (content == null) || content.isComplete(); } public boolean isContentLengthImplicit() { return contentLengthImplicit; } public void setContentLengthImplicit(boolean contentLengthImplicit) { this.contentLengthImplicit = contentLengthImplicit; } public boolean hasCookies() { return (cookies != null && !cookies.isEmpty()); } public Iterator<HttpCookie> iterateCookies() { return (cookies != null) ? cookies.iterator() : EMPTY_COOKIES.iterator(); } public Set<HttpCookie> getCookies() { Set<HttpCookie> cookies = getCookies(false); return (cookies != null && !cookies.isEmpty()) ? unmodifiableSet(cookies) : EMPTY_COOKIES; } public void addCookie(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException("cookie"); } Set<HttpCookie> cookies = getCookies(true); cookies.add(cookie); } public void removeCookie(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException("cookie"); } Set<HttpCookie> cookies = getCookies(false); if (cookies != null) { cookies.remove(cookie); } } public void clearCookies() { Set<HttpCookie> cookies = getCookies(false); if (cookies != null) { cookies.clear(); } } public void setCookies(Collection<HttpCookie> newCookies) { Set<HttpCookie> cookies = getCookies(true); cookies.clear(); cookies.addAll(newCookies); } public void setHeader(String headerName, String headerValue) { if (headerName == null) { throw new NullPointerException("headerName"); } if (headerValue == null) { throw new NullPointerException("headerValue"); } List<String> headerValues = getHeaderValues(headerName, true); headerValues.clear(); headerValues.add(headerValue); } public void addHeader(String headerName, String headerValue) { if (headerName == null) { throw new NullPointerException("headerName"); } if (headerValue == null) { throw new NullPointerException("headerValue"); } List<String> headerValues = getHeaderValues(headerName, true); headerValues.add(headerValue); } public List<String> removeHeader(String headerName) { Map<String, List<String>> headers = getHeaders(false); if (headers != null) { return headers.remove(headerName); } return EMPTY_HEADER; } public void clearHeaders() { Map<String, List<String>> headers = getHeaders(false); if (headers != null) { headers.clear(); } } public void setHeaders(Map<String, List<String>> newHeaders) { Map<String, List<String>> headers = getHeaders(true); headers.clear(); headers.putAll(newHeaders); } public void putHeaders(Map<String, List<String>> newHeaders) { Map<String, List<String>> headers = getHeaders(true); headers.putAll(newHeaders); } public Iterator<String> iterateHeaderNames() { return (headers != null && !headers.isEmpty()) ? headers.keySet().iterator() : EMPTY_HEADER_NAMES.iterator(); } public Set<String> getHeaderNames() { Map<String, List<String>> headers = getHeaders(false); return (headers != null && !headers.isEmpty()) ? unmodifiableSet(headers.keySet()) : EMPTY_HEADER_NAMES; } public Map<String, List<String>> getHeaders() { Map<String, List<String>> headers = getHeaders(false); return (headers != null && !headers.isEmpty()) ? unmodifiableMap(headers) : EMPTY_HEADERS; } public Map<String, List<String>> getModifiableHeaders() { Map<String, List<String>> headers = getHeaders(false); return (headers != null && !headers.isEmpty()) ? headers : EMPTY_HEADERS; } public List<String> getHeaderValues(String headerName) { return getHeaderValues(headerName, true); } public String getHeader(String headerName) { List<String> headerValues = getHeaderValues(headerName, false); if (headerValues == null) { return null; } return headerValues.isEmpty() ? null : headerValues.get(0); } public boolean hasHeaders() { return (headers != null && !headers.isEmpty()); } public boolean hasHeader(String headerName) { return (headers != null && headers.containsKey(headerName)); } public void setVersion(HttpVersion version) { this.version = version; } public HttpVersion getVersion() { return version; } public void setContent(HttpContentMessage content) { this.content = content; } public HttpContentMessage getContent() { return content; } private Set<HttpCookie> getCookies(boolean createIfNull) { if (cookies == null && createIfNull) { cookies = new TreeSet<HttpCookie>(HttpCookieComparator.INSTANCE); } return cookies; } private Map<String, List<String>> getHeaders(boolean createIfNull) { if (headers == null && createIfNull) { headers = createHeaders(); } return headers; } protected abstract Map<String, List<String>> createHeaders(); public List<String> getHeaderValues(String headerName, boolean createIfNull) { Map<String, List<String>> headers = getHeaders(createIfNull); if (headers == null) { return null; } List<String> headerValues = headers.get(headerName); if (headerValues == null && createIfNull) { headerValues = new LinkedList<String>(); headers.put(headerName, headerValues); } return headerValues; } @Override public int hashCode() { int hashCode = 0; if (version != null) { hashCode ^= version.hashCode(); } if (headers != null) { hashCode ^= headers.hashCode(); } if (cookies != null) { hashCode ^= cookies.hashCode(); } if (content != null) { hashCode ^= content.hashCode(); } return hashCode; } protected boolean equals(HttpStartMessage that) { return (sameOrEquals(this.version, that.version) && sameOrEquals(this.headers, that.headers) && sameOrEquals(this.cookies, that.cookies) && sameOrEquals(this.content, that.content)); } static final boolean sameOrEquals(Object this_, Object that) { return (this_ == that) || (this_ != null && this_.equals(that)); } public static final <K, V> boolean sameOrEquals(Map<K, V> this_, Map<K, V> that) { return (this_ == that) || (this_ == null && that.isEmpty()) || (that == null && this_.isEmpty()) || (this_ != null && this_.equals(that)); } static final <T> boolean sameOrEquals(Collection<T> this_, Collection<T> that) { return (this_ == that) || (this_ == null && that.isEmpty()) || (that == null && this_.isEmpty()) || (this_ != null && this_.equals(that)); } }
/* * The MIT License * Copyright (c) 2012 Microsoft Corporation * * 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 microsoft.exchange.webservices.data.property.complex.availability; import microsoft.exchange.webservices.data.ISelfValidate; import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; import microsoft.exchange.webservices.data.core.EwsUtilities; import microsoft.exchange.webservices.data.core.XmlElementNames; import microsoft.exchange.webservices.data.enumeration.OofExternalAudience; import microsoft.exchange.webservices.data.enumeration.OofState; import microsoft.exchange.webservices.data.enumeration.XmlNamespace; import microsoft.exchange.webservices.data.exception.ArgumentException; import microsoft.exchange.webservices.data.exception.ServiceXmlSerializationException; import microsoft.exchange.webservices.data.misc.availability.OofReply; import microsoft.exchange.webservices.data.misc.availability.TimeWindow; import microsoft.exchange.webservices.data.property.complex.ComplexProperty; import javax.xml.stream.XMLStreamException; /** * Represents a user's Out of Office (OOF) settings. */ public final class OofSettings extends ComplexProperty implements ISelfValidate { /** * The state. */ private OofState state = OofState.Disabled; /** * The external audience. */ private OofExternalAudience externalAudience = OofExternalAudience.None; /** * The allow external oof. */ private OofExternalAudience allowExternalOof = OofExternalAudience.None; /** * The duration. */ private TimeWindow duration; /** * The internal reply. */ private OofReply internalReply; /** * The external reply. */ private OofReply externalReply; /** * Serializes an OofReply. Emits an empty OofReply in case the one passed in * is null. * * @param oofReply The oof reply * @param writer The writer * @param xmlElementName Name of the xml element * @throws javax.xml.stream.XMLStreamException the xML stream exception * @throws microsoft.exchange.webservices.data.exception.ServiceXmlSerializationException the service xml serialization exception */ private void serializeOofReply(OofReply oofReply, EwsServiceXmlWriter writer, String xmlElementName) throws XMLStreamException, ServiceXmlSerializationException { if (oofReply != null) { oofReply.writeToXml(writer, xmlElementName); } else { OofReply.writeEmptyReplyToXml(writer, xmlElementName); } } /** * Initializes a new instance of OofSettings. */ public OofSettings() { super(); } /** * Tries to read element from XML. * * @param reader The reader * @return True if appropriate element was read. * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (reader.getLocalName().equals(XmlElementNames.OofState)) { this.state = reader.readValue(OofState.class); return true; } else if (reader.getLocalName().equals( XmlElementNames.ExternalAudience)) { this.externalAudience = reader.readValue(OofExternalAudience.class); return true; } else if (reader.getLocalName().equals(XmlElementNames.Duration)) { this.duration = new TimeWindow(); this.duration.loadFromXml(reader); return true; } else if (reader.getLocalName().equals(XmlElementNames.InternalReply)) { this.internalReply = new OofReply(); this.internalReply.loadFromXml(reader, reader.getLocalName()); return true; } else if (reader.getLocalName().equals(XmlElementNames.ExternalReply)) { this.externalReply = new OofReply(); this.externalReply.loadFromXml(reader, reader.getLocalName()); return true; } else { return false; } } /** * Writes elements to XML. * * @param writer The writer * @throws Exception the exception */ @Override public void writeElementsToXml(EwsServiceXmlWriter writer) throws Exception { super.writeElementsToXml(writer); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.OofState, this.getState()); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.ExternalAudience, this.getExternalAudience()); if (this.getDuration() != null && this.getState() == OofState.Scheduled) { this.getDuration().writeToXml(writer, XmlElementNames.Duration); } this.serializeOofReply(this.getInternalReply(), writer, XmlElementNames.InternalReply); this.serializeOofReply(this.getExternalReply(), writer, XmlElementNames.ExternalReply); } /** * Gets the user's OOF state. * * @return The user's OOF state. */ public OofState getState() { return state; } /** * Sets the user's OOF state. * * @param state the new state */ public void setState(OofState state) { this.state = state; } /** * Gets a value indicating who should receive external OOF messages. * * @return the external audience */ public OofExternalAudience getExternalAudience() { return externalAudience; } /** * Sets a value indicating who should receive external OOF messages. * * @param externalAudience the new external audience */ public void setExternalAudience(OofExternalAudience externalAudience) { this.externalAudience = externalAudience; } /** * Gets the duration of the OOF status when State is set to * OofState.Scheduled. * * @return the duration */ public TimeWindow getDuration() { return duration; } /** * Sets the duration of the OOF status when State is set to * OofState.Scheduled. * * @param duration the new duration */ public void setDuration(TimeWindow duration) { this.duration = duration; } /** * Gets the OOF response sent other users in the user's domain or trusted * domain. * * @return the internal reply */ public OofReply getInternalReply() { return internalReply; } /** * Sets the OOF response sent other users in the user's domain or trusted * domain. * * @param internalReply the new internal reply */ public void setInternalReply(OofReply internalReply) { this.internalReply = internalReply; } /** * Gets the OOF response sent to addresses outside the user's domain or * trusted domain. * * @return the external reply */ public OofReply getExternalReply() { return externalReply; } /** * Sets the OOF response sent to addresses outside the user's domain or * trusted domain. * * @param externalReply the new external reply */ public void setExternalReply(OofReply externalReply) { this.externalReply = externalReply; } /** * Gets a value indicating the authorized external OOF notification. * * @return the allow external oof */ public OofExternalAudience getAllowExternalOof() { return allowExternalOof; } /** * Sets a value indicating the authorized external OOF notification. * * @param allowExternalOof the new allow external oof */ public void setAllowExternalOof(OofExternalAudience allowExternalOof) { this.allowExternalOof = allowExternalOof; } /** * Validates this instance. * * @throws Exception the exception */ @Override public void validate() throws Exception { if (this.getState() == OofState.Scheduled) { if (this.getDuration() == null) { throw new ArgumentException("Duration must be specified when State is equal to Scheduled."); } EwsUtilities.validateParam(this.getDuration(), "Duration"); } } }
package org.elasticsearch.plugin.nlpcn; import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.internal.InternalSearchHit; import org.nlpcn.es4sql.domain.Field; import org.nlpcn.es4sql.domain.Select; import org.nlpcn.es4sql.domain.Where; import org.nlpcn.es4sql.exception.SqlParseException; import org.nlpcn.es4sql.query.join.HashJoinElasticRequestBuilder; import org.nlpcn.es4sql.query.join.TableInJoinRequestBuilder; import org.nlpcn.es4sql.query.maker.QueryMaker; import java.io.IOException; import java.util.*; /** * Created by Eliran on 22/8/2015. */ public class HashJoinElasticExecutor extends ElasticJoinExecutor { private HashJoinElasticRequestBuilder requestBuilder; private Client client; private boolean useQueryTermsFilterOptimization = false; private final int MAX_RESULTS_FOR_FIRST_TABLE = 100000; HashJoinComparisonStructure hashJoinComparisonStructure; private Set<String> alreadyMatched; public HashJoinElasticExecutor(Client client, HashJoinElasticRequestBuilder requestBuilder) { super(requestBuilder); this.client = client; this.requestBuilder = requestBuilder; this.useQueryTermsFilterOptimization = requestBuilder.isUseTermFiltersOptimization(); this.hashJoinComparisonStructure = new HashJoinComparisonStructure(requestBuilder.getT1ToT2FieldsComparison()); this.alreadyMatched = new HashSet<>(); } public List<InternalSearchHit> innerRun() throws IOException, SqlParseException { Map<String, Map<String, List<Object>>> optimizationTermsFilterStructure = initOptimizationStructure(); updateFirstTableLimitIfNeeded(); TableInJoinRequestBuilder firstTableRequest = requestBuilder.getFirstTable(); createKeyToResultsAndFillOptimizationStructure(optimizationTermsFilterStructure, firstTableRequest); TableInJoinRequestBuilder secondTableRequest = requestBuilder.getSecondTable(); if (needToOptimize(optimizationTermsFilterStructure)) { updateRequestWithTermsFilter(optimizationTermsFilterStructure, secondTableRequest); } List<InternalSearchHit> combinedResult = createCombinedResults(secondTableRequest); int currentNumOfResults = combinedResult.size(); int totalLimit = requestBuilder.getTotalLimit(); if (requestBuilder.getJoinType() == SQLJoinTableSource.JoinType.LEFT_OUTER_JOIN && currentNumOfResults < totalLimit) { String t1Alias = requestBuilder.getFirstTable().getAlias(); String t2Alias = requestBuilder.getSecondTable().getAlias(); //todo: for each till Limit addUnmatchedResults(combinedResult, this.hashJoinComparisonStructure.getAllSearchHits(), requestBuilder.getSecondTable().getReturnedFields(), currentNumOfResults, totalLimit, t1Alias, t2Alias); } if(firstTableRequest.getOriginalSelect().isOrderdSelect()){ Collections.sort(combinedResult,new Comparator<InternalSearchHit>() { @Override public int compare(InternalSearchHit o1, InternalSearchHit o2) { return o1.docId() - o2.docId(); } }); } return combinedResult; } private Map<String, Map<String, List<Object>>> initOptimizationStructure() { Map<String,Map<String, List<Object>>> optimizationTermsFilterStructure = new HashMap<>(); for(String comparisonId: this.hashJoinComparisonStructure.getComparisons().keySet()){ optimizationTermsFilterStructure.put(comparisonId,new HashMap<String, List<Object>>()); } return optimizationTermsFilterStructure; } private void updateFirstTableLimitIfNeeded() { if (requestBuilder.getJoinType() == SQLJoinTableSource.JoinType.LEFT_OUTER_JOIN) { Integer firstTableHintLimit = requestBuilder.getFirstTable().getHintLimit(); int totalLimit = requestBuilder.getTotalLimit(); if (firstTableHintLimit == null || firstTableHintLimit > totalLimit) { requestBuilder.getFirstTable().setHintLimit(totalLimit); } } } private List<InternalSearchHit> createCombinedResults( TableInJoinRequestBuilder secondTableRequest) { List<InternalSearchHit> combinedResult = new ArrayList<>(); int resultIds = 0; int totalLimit = this.requestBuilder.getTotalLimit(); Integer hintLimit = secondTableRequest.getHintLimit(); SearchResponse searchResponse; boolean finishedScrolling; if (hintLimit != null && hintLimit < MAX_RESULTS_ON_ONE_FETCH) { searchResponse = secondTableRequest.getRequestBuilder().setSize(hintLimit).get(); finishedScrolling = true; } else { searchResponse = secondTableRequest.getRequestBuilder() .setSearchType(SearchType.SCAN) .setScroll(new TimeValue(60000)) .setSize(MAX_RESULTS_ON_ONE_FETCH).get(); searchResponse = client.prepareSearchScroll(searchResponse.getScrollId()).setScroll(new TimeValue(600000)).get(); finishedScrolling = false; } updateMetaSearchResults(searchResponse); boolean limitReached = false; int fetchedSoFarFromSecondTable = 0; while (!limitReached) { SearchHit[] secondTableHits = searchResponse.getHits().getHits(); fetchedSoFarFromSecondTable += secondTableHits.length; for (SearchHit secondTableHit : secondTableHits) { if (limitReached) break; //todo: need to run on comparisons. for each comparison check if exists and add. HashMap<String, List<Map.Entry<Field, Field>>> comparisons = this.hashJoinComparisonStructure.getComparisons(); for (Map.Entry<String, List<Map.Entry<Field, Field>>> comparison : comparisons.entrySet()) { String comparisonID = comparison.getKey(); List<Map.Entry<Field, Field>> t1ToT2FieldsComparison = comparison.getValue(); String key = getComparisonKey(t1ToT2FieldsComparison, secondTableHit, false, null); SearchHitsResult searchHitsResult = this.hashJoinComparisonStructure.searchForMatchingSearchHits(comparisonID, key); if (searchHitsResult != null && searchHitsResult.getSearchHits().size() > 0) { searchHitsResult.setMatchedWithOtherTable(true); List<InternalSearchHit> searchHits = searchHitsResult.getSearchHits(); for (InternalSearchHit matchingHit : searchHits) { String combinedId = matchingHit.id() + "|" + secondTableHit.getId(); //in order to prevent same matching when using OR on hashJoins. if(this.alreadyMatched.contains(combinedId)){ continue; } else { this.alreadyMatched.add(combinedId); } Map<String,Object> copiedSource = new HashMap<String,Object>(); copyMaps(copiedSource,secondTableHit.sourceAsMap()); onlyReturnedFields(copiedSource, secondTableRequest.getReturnedFields(),secondTableRequest.getOriginalSelect().isSelectAll()); InternalSearchHit searchHit = new InternalSearchHit(matchingHit.docId(), combinedId, new Text(matchingHit.getType() + "|" + secondTableHit.getType()), matchingHit.getFields()); searchHit.sourceRef(matchingHit.getSourceRef()); searchHit.sourceAsMap().clear(); searchHit.sourceAsMap().putAll(matchingHit.sourceAsMap()); String t1Alias = requestBuilder.getFirstTable().getAlias(); String t2Alias = requestBuilder.getSecondTable().getAlias(); mergeSourceAndAddAliases(copiedSource, searchHit, t1Alias, t2Alias); combinedResult.add(searchHit); resultIds++; if (resultIds >= totalLimit) { limitReached = true; break; } } } } } if (!finishedScrolling) { if (secondTableHits.length > 0 && (hintLimit == null || fetchedSoFarFromSecondTable >= hintLimit)) { searchResponse = client.prepareSearchScroll(searchResponse.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet(); } else break; } else { break; } } return combinedResult; } private void copyMaps(Map<String, Object> into, Map<String, Object> from) { for(Map.Entry<String,Object> keyAndValue : from.entrySet()) into.put(keyAndValue.getKey(),keyAndValue.getValue()); } private void createKeyToResultsAndFillOptimizationStructure(Map<String,Map<String, List<Object>>> optimizationTermsFilterStructure, TableInJoinRequestBuilder firstTableRequest) { List<SearchHit> firstTableHits = fetchAllHits(firstTableRequest); int resultIds = 1; for (SearchHit hit : firstTableHits) { HashMap<String, List<Map.Entry<Field, Field>>> comparisons = this.hashJoinComparisonStructure.getComparisons(); for (Map.Entry<String, List<Map.Entry<Field, Field>>> comparison : comparisons.entrySet()) { String comparisonID = comparison.getKey(); List<Map.Entry<Field, Field>> t1ToT2FieldsComparison = comparison.getValue(); String key = getComparisonKey(t1ToT2FieldsComparison, hit, true, optimizationTermsFilterStructure.get(comparisonID)); //int docid , id InternalSearchHit searchHit = new InternalSearchHit(resultIds, hit.id(), new Text(hit.getType()), hit.getFields()); searchHit.sourceRef(hit.getSourceRef()); onlyReturnedFields(searchHit.sourceAsMap(), firstTableRequest.getReturnedFields(),firstTableRequest.getOriginalSelect().isSelectAll()); resultIds++; this.hashJoinComparisonStructure.insertIntoComparisonHash(comparisonID, key, searchHit); } } } private List<SearchHit> fetchAllHits(TableInJoinRequestBuilder tableInJoinRequest) { Integer hintLimit = tableInJoinRequest.getHintLimit(); SearchRequestBuilder requestBuilder = tableInJoinRequest.getRequestBuilder(); if (hintLimit != null && hintLimit < MAX_RESULTS_ON_ONE_FETCH) { requestBuilder.setSize(hintLimit); SearchResponse searchResponse = requestBuilder.get(); updateMetaSearchResults(searchResponse); return Arrays.asList(searchResponse.getHits().getHits()); } return scrollTillLimit(tableInJoinRequest, hintLimit); } private List<SearchHit> scrollTillLimit(TableInJoinRequestBuilder tableInJoinRequest, Integer hintLimit) { SearchResponse scrollResp = scrollOneTimeWithMax(client,tableInJoinRequest); updateMetaSearchResults(scrollResp); List<SearchHit> hitsWithScan = new ArrayList<>(); int curentNumOfResults = 0; SearchHit[] hits = scrollResp.getHits().hits(); if (hintLimit == null) hintLimit = MAX_RESULTS_FOR_FIRST_TABLE; while (hits.length != 0 && curentNumOfResults < hintLimit) { curentNumOfResults += hits.length; Collections.addAll(hitsWithScan, hits); if (curentNumOfResults >= MAX_RESULTS_FOR_FIRST_TABLE) { //todo: log or exception? System.out.println("too many results for first table, stoping at:" + curentNumOfResults); break; } scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet(); hits = scrollResp.getHits().getHits(); } return hitsWithScan; } private boolean needToOptimize(Map<String,Map<String, List<Object>>> optimizationTermsFilterStructure) { if(! useQueryTermsFilterOptimization && optimizationTermsFilterStructure != null && optimizationTermsFilterStructure.size() > 0) return false; boolean allEmpty = true; for(Map<String,List<Object>> optimization : optimizationTermsFilterStructure.values()){ if(optimization.size() > 0){ allEmpty = false; break; } } return !allEmpty; } private void updateRequestWithTermsFilter(Map<String,Map<String, List<Object>>> optimizationTermsFilterStructure, TableInJoinRequestBuilder secondTableRequest) throws SqlParseException { Select select = secondTableRequest.getOriginalSelect(); BoolQueryBuilder orQuery = QueryBuilders.boolQuery(); for(Map<String,List<Object>> optimization : optimizationTermsFilterStructure.values()) { BoolQueryBuilder andQuery = QueryBuilders.boolQuery(); for (Map.Entry<String, List<Object>> keyToValues : optimization.entrySet()) { String fieldName = keyToValues.getKey(); List<Object> values = keyToValues.getValue(); andQuery.must(QueryBuilders.termsQuery(fieldName, values)); } orQuery.should(andQuery); } Where where = select.getWhere(); BoolQueryBuilder boolQuery; if (where != null) { boolQuery = QueryMaker.explan(where,false); boolQuery.must(orQuery); } else boolQuery = orQuery; secondTableRequest.getRequestBuilder().setQuery(boolQuery); } private String getComparisonKey(List<Map.Entry<Field, Field>> t1ToT2FieldsComparison, SearchHit hit, boolean firstTable, Map<String, List<Object>> optimizationTermsFilterStructure) { String key = ""; Map<String, Object> sourceAsMap = hit.sourceAsMap(); for (Map.Entry<Field, Field> t1ToT2 : t1ToT2FieldsComparison) { //todo: change to our function find if key contains '.' String name; if (firstTable) name = t1ToT2.getKey().getName(); else name = t1ToT2.getValue().getName(); Object data = deepSearchInMap(sourceAsMap, name); if (firstTable && useQueryTermsFilterOptimization) { updateOptimizationData(optimizationTermsFilterStructure, data, t1ToT2.getValue().getName()); } if (data == null) key += "|null|"; else key += "|" + data.toString() + "|"; } return key; } private void updateOptimizationData(Map<String, List<Object>> optimizationTermsFilterStructure, Object data, String queryOptimizationKey) { List<Object> values = optimizationTermsFilterStructure.get(queryOptimizationKey); if (values == null) { values = new ArrayList<>(); optimizationTermsFilterStructure.put(queryOptimizationKey, values); } if (data instanceof String) { //todo: analyzed or not analyzed check.. data = ((String) data).toLowerCase(); } if(data!=null) values.add(data); } }
package edu.tamu.di.SAFCreator.model; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import edu.tamu.di.SAFCreator.Util; public class Item { private Batch batch; private List<SchematicFieldSet> schemata; private List<Bundle> bundles; private String handle; private Integer rowNumber; private boolean cancelled; private File itemDirectory; public Item(int row, Batch batch) { this.rowNumber = row; this.batch = batch; schemata = new ArrayList<SchematicFieldSet>(); bundles = new ArrayList<Bundle>(); itemDirectory = new File(batch.getOutputSAFDir().getAbsolutePath() + File.separator + getRowNumber()); itemDirectory.mkdir(); handle = null; cancelled = false; } public Integer getRowNumber() { return rowNumber; } private boolean checkIsCancelled(Object object, Method method) { try { Object arglist[] = new Object[0]; Object result = method.invoke(object, arglist); Boolean isCancelled = (Boolean) result; cancelled = isCancelled.booleanValue(); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } return cancelled; } public Batch getBatch() { return batch; } public List<Bundle> getBundles() { return bundles; } public String getHandle() { return handle; } public Bundle getOrCreateBundle(String bundleName) { for (Bundle bundle : bundles) { if (bundle.getName().equals(bundleName)) { return bundle; } } Bundle bundle = new Bundle(); bundle.setName(bundleName); bundle.setItem(this); bundles.add(bundle); return bundle; } public SchematicFieldSet getOrCreateSchema(String schemaName) { for (SchematicFieldSet schema : schemata) { if (schema.getSchemaName().equals(schemaName)) { return schema; } } SchematicFieldSet schema = new SchematicFieldSet(); schema.setSchemaName(schemaName); schemata.add(schema); return schema; } public String getSAFDirectory() { return itemDirectory.getAbsolutePath(); } public List<SchematicFieldSet> getSchemata() { return schemata; } public void setHandle(String handle) { this.handle = handle; } public List<Problem> writeItemSAF(Object object, Method method) { List<Problem> problems = new ArrayList<Problem>(); cancelled = false; if (!cancelled) { writeContents(problems, object, method); } if (!cancelled) { writeMetadata(problems, object, method); } if (!cancelled && getHandle() != null) { writeHandle(problems, object, method); } return problems; } private void writeContents(List<Problem> problems, Object object, Method method) { String contentsString = ""; for (Bundle bundle : bundles) { if (checkIsCancelled(object, method)) { return; } for (Bitstream bitstream : bundle.getBitstreams()) { if (checkIsCancelled(object, method)) { return; } if (!batch.getIgnoreFiles()) { bitstream.setAction(batch.getAction()); bitstream.copyMe(problems); } contentsString += bitstream.getContentsManifestLine(); } } if (checkIsCancelled(object, method)) { return; } if (batch.getLicense() != null) { contentsString += batch.getLicense().getContentsManifestLine(); batch.getLicense().writeToItem(this); } if (checkIsCancelled(object, method)) { return; } File contentsFile = new File(getSAFDirectory() + "/contents"); try { if (!contentsFile.exists()) { contentsFile.createNewFile(); } Util.setFileContents(contentsFile, contentsString); } catch (FileNotFoundException e) { Problem problem = new Problem(true, "Unable to write to missing contents file for item directory " + getSAFDirectory() + ", reason: " + e.getMessage()); problems.add(problem); } catch (IOException e) { Problem problem = new Problem(true, "Error writing contents file for item directory " + getSAFDirectory() + ", reason: " + e.getMessage()); problems.add(problem); } } private void writeHandle(List<Problem> problems, Object object, Method method) { File handleFile = new File(itemDirectory.getAbsolutePath() + "/handle"); try { if (!handleFile.exists()) { handleFile.createNewFile(); } Util.setFileContents(handleFile, getHandle()); } catch (FileNotFoundException e) { Problem problem = new Problem(true, "Unable to write to missing handle file for item directory " + getSAFDirectory() + ", reason: " + e.getMessage()); problems.add(problem); } catch (IOException e) { Problem problem = new Problem(true, "Error writing handle file for item directory " + getSAFDirectory() + ", reason: " + e.getMessage()); problems.add(problem); } } private void writeMetadata(List<Problem> problems, Object object, Method method) { for (SchematicFieldSet schema : schemata) { File metadataFile = new File(itemDirectory.getAbsolutePath() + "/" + schema.getFilename()); try { if (!metadataFile.exists()) { metadataFile.createNewFile(); } Util.setFileContents(metadataFile, schema.getXML()); } catch (FileNotFoundException e) { Problem problem = new Problem(true, "Unable to write to missing metadata file " + metadataFile.getAbsolutePath() + ", reason: " + e.getMessage()); problems.add(problem); } catch (IOException e) { Problem problem = new Problem(true, "Unable to create metadata file " + metadataFile.getAbsolutePath() + ", reason: " + e.getMessage()); problems.add(problem); } } } }
/* * Copyright (C) 2007 Peter Monks * * 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. * * This file is part of an unsupported extension to Alfresco. * */ package org.alfresco.extension.bulkimport.source; import java.io.Serializable; import java.math.BigDecimal; import java.util.Map; import java.util.Set; /** * This class provides some handy default implementations for some of the * methods in <code>BulkImportItem.Version</code>. Its use is optional. * * @author Peter Monks (pmonks@gmail.com) * */ public abstract class AbstractBulkImportItemVersion<C, M> implements BulkImportItemVersion, Comparable<AbstractBulkImportItemVersion<C, M>> { protected final String type; protected final BigDecimal versionNumber; protected C contentReference; protected M metadataReference; protected AbstractBulkImportItemVersion(final String type, final BigDecimal versionNumber) { // PRECONDITIONS if (type == null || type.trim().length() <= 0) throw new IllegalArgumentException("type cannot be null, empty or blank."); if (versionNumber == null) throw new IllegalArgumentException("versionNumber cannot be null."); // Body this.type = type; this.versionNumber = versionNumber; } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getType() */ @Override public String getType() { return(type); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getVersionNumber() */ @Override public BigDecimal getVersionNumber() { return(versionNumber); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getVersionComment() */ @Override public String getVersionComment() { return(null); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getAspects() */ @Override public Set<String> getAspects() { return(null); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#contentIsInPlace() */ @Override public boolean contentIsInPlace() { return(false); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#hasContent() */ @Override public boolean hasContent() { return(contentReference != null); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#hasMetadata() */ @Override public boolean hasMetadata() { return(metadataReference != null); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getContentSource() */ @Override public String getContentSource() { return(String.valueOf(contentReference)); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getMetadataSource() */ @Override public String getMetadataSource() { return(String.valueOf(metadataReference)); } /** * @see org.alfresco.extension.bulkimport.source.BulkImportItemVersion#getMetadata() */ @Override public Map<String, Serializable> getMetadata() { return(null); } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(final AbstractBulkImportItemVersion<C, M> other) { if (this.versionNumber == null && other.versionNumber == null) return(0); if (this.versionNumber == null) return(1); if (other.versionNumber == null) return(-1); return(this.versionNumber.compareTo(other.versionNumber)); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object other) { if (this == other) return(true); if (!this.getClass().equals(other.getClass())) return(false); if (!(other instanceof AbstractBulkImportItemVersion)) return(false); @SuppressWarnings("unchecked") AbstractBulkImportItemVersion<C, M> otherVersion = (AbstractBulkImportItemVersion<C, M>)other; return(compareTo(otherVersion) == 0); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return(versionNumber.hashCode()); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return((VERSION_HEAD.equals(versionNumber) ? "HEAD" : ("v" + String.valueOf(versionNumber))) + ": " + (hasContent() ? "<content>" : "<no content>") + " " + (hasMetadata() ? "<metadata>" : "<no metadata>")); } }
/* * Copyright (c) 2014 F. Mannhardt (f.mannhardt@tue.nl) * * LICENSE: * * This code 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 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 Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ package org.processmining.log.utils; import java.util.Date; import org.deckfour.xes.extension.std.XConceptExtension; import org.deckfour.xes.factory.XFactory; import org.deckfour.xes.factory.XFactoryRegistry; import org.deckfour.xes.model.XAttribute; import org.deckfour.xes.model.XEvent; import org.deckfour.xes.model.XLog; import org.deckfour.xes.model.XTrace; /** * Fluent-style builder for create a XLog in an easy way. Get an instance by * calling {@link XLogBuilder#newInstance()}, then it can be used as follows: * <pre> * {@code * XLog log = XLogBuilder.newInstance() * .startLog("logName") * .addTrace("traceName", 2) * .addAttribute("traceAttribute", "test") * .addEvent("Event1") * .addAttribute("eventAttribute", 21) * .addEvent("Event2") * .addEvent("Event3") * .addEvent("Event4", 2) * .build(); * } * </pre> * Please note that a {@link XLogBuilder} instance is design to be used to * create one log only. * * @author F. Mannhardt * */ public class XLogBuilder { public static XLogBuilder newInstance() { return new XLogBuilder(); } private XFactory factory = XFactoryRegistry.instance().currentDefault(); private final XConceptExtension conceptInstance = XConceptExtension.instance(); private XLog log = null; private XTrace currentTrace = null; private int currentTraceMultiplicity = 1; private XEvent currentEvent = null; private int currentEventMultiplicity; public XLogBuilder startLog(String name) { log = factory.createLog(); if (log != null) { XConceptExtension.instance().assignName(log, name); } return this; } public XLogBuilder addTrace(String name) { return addTrace(name, 1); } public XLogBuilder addTrace(String name, int numberOfTraces) { if (log == null) { throw new IllegalStateException("Please call 'startLog' first!"); } if (currentEvent != null) { addCurrentEventToTrace(); } if (currentTrace != null) { addCurrentTraceToLog(); currentEvent = null; } currentTrace = factory.createTrace(); if (name != null) { conceptInstance.assignName(currentTrace, name); } currentTraceMultiplicity = numberOfTraces; return this; } private void addCurrentTraceToLog() { log.add(currentTrace); if (currentTraceMultiplicity > 1) { for (int i = 0; i < currentTraceMultiplicity - 1; i++) { XTrace clone = (XTrace) currentTrace.clone(); String name = conceptInstance.extractName(clone); if (name != null) { conceptInstance.assignName(clone, name.concat("-").concat(String.valueOf(i+1))); } log.add(clone); } } } public XLogBuilder addEvent(String name) { addEvent(name, 1); return this; } public XLogBuilder addEvent(String name, int numberOfEvents) { if (currentTrace == null) { throw new IllegalStateException("Please call 'addTrace' first!"); } if (currentEvent != null) { addCurrentEventToTrace(); } currentEvent = factory.createEvent(); XConceptExtension.instance().assignName(currentEvent, name); currentEventMultiplicity = numberOfEvents; return this; } private void addCurrentEventToTrace() { currentTrace.add(currentEvent); if (currentEventMultiplicity > 1) { for (int i = 0; i < currentEventMultiplicity - 1; i++) { currentTrace.add((XEvent) currentEvent.clone()); } } } /** * Add the given attribute * * @param attribute * @return {@link XLogBuilder} */ public XLogBuilder addAttribute(XAttribute attribute) { addAttributeInternal(attribute.getKey(), attribute); return this; } /** * @param name * @param value * @return */ public XLogBuilder addAttribute(String name, boolean value) { XAttribute attribute = factory.createAttributeBoolean(name, value, null); addAttributeInternal(name, attribute); return this; } /** * @param name * @param value * @return the {@link XLogBuilder} itself */ public XLogBuilder addAttribute(String name, long value) { XAttribute attribute = factory.createAttributeDiscrete(name, value, null); addAttributeInternal(name, attribute); return this; } /** * @param name * @param value * @return the {@link XLogBuilder} itself */ public XLogBuilder addAttribute(String name, String value) { XAttribute attribute = factory.createAttributeLiteral(name, value, null); addAttributeInternal(name, attribute); return this; } /** * @param name * @param value * @return the {@link XLogBuilder} itself */ public XLogBuilder addAttribute(String name, Date value) { XAttribute attribute = factory.createAttributeTimestamp(name, value, null); addAttributeInternal(name, attribute); return this; } /** * @param name * @param value * @return the {@link XLogBuilder} itself */ public XLogBuilder addAttribute(String name, double value) { XAttribute attribute = factory.createAttributeContinuous(name, value, null); addAttributeInternal(name, attribute); return this; } private void addAttributeInternal(String name, XAttribute attribute) { if (currentEvent == null && currentTrace == null) { throw new IllegalStateException("Please call 'addEvent' or 'addTrace' first!"); } if (currentEvent == null) { // Trace Attributes currentTrace.getAttributes().put(name, attribute); } else { // Event Attributes currentEvent.getAttributes().put(name, attribute); } } /** * Builds and returns the XLog. This is only to be used once! * * @return the final XLog */ public XLog build() { if (currentEvent != null) { addCurrentEventToTrace(); } if (currentTrace != null) { addCurrentTraceToLog(); } return log; } }
package io.github.thankpoint.core.impl.strategy; import javax.crypto.Cipher; import io.github.thankpoint.core.api.ThankTokenField; import io.github.thankpoint.core.api.ThankValidityLineField; import io.github.thankpoint.core.api.context.ThankTokenContext; import io.github.thankpoint.core.api.io.ThankBuffer; import io.github.thankpoint.core.api.io.ThankTokenIoConstants; import io.github.thankpoint.core.api.io.ThankTokenReader; import io.github.thankpoint.core.api.io.ThankTokenWriter; import io.github.thankpoint.core.api.signing.ThankTokenSigner; import io.github.thankpoint.core.api.signing.ThankTokenTxSecretGenerator; import io.github.thankpoint.core.api.strategy.ThankVersionStrategy; import io.github.thankpoint.core.api.validation.ThankTokenPublicKeyAccess; import io.github.thankpoint.core.api.validation.ThankTokenValidator; import io.github.thankpoint.core.impl.context.ThankTokenContextImpl; import io.github.thankpoint.core.impl.io.ThankTokenReaderImpl; import io.github.thankpoint.core.impl.io.ThankTokenWriterImpl; import io.github.thankpoint.core.impl.signing.ThankTokenSignerImpl; import io.github.thankpoint.core.impl.signing.ThankTokenTxSecretGeneratorImpl; import io.github.thankpoint.core.impl.validation.ThankTokenValidatorImpl; import io.github.thankpoint.security.api.BinaryType; import io.github.thankpoint.security.api.hash.SecurityHashFactory; import io.github.thankpoint.security.api.key.asymmetric.SecurityPublicKey; /** * The abstract base implementation of {@link ThankVersionStrategy}. * * @author thks */ public abstract class AbstractThankVersionStrategy implements ThankVersionStrategy, ThankTokenIoConstants { private ThankTokenReader reader; private ThankTokenWriter writer; private ThankTokenSigner signer; private ThankTokenValidator validator; private int bytesForHeader; private int bytesForValidityLine; private ThankTokenTxSecretGenerator txSecretGenerator; /** * The constructor. */ public AbstractThankVersionStrategy() { super(); } /** * @return the name of the algorithm for the {@link Cipher} used for encryption. */ public abstract String getCipherAlgorithm(); /** * @return the {@link SecurityHashFactory} used to {@link SecurityHashFactory#newHashCreator() create hasher * instances} to calculate hashes. */ public abstract SecurityHashFactory getHasherFactory(); /** * @return the {@link ThankTokenPublicKeyAccess}. */ protected abstract ThankTokenPublicKeyAccess getPublicKeyAccess(); @Override public ThankTokenContext createContext() { return new ThankTokenContextImpl(this); } @Override public ThankTokenReader getReader() { if (this.reader == null) { this.reader = createReader(); } return this.reader; } /** * @return the new {@link #getReader() reader}. */ protected ThankTokenReader createReader() { return new ThankTokenReaderImpl(this); } @Override public ThankTokenWriter getWriter() { if (this.writer == null) { this.writer = createWriter(); } return this.writer; } /** * @return the new {@link #getWriter() writer}. */ protected ThankTokenWriter createWriter() { return new ThankTokenWriterImpl(this); } @Override public ThankTokenSigner getSigner() { if (this.signer == null) { this.signer = createSigner(); } return this.signer; } /** * @return the new {@link #getSigner() signer}. */ protected ThankTokenSigner createSigner() { return new ThankTokenSignerImpl(this); } @Override public ThankTokenValidator getValidator() { if (this.validator == null) { this.validator = createValidator(); } return this.validator; } /** * @return the new {@link #getValidator() validator}. */ protected ThankTokenValidator createValidator() { return new ThankTokenValidatorImpl(this, getPublicKeyAccess()); } @Override public ThankTokenTxSecretGenerator getTxSecretGenerator() { if (this.txSecretGenerator == null) { this.txSecretGenerator = createTxSecretGenerator(); } return this.txSecretGenerator; } /** * @return the new {@link #getTxSecretGenerator() txSecretGenerator}. */ protected ThankTokenTxSecretGenerator createTxSecretGenerator() { return new ThankTokenTxSecretGeneratorImpl(getBytesFor(ThankValidityLineField.TX_SECRET)); } @Override public int getMaxHeaderBytes() { if (this.bytesForHeader == 0) { int bytes = 0; for (ThankTokenField<?> field : ThankTokenField.values()) { int maxLength = field.getMaxLength(); if (maxLength > 0) { bytes = bytes + maxLength + 1; // 1 = separator / terminator } else { assert (field == ThankTokenField.TX_SECRET); } } this.bytesForHeader = bytes; } return this.bytesForHeader; } @Override public int getMaxValidityLineBytes() { if (this.bytesForValidityLine == 0) { int bytes = 0; for (ThankValidityLineField<?> field : ThankValidityLineField.values()) { bytes = bytes + getBytesFor(field) + 1; // 1 = separator / terminator } this.bytesForValidityLine = bytes; } return this.bytesForValidityLine; } @Override public ThankBuffer createBuffer() { int capacity = Math.max(getMaxHeaderBytes(), getMaxValidityLineBytes()); return new ThankBuffer(capacity); } /** * @param hex the {@link BinaryType#getHex() hexadecimal representation} of the {@link SecurityPublicKey}. * @return the parsed {@link SecurityPublicKey}. */ public abstract SecurityPublicKey parsePublicKey(String hex); /** * @param field the {@link ThankTokenField}. * @return the length for the representation of the a value for the given {@link ThankTokenField field} in bytes. */ public int getBytesFor(ThankTokenField<?> field) { if (field == ThankTokenField.TX_SECRET) { return getBytesFor(ThankValidityLineField.TX_SECRET); } return field.getMaxLength(); } /** * @param field the {@link ThankValidityLineField}. * @return the length for the representation of the a value for the given {@link ThankValidityLineField field} in * bytes. */ public abstract int getBytesFor(ThankValidityLineField<?> field); }
/* * Copyright (c) 2016 Uber Technologies, Inc. (hoodie-dev-group@uber.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.hoodie.common.table; import com.uber.hoodie.common.table.timeline.HoodieDefaultTimeline; import com.uber.hoodie.common.table.timeline.HoodieInstant; import com.uber.hoodie.common.table.timeline.HoodieInstant.State; import com.uber.hoodie.common.util.StringUtils; import java.io.Serializable; import java.util.Optional; import java.util.function.BiPredicate; import java.util.stream.Stream; /** * HoodieTimeline is a view of meta-data instants in the hoodie dataset. Instants are specific * points in time represented as HoodieInstant. <p> Timelines are immutable once created and * operations create new instance of timelines which filter on the instants and this can be * chained. * * @see com.uber.hoodie.common.table.HoodieTableMetaClient * @see HoodieDefaultTimeline * @see HoodieInstant * @since 0.3.0 */ public interface HoodieTimeline extends Serializable { String COMMIT_ACTION = "commit"; String DELTA_COMMIT_ACTION = "deltacommit"; String CLEAN_ACTION = "clean"; String ROLLBACK_ACTION = "rollback"; String SAVEPOINT_ACTION = "savepoint"; String INFLIGHT_EXTENSION = ".inflight"; // With Async Compaction, compaction instant can be in 3 states : // (compaction-requested), (compaction-inflight), (completed) String COMPACTION_ACTION = "compaction"; String REQUESTED_EXTENSION = ".requested"; String COMMIT_EXTENSION = "." + COMMIT_ACTION; String DELTA_COMMIT_EXTENSION = "." + DELTA_COMMIT_ACTION; String CLEAN_EXTENSION = "." + CLEAN_ACTION; String ROLLBACK_EXTENSION = "." + ROLLBACK_ACTION; String SAVEPOINT_EXTENSION = "." + SAVEPOINT_ACTION; //this is to preserve backwards compatibility on commit in-flight filenames String INFLIGHT_COMMIT_EXTENSION = INFLIGHT_EXTENSION; String INFLIGHT_DELTA_COMMIT_EXTENSION = "." + DELTA_COMMIT_ACTION + INFLIGHT_EXTENSION; String INFLIGHT_CLEAN_EXTENSION = "." + CLEAN_ACTION + INFLIGHT_EXTENSION; String INFLIGHT_ROLLBACK_EXTENSION = "." + ROLLBACK_ACTION + INFLIGHT_EXTENSION; String INFLIGHT_SAVEPOINT_EXTENSION = "." + SAVEPOINT_ACTION + INFLIGHT_EXTENSION; String REQUESTED_COMPACTION_SUFFIX = StringUtils.join(COMPACTION_ACTION, REQUESTED_EXTENSION); String REQUESTED_COMPACTION_EXTENSION = StringUtils.join(".", REQUESTED_COMPACTION_SUFFIX); String INFLIGHT_COMPACTION_EXTENSION = StringUtils.join(".", COMPACTION_ACTION, INFLIGHT_EXTENSION); /** * Filter this timeline to just include the in-flights * * @return New instance of HoodieTimeline with just in-flights */ HoodieTimeline filterInflights(); /** * Filter this timeline to just include the in-flights excluding compaction instants * * @return New instance of HoodieTimeline with just in-flights excluding compaction inflights */ HoodieTimeline filterInflightsExcludingCompaction(); /** * Filter this timeline to just include the completed instants * * @return New instance of HoodieTimeline with just completed instants */ HoodieTimeline filterCompletedInstants(); /** * Filter this timeline to just include the completed + compaction (inflight + requested) instants * A RT filesystem view is constructed with this timeline so that file-slice after pending compaction-requested * instant-time is also considered valid. A RT file-system view for reading must then merge the file-slices before * and after pending compaction instant so that all delta-commits are read. * @return New instance of HoodieTimeline with just completed instants */ HoodieTimeline filterCompletedAndCompactionInstants(); /** * Filter this timeline to just include inflight and requested compaction instants * @return */ HoodieTimeline filterPendingCompactionTimeline(); /** * Create a new Timeline with instants after startTs and before or on endTs */ HoodieTimeline findInstantsInRange(String startTs, String endTs); /** * Create a new Timeline with all the instants after startTs */ HoodieTimeline findInstantsAfter(String commitTime, int numCommits); /** * If the timeline has any instants * * @return true if timeline is empty */ boolean empty(); /** * @return total number of completed instants */ int countInstants(); /** * @return first completed instant if available */ Optional<HoodieInstant> firstInstant(); /** * @return nth completed instant from the first completed instant */ Optional<HoodieInstant> nthInstant(int n); /** * @return last completed instant if available */ Optional<HoodieInstant> lastInstant(); /** * @return nth completed instant going back from the last completed instant */ Optional<HoodieInstant> nthFromLastInstant(int n); /** * @return true if the passed instant is present as a completed instant on the timeline */ boolean containsInstant(HoodieInstant instant); /** * @return true if the passed instant is present as a completed instant on the timeline or if the * instant is before the first completed instant in the timeline */ boolean containsOrBeforeTimelineStarts(String ts); /** * @return Get the stream of completed instants */ Stream<HoodieInstant> getInstants(); /** * @return true if the passed in instant is before the first completed instant in the timeline */ boolean isBeforeTimelineStarts(String ts); /** * Read the completed instant details */ Optional<byte[]> getInstantDetails(HoodieInstant instant); /** * Helper methods to compare instants **/ BiPredicate<String, String> EQUAL = (commit1, commit2) -> commit1.compareTo(commit2) == 0; BiPredicate<String, String> GREATER_OR_EQUAL = (commit1, commit2) -> commit1.compareTo(commit2) >= 0; BiPredicate<String, String> GREATER = (commit1, commit2) -> commit1.compareTo(commit2) > 0; BiPredicate<String, String> LESSER_OR_EQUAL = (commit1, commit2) -> commit1.compareTo(commit2) <= 0; BiPredicate<String, String> LESSER = (commit1, commit2) -> commit1.compareTo(commit2) < 0; static boolean compareTimestamps(String commit1, String commit2, BiPredicate<String, String> predicateToApply) { return predicateToApply.test(commit1, commit2); } static HoodieInstant getCompletedInstant(final HoodieInstant instant) { return new HoodieInstant(false, instant.getAction(), instant.getTimestamp()); } static HoodieInstant getCompactionRequestedInstant(final String timestamp) { return new HoodieInstant(State.REQUESTED, COMPACTION_ACTION, timestamp); } static HoodieInstant getCompactionInflightInstant(final String timestamp) { return new HoodieInstant(State.INFLIGHT, COMPACTION_ACTION, timestamp); } static HoodieInstant getInflightInstant(final HoodieInstant instant) { return new HoodieInstant(true, instant.getAction(), instant.getTimestamp()); } static String makeCommitFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.COMMIT_EXTENSION); } static String makeInflightCommitFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.INFLIGHT_COMMIT_EXTENSION); } static String makeCleanerFileName(String instant) { return StringUtils.join(instant, HoodieTimeline.CLEAN_EXTENSION); } static String makeInflightCleanerFileName(String instant) { return StringUtils.join(instant, HoodieTimeline.INFLIGHT_CLEAN_EXTENSION); } static String makeRollbackFileName(String instant) { return StringUtils.join(instant, HoodieTimeline.ROLLBACK_EXTENSION); } static String makeInflightRollbackFileName(String instant) { return StringUtils.join(instant, HoodieTimeline.INFLIGHT_ROLLBACK_EXTENSION); } static String makeInflightSavePointFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.INFLIGHT_SAVEPOINT_EXTENSION); } static String makeSavePointFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.SAVEPOINT_EXTENSION); } static String makeInflightDeltaFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.INFLIGHT_DELTA_COMMIT_EXTENSION); } static String makeInflightCompactionFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.INFLIGHT_COMPACTION_EXTENSION); } static String makeRequestedCompactionFileName(String commitTime) { return StringUtils.join(commitTime, HoodieTimeline.REQUESTED_COMPACTION_EXTENSION); } static String makeDeltaFileName(String commitTime) { return commitTime + HoodieTimeline.DELTA_COMMIT_EXTENSION; } static String getCommitFromCommitFile(String commitFileName) { return commitFileName.split("\\.")[0]; } static String makeFileNameAsComplete(String fileName) { return fileName.replace(HoodieTimeline.INFLIGHT_EXTENSION, ""); } static String makeFileNameAsInflight(String fileName) { return StringUtils.join(fileName, HoodieTimeline.INFLIGHT_EXTENSION); } }
package com.twu.biblioteca; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class BibliotecaApp { public static List<Book> bookList = new ArrayList<Book>(); public static List<Movie> movieList = new ArrayList<Movie>(); public static List<User> userList = new ArrayList<User>(); public String getWelcomeMessage() { return "Welcome to Biblioteca!\n"; } public String getMenuMessage() { return "Please enter a number to select the option:\n" + "1. Show List Books.\n" + "2. Checkout Books.\n" + "3. Return Books.\n" + "4. Show List Movies.\n" + "5. Checkout Movies.\n" + "8. Show User Information.\n" + "0. Quit.\n"; } public String getInvalidErrorMessage() { return "Select a valid option!\n"; } public String getQuitMessage() { return "Bye!"; } public String getCheckoutBookSuccessfulMessage() { return "Thank you! Enjoy the book.\n"; } public String getCheckoutMovieSuccessfulMessage() { return "Thank you! Enjoy the movie.\n"; } public String getCheckoutBookFailedMessage() { return "That book is not available.\n"; } public String getCheckoutMovieFailedMessage() { return "That movie is not available.\n"; } public String getReturnSuccessfulMessage() { return "Thank you for returning the book.\n"; } public String getReturnFailedMessage() { return "That is not a valid book to return.\n"; } public String getAuthorizationFailedMessage() { return "login failed. Please check your library number and password.\n"; } public static void main(String[] args) { new BibliotecaApp().startWith(new ArrayList<Book>()); } public void startWith(List<Book> bookList) { if (bookList.isEmpty()) { initBookList(); } else { this.bookList = bookList; } initMovieList(); initUserList(); System.out.print(getWelcomeMessage()); printMenuOptions(); startMonitor(); } public void handleInput(String input, Scanner scanner) { if (input.equals("1")) { printBookList(); } else if (input.equals("2")) { startCheckoutBook(scanner); } else if (input.equals("3")) { startReturnBook(scanner); } else if (input.equals("4")) { printMovieList(); } else if (input.equals("5")) { startCheckoutMovie(scanner); } else if (input.equals("8")) { startShowUserInformation(scanner); } else { printInvalidErrorMessage(); } } private void startShowUserInformation(Scanner scanner) { User user = startUserAuthorization(scanner); if (user != null) { System.out.println(user.getUserInformation()); } } private void startCheckoutBook(Scanner scanner) { System.out.println("Please input the check-out book name:"); String bookName = scanner.nextLine(); User user = startUserAuthorization(scanner); if (user != null) { if (checkoutBookSuccessful(bookName, user)) { System.out.print(getCheckoutBookSuccessfulMessage()); } else { System.out.print(getCheckoutBookFailedMessage()); } } } private boolean checkoutBookSuccessful(String bookName, User user) { for(Book book : bookList) { if (book.getName().equals(bookName) && !book.isCheckedOut()) { book.setCheckedOut(true); book.setAccountableUser(user); return true; } } return false; } private void startCheckoutMovie(Scanner scanner) { System.out.println("Please input the check-out movie name:"); String movieName = scanner.nextLine(); if (checkoutMovieSuccessful(movieName)) { System.out.print(getCheckoutMovieSuccessfulMessage()); } else { System.out.print(getCheckoutMovieFailedMessage()); } } private boolean checkoutMovieSuccessful(String movieName) { for(Movie movie : movieList) { if (movie.getName().equals(movieName) && !movie.isCheckedOut()) { movie.setCheckedOut(true); return true; } } return false; } private void startReturnBook(Scanner scanner) { System.out.print("Please input the book name which you want to return:\n"); String bookName = scanner.nextLine(); if (returnBookSuccessful(bookName)) { System.out.print(getReturnSuccessfulMessage()); } else { System.out.print(getReturnFailedMessage()); } } private boolean returnBookSuccessful(String bookName) { for(Book book : bookList) { if (book.getName().equals(bookName) && book.isCheckedOut()) { book.setCheckedOut(false); return true; } } return false; } private User startUserAuthorization(Scanner scanner) { System.out.println("Please input your library number:"); String libraryNumber = scanner.nextLine(); System.out.println("Please input your password:"); String password = scanner.nextLine(); for (User user: userList) { if (user.verified(libraryNumber, password)) { return user; } } System.out.print(getAuthorizationFailedMessage()); return null; } private void printMenuOptions() { System.out.print(getMenuMessage()); } private void startMonitor() { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); while (!input.equals("0")) { handleInput(input, scanner); try { input = scanner.nextLine(); } catch (Exception e) { break; } } System.out.print(getQuitMessage()); } private void printInvalidErrorMessage() { System.out.print(getInvalidErrorMessage()); } private static void printBookList() { System.out.println("List Books:"); for(Book book : bookList) { if (!book.isCheckedOut()) System.out.println(book); } } private static void initBookList() { bookList = new ArrayList<Book>(); bookList.add(new Book("Head First Java", "1995", "KathySierra")); bookList.add(new Book("Effective C++", "1991", "Scott Meyers")); } private static void printMovieList() { System.out.println("List Movies:"); for(Movie movie : movieList) { if (!movie.isCheckedOut()) System.out.println(movie); } } private static void initMovieList() { movieList = new ArrayList<Movie>(); movieList.add(new Movie("Spider-Man", "2002", "Sam Raimi", "6.7/10")); } private static void initUserList() { userList = new ArrayList<User>(); userList.add(new User("000-0001", "password01", "firstUser", "first@gmail.com", "12345678901")); userList.add(new User("000-0002", "password02", "secondUser", "second@gmail.com", "12345678902")); } }
/** * 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.pulsar.tests.integration.topologies; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.pulsar.tests.integration.containers.PulsarContainer.BROKER_HTTP_PORT; import static org.apache.pulsar.tests.integration.containers.PulsarContainer.CS_PORT; import static org.apache.pulsar.tests.integration.containers.PulsarContainer.PULSAR_CONTAINERS_LEAVE_RUNNING; import static org.apache.pulsar.tests.integration.containers.PulsarContainer.ZK_PORT; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.pulsar.tests.integration.containers.BKContainer; import org.apache.pulsar.tests.integration.containers.BrokerContainer; import org.apache.pulsar.tests.integration.containers.CSContainer; import org.apache.pulsar.tests.integration.containers.PrestoWorkerContainer; import org.apache.pulsar.tests.integration.containers.ProxyContainer; import org.apache.pulsar.tests.integration.containers.PulsarContainer; import org.apache.pulsar.tests.integration.containers.WorkerContainer; import org.apache.pulsar.tests.integration.containers.ZKContainer; import org.apache.pulsar.tests.integration.docker.ContainerExecResult; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; /** * Pulsar Cluster in containers. */ @Slf4j public class PulsarCluster { public static final String ADMIN_SCRIPT = "/pulsar/bin/pulsar-admin"; public static final String CLIENT_SCRIPT = "/pulsar/bin/pulsar-client"; public static final String PULSAR_COMMAND_SCRIPT = "/pulsar/bin/pulsar"; public static final String CURL = "/usr/bin/curl"; /** * Pulsar Cluster Spec * * @param spec pulsar cluster spec. * @return the built pulsar cluster */ public static PulsarCluster forSpec(PulsarClusterSpec spec) { CSContainer csContainer = new CSContainer(spec.clusterName) .withNetwork(Network.newNetwork()) .withNetworkAliases(CSContainer.NAME); return new PulsarCluster(spec, csContainer, false); } public static PulsarCluster forSpec(PulsarClusterSpec spec, CSContainer csContainer) { return new PulsarCluster(spec, csContainer, true); } @Getter private final PulsarClusterSpec spec; @Getter private final String clusterName; private final Network network; private final ZKContainer zkContainer; private final CSContainer csContainer; private final boolean sharedCsContainer; private final Map<String, BKContainer> bookieContainers; private final Map<String, BrokerContainer> brokerContainers; private final Map<String, WorkerContainer> workerContainers; private final ProxyContainer proxyContainer; private PrestoWorkerContainer prestoWorkerContainer; @Getter private Map<String, PrestoWorkerContainer> sqlFollowWorkerContainers; private Map<String, GenericContainer<?>> externalServices = Collections.emptyMap(); private final boolean enablePrestoWorker; private PulsarCluster(PulsarClusterSpec spec, CSContainer csContainer, boolean sharedCsContainer) { this.spec = spec; this.sharedCsContainer = sharedCsContainer; this.clusterName = spec.clusterName(); this.network = csContainer.getNetwork(); this.enablePrestoWorker = spec.enablePrestoWorker(); this.sqlFollowWorkerContainers = Maps.newTreeMap(); if (enablePrestoWorker) { prestoWorkerContainer = buildPrestoWorkerContainer( PrestoWorkerContainer.NAME, true, null, null); } else { prestoWorkerContainer = null; } this.zkContainer = new ZKContainer(clusterName); this.zkContainer .withNetwork(network) .withNetworkAliases(appendClusterName(ZKContainer.NAME)) .withEnv("clusterName", clusterName) .withEnv("zkServers", appendClusterName(ZKContainer.NAME)) .withEnv("configurationStore", CSContainer.NAME + ":" + CS_PORT) .withEnv("forceSync", "no") .withEnv("pulsarNode", appendClusterName("pulsar-broker-0")); this.csContainer = csContainer; this.bookieContainers = Maps.newTreeMap(); this.brokerContainers = Maps.newTreeMap(); this.workerContainers = Maps.newTreeMap(); this.proxyContainer = new ProxyContainer(appendClusterName("pulsar-proxy"), ProxyContainer.NAME) .withNetwork(network) .withNetworkAliases(appendClusterName("pulsar-proxy")) .withEnv("zkServers", appendClusterName(ZKContainer.NAME)) .withEnv("zookeeperServers", appendClusterName(ZKContainer.NAME)) .withEnv("configurationStoreServers", CSContainer.NAME + ":" + CS_PORT) .withEnv("clusterName", clusterName); if (spec.proxyEnvs != null) { spec.proxyEnvs.forEach(this.proxyContainer::withEnv); } if (spec.proxyMountFiles != null) { spec.proxyMountFiles.forEach(this.proxyContainer::withFileSystemBind); } // create bookies bookieContainers.putAll( runNumContainers("bookie", spec.numBookies(), (name) -> new BKContainer(clusterName, name) .withNetwork(network) .withNetworkAliases(appendClusterName(name)) .withEnv("zkServers", appendClusterName(ZKContainer.NAME)) .withEnv("useHostNameAsBookieID", "true") // Disable fsyncs for tests since they're slow within the containers .withEnv("journalSyncData", "false") .withEnv("journalMaxGroupWaitMSec", "0") .withEnv("clusterName", clusterName) .withEnv("diskUsageThreshold", "0.99") .withEnv("nettyMaxFrameSizeBytes", "" + spec.maxMessageSize) ) ); // create brokers brokerContainers.putAll( runNumContainers("broker", spec.numBrokers(), (name) -> { BrokerContainer brokerContainer = new BrokerContainer(clusterName, appendClusterName(name)) .withNetwork(network) .withNetworkAliases(appendClusterName(name)) .withEnv("zkServers", appendClusterName(ZKContainer.NAME)) .withEnv("zookeeperServers", appendClusterName(ZKContainer.NAME)) .withEnv("configurationStoreServers", CSContainer.NAME + ":" + CS_PORT) .withEnv("clusterName", clusterName) .withEnv("brokerServiceCompactionMonitorIntervalInSeconds", "1") // used in s3 tests .withEnv("AWS_ACCESS_KEY_ID", "accesskey") .withEnv("AWS_SECRET_KEY", "secretkey") .withEnv("maxMessageSize", "" + spec.maxMessageSize); if (spec.queryLastMessage) { brokerContainer.withEnv("bookkeeperExplicitLacIntervalInMills", "10"); brokerContainer.withEnv("bookkeeperUseV2WireProtocol", "false"); } if (spec.brokerEnvs != null) { brokerContainer.withEnv(spec.brokerEnvs); } if (spec.brokerMountFiles != null) { spec.brokerMountFiles.forEach(brokerContainer::withFileSystemBind); } return brokerContainer; } )); spec.classPathVolumeMounts.forEach((key, value) -> { zkContainer.withClasspathResourceMapping(key, value, BindMode.READ_WRITE); proxyContainer.withClasspathResourceMapping(key, value, BindMode.READ_WRITE); bookieContainers.values().forEach(c -> c.withClasspathResourceMapping(key, value, BindMode.READ_WRITE)); brokerContainers.values().forEach(c -> c.withClasspathResourceMapping(key, value, BindMode.READ_WRITE)); workerContainers.values().forEach(c -> c.withClasspathResourceMapping(key, value, BindMode.READ_WRITE)); }); } public String getPlainTextServiceUrl() { return proxyContainer.getPlainTextServiceUrl(); } public String getHttpServiceUrl() { return proxyContainer.getHttpServiceUrl(); } public String getAllBrokersHttpServiceUrl() { String multiUrl = "http://"; Iterator<BrokerContainer> brokers = getBrokers().iterator(); while (brokers.hasNext()) { BrokerContainer broker = brokers.next(); multiUrl += broker.getContainerIpAddress() + ":" + broker.getMappedPort(BROKER_HTTP_PORT); if (brokers.hasNext()) { multiUrl += ","; } } return multiUrl; } public String getZKConnString() { return zkContainer.getContainerIpAddress() + ":" + zkContainer.getMappedPort(ZK_PORT); } public String getCSConnString() { return csContainer.getContainerIpAddress() + ":" + csContainer.getMappedPort(CS_PORT); } public Network getNetwork() { return network; } public Map<String, GenericContainer<?>> getExternalServices() { return externalServices; } public void start() throws Exception { // start the local zookeeper zkContainer.start(); log.info("Successfully started local zookeeper container."); // start the configuration store if (!sharedCsContainer) { csContainer.start(); log.info("Successfully started configuration store container."); } // init the cluster zkContainer.execCmd( "bin/init-cluster.sh"); log.info("Successfully initialized the cluster."); // start bookies bookieContainers.values().forEach(BKContainer::start); log.info("Successfully started {} bookie containers.", bookieContainers.size()); // start brokers this.startAllBrokers(); log.info("Successfully started {} broker containers.", brokerContainers.size()); // create proxy proxyContainer.start(); log.info("Successfully started pulsar proxy."); log.info("Pulsar cluster {} is up running:", clusterName); log.info("\tBinary Service Url : {}", getPlainTextServiceUrl()); log.info("\tHttp Service Url : {}", getHttpServiceUrl()); if (enablePrestoWorker) { log.info("Starting Presto Worker"); prestoWorkerContainer.start(); } // start external services this.externalServices = spec.externalServices; if (null != externalServices) { externalServices.entrySet().parallelStream().forEach(service -> { GenericContainer<?> serviceContainer = service.getValue(); serviceContainer.withNetwork(network); serviceContainer.withNetworkAliases(service.getKey()); PulsarContainer.configureLeaveContainerRunning(serviceContainer); serviceContainer.start(); log.info("Successfully start external service {}.", service.getKey()); }); } } public void startService(String networkAlias, GenericContainer<?> serviceContainer) { log.info("Starting external service {} ...", networkAlias); serviceContainer.withNetwork(network); serviceContainer.withNetworkAliases(networkAlias); PulsarContainer.configureLeaveContainerRunning(serviceContainer); serviceContainer.start(); log.info("Successfully start external service {}", networkAlias); } public static void stopService(String networkAlias, GenericContainer<?> serviceContainer) { if (PULSAR_CONTAINERS_LEAVE_RUNNING) { logIgnoringStopDueToLeaveRunning(); return; } log.info("Stopping external service {} ...", networkAlias); serviceContainer.stop(); log.info("Successfully stop external service {}", networkAlias); } private static <T extends PulsarContainer> Map<String, T> runNumContainers(String serviceName, int numContainers, Function<String, T> containerCreator) { Map<String, T> containers = Maps.newTreeMap(); for (int i = 0; i < numContainers; i++) { String name = "pulsar-" + serviceName + "-" + i; T container = containerCreator.apply(name); containers.put(name, container); } return containers; } public PrestoWorkerContainer getPrestoWorkerContainer() { return prestoWorkerContainer; } public synchronized void stop() { if (PULSAR_CONTAINERS_LEAVE_RUNNING) { logIgnoringStopDueToLeaveRunning(); return; } List<GenericContainer> containers = new ArrayList<>(); containers.addAll(workerContainers.values()); containers.addAll(brokerContainers.values()); containers.addAll(bookieContainers.values()); if (externalServices != null) { containers.addAll(externalServices.values()); } if (null != proxyContainer) { containers.add(proxyContainer); } if (!sharedCsContainer && null != csContainer) { containers.add(csContainer); } if (null != zkContainer) { containers.add(zkContainer); } if (null != prestoWorkerContainer) { containers.add(prestoWorkerContainer); } containers = containers.parallelStream() .filter(Objects::nonNull) .collect(Collectors.toList()); containers.parallelStream().forEach(GenericContainer::stop); try { network.close(); } catch (Exception e) { log.info("Failed to shutdown network for pulsar cluster {}", clusterName, e); } } public void startPrestoWorker() { startPrestoWorker(null, null); } public void startPrestoWorker(String offloadDriver, String offloadProperties) { log.info("[startPrestoWorker] offloadDriver: {}, offloadProperties: {}", offloadDriver, offloadProperties); if (null == prestoWorkerContainer) { prestoWorkerContainer = buildPrestoWorkerContainer( PrestoWorkerContainer.NAME, true, offloadDriver, offloadProperties); } prestoWorkerContainer.start(); log.info("[{}] Presto coordinator start finished.", prestoWorkerContainer.getContainerName()); } public void stopPrestoWorker() { if (PULSAR_CONTAINERS_LEAVE_RUNNING) { logIgnoringStopDueToLeaveRunning(); return; } if (sqlFollowWorkerContainers != null && sqlFollowWorkerContainers.size() > 0) { for (PrestoWorkerContainer followWorker : sqlFollowWorkerContainers.values()) { followWorker.stop(); log.info("Stopped presto follow worker {}.", followWorker.getContainerName()); } sqlFollowWorkerContainers.clear(); log.info("Stopped all presto follow workers."); } if (null != prestoWorkerContainer) { prestoWorkerContainer.stop(); log.info("Stopped presto coordinator."); prestoWorkerContainer = null; } } public void startPrestoFollowWorkers(int numSqlFollowWorkers, String offloadDriver, String offloadProperties) { log.info("start presto follow worker containers."); sqlFollowWorkerContainers.putAll(runNumContainers( "sql-follow-worker", numSqlFollowWorkers, (name) -> { log.info("build presto follow worker with name {}", name); return buildPrestoWorkerContainer(name, false, offloadDriver, offloadProperties); } )); // Start workers that have been initialized sqlFollowWorkerContainers.values().parallelStream().forEach(PrestoWorkerContainer::start); log.info("Successfully started {} presto follow worker containers.", sqlFollowWorkerContainers.size()); } private PrestoWorkerContainer buildPrestoWorkerContainer(String hostName, boolean isCoordinator, String offloadDriver, String offloadProperties) { String resourcePath = isCoordinator ? "presto-coordinator-config.properties" : "presto-follow-worker-config.properties"; PrestoWorkerContainer container = new PrestoWorkerContainer( clusterName, hostName) .withNetwork(network) .withNetworkAliases(hostName) .withEnv("clusterName", clusterName) .withEnv("zkServers", ZKContainer.NAME) .withEnv("zookeeperServers", ZKContainer.NAME + ":" + ZKContainer.ZK_PORT) .withEnv("pulsar.zookeeper-uri", ZKContainer.NAME + ":" + ZKContainer.ZK_PORT) .withEnv("pulsar.web-service-url", "http://pulsar-broker-0:8080") .withEnv("SQL_PREFIX_pulsar.max-message-size", "" + spec.maxMessageSize) .withClasspathResourceMapping( resourcePath, "/pulsar/conf/presto/config.properties", BindMode.READ_WRITE); if (spec.queryLastMessage) { container.withEnv("pulsar.bookkeeper-use-v2-protocol", "false") .withEnv("pulsar.bookkeeper-explicit-interval", "10"); } if (offloadDriver != null && offloadProperties != null) { log.info("[startPrestoWorker] set offload env offloadDriver: {}, offloadProperties: {}", offloadDriver, offloadProperties); // used to query from tiered storage container.withEnv("SQL_PREFIX_pulsar.managed-ledger-offload-driver", offloadDriver); container.withEnv("SQL_PREFIX_pulsar.offloader-properties", offloadProperties); container.withEnv("SQL_PREFIX_pulsar.offloaders-directory", "/pulsar/offloaders"); container.withEnv("AWS_ACCESS_KEY_ID", "accesskey"); container.withEnv("AWS_SECRET_KEY", "secretkey"); } log.info("[{}] build presto worker container. isCoordinator: {}, resourcePath: {}", container.getContainerName(), isCoordinator, resourcePath); return container; } public synchronized void setupFunctionWorkers(String suffix, FunctionRuntimeType runtimeType, int numFunctionWorkers) { switch (runtimeType) { case THREAD: startFunctionWorkersWithThreadContainerFactory(suffix, numFunctionWorkers); break; case PROCESS: startFunctionWorkersWithProcessContainerFactory(suffix, numFunctionWorkers); break; } } private void startFunctionWorkersWithProcessContainerFactory(String suffix, int numFunctionWorkers) { String serviceUrl = "pulsar://pulsar-broker-0:" + PulsarContainer.BROKER_PORT; String httpServiceUrl = "http://pulsar-broker-0:" + PulsarContainer.BROKER_HTTP_PORT; workerContainers.putAll(runNumContainers( "functions-worker-process-" + suffix, numFunctionWorkers, (name) -> new WorkerContainer(clusterName, name) .withNetwork(network) .withNetworkAliases(name) // worker settings .withEnv("PF_workerId", name) .withEnv("PF_workerHostname", name) .withEnv("PF_workerPort", "" + PulsarContainer.BROKER_HTTP_PORT) .withEnv("PF_pulsarFunctionsCluster", clusterName) .withEnv("PF_pulsarServiceUrl", serviceUrl) .withEnv("PF_pulsarWebServiceUrl", httpServiceUrl) // script .withEnv("clusterName", clusterName) .withEnv("zookeeperServers", ZKContainer.NAME) // bookkeeper tools .withEnv("zkServers", ZKContainer.NAME) )); this.startWorkers(); } private void startFunctionWorkersWithThreadContainerFactory(String suffix, int numFunctionWorkers) { String serviceUrl = "pulsar://pulsar-broker-0:" + PulsarContainer.BROKER_PORT; String httpServiceUrl = "http://pulsar-broker-0:" + PulsarContainer.BROKER_HTTP_PORT; workerContainers.putAll(runNumContainers( "functions-worker-thread-" + suffix, numFunctionWorkers, (name) -> new WorkerContainer(clusterName, name) .withNetwork(network) .withNetworkAliases(name) // worker settings .withEnv("PF_workerId", name) .withEnv("PF_workerHostname", name) .withEnv("PF_workerPort", "" + PulsarContainer.BROKER_HTTP_PORT) .withEnv("PF_pulsarFunctionsCluster", clusterName) .withEnv("PF_pulsarServiceUrl", serviceUrl) .withEnv("PF_pulsarWebServiceUrl", httpServiceUrl) .withEnv("PF_functionRuntimeFactoryClassName", "org.apache.pulsar.functions.runtime.thread.ThreadRuntimeFactory") .withEnv("PF_functionRuntimeFactoryConfigs_threadGroupName", "pf-container-group") // script .withEnv("clusterName", clusterName) .withEnv("zookeeperServers", ZKContainer.NAME) // bookkeeper tools .withEnv("zkServers", ZKContainer.NAME) )); this.startWorkers(); } public synchronized void startWorkers() { // Start workers that have been initialized workerContainers.values().parallelStream().forEach(WorkerContainer::start); log.info("Successfully started {} worker containers.", workerContainers.size()); } public synchronized void stopWorker(String workerName) { if (PULSAR_CONTAINERS_LEAVE_RUNNING) { logIgnoringStopDueToLeaveRunning(); return; } // Stop the named worker. WorkerContainer worker = workerContainers.get(workerName); if (worker == null) { log.warn("Failed to find the worker to stop ({})", workerName); return; } worker.stop(); workerContainers.remove(workerName); log.info("Worker {} stopped and removed from the map of worker containers", workerName); } public synchronized void stopWorkers() { if (PULSAR_CONTAINERS_LEAVE_RUNNING) { logIgnoringStopDueToLeaveRunning(); return; } // Stop workers that have been initialized workerContainers.values().parallelStream().forEach(WorkerContainer::stop); workerContainers.clear(); } public void startContainers(Map<String, GenericContainer<?>> containers) { containers.forEach((name, container) -> { PulsarContainer.configureLeaveContainerRunning(container); container .withNetwork(network) .withNetworkAliases(name) .start(); log.info("Successfully start container {}.", name); }); } public static void stopContainers(Map<String, GenericContainer<?>> containers) { if (PULSAR_CONTAINERS_LEAVE_RUNNING) { logIgnoringStopDueToLeaveRunning(); return; } containers.values().parallelStream().forEach(GenericContainer::stop); log.info("Successfully stop containers : {}", containers); } private static void logIgnoringStopDueToLeaveRunning() { log.warn("Ignoring stop due to PULSAR_CONTAINERS_LEAVE_RUNNING=true."); } public BrokerContainer getAnyBroker() { return getAnyContainer(brokerContainers, "pulsar-broker"); } public synchronized WorkerContainer getAnyWorker() { return getAnyContainer(workerContainers, "pulsar-functions-worker"); } public synchronized List<WorkerContainer> getAlWorkers() { return new ArrayList<WorkerContainer>(workerContainers.values()); } public BrokerContainer getBroker(int index) { return getAnyContainer(brokerContainers, "pulsar-broker", index); } public synchronized WorkerContainer getWorker(int index) { return getAnyContainer(workerContainers, "pulsar-functions-worker", index); } public synchronized WorkerContainer getWorker(String workerName) { return workerContainers.get(workerName); } private <T> T getAnyContainer(Map<String, T> containers, String serviceName) { List<T> containerList = Lists.newArrayList(); containerList.addAll(containers.values()); Collections.shuffle(containerList); checkArgument(!containerList.isEmpty(), "No " + serviceName + " is alive"); return containerList.get(0); } private <T> T getAnyContainer(Map<String, T> containers, String serviceName, int index) { checkArgument(!containers.isEmpty(), "No " + serviceName + " is alive"); checkArgument((index >= 0 && index < containers.size()), "Index : " + index + " is out range"); return containers.get(serviceName.toLowerCase() + "-" + index); } public Collection<BrokerContainer> getBrokers() { return brokerContainers.values(); } public ProxyContainer getProxy() { return proxyContainer; } public Collection<BKContainer> getBookies() { return bookieContainers.values(); } public ZKContainer getZooKeeper() { return zkContainer; } public ContainerExecResult runAdminCommandOnAnyBroker(String...commands) throws Exception { return runCommandOnAnyBrokerWithScript(ADMIN_SCRIPT, commands); } public ContainerExecResult runPulsarBaseCommandOnAnyBroker(String...commands) throws Exception { return runCommandOnAnyBrokerWithScript(PULSAR_COMMAND_SCRIPT, commands); } private ContainerExecResult runCommandOnAnyBrokerWithScript(String scriptType, String...commands) throws Exception { BrokerContainer container = getAnyBroker(); String[] cmds = new String[commands.length + 1]; cmds[0] = scriptType; System.arraycopy(commands, 0, cmds, 1, commands.length); return container.execCmd(cmds); } public void stopAllBrokers() { brokerContainers.values().forEach(BrokerContainer::stop); } public void startAllBrokers() { brokerContainers.values().forEach(BrokerContainer::start); } public void stopAllBookies() { bookieContainers.values().forEach(BKContainer::stop); } public void startAllBookies() { bookieContainers.values().forEach(BKContainer::start); } public void stopZooKeeper() { zkContainer.stop(); } public void startZooKeeper() { zkContainer.start(); } public ContainerExecResult createNamespace(String nsName) throws Exception { return runAdminCommandOnAnyBroker( "namespaces", "create", "public/" + nsName, "--clusters", clusterName); } public ContainerExecResult createPartitionedTopic(String topicName, int partitions) throws Exception { return runAdminCommandOnAnyBroker( "topics", "create-partitioned-topic", topicName, "-p", String.valueOf(partitions)); } public ContainerExecResult enableDeduplication(String nsName, boolean enabled) throws Exception { return runAdminCommandOnAnyBroker( "namespaces", "set-deduplication", "public/" + nsName, enabled ? "--enable" : "--disable"); } public void dumpFunctionLogs(String name) { for (WorkerContainer container : getAlWorkers()) { log.info("Trying to get function {} logs from container {}", name, container.getContainerName()); try { String logFile = "/pulsar/logs/functions/public/default/" + name + "/" + name + "-0.log"; String logs = container.<String>copyFileFromContainer(logFile, (inputStream) -> { return IOUtils.toString(inputStream, "utf-8"); }); log.info("Function {} logs {}", name, logs); } catch (com.github.dockerjava.api.exception.NotFoundException notFound) { log.info("Cannot download {} logs from {} not found exception {}", name, container.getContainerName(), notFound.toString()); } catch (Throwable err) { log.info("Cannot download {} logs from {}", name, container.getContainerName(), err); } } } private String appendClusterName(String name) { return sharedCsContainer ? clusterName + "-" + name : name; } }
/********************************************************************************** * * $Id$ * *********************************************************************************** * * Copyright (c) 2007, 2008 Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.user.impl.test; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.test.SakaiKernelTestBase; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.user.api.AuthenticatedUserProvider; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserDirectoryProvider; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserFactory; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.impl.DbUserService; /** * */ public class AuthenticatedUserProviderTest extends SakaiKernelTestBase { protected static final String CONFIG = null; private static Log log = LogFactory.getLog(AuthenticatedUserProviderTest.class); private static TestProvider userDirectoryProvider; private UserDirectoryService userDirectoryService; // These services are only used to clear out various caches to make sure // we're fetching from the DB. private ThreadLocalManager threadLocalManager; @BeforeClass public static void beforeClass() { try { log.debug("starting oneTimeSetup"); oneTimeSetup("disable_user_cache"); oneTimeSetupAfter(); log.debug("finished oneTimeSetup"); } catch (Exception e) { log.warn(e); } } private static void oneTimeSetupAfter() throws Exception { userDirectoryProvider = new TestProvider(); // This is a workaround until we can make it easier to load sakai.properties // for specific integration tests. DbUserService dbUserService = (DbUserService)getService(UserDirectoryService.class.getName()); dbUserService.setProvider(userDirectoryProvider); // Inject service so that provider can create new user records or search // for existing ones. userDirectoryProvider.setUserFactory(dbUserService); userDirectoryProvider.setUserDirectoryService(dbUserService); userDirectoryProvider.setSecurityService((SecurityService)getService(SecurityService.class.getName())); } @Before public void setUp() throws Exception { log.debug("Setting up UserDirectoryServiceIntegrationTest"); userDirectoryService = (UserDirectoryService)getService(UserDirectoryService.class.getName()); threadLocalManager = (ThreadLocalManager)getService(ThreadLocalManager.class.getName()); } @Test public void testLocalUserFallThrough() throws Exception { User user = userDirectoryService.addUser(null, "local", null, null, null, "localPW", null, null); User authUser = userDirectoryService.authenticate("local", "localPW"); Assert.assertTrue(authUser.getId().equals(user.getId())); } @Test public void testExistingProvidedUser() throws Exception { User user = userDirectoryService.getUserByEid("provideduser"); Assert.assertTrue(user != null); User authUser = userDirectoryService.authenticate("LOGINprovideduser", "provideduserPW"); Assert.assertTrue(authUser.getId().equals(user.getId())); User failedUser = userDirectoryService.authenticate("LOGINprovideduser", "BadPassword"); Assert.assertTrue(failedUser == null); } @Test public void testNewProvidedUsers() throws Exception { User providedByAuthn = userDirectoryService.authenticate("LOGINprovidedauthn", "providedauthnPW"); Assert.assertTrue(providedByAuthn != null); User providedByDelayedAuthn = userDirectoryService.authenticate("LOGINprovidernotfirst", "providernotfirstPW"); Assert.assertTrue(providedByDelayedAuthn != null); User user = userDirectoryService.getUserByEid("providedauthn"); Assert.assertTrue(user.getId().equals(providedByAuthn.getId())); user = userDirectoryService.getUserByEid("providernotfirst"); Assert.assertTrue(user.getId().equals(providedByDelayedAuthn.getId())); } @Test public void testProviderCreatedAndUpdatedLocalUsers() throws Exception { // Authenticate a user who will then magically appear in the Sakai user tables. User providedByAuthn = userDirectoryService.authenticate("LOGINprovidercreated", "providercreatedPW"); String eid = providedByAuthn.getEid(); Assert.assertTrue(eid.equals("providercreated")); String userId = providedByAuthn.getId(); // This is the tough part: make sure we get the new user from Sakai's user // DB rather than any of the three caches. clearUserFromServiceCaches(userId); providedByAuthn = userDirectoryService.getUserByEid(eid); Assert.assertTrue(providedByAuthn.getLastName().equals("Last Name, Sr.")); // Now authenticate the same user and make sure the Sakai-maintained // user record was updated. providedByAuthn = userDirectoryService.authenticate("LOGINprovidercreated", "providercreatedPW"); clearUserFromServiceCaches(userId); providedByAuthn = userDirectoryService.getUserByEid(eid); Assert.assertTrue(providedByAuthn.getLastName().equals("Last Name, Jr.")); } /** * WARNING: There seems to be NO easy way to reset the UserDirectoryService MemoryService-managed * cache, and so the only way currently to test for real DB storage is to have this line * in the "sakai.properties" file used for the test: * cacheMinutes@org.sakaiproject.user.api.UserDirectoryService=0 */ private void clearUserFromServiceCaches(String userId) { ((DbUserService)userDirectoryService).getIdEidCache().clear(); String ref = "/user/" + userId; threadLocalManager.set(ref, null); } public static class TestProvider implements UserDirectoryProvider, AuthenticatedUserProvider { private UserFactory userFactory; private UserDirectoryService userDirectoryService; private SecurityService securityService; public boolean authenticateUser(String eid, UserEdit user, String password) { // This should never be called since we implement the new interface. throw new RuntimeException("authenticateUser unexpectedly called"); } public boolean authenticateWithProviderFirst(String loginId) { return !loginId.equals("loginprovidernotfirst"); } public boolean findUserByEmail(UserEdit edit, String email) { return false; } public boolean getUser(UserEdit user) { String eid = user.getEid(); if (!eid.startsWith("provide")) { return false; } else if (eid.equals("providercreated")) { // It's a little tricky to create a Sakai-stored user record from a // provider. When Sakai doesn't find any record of the new EID, // it will ask the provider for the corresponding user. If we // obligingly fill in the data and hand it over, Sakai will continue // to ask us for the provided user from then on. The only way // for a provider to force local storage is to deny all // knowledge of the user here and then add the Sakai user // record later in the authentication logic. return false; } else { return true; } } @SuppressWarnings("unchecked") public void getUsers(Collection users) { } public UserEdit getAuthenticatedUser(String loginId, String password) { log.debug("getAuthenticatedUser " + loginId + ", " + password); if (!loginId.startsWith("loginprovide")) return null; String eid = loginId.substring("login".length()); if (password.equals(eid + "PW")) { if (eid.equals("providercreated")) { return createOrUpdateUserAfterAuthentication(eid, password); } else { // Thoroughly provided user. UserEdit user = userFactory.newUser(); user.setEid(eid); return user; } } else { return null; } } /** * Sakai framework APIs don't always clearly distinguish between internal core utility services * (which just do their specialized job) and application-facing support services (which * require authorization checks). UserDirectoryService's user record modification methods * were originally written for application support, and so they check the permissions of the * current user. During the authentication process, there is no current user, and so * if we want to modify the Sakai-stored user record, we need to push a SecurityAdvisor * to bypass the checks. */ private UserEdit createOrUpdateUserAfterAuthentication(String eid, String password) { // User record is created by provider but stored by core Sakai. UserEdit user = null; try { user = (UserEdit)userDirectoryService.getUserByEid(eid); try { securityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { if (function.equals(UserDirectoryService.SECURE_UPDATE_USER_ANY)) { return SecurityAdvice.ALLOWED; } else { return SecurityAdvice.NOT_ALLOWED; } } }); user = userDirectoryService.editUser(user.getId()); user.setLastName("Last Name, Jr."); userDirectoryService.commitEdit(user); } catch (Exception e) { log.warn(e); } finally { securityService.popAdvisor(); } } catch (UserNotDefinedException e) { try { securityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { if (function.equals(UserDirectoryService.SECURE_ADD_USER)) { return SecurityAdvice.ALLOWED; } else { return SecurityAdvice.NOT_ALLOWED; } } }); user = (UserEdit)userDirectoryService.addUser(null, eid, "First", "Last Name, Sr.", "eid@somewhere.edu", password, "Student", null); } catch (Exception e1) { log.warn(e1); } finally { securityService.popAdvisor(); } } return user; } public void setUserFactory(UserFactory userFactory) { this.userFactory = userFactory; } public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide; import com.apple.eawt.Application; import com.intellij.ide.actions.AboutAction; import com.intellij.ide.actions.OpenFileAction; import com.intellij.ide.actions.ShowSettingsAction; import com.intellij.ide.impl.ProjectUtil; import com.intellij.idea.IdeaApplication; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.impl.IdeKeyEventDispatcher; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.platform.PlatformProjectOpenProcessor; import com.intellij.ui.mac.foundation.Foundation; import com.intellij.ui.mac.foundation.ID; import com.sun.jna.Callback; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * @author max */ public class MacOSApplicationProvider { private static final Logger LOG = Logger.getInstance(MacOSApplicationProvider.class); private static final AtomicBoolean ENABLED = new AtomicBoolean(true); private static final Callback IMPL = new Callback() { @SuppressWarnings("unused") public void callback(ID self, String selector) { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { ActionManagerEx am = ActionManagerEx.getInstanceEx(); MouseEvent me = new MouseEvent(JOptionPane.getRootFrame(), MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, 0, 0, 1, false); am.tryToExecute(am.getAction("CheckForUpdate"), me, null, null, false); }); } }; private static final String GENERIC_RGB_PROFILE_PATH = "/System/Library/ColorSync/Profiles/Generic RGB Profile.icc"; private final ColorSpace genericRgbColorSpace; public static MacOSApplicationProvider getInstance() { return ApplicationManager.getApplication().getComponent(MacOSApplicationProvider.class); } public MacOSApplicationProvider() { if (SystemInfo.isMac) { try { Worker.initMacApplication(); } catch (Throwable t) { LOG.warn(t); } genericRgbColorSpace = initializeNativeColorSpace(); } else { genericRgbColorSpace = null; } } private static ColorSpace initializeNativeColorSpace() { try (InputStream is = new FileInputStream(GENERIC_RGB_PROFILE_PATH)) { ICC_Profile profile = ICC_Profile.getInstance(is); return new ICC_ColorSpace(profile); } catch (Throwable e) { LOG.warn("Couldn't load generic RGB color profile", e); return null; } } @Nullable public ColorSpace getGenericRgbColorSpace() { return genericRgbColorSpace; } private static class Worker { public static void initMacApplication() { Application application = Application.getApplication(); application.setAboutHandler(event -> AboutAction.perform(getProject(false))); application.setPreferencesHandler(event -> { Project project = getProject(true); submit("Preferences", () -> ShowSettingsAction.perform(project)); }); application.setQuitHandler((event, response) -> { submit("Quit", () -> ApplicationManager.getApplication().exit()); response.cancelQuit(); }); application.setOpenFileHandler(event -> { Project project = getProject(false); List<File> list = event.getFiles(); if (list.isEmpty()) return; submit("OpenFile", () -> { for (File file : list) { if (ProjectUtil.openOrImport(file.getAbsolutePath(), project, true) != null) { LOG.debug("MacMenu: load project from ", file); IdeaApplication.getInstance().disableProjectLoad(); return; } } for (File file : list) { if (file.exists()) { LOG.debug("MacMenu: open file ", file); String path = file.getAbsolutePath(); if (project != null) { OpenFileAction.openFile(path, project); } else { PlatformProjectOpenProcessor processor = PlatformProjectOpenProcessor.getInstanceIfItExists(); if (processor != null) { VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); if (virtualFile != null && virtualFile.isValid()) processor.doOpenProject(virtualFile, null, false); } } } } }); }); installAutoUpdateMenu(); } private static void installAutoUpdateMenu() { ID pool = Foundation.invoke("NSAutoreleasePool", "new"); ID app = Foundation.invoke("NSApplication", "sharedApplication"); ID menu = Foundation.invoke(app, Foundation.createSelector("menu")); ID item = Foundation.invoke(menu, Foundation.createSelector("itemAtIndex:"), 0); ID appMenu = Foundation.invoke(item, Foundation.createSelector("submenu")); ID checkForUpdatesClass = Foundation.allocateObjcClassPair(Foundation.getObjcClass("NSMenuItem"), "NSCheckForUpdates"); Foundation.addMethod(checkForUpdatesClass, Foundation.createSelector("checkForUpdates"), IMPL, "v"); Foundation.registerObjcClassPair(checkForUpdatesClass); ID checkForUpdates = Foundation.invoke("NSCheckForUpdates", "alloc"); Foundation.invoke(checkForUpdates, Foundation.createSelector("initWithTitle:action:keyEquivalent:"), Foundation.nsString("Check for Updates..."), Foundation.createSelector("checkForUpdates"), Foundation.nsString("")); Foundation.invoke(checkForUpdates, Foundation.createSelector("setTarget:"), checkForUpdates); Foundation.invoke(appMenu, Foundation.createSelector("insertItem:atIndex:"), checkForUpdates, 1); Foundation.invoke(checkForUpdates, Foundation.createSelector("release")); Foundation.invoke(pool, Foundation.createSelector("release")); } private static Project getProject(boolean useDefault) { @SuppressWarnings("deprecation") Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); if (project == null) { LOG.debug("MacMenu: no project in data context"); Project[] projects = ProjectManager.getInstance().getOpenProjects(); project = projects.length > 0 ? projects[0] : null; if (project == null && useDefault) { LOG.debug("MacMenu: use default project instead"); project = ProjectManager.getInstance().getDefaultProject(); } } LOG.debug("MacMenu: project = ", project); return project; } private static void submit(@NotNull String name, @NotNull Runnable task) { LOG.debug("MacMenu: on EDT = ", SwingUtilities.isEventDispatchThread(), "; ENABLED = ", ENABLED.get()); if (!ENABLED.get()) { LOG.debug("MacMenu: disabled"); } else { Component component = IdeFocusManager.getGlobalInstance().getFocusOwner(); if (component != null && IdeKeyEventDispatcher.isModalContext(component)) { LOG.debug("MacMenu: component in modal context"); } else { ENABLED.set(false); TransactionGuard.submitTransaction(ApplicationManager.getApplication(), () -> { try { LOG.debug("MacMenu: init ", name); task.run(); } finally { LOG.debug("MacMenu: done ", name); ENABLED.set(true); } }); } } } } }
package org.targettest.org.apache.lucene.analysis; /** * 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. */ import org.targettest.org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.targettest.org.apache.lucene.analysis.tokenattributes.TermAttribute; import org.targettest.org.apache.lucene.analysis.tokenattributes.TypeAttribute; import org.targettest.org.apache.lucene.document.NumericField; import org.targettest.org.apache.lucene.search.FieldCache; import org.targettest.org.apache.lucene.search.NumericRangeFilter; import org.targettest.org.apache.lucene.search.NumericRangeQuery; import org.targettest.org.apache.lucene.search.SortField; import org.targettest.org.apache.lucene.util.AttributeSource; import org.targettest.org.apache.lucene.util.NumericUtils; /** * <b>Expert:</b> This class provides a {@link TokenStream} * for indexing numeric values that can be used by {@link * NumericRangeQuery} or {@link NumericRangeFilter}. * * <p>Note that for simple usage, {@link NumericField} is * recommended. {@link NumericField} disables norms and * term freqs, as they are not usually needed during * searching. If you need to change these settings, you * should use this class. * * <p>See {@link NumericField} for capabilities of fields * indexed numerically.</p> * * <p>Here's an example usage, for an <code>int</code> field: * * <pre> * Field field = new Field(name, new NumericTokenStream(precisionStep).setIntValue(value)); * field.setOmitNorms(true); * field.setOmitTermFreqAndPositions(true); * document.add(field); * </pre> * * <p>For optimal performance, re-use the TokenStream and Field instance * for more than one document: * * <pre> * NumericTokenStream stream = new NumericTokenStream(precisionStep); * Field field = new Field(name, stream); * field.setOmitNorms(true); * field.setOmitTermFreqAndPositions(true); * Document document = new Document(); * document.add(field); * * for(all documents) { * stream.setIntValue(value) * writer.addDocument(document); * } * </pre> * * <p>This stream is not intended to be used in analyzers; * it's more for iterating the different precisions during * indexing a specific numeric value.</p> * <p><b>NOTE</b>: as token streams are only consumed once * the document is added to the index, if you index more * than one numeric field, use a separate <code>NumericTokenStream</code> * instance for each.</p> * * <p>See {@link NumericRangeQuery} for more details on the * <a * href="../search/NumericRangeQuery.html#precisionStepDesc"><code>precisionStep</code></a> * parameter as well as how numeric fields work under the hood.</p> * * <p><font color="red"><b>NOTE:</b> This API is experimental and * might change in incompatible ways in the next release.</font> * * @since 2.9 */ public final class NumericTokenStream extends TokenStream { /** The full precision token gets this token type assigned. */ public static final String TOKEN_TYPE_FULL_PREC = "fullPrecNumeric"; /** The lower precision tokens gets this token type assigned. */ public static final String TOKEN_TYPE_LOWER_PREC = "lowerPrecNumeric"; /** * Creates a token stream for numeric values using the default <code>precisionStep</code> * {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). The stream is not yet initialized, * before using set a value using the various set<em>???</em>Value() methods. */ public NumericTokenStream() { this(NumericUtils.PRECISION_STEP_DEFAULT); } /** * Creates a token stream for numeric values with the specified * <code>precisionStep</code>. The stream is not yet initialized, * before using set a value using the various set<em>???</em>Value() methods. */ public NumericTokenStream(final int precisionStep) { super(); this.precisionStep = precisionStep; if (precisionStep < 1) throw new IllegalArgumentException("precisionStep must be >=1"); } /** * Expert: Creates a token stream for numeric values with the specified * <code>precisionStep</code> using the given {@link AttributeSource}. * The stream is not yet initialized, * before using set a value using the various set<em>???</em>Value() methods. */ public NumericTokenStream(AttributeSource source, final int precisionStep) { super(source); this.precisionStep = precisionStep; if (precisionStep < 1) throw new IllegalArgumentException("precisionStep must be >=1"); } /** * Expert: Creates a token stream for numeric values with the specified * <code>precisionStep</code> using the given * {@link org.targettest.org.apache.lucene.util.AttributeSource.AttributeFactory}. * The stream is not yet initialized, * before using set a value using the various set<em>???</em>Value() methods. */ public NumericTokenStream(AttributeFactory factory, final int precisionStep) { super(factory); this.precisionStep = precisionStep; if (precisionStep < 1) throw new IllegalArgumentException("precisionStep must be >=1"); } /** * Initializes the token stream with the supplied <code>long</code> value. * @param value the value, for which this TokenStream should enumerate tokens. * @return this instance, because of this you can use it the following way: * <code>new Field(name, new NumericTokenStream(precisionStep).setLongValue(value))</code> */ public NumericTokenStream setLongValue(final long value) { this.value = value; valSize = 64; shift = 0; return this; } /** * Initializes the token stream with the supplied <code>int</code> value. * @param value the value, for which this TokenStream should enumerate tokens. * @return this instance, because of this you can use it the following way: * <code>new Field(name, new NumericTokenStream(precisionStep).setIntValue(value))</code> */ public NumericTokenStream setIntValue(final int value) { this.value = (long) value; valSize = 32; shift = 0; return this; } /** * Initializes the token stream with the supplied <code>double</code> value. * @param value the value, for which this TokenStream should enumerate tokens. * @return this instance, because of this you can use it the following way: * <code>new Field(name, new NumericTokenStream(precisionStep).setDoubleValue(value))</code> */ public NumericTokenStream setDoubleValue(final double value) { this.value = NumericUtils.doubleToSortableLong(value); valSize = 64; shift = 0; return this; } /** * Initializes the token stream with the supplied <code>float</code> value. * @param value the value, for which this TokenStream should enumerate tokens. * @return this instance, because of this you can use it the following way: * <code>new Field(name, new NumericTokenStream(precisionStep).setFloatValue(value))</code> */ public NumericTokenStream setFloatValue(final float value) { this.value = (long) NumericUtils.floatToSortableInt(value); valSize = 32; shift = 0; return this; } @Override public void reset() { if (valSize == 0) throw new IllegalStateException("call set???Value() before usage"); shift = 0; } @Override public boolean incrementToken() { if (valSize == 0) throw new IllegalStateException("call set???Value() before usage"); if (shift >= valSize) return false; clearAttributes(); final char[] buffer; switch (valSize) { case 64: buffer = termAtt.resizeTermBuffer(NumericUtils.BUF_SIZE_LONG); termAtt.setTermLength(NumericUtils.longToPrefixCoded(value, shift, buffer)); break; case 32: buffer = termAtt.resizeTermBuffer(NumericUtils.BUF_SIZE_INT); termAtt.setTermLength(NumericUtils.intToPrefixCoded((int) value, shift, buffer)); break; default: // should not happen throw new IllegalArgumentException("valSize must be 32 or 64"); } typeAtt.setType((shift == 0) ? TOKEN_TYPE_FULL_PREC : TOKEN_TYPE_LOWER_PREC); posIncrAtt.setPositionIncrement((shift == 0) ? 1 : 0); shift += precisionStep; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder("(numeric,valSize=").append(valSize); sb.append(",precisionStep=").append(precisionStep).append(')'); return sb.toString(); } // members private final TermAttribute termAtt = addAttribute(TermAttribute.class); private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class); private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class); private int shift = 0, valSize = 0; // valSize==0 means not initialized private final int precisionStep; private long value = 0L; }
/* * Copyright 2014 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.rendering.nui.layouts.miglayout; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.miginfocom.layout.AC; import net.miginfocom.layout.CC; import net.miginfocom.layout.ComponentWrapper; import net.miginfocom.layout.ConstraintParser; import net.miginfocom.layout.ContainerWrapper; import net.miginfocom.layout.Grid; import net.miginfocom.layout.LC; import org.terasology.math.geom.Rect2i; import org.terasology.math.geom.Vector2i; import org.terasology.rendering.nui.Canvas; import org.terasology.rendering.nui.Color; import org.terasology.rendering.nui.CoreLayout; import org.terasology.rendering.nui.LayoutConfig; import org.terasology.rendering.nui.LayoutHint; import org.terasology.rendering.nui.UIWidget; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * MigLayout Binding * <br><br> * see: http://www.miglayout.com/ * <br><br> */ public class MigLayout extends CoreLayout<MigLayout.CCHint> implements ContainerWrapper { private Map<ComponentWrapper, CC> ccMap = Maps.newHashMap(); private Map<UIWidget, ComponentWrapper> wrappers = Maps.newHashMap(); private List<ComponentWrapper> children = Lists.newArrayList(); @LayoutConfig private String layoutConstraints; @LayoutConfig private String rowConstraints; @LayoutConfig private String colConstraints; private LC lc; private AC rc; private AC cc; private Grid grid; private boolean dirty; private MigComponent delegate = new MigComponent(null, null); private List<Rect2i> debugRects = Lists.newArrayList(); @LayoutConfig private boolean debug; public MigLayout() { setLayoutConstraints(""); setRowConstraints(""); setColConstraints(""); } public MigLayout(String id) { super(id); setLayoutConstraints(""); setRowConstraints(""); setColConstraints(""); } public void setLc(LC lc) { this.lc = lc; dirty = true; } public void setLayoutConstraints(String constraint) { layoutConstraints = constraint; setLc(ConstraintParser.parseLayoutConstraint(ConstraintParser.prepare(constraint))); } public void setCC(AC columnConstraint) { this.cc = columnConstraint; dirty = true; } public void setColConstraints(String constraint) { colConstraints = constraint; setCC(ConstraintParser.parseColumnConstraints(ConstraintParser.prepare(constraint))); } public void setDebug(boolean debug) { this.debug = debug; } public void setRc(AC rc) { this.rc = rc; dirty = true; } public void setRowConstraints(String constraint) { rowConstraints = constraint; setRc(ConstraintParser.parseColumnConstraints(ConstraintParser.prepare(constraint))); } @Override public void onDraw(Canvas canvas) { int[] bounds = {0, 0, canvas.size().x, canvas.size().y}; layoutContainer(canvas, bounds); for (ComponentWrapper wrapper : wrappers.values()) { UIWidget component = (UIWidget) wrapper.getComponent(); Rect2i region = Rect2i.createFromMinAndSize(wrapper.getX(), wrapper.getY(), wrapper.getWidth(), wrapper.getHeight()); canvas.drawWidget(component, region); } if (debug) { grid.paintDebug(); } for (Rect2i region : debugRects) { canvas.drawLine(region.minX(), region.minY(), region.maxX(), region.minY(), Color.WHITE); canvas.drawLine(region.maxX(), region.minY(), region.maxX(), region.maxY(), Color.WHITE); canvas.drawLine(region.maxX(), region.maxY(), region.minX(), region.maxY(), Color.WHITE); canvas.drawLine(region.minX(), region.maxY(), region.minX(), region.minY(), Color.WHITE); } } @Override public void addWidget(UIWidget element, CCHint hint) { final ComponentWrapper cw = getWrapper(element); final String cStr = ConstraintParser.prepare(hint != null ? hint.cc : ""); CC constraint = AccessController.doPrivileged((PrivilegedAction<CC>) () -> ConstraintParser.parseComponentConstraint(cStr)); ccMap.put(cw, constraint); wrappers.put(element, cw); children.add(cw); dirty = true; } @Override public void removeWidget(UIWidget element) { ComponentWrapper cw = wrappers.remove(element); ccMap.remove(cw); children.remove(cw); invalidate(); } @Override public void removeAllWidgets() { clear(); } public void clear() { wrappers.clear(); ccMap.clear(); children.clear(); invalidate(); } public void invalidate() { dirty = true; } @Override public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) { int[] bounds = {0, 0, canvas.size().x, canvas.size().y}; layoutContainer(canvas, bounds); return new Vector2i(grid.getWidth()[1], grid.getHeight()[1]); } @Override public Vector2i getMaxContentSize(Canvas canvas) { return getPreferredContentSize(canvas, Vector2i.zero()); } private ComponentWrapper getWrapper(UIWidget comp) { ComponentWrapper cw; if (comp instanceof MigLayout) { MigLayout migLayout = (MigLayout) comp; migLayout.setParent(this); cw = migLayout; } else { cw = new MigComponent(this, comp); } return cw; } private void checkCache() { if (dirty) { grid = null; } if (grid == null) { grid = new Grid(this, lc, rc, cc, ccMap, new ArrayList<>()); } debugRects.clear(); dirty = false; } public void layoutContainer(Canvas canvas, int[] bounds) { for (ComponentWrapper wrapper : children) { if (wrapper instanceof MigLayout) { MigLayout layout = (MigLayout) wrapper; layout.layoutContainer(canvas, bounds); } else if (wrapper instanceof MigComponent) { MigComponent migComponent = (MigComponent) wrapper; migComponent.calculatePreferredSize(canvas, canvas.size()); } } checkCache(); if (grid.layout(bounds, lc.getAlignX(), lc.getAlignY(), debug, true)) { grid = null; checkCache(); grid.layout(bounds, lc.getAlignX(), lc.getAlignY(), debug, false); } } @Override public ComponentWrapper[] getComponents() { return children.toArray(new ComponentWrapper[children.size()]); } @Override public int getComponentCount() { return children.size(); } @Override public Object getLayout() { return this; } @Override public boolean isLeftToRight() { return true; } @Override public void paintDebugCell(int x, int y, int width, int height) { debugRects.add(Rect2i.createFromMinAndSize(x, y, width, height)); } @Override public Object getComponent() { return this; } @Override public int getX() { return delegate.getX(); } @Override public int getY() { return delegate.getY(); } @Override public int getWidth() { return delegate.getWidth(); } @Override public int getHeight() { return delegate.getHeight(); } @Override public int getScreenLocationX() { return delegate.getScreenLocationX(); } @Override public int getScreenLocationY() { return delegate.getScreenLocationY(); } @Override public int getMinimumWidth(int hHint) { return grid.getWidth()[0]; } @Override public int getMinimumHeight(int wHint) { return grid.getHeight()[0]; } @Override public int getPreferredWidth(int hHint) { return grid.getWidth()[1]; } @Override public int getPreferredHeight(int wHint) { return grid.getHeight()[1]; } @Override public int getMaximumWidth(int hHint) { return grid.getWidth()[2]; } @Override public int getMaximumHeight(int wHint) { return grid.getHeight()[2]; } @Override public void setBounds(int x, int y, int width, int height) { delegate.setBounds(x, y, width, height); } @Override public boolean isVisible() { return delegate.isVisible(); } @Override public int getBaseline(int width, int height) { return delegate.getBaseline(width, height); } @Override public boolean hasBaseline() { return delegate.hasBaseline(); } @Override public ContainerWrapper getParent() { return delegate.getParent(); } public void setParent(MigLayout parent) { delegate.setParent(parent); } @Override public float getPixelUnitFactor(boolean isHor) { return delegate.getPixelUnitFactor(isHor); } @Override public int getHorizontalScreenDPI() { return delegate.getHorizontalScreenDPI(); } @Override public int getVerticalScreenDPI() { return delegate.getVerticalScreenDPI(); } @Override public int getScreenWidth() { throw new IllegalAccessError("Not supported!"); } @Override public int getScreenHeight() { throw new IllegalAccessError("Not supported!"); } @Override public String getLinkId() { return null; } @Override public int getLayoutHashCode() { return delegate.getLayoutHashCode(); } @Override public int[] getVisualPadding() { return delegate.getVisualPadding(); } @Override public void paintDebugOutline(boolean showVisualPadding) { } @Override public int getComponentType(boolean disregardScrollPane) { return 0; } @Override public int getContentBias() { return -1; } @Override public Iterator<UIWidget> iterator() { return new Iterator<UIWidget>() { private Iterator<ComponentWrapper> it = children.iterator(); @Override public boolean hasNext() { return it.hasNext(); } @Override public UIWidget next() { return (UIWidget) it.next().getComponent(); } @Override public void remove() { it.remove(); } }; } public static class CCHint implements LayoutHint { private String cc = ""; public CCHint() { } public CCHint(String cc) { this.cc = cc; } } }
package ru.agolovin.server; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; /** * @author agolovin (agolovin@list.ru) * @version $Id$ * @since 0.1 */ class ServerMenu { /** * Check. */ private static final String CHECKCORRECT = "correct"; /** * Menu size. */ private static final int MENUSIZE = 6; /** * Transfer result. */ private static final String TRANSFERRESULT = "Transfer correct"; /** * Transfer result Error. */ private static final String TRANSFERRESULTERR = "Error transferring"; /** * BufferSize. */ private final int bufferSize = 16; /** * BufferSize. */ private final int bufferSizeN = 1024; /** * PrintWriter. */ private PrintWriter prW; /** * DataOutPutStream. */ private DataOutputStream dataOutputStream; /** * DataInputStream. */ private DataInputStream dataInputStream; /** * BufferedReader. */ private BufferedReader reader; /** * Position. */ private int position = 0; /** * Current Directory. */ private File currentFileDir; /** * Base action array. */ private BaseAction[] baseActionArray = new BaseAction[MENUSIZE]; /** * Constructor. * * @param sReader BufferedReader. * @param inputStream InputStream. * @param outputStream OutPutStream. * @param home File. */ ServerMenu(BufferedReader sReader, InputStream inputStream, OutputStream outputStream, File home) { this.prW = new PrintWriter(outputStream, true); this.dataOutputStream = new DataOutputStream(outputStream); this.dataInputStream = new DataInputStream(inputStream); this.currentFileDir = home; this.reader = sReader; } /** * Init menu. */ void fillActions() { this.baseActionArray[position++] = new Exit(); this.baseActionArray[position++] = new ShowCurDir(); this.baseActionArray[position++] = new InDir(); this.baseActionArray[position++] = new OutDir(); this.baseActionArray[position++] = new Download(); this.baseActionArray[position++] = new Upload(); } /** * Select key menu. * * @param input String */ void select(String input) { for (BaseAction element : this.baseActionArray) { if (element != null && element.key().equals(input)) { int key = Integer.parseInt(input); this.baseActionArray[key].execute(); } } } /** * Show menu. */ void show() { for (BaseAction element : baseActionArray) { if (element != null) { this.prW.println(element.info()); } } this.prW.println(""); System.out.println("Show server menu"); } /** * Exit. */ public class Exit extends BaseAction { /** * Constructor. */ Exit() { super("Exit"); } @Override String key() { return "0"; } @Override void execute() { try { System.out.println("Exit"); prW.close(); dataInputStream.close(); dataOutputStream.close(); reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * Show current directory. */ public class ShowCurDir extends BaseAction { /** * Constructor. */ ShowCurDir() { super("Show current directory"); } @Override String key() { return "1"; } @Override void execute() { prW.println("File list in " + currentFileDir); File[] element = currentFileDir.listFiles(); if (element != null) { for (File file : element) { prW.println(file.getName()); } } else { prW.println("Empty directory"); } } } /** * Go to parent directory. */ public class OutDir extends BaseAction { /** * Constructor. */ OutDir() { super("Go to parent directory"); } @Override String key() { return "3"; } @Override void execute() { String line; if (currentFileDir.getParent() != null) { currentFileDir = new File(currentFileDir.getParent()); line = String.format("Current dir is: %s", currentFileDir); System.out.println(line); prW.println(line); } else { System.out.println("No parent directory"); prW.println("No parent directory"); } } } /** * Change directory. */ public class InDir extends BaseAction { /** * Constructor. */ InDir() { super("Step into dir"); } @Override String key() { return "2"; } @Override void execute() { File[] element = currentFileDir.listFiles(); String directoryName = ""; boolean flag = false; if (element != null) { prW.println("Enter directory"); prW.println(""); try { directoryName = reader.readLine(); System.out.println(directoryName); } catch (IOException ioe) { ioe.printStackTrace(); } for (File file : element) { if (file.getName().equals(directoryName) && file.isDirectory()) { currentFileDir = file.getAbsoluteFile(); flag = true; } } if (flag) { prW.println("Directory changed to: " + currentFileDir); } else { prW.println("Error change directory"); } } } } /** * Download file to client. */ public class Download extends BaseAction { /** * Constructor. */ Download() { super("Download file from server"); } @Override String key() { return "4"; } @Override void execute() { prW.println("Enter file name to download: "); prW.println(""); try { String fileName = reader.readLine(); System.out.println("File name: " + fileName); File[] element; boolean flag = false; element = currentFileDir.listFiles(); if (element != null) { for (File file : element) { if (file.getName().equals(fileName)) { File fileServer = new File(currentFileDir + "/" + fileName); if (fileServer.exists() && fileServer.isFile()) { flag = true; prW.println("correct"); prW.println(file.length()); try (FileInputStream fis = new FileInputStream(fileServer)) { byte[] buffer = new byte[bufferSize * bufferSizeN]; int partBuf; while ((partBuf = fis.read(buffer)) != -1) { dataOutputStream.write(buffer, 0, partBuf); dataOutputStream.flush(); } } } else { prW.print("File error"); } } } if (!flag) { prW.println("File not found"); System.out.println("File not found"); } String resultTransfer = reader.readLine(); if (TRANSFERRESULT.equals(resultTransfer)) { System.out.println(resultTransfer); } else if (TRANSFERRESULTERR.equals(resultTransfer)) { System.out.println(resultTransfer); } else { System.out.println("Error"); } } } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * Download file to server. */ public class Upload extends BaseAction { /** * Constructor. */ Upload() { super("Upload file to server"); } @Override String key() { return "5"; } @Override void execute() { try { String fileName = reader.readLine(); String check = reader.readLine(); long fileLength; if (CHECKCORRECT.equals(check)) { fileLength = Long.parseLong(reader.readLine()); if (fileLength > 0) { String filePath = String.format("%s/upload", currentFileDir); String filePath2 = String.format("%s/upload/%s", currentFileDir, fileName); File newFile = new File(filePath); if (!newFile.isDirectory()) { if (!newFile.mkdir()) { System.out.println("Error downloading"); } } File newFile2 = new File(filePath2); try (FileOutputStream fos = new FileOutputStream(newFile2)) { byte[] buffer = new byte[bufferSize * bufferSizeN]; int partBuffer; long tempLength = fileLength; while (tempLength > 0) { partBuffer = dataInputStream.read(buffer); fos.write(buffer, 0, partBuffer); fos.flush(); tempLength -= partBuffer; } if (fileLength == newFile2.length()) { System.out.println(TRANSFERRESULT); prW.println(TRANSFERRESULT); System.out.println(String.format("File download to: %s", newFile.getAbsoluteFile())); } else { prW.println(TRANSFERRESULTERR); System.out.println(TRANSFERRESULTERR); } } catch (IOException ioe) { ioe.printStackTrace(); } } } } catch (IOException ioe) { ioe.printStackTrace(); } } } }
/* * Copyright 2015 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.commons.models.metadata; import org.springframework.data.jpa.domain.AbstractPersistable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import javax.persistence.Table; import javax.persistence.Transient; import java.net.URI; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; @Entity @Table(indexes = {@Index(name = "study_unique", columnList = "title,material,scope,description,alias", unique = true)}) public class Study extends AbstractPersistable<Long> { private static final long serialVersionUid = 3947143813564096660L; private String title; private String alias; private String description; private Material material; private Scope scope; private String type; // e.g. umbrella, pop genomics BUT separate column for study_type (aggregate, control set, case control) private String studyAccession; // Bioproject ID? @ManyToOne(cascade = CascadeType.PERSIST) private Organisation centre; @ManyToOne(cascade = CascadeType.PERSIST) private Organisation broker; @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "study") private Set<FileGenerator> fileGenerators; @Transient private Set<URI> uris; @Transient private Set<Publication> publications; @ManyToOne(cascade = CascadeType.PERSIST) private Study parentStudy; @OneToMany(mappedBy = "parentStudy", cascade = CascadeType.PERSIST) private Set<Study> childStudies; public Study() { this.title = null; this.alias = null; this.description = null; this.material = Material.OTHER; this.scope = Scope.OTHER; } public Study(Long id) { this.setId(id); } public Study(String title, String alias, String description, Material material, Scope scope) { setTitle(title); setAlias(alias); setDescription(description); setMaterial(material); setScope(scope); fileGenerators = new HashSet<>(); uris = new HashSet<>(); publications = new HashSet<>(); childStudies = new HashSet<>(); } public String getStudyAccession() { return studyAccession; } public void setStudyAccession(String studyAccession) { // starts with "PRJEA or PRJEB PRJNA\d+" if (studyAccession.matches("PRJ(E(A|B)|NA)\\d+")) { this.studyAccession = studyAccession; } else { throw new IllegalArgumentException( "Study accession must begin with a prefix from the following: (PRJEA, PRJEB, PRJNA), " + "followed by multiple numerical digits."); // TODO openpojo tester throws exception with this } } public String getTitle() { return title; } public final void setTitle(String title) { Objects.requireNonNull(title, "Title not specified"); this.title = title; } public String getAlias() { return alias; } public final void setAlias(String alias) { Objects.requireNonNull(alias, "Alias not specified"); this.alias = alias; } public String getDescription() { return description; } public final void setDescription(String description) { Objects.requireNonNull(description, "Description not specified"); this.description = description; } public Organisation getCentre() { return centre; } public void setCentre(Organisation centre) { this.centre = centre; } public Scope getScope() { return scope; } public final void setScope(Scope scope) { Objects.requireNonNull(scope, "Scope not specified"); this.scope = scope; } public Material getMaterial() { return material; } public final void setMaterial(Material material) { Objects.requireNonNull(material, "Material not specified"); this.material = material; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Set<URI> getUris() { return Collections.unmodifiableSet(uris); } public void addUri(URI uri) { uris.add(uri); } public void removeUrl(URI url) { uris.remove(url); } public void setUris(Set<URI> uris) { this.uris.clear(); if (uris != null) { for (URI uri : uris) { addUri(uri); } } } public Set<FileGenerator> getFileGenerators() { return Collections.unmodifiableSet(fileGenerators); } @PreRemove private void preRemove() { for (FileGenerator generator : fileGenerators) { generator.unsetStudy(); } } public void removeFileGenerator(FileGenerator fileGenerator) { fileGenerator.unsetStudy(); fileGenerators.remove(fileGenerator); } public void addFileGenerator(FileGenerator fileGenerator) { fileGenerator.setStudy(this); fileGenerators.add(fileGenerator); } public void setFileGenerators(Set<FileGenerator> fileGenerators) { this.fileGenerators.clear(); for (FileGenerator fileGenerator : fileGenerators) { addFileGenerator(fileGenerator); } } public Set<Publication> getPublications() { return Collections.unmodifiableSet(publications); } public void removePublication(Publication publication) { publication.removeStudy(this); publications.remove(publication); } public void addPublication(Publication publication) { publications.add(publication); publication.addStudy(this); } public void setPublications(Set<Publication> publications) { this.publications.clear(); for (Publication publication : publications) { addPublication(publication); } } public Organisation getBroker() { return broker; } public void setBroker(Organisation broker) { this.broker = broker; } public Study getParentStudy() { return parentStudy; } void setParentStudy(Study parentStudy) { if (this.equals(parentStudy)) { throw new IllegalArgumentException("A study can't be its own parent study."); } this.parentStudy = parentStudy; } void unsetParentStudy() { this.parentStudy = null; } public Set<Study> getChildStudies() { return Collections.unmodifiableSet(childStudies); } public void addChildStudy(Study childStudy) { if (this.equals(childStudy)) { throw new IllegalArgumentException("A study can't be its own child study."); } childStudies.add(childStudy); childStudy.setParentStudy(this); } public void removeChildStudy(Study childStudy) { childStudies.remove(childStudy); childStudy.unsetParentStudy(); } public void setChildStudies(Set<Study> childStudies) { this.childStudies.clear(); for (Study childStudy : childStudies) { addChildStudy(childStudy); childStudy.setParentStudy(this); } } @Override public String toString() { return "Study{" + "title=" + title + ", material=" + material + ", scope=" + scope + ", description=" + description + ", alias=" + alias + '}'; } @Override public boolean equals(Object e) { if (e == this) { return true; } else if (!(e instanceof Study)) { return false; } else { return (Objects.equals(((Study) e).getTitle(), title) && Objects.equals(((Study) e).getMaterial(), material) && Objects.equals(((Study) e).getScope(), scope) && Objects.equals(((Study) e).getDescription(), description) && Objects.equals(((Study) e).getAlias(), alias)); } } @Override public int hashCode() { int result = 17; result = (title != null) ? 31 * result + title.hashCode() : result; result = (material != null) ? 31 * result + material.hashCode() : result; result = (scope != null) ? 31 * result + scope.hashCode() : result; result = (description != null) ? 31 * result + description.hashCode() : result; result = (alias != null) ? 31 * result + alias.hashCode() : result; return result; } public enum Scope { SINGLE_ISOLATE("single isolate"), MULTI_ISOLATE("multi-isolate"), SINGLE_CELL("single cell"), COMMUNITY("community"), UNKNOWN("unknown"), OTHER("other"); private final String name; private Scope(String s) { name = s; } public boolean equalsName(String otherName) { return (otherName != null) && name.equals(otherName); } @Override public String toString() { return this.name; } } public enum Material { DNA("DNA"), EXONIC_RNA("exonic RNA"), TRANSCRIBED_RNA("transcribed RNA"), UNKNOWN("unknown"), OTHER("other"); private final String name; private Material(String s) { name = s; } public boolean equalsName(String otherName) { return (otherName != null) && name.equals(otherName); } @Override public String toString() { return this.name; } } }
package org.knowm.xchange.hitbtc; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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.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.meta.CurrencyMetaData; import org.knowm.xchange.dto.meta.CurrencyPairMetaData; import org.knowm.xchange.dto.meta.ExchangeMetaData; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.hitbtc.dto.account.HitbtcBalance; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcOrderBook; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcSymbol; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcSymbols; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcTicker; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcTime; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcTrade; import org.knowm.xchange.hitbtc.dto.marketdata.HitbtcTrades; import org.knowm.xchange.hitbtc.dto.trade.HitbtcOrder; import org.knowm.xchange.hitbtc.dto.trade.HitbtcOwnTrade; import org.knowm.xchange.utils.jackson.CurrencyPairDeserializer; public class HitbtcAdapters { public static final char DELIM = '_'; /** * Singleton */ private HitbtcAdapters() { } public static Date adaptTime(HitbtcTime hitbtcTime) { return new Date(hitbtcTime.getTimestamp()); } public static CurrencyPair adaptSymbol(String symbolString) { return CurrencyPairDeserializer.getCurrencyPairFromString(symbolString); } public static CurrencyPair adaptSymbol(HitbtcSymbol hitbtcSymbol) { return new CurrencyPair(hitbtcSymbol.getCommodity(), hitbtcSymbol.getCurrency()); } /** * Adapts a HitbtcTicker to a Ticker Object * * @param hitbtcTicker The exchange specific ticker * @param currencyPair (e.g. BTC/USD) * @return The ticker */ public static Ticker adaptTicker(HitbtcTicker hitbtcTicker, CurrencyPair currencyPair) { BigDecimal bid = hitbtcTicker.getBid(); BigDecimal ask = hitbtcTicker.getAsk(); BigDecimal high = hitbtcTicker.getHigh(); BigDecimal low = hitbtcTicker.getLow(); BigDecimal last = hitbtcTicker.getLast(); BigDecimal volume = hitbtcTicker.getVolume(); Date timestamp = new Date(hitbtcTicker.getTimestamp()); return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp) .build(); } public static List<Ticker> adaptTickers(Map<String, HitbtcTicker> hitbtcTickers) { List<Ticker> tickers = new ArrayList<Ticker>(hitbtcTickers.size()); for (Map.Entry<String, HitbtcTicker> ticker : hitbtcTickers.entrySet()) { tickers.add(adaptTicker(ticker.getValue(), adaptSymbol(ticker.getKey()))); } return tickers; } public static OrderBook adaptOrderBook(HitbtcOrderBook hitbtcOrderBook, CurrencyPair currencyPair) { List<LimitOrder> asks = adaptMarketOrderToLimitOrder(hitbtcOrderBook.getAsks(), OrderType.ASK, currencyPair); List<LimitOrder> bids = adaptMarketOrderToLimitOrder(hitbtcOrderBook.getBids(), OrderType.BID, currencyPair); return new OrderBook(null, asks, bids); } private static List<LimitOrder> adaptMarketOrderToLimitOrder(BigDecimal[][] hitbtcOrders, OrderType orderType, CurrencyPair currencyPair) { List<LimitOrder> orders = new ArrayList<LimitOrder>(hitbtcOrders.length); for (int i = 0; i < hitbtcOrders.length; i++) { BigDecimal[] hitbtcOrder = hitbtcOrders[i]; BigDecimal price = hitbtcOrder[0]; BigDecimal amount = hitbtcOrder[1]; LimitOrder limitOrder = new LimitOrder(orderType, amount, currencyPair, null, null, price); orders.add(limitOrder); } return orders; } public static OrderType adaptSide(HitbtcTrade.HitbtcTradeSide side) { switch (side) { case BUY: return OrderType.BID; case SELL: return OrderType.ASK; default: return null; } } public static Trades adaptTrades(HitbtcTrades hitbtcTrades, CurrencyPair currencyPair) { List<HitbtcTrade> allHitbtcTrades = hitbtcTrades.getHitbtcTrades(); return adaptTrades(allHitbtcTrades, currencyPair); } public static Trades adaptTrades(List<? extends HitbtcTrade> allHitbtcTrades, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<Trade>(allHitbtcTrades.size()); long lastTradeId = 0; for (int i = 0; i < allHitbtcTrades.size(); i++) { HitbtcTrade hitbtcTrade = allHitbtcTrades.get(i); Date timestamp = new Date(hitbtcTrade.getDate()); BigDecimal price = hitbtcTrade.getPrice(); BigDecimal amount = hitbtcTrade.getAmount(); String tid = hitbtcTrade.getTid(); long longTradeId = tid == null ? 0 : Long.parseLong(tid); if (longTradeId > lastTradeId) { lastTradeId = longTradeId; } OrderType orderType = adaptSide(hitbtcTrade.getSide()); Trade trade = new Trade(orderType, amount, currencyPair, price, timestamp, tid); trades.add(trade); } return new Trades(trades, lastTradeId, Trades.TradeSortType.SortByTimestamp); } public static OpenOrders adaptOpenOrders(HitbtcOrder[] openOrdersRaw) { List<LimitOrder> openOrders = new ArrayList<LimitOrder>(openOrdersRaw.length); for (int i = 0; i < openOrdersRaw.length; i++) { HitbtcOrder o = openOrdersRaw[i]; OrderType type = adaptOrderType(o.getSide()); LimitOrder order = new LimitOrder(type, o.getExecQuantity(), adaptSymbol(o.getSymbol()), o.getClientOrderId(), new Date(o.getLastTimestamp()), o.getOrderPrice()); openOrders.add(order); } return new OpenOrders(openOrders); } public static OrderType adaptOrderType(String side) { return side.equals("buy") ? OrderType.BID : OrderType.ASK; } public static UserTrades adaptTradeHistory(HitbtcOwnTrade[] tradeHistoryRaw, ExchangeMetaData metaData) { List<UserTrade> trades = new ArrayList<UserTrade>(tradeHistoryRaw.length); for (int i = 0; i < tradeHistoryRaw.length; i++) { HitbtcOwnTrade t = tradeHistoryRaw[i]; OrderType type = adaptOrderType(t.getSide()); CurrencyPair pair = adaptSymbol(t.getSymbol()); // minimumAmount is equal to lot size BigDecimal tradableAmount = t.getExecQuantity().multiply(metaData.getCurrencyPairs().get(pair).getMinimumAmount()); Date timestamp = new Date(t.getTimestamp()); String id = Long.toString(t.getTradeId()); UserTrade trade = new UserTrade(type, tradableAmount, pair, t.getExecPrice(), timestamp, id, t.getClientOrderId(), t.getFee(), Currency.getInstance(pair.counter.getCurrencyCode())); trades.add(trade); } return new UserTrades(trades, Trades.TradeSortType.SortByTimestamp); } public static Wallet adaptWallet(HitbtcBalance[] walletRaw) { List<Balance> balances = new ArrayList<Balance>(walletRaw.length); for (HitbtcBalance balanceRaw : walletRaw) { Balance balance = new Balance(Currency.getInstance(balanceRaw.getCurrencyCode()), null, balanceRaw.getCash(), balanceRaw.getReserved()); balances.add(balance); } return new Wallet(balances); } public static String adaptCurrencyPair(CurrencyPair pair) { return pair == null ? null : pair.base.getCurrencyCode() + pair.counter.getCurrencyCode(); } public static String createOrderId(Order order, long nonce) { if (order.getId() == null || "".equals(order.getId())) { // encoding side in client order id return order.getType().name().substring(0, 1) + DELIM + adaptCurrencyPair(order.getCurrencyPair()) + DELIM + nonce; } else { return order.getId(); } } public static OrderType readOrderType(String orderId) { return orderId.charAt(0) == 'A' ? OrderType.ASK : OrderType.BID; } public static String readSymbol(String orderId) { int start = orderId.indexOf(DELIM); int end = orderId.indexOf(DELIM, start + 1); return orderId.substring(start + 1, end); } public static HitbtcTrade.HitbtcTradeSide getSide(OrderType type) { return type == OrderType.BID ? HitbtcTrade.HitbtcTradeSide.BUY : HitbtcTrade.HitbtcTradeSide.SELL; } public static ExchangeMetaData adaptToExchangeMetaData(HitbtcSymbols symbols, Map<Currency, CurrencyMetaData> currencies) { Map<CurrencyPair, CurrencyPairMetaData> currencyPairs = new HashMap<CurrencyPair, CurrencyPairMetaData>(); if (symbols != null) { for (HitbtcSymbol symbol : symbols.getHitbtcSymbols()) { CurrencyPair pair = adaptSymbol(symbol); CurrencyPairMetaData meta = new CurrencyPairMetaData(symbol.getTakeLiquidityRate(), symbol.getLot(), null, symbol.getStep().scale()); currencyPairs.put(pair, meta); } } return new ExchangeMetaData(currencyPairs, currencies, null, null, null); } }
/* * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.border; import java.awt.Graphics; import java.awt.Insets; import java.awt.Component; import java.awt.Color; import javax.swing.Icon; /** * A class which provides a matte-like border of either a solid color * or a tiled icon. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Amy Fowler */ public class MatteBorder extends EmptyBorder { protected Color color; protected Icon tileIcon; /** * Creates a matte border with the specified insets and color. * @param top the top inset of the border * @param left the left inset of the border * @param bottom the bottom inset of the border * @param right the right inset of the border * @param matteColor the color rendered for the border */ public MatteBorder(int top, int left, int bottom, int right, Color matteColor) { super(top, left, bottom, right); this.color = matteColor; } /** * Creates a matte border with the specified insets and color. * @param borderInsets the insets of the border * @param matteColor the color rendered for the border * @since 1.3 */ public MatteBorder(Insets borderInsets, Color matteColor) { super(borderInsets); this.color = matteColor; } /** * Creates a matte border with the specified insets and tile icon. * @param top the top inset of the border * @param left the left inset of the border * @param bottom the bottom inset of the border * @param right the right inset of the border * @param tileIcon the icon to be used for tiling the border */ public MatteBorder(int top, int left, int bottom, int right, Icon tileIcon) { super(top, left, bottom, right); this.tileIcon = tileIcon; } /** * Creates a matte border with the specified insets and tile icon. * @param borderInsets the insets of the border * @param tileIcon the icon to be used for tiling the border * @since 1.3 */ public MatteBorder(Insets borderInsets, Icon tileIcon) { super(borderInsets); this.tileIcon = tileIcon; } /** * Creates a matte border with the specified tile icon. The * insets will be calculated dynamically based on the size of * the tile icon, where the top and bottom will be equal to the * tile icon's height, and the left and right will be equal to * the tile icon's width. * @param tileIcon the icon to be used for tiling the border */ public MatteBorder(Icon tileIcon) { this(-1,-1,-1,-1, tileIcon); } /** * Paints the matte border. */ public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Insets insets = getBorderInsets(c); Color oldColor = g.getColor(); g.translate(x, y); // If the tileIcon failed loading, paint as gray. if (tileIcon != null) { color = (tileIcon.getIconWidth() == -1) ? Color.gray : null; } if (color != null) { g.setColor(color); g.fillRect(0, 0, width - insets.right, insets.top); g.fillRect(0, insets.top, insets.left, height - insets.top); g.fillRect(insets.left, height - insets.bottom, width - insets.left, insets.bottom); g.fillRect(width - insets.right, 0, insets.right, height - insets.bottom); } else if (tileIcon != null) { int tileW = tileIcon.getIconWidth(); int tileH = tileIcon.getIconHeight(); paintEdge(c, g, 0, 0, width - insets.right, insets.top, tileW, tileH); paintEdge(c, g, 0, insets.top, insets.left, height - insets.top, tileW, tileH); paintEdge(c, g, insets.left, height - insets.bottom, width - insets.left, insets.bottom, tileW, tileH); paintEdge(c, g, width - insets.right, 0, insets.right, height - insets.bottom, tileW, tileH); } g.translate(-x, -y); g.setColor(oldColor); } private void paintEdge(Component c, Graphics g, int x, int y, int width, int height, int tileW, int tileH) { g = g.create(x, y, width, height); int sY = -(y % tileH); for (x = -(x % tileW); x < width; x += tileW) { for (y = sY; y < height; y += tileH) { this.tileIcon.paintIcon(c, g, x, y); } } g.dispose(); } /** * Reinitialize the insets parameter with this Border's current Insets. * @param c the component for which this border insets value applies * @param insets the object to be reinitialized * @since 1.3 */ public Insets getBorderInsets(Component c, Insets insets) { return computeInsets(insets); } /** * Returns the insets of the border. * @since 1.3 */ public Insets getBorderInsets() { return computeInsets(new Insets(0,0,0,0)); } /* should be protected once api changes area allowed */ private Insets computeInsets(Insets insets) { if (tileIcon != null && top == -1 && bottom == -1 && left == -1 && right == -1) { int w = tileIcon.getIconWidth(); int h = tileIcon.getIconHeight(); insets.top = h; insets.right = w; insets.bottom = h; insets.left = w; } else { insets.left = left; insets.top = top; insets.right = right; insets.bottom = bottom; } return insets; } /** * Returns the color used for tiling the border or null * if a tile icon is being used. * @since 1.3 */ public Color getMatteColor() { return color; } /** * Returns the icon used for tiling the border or null * if a solid color is being used. * @since 1.3 */ public Icon getTileIcon() { return tileIcon; } /** * Returns whether or not the border is opaque. */ public boolean isBorderOpaque() { // If a tileIcon is set, then it may contain transparent bits return color != null; } }
/* * Copyright (C) 2008 ZXing 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 com.google.zxing.web.generator.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLTable; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import java.util.ArrayList; import java.util.List; public final class Generator implements EntryPoint { private final List<GeneratorSource> generators = new ArrayList<GeneratorSource>(); private final ListBox genList = new ListBox(); private final ListBox sizeList = new ListBox(); private final ListBox ecLevelList = new ListBox(); private final ListBox encodingList = new ListBox(); private final Image result = new Image(""); private final HTMLTable topPanel = new Grid(5, 1); private GeneratorSource selectedGenerator = null; private final VerticalPanel rightPanel = new VerticalPanel(); private final TextBox urlResult = new TextBox(); private final Widget downloadText = new HTML("<a href=\"\" id=\"downloadlink\" >Download</a> or embed with this URL:"); private final TextArea rawTextResult = new TextArea(); @Override public void onModuleLoad() { loadGenerators(); HorizontalPanel mainPanel = new HorizontalPanel(); setupLeftPanel(); topPanel.getElement().setId("leftpanel"); Widget leftPanel = topPanel; mainPanel.add(leftPanel); SimplePanel div = new SimplePanel(); SimplePanel div2 = new SimplePanel(); div2.add(result); div2.getElement().setId("innerresult"); div.add(div2); div.getElement().setId("imageresult"); urlResult.getElement().setId("urlresult"); rawTextResult.getElement().setId("rawtextresult"); rawTextResult.setCharacterWidth(50); rawTextResult.setVisibleLines(8); downloadText.getElement().setId("downloadText"); rightPanel.add(div); rightPanel.add(downloadText); rightPanel.add(urlResult); rightPanel.add(rawTextResult); mainPanel.add(rightPanel); mainPanel.getElement().setId("mainpanel"); RootPanel.get("ui").add(mainPanel); setWidget(1); invalidateBarcode(); } private void setWidget(int id) { if (id >= 0 && id < generators.size()) { topPanel.setWidget(1, 0, generators.get(id).getWidget()); genList.setSelectedIndex(id); selectedGenerator = generators.get(id); eraseErrorMessage(); invalidateBarcode(); genList.setFocus(false); selectedGenerator.setFocus(); } } private void loadGenerators() { generators.add(new CalendarEventGenerator(changeHandler, keyPressHandler)); generators.add(new ContactInfoGenerator(changeHandler, keyPressHandler)); generators.add(new EmailGenerator(changeHandler, keyPressHandler)); generators.add(new GeoLocationGenerator(changeHandler, keyPressHandler)); generators.add(new PhoneNumberGenerator(changeHandler, keyPressHandler)); generators.add(new SmsAddressGenerator(changeHandler, keyPressHandler)); generators.add(new TextGenerator(changeHandler)); generators.add(new UrlGenerator(changeHandler, keyPressHandler)); generators.add(new WifiGenerator(changeHandler, keyPressHandler)); } void setupLeftPanel() { topPanel.setHTML(2, 0, "<span id=\"errorMessageID\" class=\""+StylesDefs.ERROR_MESSAGE+"\"></span>"); // fills up the list of generators for(GeneratorSource generator: generators) { genList.addItem(generator.getName()); setGridStyle(generator.getWidget()); } sizeList.addItem("Small", "120"); sizeList.addItem("Medium", "230"); sizeList.addItem("Large", "350"); sizeList.setSelectedIndex(2); ecLevelList.addItem("L"); ecLevelList.addItem("M"); ecLevelList.addItem("Q"); ecLevelList.addItem("H"); ecLevelList.setSelectedIndex(0); encodingList.addItem("UTF-8"); encodingList.addItem("ISO-8859-1"); encodingList.addItem("Shift_JIS"); encodingList.setSelectedIndex(0); // updates the second row of the table with the content of the selected generator genList.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent Event) { int i = genList.getSelectedIndex(); setWidget(i); } }); // grid for the generator picker HTMLTable selectionTable = new Grid(1, 2); selectionTable.setText(0, 0, "Contents"); selectionTable.setWidget(0, 1, genList); setGridStyle(selectionTable); topPanel.setWidget(0, 0, selectionTable); // grid for the generate button HTMLTable generateGrid = new Grid(1, 2); setGridStyle(generateGrid); Button generateButton = new Button("Generate &rarr;"); generateButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { generate(); } }); generateGrid.setWidget(0, 1, generateButton); topPanel.setWidget(4, 0, generateGrid); HTMLTable configTable = new Grid(3, 2); configTable.setText(0, 0, "Barcode size"); configTable.setWidget(0, 1, sizeList); configTable.setText(1, 0, "Error correction"); configTable.setWidget(1, 1, ecLevelList); configTable.setText(2, 0, "Character encoding"); configTable.setWidget(2, 1, encodingList); setGridStyle(configTable); topPanel.setWidget(3, 0, configTable); } private static void setGridStyle(HTMLTable grid) { grid.getColumnFormatter().addStyleName(0, "firstColumn"); grid.getColumnFormatter().addStyleName(1, "secondColumn"); HTMLTable.CellFormatter cellFormatter = grid.getCellFormatter(); for (int i = 0; i < grid.getRowCount(); ++i) { cellFormatter.addStyleName(i, 0, "firstColumn"); cellFormatter.addStyleName(i, 1, "secondColumn"); } } private static String getUrl(int sizeX, int sizeY, String ecLevel, String encoding, String content) { StringBuilder result = new StringBuilder(100); result.append("http://chart.apis.google.com/chart?cht=qr"); result.append("&chs=").append(sizeX).append('x').append(sizeY); result.append("&chld=").append(ecLevel); result.append("&choe=").append(encoding); result.append("&chl=").append(URL.encodeQueryString(content)); return result.toString(); } private void generate() { try { String text = selectedGenerator.getText(); eraseErrorMessage(); int size = Integer.parseInt(sizeList.getValue(sizeList.getSelectedIndex())); String ecLevel = ecLevelList.getValue(ecLevelList.getSelectedIndex()); String encoding = encodingList.getValue(encodingList.getSelectedIndex()); String url = getUrl(size, size, ecLevel, encoding, text); result.setUrl(url); result.setVisible(true); urlResult.setText(url); urlResult.setVisible(true); rawTextResult.setText(text); rawTextResult.setVisible(true); Element linkElement = DOM.getElementById("downloadlink"); linkElement.setAttribute("href", url); downloadText.setVisible(true); } catch (GeneratorException ex) { invalidateBarcode(); String error = ex.getMessage(); showErrorMessage(error); } } void invalidateBarcode() { result.setVisible(false); urlResult.setText(""); urlResult.setVisible(false); rawTextResult.setText(""); rawTextResult.setVisible(false); Element linkElement = DOM.getElementById("downloadlink"); linkElement.setAttribute("href", ""); downloadText.setVisible(false); } private static void showErrorMessage(String error) { Element errorElement = DOM.getElementById("errorMessageID"); errorElement.setInnerHTML(error); } private static void eraseErrorMessage() { Element errorElement = DOM.getElementById("errorMessageID"); errorElement.setInnerHTML("&nbsp;"); } private final ChangeHandler changeHandler = new ChangeHandler() { @Override public void onChange(ChangeEvent event) { try { selectedGenerator.validate((Widget) event.getSource()); eraseErrorMessage(); } catch (GeneratorException ex) { String error = ex.getMessage(); showErrorMessage(error); invalidateBarcode(); } } }; private final KeyPressHandler keyPressHandler = new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == '\n' || event.getCharCode() == '\r') { generate(); } } }; }
/* * Copyright 2016 Netbrasoft * * 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 br.com.netbrasoft.gnuob.generic.security; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.google.common.collect.Lists; import br.com.netbrasoft.gnuob.exception.GNUOpenBusinessServiceException; import br.com.netbrasoft.gnuob.generic.contract.Contract; import br.com.netbrasoft.gnuob.generic.customer.Address; import br.com.netbrasoft.gnuob.generic.customer.Customer; import br.com.netbrasoft.gnuob.generic.order.IPagseguroCheckOutService; import br.com.netbrasoft.gnuob.generic.order.Invoice; import br.com.netbrasoft.gnuob.generic.order.Order; import br.com.netbrasoft.gnuob.generic.order.OrderRecord; import br.com.netbrasoft.gnuob.generic.order.Payment; import br.com.netbrasoft.gnuob.generic.order.Shipment; import br.com.netbrasoft.gnuob.generic.security.ISecuredGenericTypeCheckOutService; import br.com.netbrasoft.gnuob.generic.security.MetaData; import br.com.netbrasoft.gnuob.generic.security.SecuredPagseguroCheckOutServiceImpl; import br.com.netbrasoft.gnuob.generic.security.Site; import br.com.uol.pagseguro.domain.Item; import br.com.uol.pagseguro.domain.PaymentMethod; import br.com.uol.pagseguro.domain.Phone; import br.com.uol.pagseguro.domain.Sender; import br.com.uol.pagseguro.domain.Shipping; import br.com.uol.pagseguro.domain.Transaction; import br.com.uol.pagseguro.enums.PaymentMethodType; import br.com.uol.pagseguro.enums.ShippingType; import br.com.uol.pagseguro.enums.TransactionStatus; import br.com.uol.pagseguro.enums.TransactionType; import br.com.uol.pagseguro.exception.PagSeguroServiceException; public class SecuredPagseguroCheckOutServiceImplTest { private MetaData mockCredentials; private IPagseguroCheckOutService mockPagseguroCheckOutService; private ISecuredGenericTypeCheckOutService<Order> securedGenericTypeCheckOutService = new SecuredPagseguroCheckOutServiceImpl<>(); private Order spyOrder; private OrderRecord spyOrderRecord; private Transaction mockTransaction; private Sender mockSender; private Shipping mockShipping; private br.com.uol.pagseguro.domain.Address mockAddress; private Item mockItem; private PaymentMethod mockPaymentMethod; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() throws Exception { Locale.setDefault(new Locale("pt", "BR")); mockCredentials = mock(MetaData.class); mockPagseguroCheckOutService = mock(IPagseguroCheckOutService.class); securedGenericTypeCheckOutService = new SecuredPagseguroCheckOutServiceImpl<>(mockPagseguroCheckOutService); spyOrderRecord = spy(OrderRecord.class); spyOrder = spy(Order.class); spyOrder.setContract(spy(Contract.class)); spyOrder.getContract().setCustomer(spy(Customer.class)); spyOrder.setShipment(spy(Shipment.class)); spyOrder.getShipment().setAddress(spy(Address.class)); spyOrder.getRecords().add(spyOrderRecord); spyOrder.setSite(spy(Site.class)); spyOrder.setInvoice(spy(Invoice.class)); mockTransaction = mock(Transaction.class); mockSender = mock(Sender.class); mockShipping = mock(Shipping.class); mockAddress = mock(br.com.uol.pagseguro.domain.Address.class); mockItem = mock(Item.class); mockPaymentMethod = mock(PaymentMethod.class); } @After public void tearDown() throws Exception { Locale.setDefault(Locale.US); } @Test public void testDoCheckoutSucessfully() throws PagSeguroServiceException { spyOrder.setExtraAmount(BigDecimal.valueOf(100.00)); spyOrder.setOrderId("ORDER ID"); spyOrder.setShippingTotal(BigDecimal.valueOf(100.00)); spyOrder.setShippingDiscount(BigDecimal.ZERO); spyOrder.getShipment().setShipmentType("PAC"); spyOrder.getShipment().getAddress().setCityName("CITY NAME"); spyOrder.getShipment().getAddress().setStreet1("STREET 1"); spyOrder.getShipment().getAddress().setComplement("COMPLEMENT"); spyOrder.getShipment().getAddress().setCountry("BR"); spyOrder.getShipment().getAddress().setDistrict("DISTRICT"); spyOrder.getShipment().getAddress().setNumber("NUMBER"); spyOrder.getShipment().getAddress().setPostalCode("POSTAL CODE"); spyOrder.getShipment().getAddress().setStateOrProvince("STATE OR PROVINCE"); spyOrderRecord.setAmount(BigDecimal.valueOf(100.00)); spyOrderRecord.setDescription("DESCRIPTION"); spyOrderRecord.setOrderRecordId("NUMBER"); spyOrderRecord.setQuantity(BigInteger.valueOf(100)); spyOrderRecord.setShippingCost(BigDecimal.valueOf(10.00)); spyOrderRecord.setItemWeight(BigDecimal.valueOf(1.00)); spyOrder.getContract().getCustomer().setBuyerEmail("BUYER EMAIL"); spyOrder.getContract().getCustomer().setFriendlyName("FRIENDLY NAME"); when(mockPagseguroCheckOutService.createCheckoutRequest(any(), anyBoolean())).thenReturn("code=1234567890"); securedGenericTypeCheckOutService.doCheckout(mockCredentials, spyOrder); assertEquals("1234567890", spyOrder.getToken()); verify(mockPagseguroCheckOutService).createCheckoutRequest(any(), anyBoolean()); } @Test public void testDoCheckoutUnSucessfully() throws PagSeguroServiceException { expectedException.expect(GNUOpenBusinessServiceException.class); expectedException.expectMessage("Exception from Pagseguro Checkout, please try again."); spyOrder.setExtraAmount(BigDecimal.valueOf(100.00)); spyOrder.setOrderId("ORDER ID"); spyOrder.setShippingTotal(BigDecimal.valueOf(100.00)); spyOrder.setShippingDiscount(BigDecimal.ZERO); spyOrder.getShipment().setShipmentType("PAC"); spyOrder.getShipment().getAddress().setCityName("CITY NAME"); spyOrder.getShipment().getAddress().setStreet1("STREET 1"); spyOrder.getShipment().getAddress().setComplement("COMPLEMENT"); spyOrder.getShipment().getAddress().setCountry("BR"); spyOrder.getShipment().getAddress().setDistrict("DISTRICT"); spyOrder.getShipment().getAddress().setNumber("NUMBER"); spyOrder.getShipment().getAddress().setPostalCode("POSTAL CODE"); spyOrder.getShipment().getAddress().setStateOrProvince("STATE OR PROVINCE"); spyOrderRecord.setAmount(BigDecimal.valueOf(100.00)); spyOrderRecord.setDescription("DESCRIPTION"); spyOrderRecord.setOrderRecordId("NUMBER"); spyOrderRecord.setQuantity(BigInteger.valueOf(100)); spyOrderRecord.setShippingCost(BigDecimal.valueOf(10.00)); spyOrderRecord.setItemWeight(BigDecimal.valueOf(1.00)); spyOrder.getContract().getCustomer().setBuyerEmail("BUYER EMAIL"); spyOrder.getContract().getCustomer().setFriendlyName("FRIENDLY NAME"); when(mockPagseguroCheckOutService.createCheckoutRequest(any(), anyBoolean())) .thenThrow(new PagSeguroServiceException(StringUtils.EMPTY)); securedGenericTypeCheckOutService.doCheckout(mockCredentials, spyOrder); } @Test public void testDoCheckoutDetailsSucessfully() throws PagSeguroServiceException { spyOrderRecord.setOrderRecordId("NUMBER"); when(mockPagseguroCheckOutService.searchByCode(anyString())).thenReturn(mockTransaction); when(mockTransaction.getSender()).thenReturn(mockSender); when(mockSender.getEmail()).thenReturn("PAYER"); when(mockSender.getName()).thenReturn("FRIENDLY NAME"); when(mockSender.getPhone()).thenReturn(mock(Phone.class)); when(mockTransaction.getCode()).thenReturn("TRANSACTION ID"); when(mockTransaction.getReference()).thenReturn("ORDER ID"); when(mockTransaction.getDiscountAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getExtraAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getShipping()).thenReturn(mockShipping); when(mockShipping.getCost()).thenReturn(BigDecimal.valueOf(100.00)); when(mockShipping.getType()).thenReturn(ShippingType.PAC); when(mockShipping.getAddress()).thenReturn(mockAddress); when(mockAddress.getCountry()).thenReturn("BR"); when(mockAddress.getState()).thenReturn("STATE OR PROVINCE"); when(mockAddress.getCity()).thenReturn("CITY NAME"); when(mockAddress.getPostalCode()).thenReturn("POSTAL CODE"); when(mockAddress.getDistrict()).thenReturn("DISTRICT"); when(mockAddress.getStreet()).thenReturn("STREET 1"); when(mockAddress.getNumber()).thenReturn("NUMBER"); when(mockAddress.getComplement()).thenReturn("COMPLEMENT"); when(mockItem.getId()).thenReturn("NUMBER"); when(mockItem.getDescription()).thenReturn("DESCRIPTION"); when(mockItem.getAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockItem.getQuantity()).thenReturn(100); when(mockTransaction.getItems()).thenReturn(Lists.newArrayList(mockItem)); when(mockTransaction.getStatus()).thenReturn(TransactionStatus.PAID); securedGenericTypeCheckOutService.doCheckoutDetails(mockCredentials, spyOrder); assertEquals("Payer", "PAYER", spyOrder.getContract().getCustomer().getPayer()); assertEquals("FriendlyName", "FRIENDLY NAME", spyOrder.getContract().getCustomer().getFriendlyName()); assertEquals("TransactionId", "TRANSACTION ID", spyOrder.getTransactionId()); assertEquals("OrderId", "ORDER ID", spyOrder.getOrderId()); assertEquals("DiscountTotal", 0, BigDecimal.valueOf(100.00).compareTo(spyOrder.getDiscountTotal())); assertEquals("ExtraAmount", 0, BigDecimal.valueOf(100.00).compareTo(spyOrder.getExtraAmount())); assertEquals("ShippingTotal", 0, BigDecimal.valueOf(100.00).compareTo(spyOrder.getShippingTotal())); assertEquals("ShipmentType", "PAC", spyOrder.getShipment().getShipmentType()); assertEquals("Country", "BR", spyOrder.getShipment().getAddress().getCountry()); assertEquals("StateOrProvince", "STATE OR PROVINCE", spyOrder.getShipment().getAddress().getStateOrProvince()); assertEquals("CityName", "CITY NAME", spyOrder.getShipment().getAddress().getCityName()); assertEquals("PostalCode", "POSTAL CODE", spyOrder.getShipment().getAddress().getPostalCode()); assertEquals("District", "DISTRICT", spyOrder.getShipment().getAddress().getDistrict()); assertEquals("Street1", "STREET 1", spyOrder.getShipment().getAddress().getStreet1()); assertEquals("Number", "NUMBER", spyOrder.getShipment().getAddress().getNumber()); assertEquals("Complement", "COMPLEMENT", spyOrder.getShipment().getAddress().getComplement()); assertEquals("OrderRecordId", "NUMBER", spyOrderRecord.getOrderRecordId()); assertEquals("Description", "DESCRIPTION", spyOrderRecord.getDescription()); assertEquals("Amount", 0, BigDecimal.valueOf(100.00).compareTo(spyOrderRecord.getAmount())); assertEquals("Quantity", 0, BigInteger.valueOf(100).compareTo(spyOrderRecord.getQuantity())); assertEquals("CheckoutStatus", "PAID", spyOrder.getCheckoutStatus()); verify(mockPagseguroCheckOutService).searchByCode(anyString()); } @Test public void testDoCheckoutDetailsUnSucessfully() throws PagSeguroServiceException { expectedException.expect(GNUOpenBusinessServiceException.class); expectedException.expectMessage("Exception from Pagseguro Checkout, please try again."); when(mockPagseguroCheckOutService.searchByCode(anyString())) .thenThrow(new PagSeguroServiceException(StringUtils.EMPTY)); securedGenericTypeCheckOutService.doCheckoutDetails(mockCredentials, spyOrder); } @Test public void testDoCheckoutPaymentSucessfully() throws PagSeguroServiceException { when(mockPagseguroCheckOutService.searchByCode(anyString())).thenReturn(mockTransaction); when(mockTransaction.getCode()).thenReturn("TRANSACTION ID"); when(mockTransaction.getType()).thenReturn(TransactionType.PAYMENT); when(mockPaymentMethod.getType()).thenReturn(PaymentMethodType.CREDIT_CARD); when(mockTransaction.getPaymentMethod()).thenReturn(mockPaymentMethod); when(mockTransaction.getGrossAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getNetAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getEscrowEndDate()).thenReturn(new Date()); when(mockTransaction.getCancellationSource()).thenReturn("HOLD DECISION"); when(mockTransaction.getInstallmentCount()).thenReturn(100); when(mockTransaction.getFeeAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getStatus()).thenReturn(TransactionStatus.PAID); securedGenericTypeCheckOutService.doCheckoutPayment(mockCredentials, spyOrder); final Payment payment = spyOrder.getInvoice().getPayments().iterator().next(); assertEquals("TransactionId", "TRANSACTION ID", payment.getTransactionId()); assertEquals("TransactionType", "PAYMENT", payment.getTransactionType()); assertEquals("PaymentType", "CREDIT CARD", payment.getPaymentType()); assertEquals("GrossAmount", 0, BigDecimal.valueOf(100.00).compareTo(payment.getGrossAmount())); assertEquals("SettleAmount", 0, BigDecimal.valueOf(100.00).compareTo(payment.getSettleAmount())); assertEquals("HoldDecision", "HOLD DECISION", payment.getHoldDecision()); assertEquals("InstallmentCount", 0, BigInteger.valueOf(100).compareTo(payment.getInstallmentCount())); assertEquals("FeeAmount", 0, BigDecimal.valueOf(100.00).compareTo(payment.getFeeAmount())); assertEquals("PaymentStatus", "PAID", payment.getPaymentStatus()); assertEquals("CheckoutStatus", "PAID", spyOrder.getCheckoutStatus()); verify(mockPagseguroCheckOutService).searchByCode(anyString()); } @Test public void testDoCheckoutPaymentUnSucessfully() throws PagSeguroServiceException { expectedException.expect(GNUOpenBusinessServiceException.class); expectedException.expectMessage("Exception from Pagseguro Checkout, please try again."); when(mockPagseguroCheckOutService.searchByCode(anyString())) .thenThrow(new PagSeguroServiceException(StringUtils.EMPTY)); securedGenericTypeCheckOutService.doCheckoutPayment(mockCredentials, spyOrder); } @Test public void testDoNotificationSucessfully() throws PagSeguroServiceException { when(mockPagseguroCheckOutService.checkTransaction(anyString())).thenReturn(mockTransaction); when(mockTransaction.getCode()).thenReturn("TRANSACTION ID"); when(mockTransaction.getReference()).thenReturn("ORDER ID"); securedGenericTypeCheckOutService.doNotification(mockCredentials, spyOrder); assertEquals("TransactionId", "TRANSACTION ID", spyOrder.getTransactionId()); assertEquals("OrderId", "ORDER ID", spyOrder.getOrderId()); assertNull("NotificationId", spyOrder.getNotificationId()); verify(mockPagseguroCheckOutService).checkTransaction(anyString()); } @Test public void testDoNotificationUnSucessfully() throws PagSeguroServiceException { expectedException.expect(GNUOpenBusinessServiceException.class); expectedException.expectMessage("Exception from Pagseguro Notification, please try again."); when(mockPagseguroCheckOutService.checkTransaction(anyString())) .thenThrow(new PagSeguroServiceException(StringUtils.EMPTY)); securedGenericTypeCheckOutService.doNotification(mockCredentials, spyOrder); } @Test public void testDoRefundTransaction() { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Refund transaction is not supported for PagSeguro."); securedGenericTypeCheckOutService.doRefundTransaction(mockCredentials, spyOrder); } @Test public void testDoTransactionDetailsSucessfully() throws PagSeguroServiceException { spyOrderRecord.setOrderRecordId("NUMBER"); when(mockPagseguroCheckOutService.searchByCode(anyString())).thenReturn(mockTransaction); when(mockTransaction.getSender()).thenReturn(mockSender); when(mockSender.getEmail()).thenReturn("PAYER"); when(mockSender.getName()).thenReturn("FRIENDLY NAME"); when(mockSender.getPhone()).thenReturn(mock(Phone.class)); when(mockTransaction.getCode()).thenReturn("TRANSACTION ID"); when(mockTransaction.getReference()).thenReturn("ORDER ID"); when(mockTransaction.getDiscountAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getExtraAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getShipping()).thenReturn(mockShipping); when(mockShipping.getCost()).thenReturn(BigDecimal.valueOf(100.00)); when(mockShipping.getType()).thenReturn(ShippingType.PAC); when(mockShipping.getAddress()).thenReturn(mockAddress); when(mockAddress.getCountry()).thenReturn("BR"); when(mockAddress.getState()).thenReturn("STATE OR PROVINCE"); when(mockAddress.getCity()).thenReturn("CITY NAME"); when(mockAddress.getPostalCode()).thenReturn("POSTAL CODE"); when(mockAddress.getDistrict()).thenReturn("DISTRICT"); when(mockAddress.getStreet()).thenReturn("STREET 1"); when(mockAddress.getNumber()).thenReturn("NUMBER"); when(mockAddress.getComplement()).thenReturn("COMPLEMENT"); when(mockItem.getId()).thenReturn("NUMBER"); when(mockItem.getDescription()).thenReturn("DESCRIPTION"); when(mockItem.getAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockItem.getQuantity()).thenReturn(100); when(mockTransaction.getItems()).thenReturn(Lists.newArrayList(mockItem)); when(mockTransaction.getStatus()).thenReturn(TransactionStatus.PAID); when(mockTransaction.getType()).thenReturn(TransactionType.PAYMENT); when(mockPaymentMethod.getType()).thenReturn(PaymentMethodType.CREDIT_CARD); when(mockTransaction.getPaymentMethod()).thenReturn(mockPaymentMethod); when(mockTransaction.getGrossAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getNetAmount()).thenReturn(BigDecimal.valueOf(100.00)); when(mockTransaction.getEscrowEndDate()).thenReturn(new Date()); when(mockTransaction.getCancellationSource()).thenReturn("HOLD DECISION"); when(mockTransaction.getInstallmentCount()).thenReturn(100); when(mockTransaction.getFeeAmount()).thenReturn(BigDecimal.valueOf(100.00)); securedGenericTypeCheckOutService.doTransactionDetails(mockCredentials, spyOrder); assertEquals("Payer", "PAYER", spyOrder.getContract().getCustomer().getPayer()); assertEquals("FriendlyName", "FRIENDLY NAME", spyOrder.getContract().getCustomer().getFriendlyName()); assertEquals("TransactionId", "TRANSACTION ID", spyOrder.getTransactionId()); assertEquals("OrderId", "ORDER ID", spyOrder.getOrderId()); assertEquals("DiscountTotal", 0, BigDecimal.valueOf(100.00).compareTo(spyOrder.getDiscountTotal())); assertEquals("ExtraAmount", 0, BigDecimal.valueOf(100.00).compareTo(spyOrder.getExtraAmount())); assertEquals("ShippingTotal", 0, BigDecimal.valueOf(100.00).compareTo(spyOrder.getShippingTotal())); assertEquals("ShipmentType", "PAC", spyOrder.getShipment().getShipmentType()); assertEquals("Country", "BR", spyOrder.getShipment().getAddress().getCountry()); assertEquals("StateOrProvince", "STATE OR PROVINCE", spyOrder.getShipment().getAddress().getStateOrProvince()); assertEquals("CityName", "CITY NAME", spyOrder.getShipment().getAddress().getCityName()); assertEquals("PostalCode", "POSTAL CODE", spyOrder.getShipment().getAddress().getPostalCode()); assertEquals("District", "DISTRICT", spyOrder.getShipment().getAddress().getDistrict()); assertEquals("Street1", "STREET 1", spyOrder.getShipment().getAddress().getStreet1()); assertEquals("Number", "NUMBER", spyOrder.getShipment().getAddress().getNumber()); assertEquals("Complement", "COMPLEMENT", spyOrder.getShipment().getAddress().getComplement()); assertEquals("OrderRecordId", "NUMBER", spyOrderRecord.getOrderRecordId()); assertEquals("Description", "DESCRIPTION", spyOrderRecord.getDescription()); assertEquals("Amount", 0, BigDecimal.valueOf(100.00).compareTo(spyOrderRecord.getAmount())); assertEquals("Quantity", 0, BigInteger.valueOf(100).compareTo(spyOrderRecord.getQuantity())); final Payment payment = spyOrder.getInvoice().getPayments().iterator().next(); assertEquals("TransactionId", "TRANSACTION ID", payment.getTransactionId()); assertEquals("TransactionType", "PAYMENT", payment.getTransactionType()); assertEquals("PaymentType", "CREDIT CARD", payment.getPaymentType()); assertEquals("GrossAmount", 0, BigDecimal.valueOf(100.00).compareTo(payment.getGrossAmount())); assertEquals("SettleAmount", 0, BigDecimal.valueOf(100.00).compareTo(payment.getSettleAmount())); assertEquals("HoldDecision", "HOLD DECISION", payment.getHoldDecision()); assertEquals("InstallmentCount", 0, BigInteger.valueOf(100).compareTo(payment.getInstallmentCount())); assertEquals("FeeAmount", 0, BigDecimal.valueOf(100.00).compareTo(payment.getFeeAmount())); assertEquals("PaymentStatus", "PAID", payment.getPaymentStatus()); assertEquals("CheckoutStatus", "PAID", spyOrder.getCheckoutStatus()); verify(mockPagseguroCheckOutService).searchByCode(anyString()); } @Test public void testDoTransactionDetailsUnSucessfully() throws PagSeguroServiceException { expectedException.expect(GNUOpenBusinessServiceException.class); expectedException.expectMessage("Exception from Pagseguro Transaction Details, please try again."); when(mockPagseguroCheckOutService.searchByCode(anyString())) .thenThrow(new PagSeguroServiceException(StringUtils.EMPTY)); securedGenericTypeCheckOutService.doTransactionDetails(mockCredentials, spyOrder); } }
/* * 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.sysml.lops; import org.apache.sysml.lops.LopProperties.ExecLocation; import org.apache.sysml.lops.LopProperties.ExecType; import org.apache.sysml.lops.compile.JobType; import org.apache.sysml.parser.Expression.DataType; import org.apache.sysml.parser.Expression.ValueType; /** * Lop to perform following operations: with one operand -- NOT(A), ABS(A), * SQRT(A), LOG(A) with two operands where one of them is a scalar -- H=H*i, * H=H*5, EXP(A,2), LOG(A,2) * */ public class Unary extends Lop { public enum OperationTypes { ADD, SUBTRACT, SUBTRACTRIGHT, MULTIPLY, MULTIPLY2, DIVIDE, MODULUS, INTDIV, MINUS1_MULTIPLY, POW, POW2, LOG, MAX, MIN, NOT, ABS, SIN, COS, TAN, ASIN, ACOS, ATAN, SINH, COSH, TANH, SIGN, SQRT, EXP, Over, LESS_THAN, LESS_THAN_OR_EQUALS, GREATER_THAN, GREATER_THAN_OR_EQUALS, EQUALS, NOT_EQUALS, AND, OR, XOR, BW_AND, BW_OR, BW_XOR, BW_SHIFTL, BW_SHIFTR, ROUND, CEIL, FLOOR, MR_IQM, INVERSE, CHOLESKY, CUMSUM, CUMPROD, CUMMIN, CUMMAX, SPROP, SIGMOID, SUBTRACT_NZ, LOG_NZ, CAST_AS_MATRIX, CAST_AS_FRAME, NOTSUPPORTED } private OperationTypes operation; private Lop valInput; //cp-specific parameters private int _numThreads = 1; /** * Constructor to perform a unary operation with 2 inputs * * @param input1 low-level operator 1 * @param input2 low-level operator 2 * @param op operation type * @param dt data type * @param vt value type * @param et execution type */ public Unary(Lop input1, Lop input2, OperationTypes op, DataType dt, ValueType vt, ExecType et) { super(Lop.Type.UNARY, dt, vt); init(input1, input2, op, dt, vt, et); } private void init(Lop input1, Lop input2, OperationTypes op, DataType dt, ValueType vt, ExecType et) { operation = op; if (input1.getDataType() == DataType.MATRIX) valInput = input2; else valInput = input1; this.addInput(input1); input1.addOutput(this); this.addInput(input2); input2.addOutput(this); // By definition, this lop should not break alignment boolean breaksAlignment = false; boolean aligner = false; boolean definesMRJob = false; if ( et == ExecType.MR ) { /* * This lop CAN NOT be executed in PARTITION, SORT, CM_COV, and COMBINE * jobs MMCJ: only in mapper. */ lps.addCompatibility(JobType.ANY); lps.removeNonPiggybackableJobs(); lps.removeCompatibility(JobType.CM_COV); // CM_COV allows only reducer instructions but this is MapOrReduce. TODO: piggybacking should be updated to take this extra constraint. lps.setProperties(inputs, et, ExecLocation.MapOrReduce, breaksAlignment, aligner, definesMRJob); } else { lps.addCompatibility(JobType.INVALID); lps.setProperties(inputs, et, ExecLocation.ControlProgram, breaksAlignment, aligner, definesMRJob); } } /** * Constructor to perform a unary operation with 1 input. * * @param input1 low-level operator 1 * @param op operation type * @param dt data type * @param vt value type * @param et execution type * @param numThreads number of threads */ public Unary(Lop input1, OperationTypes op, DataType dt, ValueType vt, ExecType et, int numThreads) { super(Lop.Type.UNARY, dt, vt); init(input1, op, dt, vt, et); _numThreads = numThreads; } private void init(Lop input1, OperationTypes op, DataType dt, ValueType vt, ExecType et) { //sanity check if ( (op == OperationTypes.INVERSE || op == OperationTypes.CHOLESKY) && (et == ExecType.SPARK || et == ExecType.MR) ) { throw new LopsException("Invalid exection type "+et.toString()+" for operation "+op.toString()); } operation = op; valInput = null; this.addInput(input1); input1.addOutput(this); boolean breaksAlignment = false; boolean aligner = false; boolean definesMRJob = false; if ( et == ExecType.MR ) { /* * This lop can be executed in all jobs except for PARTITION. MMCJ: only * in mapper. GroupedAgg: only in reducer. */ lps.addCompatibility(JobType.ANY); lps.removeNonPiggybackableJobs(); lps.removeCompatibility(JobType.CM_COV); // CM_COV allows only reducer instructions but this is MapOrReduce. TODO: piggybacking should be updated to take this extra constraint. lps.setProperties(inputs, et, ExecLocation.MapOrReduce, breaksAlignment, aligner, definesMRJob); } else { lps.addCompatibility(JobType.INVALID); lps.setProperties(inputs, et, ExecLocation.ControlProgram, breaksAlignment, aligner, definesMRJob); } } @Override public String toString() { if (valInput != null) return "Operation: " + operation + " " + "Label: " + valInput.getOutputParameters().getLabel() + " input types " + this.getInputs().get(0).toString() + " " + this.getInputs().get(1).toString(); else return "Operation: " + operation + " " + "Label: N/A"; } private String getOpcode() { return getOpcode(operation); } public static String getOpcode(OperationTypes op) { switch (op) { case NOT: return "!"; case ABS: return "abs"; case SIN: return "sin"; case COS: return "cos"; case TAN: return "tan"; case ASIN: return "asin"; case ACOS: return "acos"; case ATAN: return "atan"; case SINH: return "sinh"; case COSH: return "cosh"; case TANH: return "tanh"; case SIGN: return "sign"; case SQRT: return "sqrt"; case EXP: return "exp"; case LOG: return "log"; case LOG_NZ: return "log_nz"; case ROUND: return "round"; case ADD: return "+"; case SUBTRACT: return "-"; case SUBTRACT_NZ: return "-nz"; case SUBTRACTRIGHT: return "s-r"; case MULTIPLY: return "*"; case MULTIPLY2: return "*2"; case MINUS1_MULTIPLY: return "1-*"; case DIVIDE: return "/"; case MODULUS: return "%%"; case INTDIV: return "%/%"; case Over: return "so"; case POW: return "^"; case POW2: return "^2"; case GREATER_THAN: return ">"; case GREATER_THAN_OR_EQUALS: return ">="; case LESS_THAN: return "<"; case LESS_THAN_OR_EQUALS: return "<="; case EQUALS: return "=="; case NOT_EQUALS: return "!="; case MAX: return "max"; case MIN: return "min"; case CEIL: return "ceil"; case FLOOR: return "floor"; case CUMSUM: return "ucumk+"; case CUMPROD: return "ucum*"; case CUMMIN: return "ucummin"; case CUMMAX: return "ucummax"; case INVERSE: return "inverse"; case CHOLESKY: return "cholesky"; case MR_IQM: return "qpick"; case SPROP: return "sprop"; case SIGMOID: return "sigmoid"; case CAST_AS_MATRIX: return UnaryCP.CAST_AS_MATRIX_OPCODE; case CAST_AS_FRAME: return UnaryCP.CAST_AS_FRAME_OPCODE; case AND: return "&&"; case OR: return "||"; case XOR: return "xor"; case BW_AND: return "bitwAnd"; case BW_OR: return "bitwOr"; case BW_XOR: return "bitwXor"; case BW_SHIFTL: return "bitwShiftL"; case BW_SHIFTR: return "bitwShiftR"; default: throw new LopsException( "Instruction not defined for Unary operation: " + op); } } public static boolean isMultiThreadedOp(OperationTypes op) { return op==OperationTypes.CUMSUM || op==OperationTypes.CUMPROD || op==OperationTypes.CUMMIN || op==OperationTypes.CUMMAX || op==OperationTypes.EXP || op==OperationTypes.LOG || op==OperationTypes.SIGMOID; } @Override public String getInstructions(String input1, String output) { //sanity check number of operands if( getInputs().size() != 1 ) { throw new LopsException(printErrorLocation() + "Invalid number of operands (" + getInputs().size() + ") for an Unary opration: " + operation); } // Unary operators with one input StringBuilder sb = new StringBuilder(); sb.append( getExecType() ); sb.append( Lop.OPERAND_DELIMITOR ); sb.append( getOpcode() ); sb.append( OPERAND_DELIMITOR ); sb.append( getInputs().get(0).prepInputOperand(input1) ); sb.append( OPERAND_DELIMITOR ); sb.append( prepOutputOperand(output) ); //num threads for cumulative cp ops if( getExecType() == ExecType.CP && isMultiThreadedOp(operation) ) { sb.append( OPERAND_DELIMITOR ); sb.append( _numThreads ); } return sb.toString(); } @Override public String getInstructions(int input_index, int output_index) { return getInstructions(String.valueOf(input_index), String.valueOf(output_index)); } @Override public String getInstructions(String input1, String input2, String output) { StringBuilder sb = new StringBuilder(); sb.append( getExecType() ); sb.append( Lop.OPERAND_DELIMITOR ); sb.append( getOpcode() ); sb.append( OPERAND_DELIMITOR ); if ( getInputs().get(0).getDataType() == DataType.SCALAR ) sb.append( getInputs().get(0).prepScalarInputOperand(getExecType())); else sb.append( getInputs().get(0).prepInputOperand(input1)); sb.append( OPERAND_DELIMITOR ); if ( getInputs().get(1).getDataType() == DataType.SCALAR ) sb.append( getInputs().get(1).prepScalarInputOperand(getExecType())); else sb.append( getInputs().get(1).prepInputOperand(input2)); sb.append( OPERAND_DELIMITOR ); sb.append( this.prepOutputOperand(output)); return sb.toString(); } @Override public String getInstructions(int inputIndex1, int inputIndex2, int outputIndex) { if (this.getInputs().size() == 2) { // Unary operators with two inputs // Determine the correct operation, depending on the scalar input Lop linput1 = getInputs().get(0); Lop linput2 = getInputs().get(1); int scalarIndex = -1, matrixIndex = -1; String matrixLabel= null; if( linput1.getDataType() == DataType.MATRIX ) { // inputIndex1 is matrix, and inputIndex2 is scalar scalarIndex = 1; matrixLabel = String.valueOf(inputIndex1); } else { // inputIndex2 is matrix, and inputIndex1 is scalar scalarIndex = 0; matrixLabel = String.valueOf(inputIndex2); // when the first operand is a scalar, setup the operation type accordingly if (operation == OperationTypes.SUBTRACT) operation = OperationTypes.SUBTRACTRIGHT; else if (operation == OperationTypes.DIVIDE) operation = OperationTypes.Over; } matrixIndex = 1-scalarIndex; // Prepare the instruction StringBuilder sb = new StringBuilder(); sb.append( getExecType() ); sb.append( Lop.OPERAND_DELIMITOR ); sb.append( getOpcode() ); sb.append( OPERAND_DELIMITOR ); if( operation == OperationTypes.INTDIV || operation == OperationTypes.MODULUS || operation == OperationTypes.POW || operation == OperationTypes.GREATER_THAN || operation == OperationTypes.GREATER_THAN_OR_EQUALS || operation == OperationTypes.LESS_THAN || operation == OperationTypes.LESS_THAN_OR_EQUALS || operation == OperationTypes.EQUALS || operation == OperationTypes.NOT_EQUALS ) { //TODO discuss w/ Shirish: we should consolidate the other operations (see ScalarInstruction.parseInstruction / BinaryCPInstruction.getScalarOperator) //append both operands sb.append( (linput1.getDataType()==DataType.MATRIX? linput1.prepInputOperand(String.valueOf(inputIndex1)) : linput1.prepScalarInputOperand(getExecType())) ); sb.append( OPERAND_DELIMITOR ); sb.append( (linput2.getDataType()==DataType.MATRIX? linput2.prepInputOperand(String.valueOf(inputIndex2)) : linput2.prepScalarInputOperand(getExecType())) ); sb.append( OPERAND_DELIMITOR ); } else { // append the matrix operand sb.append( getInputs().get(matrixIndex).prepInputOperand(matrixLabel)); sb.append( OPERAND_DELIMITOR ); // append the scalar operand sb.append( getInputs().get(scalarIndex).prepScalarInputOperand(getExecType())); sb.append( OPERAND_DELIMITOR ); } sb.append( prepOutputOperand(outputIndex) ); return sb.toString(); } else { throw new LopsException(this.printErrorLocation() + "Invalid number of operands (" + this.getInputs().size() + ") for an Unary opration: " + operation); } } }
/* * 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.carbondata.core.datastore.page.statistics; import java.math.BigDecimal; import org.apache.carbondata.core.datastore.page.encoding.ColumnPageEncoderMeta; import org.apache.carbondata.core.datastore.page.encoding.bool.BooleanConvert; import org.apache.carbondata.core.metadata.ValueEncoderMeta; import org.apache.carbondata.core.metadata.datatype.DataType; import org.apache.carbondata.core.metadata.datatype.DataTypes; import static org.apache.carbondata.core.datastore.page.encoding.bool.BooleanConvert.FALSE_VALUE; import static org.apache.carbondata.core.datastore.page.encoding.bool.BooleanConvert.TRUE_VALUE; /** statics for primitive column page */ public class PrimitivePageStatsCollector implements ColumnPageStatsCollector, SimpleStatsResult { private DataType dataType; private byte minByte, maxByte; private short minShort, maxShort; private int minInt, maxInt; private long minLong, maxLong; private double minDouble, maxDouble; private float minFloat, maxFloat; private BigDecimal minDecimal, maxDecimal; // scale of the double value, apply adaptive encoding if this is positive private int decimal; // scale of the double value, only for complex primitive. private int decimalCountForComplexPrimitive; private boolean isFirst = true; private BigDecimal zeroDecimal; // this is for encode flow public static PrimitivePageStatsCollector newInstance(DataType dataType) { return new PrimitivePageStatsCollector(dataType); } // this is for decode flow, create stats from encoder meta in carbondata file public static PrimitivePageStatsCollector newInstance(ColumnPageEncoderMeta meta) { PrimitivePageStatsCollector instance = new PrimitivePageStatsCollector(meta.getSchemaDataType()); // set min max from meta DataType dataType = meta.getSchemaDataType(); if (dataType == DataTypes.BOOLEAN || dataType == DataTypes.BYTE) { instance.minByte = (byte) meta.getMinValue(); instance.maxByte = (byte) meta.getMaxValue(); } else if (dataType == DataTypes.SHORT) { instance.minShort = (short) meta.getMinValue(); instance.maxShort = (short) meta.getMaxValue(); } else if (dataType == DataTypes.INT) { instance.minInt = (int) meta.getMinValue(); instance.maxInt = (int) meta.getMaxValue(); } else if (dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { instance.minLong = (long) meta.getMinValue(); instance.maxLong = (long) meta.getMaxValue(); } else if (dataType == DataTypes.DOUBLE) { instance.minDouble = (double) meta.getMinValue(); instance.maxDouble = (double) meta.getMaxValue(); instance.decimal = meta.getDecimal(); } else if (dataType == DataTypes.FLOAT) { instance.minFloat = (float) meta.getMinValue(); instance.maxFloat = (float) meta.getMaxValue(); instance.decimal = meta.getDecimal(); } else if (DataTypes.isDecimal(dataType)) { instance.minDecimal = (BigDecimal) meta.getMinValue(); instance.maxDecimal = (BigDecimal) meta.getMaxValue(); instance.decimal = meta.getDecimal(); } else { throw new UnsupportedOperationException( "unsupported data type for stats collection: " + meta.getSchemaDataType()); } return instance; } public static PrimitivePageStatsCollector newInstance(ValueEncoderMeta meta) { PrimitivePageStatsCollector instance = new PrimitivePageStatsCollector(DataType.getDataType(meta.getType())); // set min max from meta DataType dataType = DataType.getDataType(meta.getType()); if (dataType == DataTypes.BOOLEAN || dataType == DataTypes.BYTE) { instance.minByte = (byte) meta.getMinValue(); instance.maxByte = (byte) meta.getMaxValue(); } else if (dataType == DataTypes.SHORT) { instance.minShort = (short) meta.getMinValue(); instance.maxShort = (short) meta.getMaxValue(); } else if (dataType == DataTypes.INT) { instance.minInt = (int) meta.getMinValue(); instance.maxInt = (int) meta.getMaxValue(); } else if (dataType == DataTypes.LEGACY_LONG || dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { instance.minLong = (long) meta.getMinValue(); instance.maxLong = (long) meta.getMaxValue(); } else if (dataType == DataTypes.DOUBLE) { instance.minDouble = (double) meta.getMinValue(); instance.maxDouble = (double) meta.getMaxValue(); instance.decimal = meta.getDecimal(); } else if (dataType == DataTypes.FLOAT) { instance.minFloat = (float) meta.getMinValue(); instance.maxFloat = (float) meta.getMaxValue(); instance.decimal = meta.getDecimal(); } else if (DataTypes.isDecimal(dataType)) { instance.minDecimal = (BigDecimal) meta.getMinValue(); instance.maxDecimal = (BigDecimal) meta.getMaxValue(); instance.decimal = meta.getDecimal(); } else { throw new UnsupportedOperationException( "unsupported data type for Stats collection: " + meta.getType()); } return instance; } private PrimitivePageStatsCollector(DataType dataType) { this.dataType = dataType; if (dataType == DataTypes.BOOLEAN) { minByte = TRUE_VALUE; maxByte = FALSE_VALUE; } else if (dataType == DataTypes.BYTE) { minByte = Byte.MAX_VALUE; maxByte = Byte.MIN_VALUE; } else if (dataType == DataTypes.SHORT) { minShort = Short.MAX_VALUE; maxShort = Short.MIN_VALUE; } else if (dataType == DataTypes.INT) { minInt = Integer.MAX_VALUE; maxInt = Integer.MIN_VALUE; } else if (dataType == DataTypes.LEGACY_LONG || dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { minLong = Long.MAX_VALUE; maxLong = Long.MIN_VALUE; } else if (dataType == DataTypes.DOUBLE) { minDouble = Double.POSITIVE_INFINITY; maxDouble = Double.NEGATIVE_INFINITY; decimal = 0; } else if (dataType == DataTypes.FLOAT) { minFloat = Float.MAX_VALUE; maxFloat = Float.MIN_VALUE; decimal = 0; } else if (DataTypes.isDecimal(dataType)) { this.zeroDecimal = BigDecimal.ZERO; decimal = 0; } else { throw new UnsupportedOperationException( "unsupported data type for Stats collection: " + dataType); } } @Override public void updateNull(int rowId) { long value = 0; if (dataType == DataTypes.BOOLEAN || dataType == DataTypes.BYTE) { update((byte) value); } else if (dataType == DataTypes.SHORT) { update((short) value); } else if (dataType == DataTypes.INT) { update((int) value); } else if (dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { update(value); } else if (dataType == DataTypes.DOUBLE) { update(0d); } else if (dataType == DataTypes.FLOAT) { update(0f); } else if (DataTypes.isDecimal(dataType)) { if (isFirst) { maxDecimal = zeroDecimal; minDecimal = zeroDecimal; isFirst = false; } else { maxDecimal = (maxDecimal.compareTo(zeroDecimal) > 0) ? maxDecimal : zeroDecimal; minDecimal = (minDecimal.compareTo(zeroDecimal) < 0) ? minDecimal : zeroDecimal; } } else { throw new UnsupportedOperationException( "unsupported data type for Stats collection: " + dataType); } } @Override public void update(byte value) { if (minByte > value) { minByte = value; } if (maxByte < value) { maxByte = value; } } @Override public void update(short value) { if (minShort > value) { minShort = value; } if (maxShort < value) { maxShort = value; } } @Override public void update(int value) { if (minInt > value) { minInt = value; } if (maxInt < value) { maxInt = value; } } @Override public void update(long value) { if (minLong > value) { minLong = value; } if (maxLong < value) { maxLong = value; } } /** * Return number of digit after decimal point * TODO: it operation is costly, optimize for performance */ private int getDecimalCount(double value) { int decimalPlaces = 0; try { String strValue = BigDecimal.valueOf(Math.abs(value)).toPlainString(); int integerPlaces = strValue.indexOf('.'); if (-1 != integerPlaces) { decimalPlaces = strValue.length() - integerPlaces - 1; } } catch (NumberFormatException e) { if (!Double.isInfinite(value)) { throw e; } } return decimalPlaces; } private int getDecimalCount(float value) { int decimalPlaces = 0; try { String strValue = Float.valueOf(Math.abs(value)).toString(); int integerPlaces = strValue.indexOf('.'); if (-1 != integerPlaces) { decimalPlaces = strValue.length() - integerPlaces - 1; } } catch (NumberFormatException e) { if (!Double.isInfinite(value)) { throw e; } } return decimalPlaces; } @Override public void update(double value) { if (minDouble > value) { minDouble = value; } if (maxDouble < value) { maxDouble = value; } if (decimal >= 0) { int decimalCount = getDecimalCount(value); decimalCountForComplexPrimitive = decimalCount; if (decimalCount > 5) { // If deciaml count is too big, we do not do adaptive encoding. // So set decimal to negative value decimal = -1; } else if (decimalCount > decimal) { this.decimal = decimalCount; } } } @Override public void update(float value) { if (minFloat > value) { minFloat = value; } if (maxFloat < value) { maxFloat = value; } if (decimal >= 0) { int decimalCount = getDecimalCount(value); decimalCountForComplexPrimitive = decimalCount; if (decimalCount > 5) { // If deciaml count is too big, we do not do adaptive encoding. // So set decimal to negative value decimal = -1; } else if (decimalCount > decimal) { this.decimal = decimalCount; } } } public int getDecimalForComplexPrimitive() { decimal = decimalCountForComplexPrimitive; return decimalCountForComplexPrimitive; } @Override public void update(BigDecimal decimalValue) { if (isFirst) { maxDecimal = decimalValue; minDecimal = decimalValue; isFirst = false; } else { maxDecimal = (decimalValue.compareTo(maxDecimal) > 0) ? decimalValue : maxDecimal; minDecimal = (decimalValue.compareTo(minDecimal) < 0) ? decimalValue : minDecimal; } } @Override public void update(byte[] value) { } @Override public SimpleStatsResult getPageStats() { return this; } @Override public String toString() { if (dataType == DataTypes.BOOLEAN) { return String.format("min: %s, max: %s ", BooleanConvert.byte2Boolean(minByte), BooleanConvert.byte2Boolean(minByte)); } else if (dataType == DataTypes.BYTE) { return String.format("min: %s, max: %s, decimal: %s ", minByte, maxByte, decimal); } else if (dataType == DataTypes.SHORT) { return String.format("min: %s, max: %s, decimal: %s ", minShort, maxShort, decimal); } else if (dataType == DataTypes.INT) { return String.format("min: %s, max: %s, decimal: %s ", minInt, maxInt, decimal); } else if (dataType == DataTypes.LONG) { return String.format("min: %s, max: %s, decimal: %s ", minLong, maxLong, decimal); } else if (dataType == DataTypes.DOUBLE) { return String.format("min: %s, max: %s, decimal: %s ", minDouble, maxDouble, decimal); } else if (dataType == DataTypes.FLOAT) { return String.format("min: %s, max: %s, decimal: %s ", minFloat, maxFloat, decimal); } return super.toString(); } @Override public Object getMin() { if (dataType == DataTypes.BOOLEAN || dataType == DataTypes.BYTE) { return minByte; } else if (dataType == DataTypes.SHORT) { return minShort; } else if (dataType == DataTypes.INT) { return minInt; } else if (dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { return minLong; } else if (dataType == DataTypes.DOUBLE) { return minDouble; } else if (dataType == DataTypes.FLOAT) { return minFloat; } else if (DataTypes.isDecimal(dataType)) { return minDecimal; } return null; } @Override public Object getMax() { if (dataType == DataTypes.BOOLEAN || dataType == DataTypes.BYTE) { return maxByte; } else if (dataType == DataTypes.SHORT) { return maxShort; } else if (dataType == DataTypes.INT) { return maxInt; } else if (dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { return maxLong; } else if (dataType == DataTypes.DOUBLE) { return maxDouble; } else if (dataType == DataTypes.FLOAT) { return maxFloat; } else if (DataTypes.isDecimal(dataType)) { return maxDecimal; } return null; } @Override public int getDecimalCount() { return decimal; } @Override public DataType getDataType() { return dataType; } @Override public boolean writeMinMax() { return true; } }
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.ait.lienzo.client.widget.panel.scrollbars; import com.ait.lienzo.client.core.event.ViewportTransformChangedEvent; import com.ait.lienzo.client.core.event.ViewportTransformChangedHandler; import com.ait.lienzo.client.core.shape.Layer; import com.ait.lienzo.client.core.shape.Viewport; import com.ait.lienzo.client.core.types.Transform; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseMoveHandler; import com.google.gwt.event.dom.client.MouseWheelEvent; import com.google.gwt.event.dom.client.MouseWheelHandler; import com.google.gwt.event.dom.client.ScrollEvent; import com.google.gwt.event.dom.client.ScrollHandler; import com.google.gwt.user.client.ui.AbsolutePanel; public class ScrollablePanelHandler { private final ScrollablePanel panel; private final ScrollBounds scrollBounds; static final int DEFAULT_INTERNAL_SCROLL_HEIGHT = 1; static final int DEFAULT_INTERNAL_SCROLL_WIDTH = 1; public ScrollablePanelHandler(final ScrollablePanel panel) { this.panel = panel; this.scrollBounds = new ScrollBounds(this); } ScrollablePanelHandler(final ScrollablePanel panel, final ScrollBounds scrollBounds) { this.panel = panel; this.scrollBounds = scrollBounds; } public void init() { setupLienzoScrollStyle(); setupScrollBarSynchronization(); setupContextSwitcher(); } void setupContextSwitcher() { getPanel().register( getDomElementContainer().addDomHandler(disablePointerEvents(), MouseWheelEvent.getType()) ); getPanel().register( getPanel().addMouseMoveHandler(enablePointerEvents()) ); } MouseWheelHandler disablePointerEvents() { return new MouseWheelHandler() { @Override public void onMouseWheel(MouseWheelEvent event) { ScrollablePanelHandler.this.scrollUI().disablePointerEvents(ScrollablePanelHandler.this.getDomElementContainer()); } }; } MouseMoveHandler enablePointerEvents() { return new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent event) { ScrollablePanelHandler.this.scrollUI().enablePointerEvents(ScrollablePanelHandler.this.getDomElementContainer()); } }; } public int scrollbarWidth() { return getScrollPanel().getElement().getOffsetWidth() - getScrollPanel().getElement().getClientWidth(); } public int scrollbarHeight() { return getScrollPanel().getElement().getOffsetHeight() - getScrollPanel().getElement().getClientHeight(); } void setupLienzoScrollStyle() { scrollUI().setup(); } ScrollUI scrollUI() { return new ScrollUI(this); } void setupScrollBarSynchronization() { getPanel().register( getPanel().addScrollHandler(onScroll())); synchronizeScrollSize(); } ScrollHandler onScroll() { return new ScrollHandler() { @Override public void onScroll(ScrollEvent event) { final ScrollBars scrollBars = scrollBars(); ScrollablePanelHandler.this.updateLienzoPosition(scrollBars.getHorizontalScrollPosition(), scrollBars.getVerticalScrollPosition()); } }; } public void refresh() { synchronizeScrollSize(); refreshScrollPosition(); } void refreshScrollPosition() { final ScrollPosition position = scrollPosition(); setScrollBarsPosition(position.currentRelativeX(), position.currentRelativeY()); } public void setScrollBarsPosition(final Double xPercentage, final Double yPercentage) { final ScrollBars scrollBars = scrollBars(); scrollBars.setHorizontalScrollPosition(xPercentage); scrollBars.setVerticalScrollPosition(yPercentage); } void synchronizeScrollSize() { synchronizeScrollSize(calculateInternalScrollPanelWidth(), calculateInternalScrollPanelHeight()); } void synchronizeScrollSize(final int width, final int height) { if (!getInternalScrollPanel().getElement().getStyle().getProperty("width").equals(Integer.toString(width)) || !getInternalScrollPanel().getElement().getStyle().getProperty("height").equals(Integer.toString(height))) { getInternalScrollPanel().setPixelSize(width, height); getPanel().fireLienzoPanelBoundsChangedEvent(); } } Integer calculateInternalScrollPanelWidth() { final ScrollBounds bounds = scrollBounds(); final double absWidth = bounds.maxBoundX() - bounds.minBoundX(); if (getViewport() != null && scrollPosition().deltaX() != 0) { final Double scaleX = getViewport().getTransform().getScaleX(); final Double width = absWidth * scaleX; return width.intValue(); } return DEFAULT_INTERNAL_SCROLL_WIDTH; } Integer calculateInternalScrollPanelHeight() { final ScrollBounds bounds = scrollBounds(); final Double absHeight = bounds.maxBoundY() - bounds.minBoundY(); if (getViewport() != null && scrollPosition().deltaY() != 0) { final Double scaleY = getViewport().getTransform().getScaleY(); final Double height = absHeight * scaleY; return height.intValue(); } return DEFAULT_INTERNAL_SCROLL_HEIGHT; } public void updateLienzoPosition(final double percentageX, final double percentageY) { final ScrollPosition position = scrollPosition(); final double currentXPosition = position.currentPositionX(percentageX); final double currentYPosition = position.currentPositionY(percentageY); updateLayerLienzoTransform(currentXPosition, currentYPosition); getPanel().fireLienzoPanelScrollEvent(percentageX, percentageY); } private void updateLayerLienzoTransform(final double currentXPosition, final double currentYPosition) { final Transform oldTransform = getViewport().getTransform(); final double dx = currentXPosition - (oldTransform.getTranslateX() / oldTransform.getScaleX()); final double dy = currentYPosition - (oldTransform.getTranslateY() / oldTransform.getScaleY()); final Transform newTransform = oldTransform.copy().translate(dx, dy); getViewport().setTransform(newTransform); getLayer().batch(); } AbsolutePanel getScrollPanel() { return getPanel().getScrollPanel(); } AbsolutePanel getInternalScrollPanel() { return getPanel().getInternalScrollPanel(); } AbsolutePanel getDomElementContainer() { return getPanel().getDomElementContainer(); } ScrollablePanel getPanel() { return panel; } Layer getLayer() { return panel.getLayer(); } Viewport getViewport() { return null != getLayer() ? getLayer().getViewport() : null; } public ScrollBars scrollBars() { return new ScrollBars(this); } ScrollPosition scrollPosition() { return new ScrollPosition(this); } ScrollBounds scrollBounds() { return scrollBounds; } public static class ViewportScaleChangeHandler implements ViewportTransformChangedHandler { private final ScrollablePanelHandler panelHandler; private double scaleX; private double scaleY; public ViewportScaleChangeHandler(final ScrollablePanelHandler panelHandler) { this(panelHandler, 1, 1); } public ViewportScaleChangeHandler(final ScrollablePanelHandler panelHandler, final double scaleX, final double scaleY) { this.panelHandler = panelHandler; this.scaleX = scaleX; this.scaleY = scaleY; } public ViewportScaleChangeHandler(final ScrollablePanelHandler panelHandler, final Transform transform) { this.panelHandler = panelHandler; if (null == transform) { this.scaleX = 1; this.scaleY = 1; } else { this.scaleX = transform.getScaleX(); this.scaleY = transform.getScaleY(); } } @Override public void onViewportTransformChanged(final ViewportTransformChangedEvent event) { final Transform newTransform = event.getViewport().getTransform(); if (scaleX != newTransform.getScaleX() || scaleY != newTransform.getScaleY()) { panelHandler.refresh(); scaleX = newTransform.getScaleX(); scaleY = newTransform.getScaleY(); getPanel().fireLienzoPanelScaleChangedEvent(); final ScrollBars scrollBars = panelHandler.scrollBars(); getPanel().fireLienzoPanelScrollEvent(scrollBars.getHorizontalScrollPosition(), scrollBars.getVerticalScrollPosition()); } } private ScrollablePanel getPanel() { return panelHandler.getPanel(); } } }
/* * This file is derived from ZXing project ( https://github.com/zxing/zxing ) * and is modified for android-lib-ZXingCaptureActivity project. * * Copyright (C) 2008 ZXing authors * Copyright (C) 2014 NOBUOKA Yu * * 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 info.vividcode.android.zxing.camera; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.hardware.Camera; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; import com.google.zxing.PlanarYUVLuminanceSource; import info.vividcode.android.zxing.camera.open.OpenCameraInterface; import java.io.IOException; /** * This object wraps the Camera service object and expects to be the only one talking to it. The * implementation encapsulates the steps needed to take preview-sized images, which are used for * both preview and decoding. * * @author dswitkin@google.com (Daniel Switkin) */ public final class CameraManager { private static final String TAG = CameraManager.class.getSimpleName(); private static final int MIN_FRAME_WIDTH = 240; private static final int MIN_FRAME_HEIGHT = 240; private static final int MAX_FRAME_WIDTH = 1200; // = 5/8 * 1920 private static final int MAX_FRAME_HEIGHT = 675; // = 5/8 * 1080 private final CameraConfigurationManager configManager; private Camera camera; private AutoFocusManager autoFocusManager; private Rect framingRect; private Rect framingRectInPreview; private boolean initialized; private boolean previewing; private int requestedFramingRectWidth; private int requestedFramingRectHeight; /** * Preview frames are delivered here, which we pass on to the registered handler. Make sure to * clear the handler so it will only receive one message. */ private final PreviewCallback previewCallback; public CameraManager(Context context) { this.configManager = new CameraConfigurationManager(context); previewCallback = new PreviewCallback(configManager); } /** * Opens the camera driver and initializes the hardware parameters. * * @param holder The surface object which the camera will draw preview frames into. * @throws IOException Indicates the camera driver failed to open. */ public synchronized void openDriver(SurfaceHolder holder) throws IOException { Camera theCamera = camera; if (theCamera == null) { theCamera = OpenCameraInterface.open(); if (theCamera == null) { throw new IOException(); } camera = theCamera; } theCamera.setPreviewDisplay(holder); if (!initialized) { initialized = true; configManager.initFromCameraParameters(theCamera); if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight); requestedFramingRectWidth = 0; requestedFramingRectHeight = 0; } } Camera.Parameters parameters = theCamera.getParameters(); String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save these, temporarily try { configManager.setDesiredCameraParameters(theCamera, false); } catch (RuntimeException re) { // Driver failed Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); // Reset: if (parametersFlattened != null) { parameters = theCamera.getParameters(); parameters.unflatten(parametersFlattened); try { theCamera.setParameters(parameters); configManager.setDesiredCameraParameters(theCamera, true); } catch (RuntimeException re2) { // Well, darn. Give up Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); } } } } public synchronized boolean isOpen() { return camera != null; } /** * Closes the camera driver if still in use. */ public synchronized void closeDriver() { if (camera != null) { camera.release(); camera = null; // Make sure to clear these each time we close the camera, so that any scanning rect // requested by intent is forgotten. framingRect = null; framingRectInPreview = null; } } /** * Asks the camera hardware to begin drawing preview frames to the screen. */ public synchronized void startPreview() { Camera theCamera = camera; if (theCamera != null && !previewing) { theCamera.startPreview(); previewing = true; autoFocusManager = new AutoFocusManager(camera); } } /** * Tells the camera to stop drawing preview frames. */ public synchronized void stopPreview() { if (autoFocusManager != null) { autoFocusManager.stop(); autoFocusManager = null; } if (camera != null && previewing) { camera.stopPreview(); previewCallback.setHandler(null, 0); previewing = false; } } /** * Convenience method for {@link info.vividcode.android.zxing.CaptureActivity} */ public synchronized void setTorch(boolean newSetting) { if (newSetting != configManager.getTorchState(camera)) { if (camera != null) { if (autoFocusManager != null) { autoFocusManager.stop(); } configManager.setTorch(camera, newSetting); if (autoFocusManager != null) { autoFocusManager.start(); } } } } /** * A single preview frame will be returned to the handler supplied. The data will arrive as byte[] * in the message.obj field, with width and height encoded as message.arg1 and message.arg2, * respectively. * * @param handler The handler to send the message to. * @param message The what field of the message to be sent. */ public synchronized void requestPreviewFrame(Handler handler, int message) { Camera theCamera = camera; if (theCamera != null && previewing) { previewCallback.setHandler(handler, message); theCamera.setOneShotPreviewCallback(previewCallback); } } /** * Calculates the framing rect which the UI should draw to show the user where to place the * barcode. This target helps with alignment as well as forces the user to hold the device * far enough away to ensure the image will be in focus. * * @return The rectangle to draw on screen in window coordinates. */ public synchronized Rect getFramingRect() { if (framingRect == null) { if (camera == null) { return null; } Point screenResolution = configManager.getScreenResolution(); if (screenResolution == null) { // Called early, before init even finished return null; } int width = findDesiredDimensionInRange(screenResolution.x, MIN_FRAME_WIDTH, MAX_FRAME_WIDTH); int height = findDesiredDimensionInRange(screenResolution.y, MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT); int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated framing rect: " + framingRect); } return framingRect; } private static int findDesiredDimensionInRange(int resolution, int hardMin, int hardMax) { int dim = 5 * resolution / 8; // Target 5/8 of each dimension if (dim < hardMin) { return hardMin; } if (dim > hardMax) { return hardMax; } return dim; } /** * Like {@link #getFramingRect} but coordinates are in terms of the preview frame, * not UI / screen. */ public synchronized Rect getFramingRectInPreview() { if (framingRectInPreview == null) { Rect framingRect = getFramingRect(); if (framingRect == null) { return null; } Rect rect = new Rect(framingRect); Point cameraResolution = configManager.getCameraResolution(); Point screenResolution = configManager.getScreenResolution(); if (cameraResolution == null || screenResolution == null) { // Called early, before init even finished return null; } rect.left = rect.left * cameraResolution.x / screenResolution.x; rect.right = rect.right * cameraResolution.x / screenResolution.x; rect.top = rect.top * cameraResolution.y / screenResolution.y; rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y; framingRectInPreview = rect; } return framingRectInPreview; } /** * Allows third party apps to specify the scanning rectangle dimensions, rather than determine * them automatically based on screen resolution. * * @param width The width in pixels to scan. * @param height The height in pixels to scan. */ public synchronized void setManualFramingRect(int width, int height) { if (initialized) { Point screenResolution = configManager.getScreenResolution(); if (width > screenResolution.x) { width = screenResolution.x; } if (height > screenResolution.y) { height = screenResolution.y; } int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated manual framing rect: " + framingRect); framingRectInPreview = null; } else { requestedFramingRectWidth = width; requestedFramingRectHeight = height; } } /** * A factory method to build the appropriate LuminanceSource object based on the format * of the preview buffers, as described by Camera.Parameters. * * @param data A preview frame. * @param width The width of the image. * @param height The height of the image. * @return A PlanarYUVLuminanceSource instance. */ public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) { Rect rect = getFramingRectInPreview(); if (rect == null) { return null; } // Go ahead and assume it's YUV rather than die. return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false); } }
/* * Copyright (c) 2003-2012 Fred Hutchinson Cancer Research Center * * 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.fhcrc.cpl.viewer.amt.commandline; import org.fhcrc.cpl.viewer.commandline.modules.BaseViewerCommandLineModuleImpl; import org.fhcrc.cpl.toolbox.proteomics.commandline.arguments.ModificationListArgumentDefinition; import org.fhcrc.cpl.toolbox.commandline.arguments.*; import org.fhcrc.cpl.toolbox.gui.chart.ChartDialog; import org.fhcrc.cpl.toolbox.gui.chart.PanelWithHistogram; import org.fhcrc.cpl.toolbox.proteomics.feature.FeatureSet; import org.fhcrc.cpl.toolbox.proteomics.feature.AnalyzeICAT; import org.fhcrc.cpl.viewer.amt.AmtLabeledQuant; import org.fhcrc.cpl.toolbox.ApplicationContext; import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException; import org.fhcrc.cpl.toolbox.commandline.CommandLineModule; import org.apache.log4j.Logger; import org.fhcrc.cpl.toolbox.proteomics.PeptideGenerator; import org.fhcrc.cpl.toolbox.proteomics.MS2Modification; import java.io.File; import java.util.*; /** * Command linemodule for */ public class AmtLabeledQuantCLM extends BaseViewerCommandLineModuleImpl implements CommandLineModule { protected static Logger _log = Logger.getLogger(AmtLabeledQuantCLM.class); protected File[] featureFiles = null; protected File outFile; protected File outDir; protected boolean showCharts = false; protected List<Float> logRatiosAllFiles = new ArrayList<Float>(); protected boolean perCharge = true; float maxRatio = 15f; float minRatio = 1f/15f; AmtLabeledQuant amtLabeledQuant = null; public AmtLabeledQuantCLM() { init(); } protected void init() { mCommandName = "amtlabeledquant"; mShortDescription = "Performs labeled quantitation by mining AMT results for isotopic pairs."; mHelpMessage = "Performs labeled quantitation by mining AMT results for isotopic pairs. " + "Calculates ratios for each peptide within each charge state and then takes " + "the geometric mean."; CommandLineArgumentDefinition[] argDefs = { createUnnamedSeriesFileArgumentDefinition(true, "AMT matching result file(s)"), new FileToWriteArgumentDefinition("out",false, null), new DirectoryToWriteArgumentDefinition("outdir",false, null), new DecimalArgumentDefinition("separation", false, "light-heavy separation", AmtLabeledQuant.ACRYLAMIDE_MASS_DIFF), new StringArgumentDefinition("residue", false, "Labeled residue (leave blank for n-terminal)", "" + AmtLabeledQuant.ACRYLAMIDE_RESIDUE), new DecimalArgumentDefinition("minratiohighpprophet", false, "Minimum AMT probability for consideration in a ratio: the higher of the two " + "probabilities must be at least this high", AmtLabeledQuant.DEFAULT_MIN_RATIO_HIGH_PROB), new DecimalArgumentDefinition("minratiolowpprophet", false, "Minimum AMT probability for consideration in a ratio: the lower of the two " + "probabilities must be at least this high", AmtLabeledQuant.DEFAULT_MIN_RATIO_LOW_PROB), new BooleanArgumentDefinition("percharge", false, "Calculate ratios per charge (vs. all charges together)?", perCharge), new BooleanArgumentDefinition("showcharts", false, "show charts?", showCharts), new DecimalArgumentDefinition("minratio", false, "Minimum ratio to keep", minRatio), new DecimalArgumentDefinition("maxratio", false, "Maximum ratio to keep", maxRatio), new ModificationListArgumentDefinition("othermods", false, "a list of other modifications applied to sample", AmtLabeledQuant.DEFAULT_OTHER_MODS), }; addArgumentDefinitions(argDefs); } public void assignArgumentValues() throws ArgumentValidationException { featureFiles = this.getUnnamedSeriesFileArgumentValues(); if (featureFiles.length > 1) { assertArgumentPresent("outdir"); assertArgumentAbsent("out"); } else { assertArgumentPresent("out"); assertArgumentAbsent("outdir"); } outFile = getFileArgumentValue("out"); outDir = getFileArgumentValue("outdir"); double separation = getDoubleArgumentValue("separation"); String residue = getStringArgumentValue("residue"); if (residue != null && residue.length() > 1) throw new ArgumentValidationException("Invalid residue " + residue); AnalyzeICAT.IsotopicLabel isotopicLabel = AmtLabeledQuant.DEFAULT_ISOTOPIC_LABEL; if (residue != null) { isotopicLabel = new AnalyzeICAT.IsotopicLabel((float) PeptideGenerator.AMINO_ACID_MONOISOTOPIC_MASSES[residue.charAt(0)], (float) (PeptideGenerator.AMINO_ACID_MONOISOTOPIC_MASSES[residue.charAt(0)] + separation), residue.charAt(0), 5); } ApplicationContext.infoMessage("Using separation " + separation + "Da, residue " + residue); perCharge = getBooleanArgumentValue("percharge"); showCharts = getBooleanArgumentValue("showcharts"); amtLabeledQuant = new AmtLabeledQuant(); amtLabeledQuant.setIsotopicLabel(isotopicLabel); amtLabeledQuant.setMinRatioHigherProbability(getFloatArgumentValue("minratiohighpprophet")); amtLabeledQuant.setMinRatioLowerProbability(getFloatArgumentValue("minratiolowpprophet")); if (hasArgumentValue("othermods")) { MS2Modification[] specifiedMods = getModificationListArgumentValue("othermods"); if (specifiedMods != null) { for (MS2Modification specifiedMod : specifiedMods) { _log.debug("Including user-specified modification: " + specifiedMod); } amtLabeledQuant.setOtherModifications(specifiedMods); } } } /** * do the actual work */ public void execute() throws CommandLineModuleExecutionException { if (featureFiles.length == 1) { handleFile(featureFiles[0], outFile); } else { for (File featureFile : featureFiles) { File outputFile = new File(outDir, featureFile.getName() + ".amtquant.pep.xml"); ApplicationContext.infoMessage("Processing file " + featureFile.getName() + "..."); handleFile(featureFile, outputFile); } if (showCharts) { PanelWithHistogram pwh = new PanelWithHistogram(logRatiosAllFiles,"Log ratios"); ChartDialog cd = new ChartDialog(pwh); cd.setVisible(true); } } } protected void handleFile(File featureFile, File outputFile) throws CommandLineModuleExecutionException { FeatureSet featureSet = null; try { featureSet = new FeatureSet(featureFile); } catch (Exception e) { throw new CommandLineModuleExecutionException("Failed to load feature file " + featureFile.getAbsolutePath(),e); } ApplicationContext.setMessage("Read " + featureSet.getFeatures().length + " features from file " + featureFile.getAbsolutePath()); amtLabeledQuant.quantitate(featureSet); try { featureSet.savePepXml(outputFile); ApplicationContext.setMessage("Wrote " + featureSet.getFeatures().length + " features to file " + outputFile.getAbsolutePath()); } catch (Exception e) { throw new CommandLineModuleExecutionException(e); } if (showCharts) { // if (allLogRatios.size() > 0) // { // if (featureFiles.length == 1) // { // PanelWithHistogram pwh = new PanelWithHistogram(allLogRatios,"Log ratios"); // ChartDialog cd = new ChartDialog(pwh); // cd.setVisible(true); // } // else // logRatiosAllFiles.addAll(allLogRatios); // } // else ApplicationContext.infoMessage("Failed to build histogram, no ratios to plot"); } } }