gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* 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.sling.jcr.base.util;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.AccessDeniedException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.security.AccessControlEntry;
import javax.jcr.security.AccessControlException;
import javax.jcr.security.AccessControlList;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.AccessControlPolicy;
import javax.jcr.security.AccessControlPolicyIterator;
import javax.jcr.security.Privilege;
/**
* A simple utility class providing utilities with respect to
* access control over repositories.
*/
public class AccessControlUtil {
// the name of the accessor method for the AccessControlManager
private static final String METHOD_GET_ACCESS_CONTROL_MANAGER = "getAccessControlManager";
// the name of the accessor method for the UserManager
private static final String METHOD_GET_USER_MANAGER = "getUserManager";
// the name of the accessor method for the PrincipalManager
private static final String METHOD_GET_PRINCIPAL_MANAGER = "getPrincipalManager";
// the name of the JackrabbitAccessControlList method getPath
private static final String METHOD_JACKRABBIT_ACL_GET_PATH = "getPath";
// the name of the JackrabbitAccessControlList method
private static final String METHOD_JACKRABBIT_ACL_IS_EMPTY = "isEmpty";
// the name of the JackrabbitAccessControlList method
private static final String METHOD_JACKRABBIT_ACL_SIZE = "size";
// the name of the JackrabbitAccessControlList method
private static final String METHOD_JACKRABBIT_ACL_ADD_ENTRY = "addEntry";
// the name of the JackrabbitAccessControlEntry method
private static final String METHOD_JACKRABBIT_ACE_IS_ALLOW = "isAllow";
private static final Logger log = LoggerFactory.getLogger(AccessControlUtil.class);
// ---------- SessionImpl methods -----------------------------------------------------
/**
* Returns the <code>AccessControlManager</code> for the given
* <code>session</code>. If the session does not have a
* <code>getAccessControlManager</code> method, a
* <code>UnsupportedRepositoryOperationException</code> is thrown. Otherwise
* the <code>AccessControlManager</code> is returned or if the call fails,
* the respective exception is thrown.
*
* @param session The JCR Session whose <code>AccessControlManager</code> is
* to be returned. If the session is a pooled session, the
* session underlying the pooled session is actually used.
* @return The <code>AccessControlManager</code> of the session
* @throws UnsupportedRepositoryOperationException If the session has no
* <code>getAccessControlManager</code> method or the exception
* thrown by the method.
* @throws RepositoryException Forwarded from the
* <code>getAccessControlManager</code> method call.
*/
public static AccessControlManager getAccessControlManager(Session session)
throws UnsupportedRepositoryOperationException, RepositoryException {
return safeInvokeRepoMethod(session, METHOD_GET_ACCESS_CONTROL_MANAGER, AccessControlManager.class);
}
// ---------- JackrabbitSession methods -----------------------------------------------
/**
* Returns the <code>UserManager</code> for the given
* <code>session</code>. If the session does not have a
* <code>getUserManager</code> method, a
* <code>UnsupportedRepositoryOperationException</code> is thrown. Otherwise
* the <code>UserManager</code> is returned or if the call fails,
* the respective exception is thrown.
*
* @param session The JCR Session whose <code>UserManager</code> is
* to be returned. If the session is not a <code>JackrabbitSession</code>
* uses reflection to retrive the manager from the repository.
* @return The <code>UserManager</code> of the session.
* @throws AccessDeniedException If this session is not allowed
* to access user data.
* @throws UnsupportedRepositoryOperationException If the session has no
* <code>getUserManager</code> method or the exception
* thrown by the method.
* @throws RepositoryException Forwarded from the
* <code>getUserManager</code> method call.
*/
public static UserManager getUserManager(Session session)
throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException {
JackrabbitSession jackrabbitSession = getJackrabbitSession(session);
if(jackrabbitSession != null) {
return jackrabbitSession.getUserManager();
} else {
return safeInvokeRepoMethod(session, METHOD_GET_USER_MANAGER, UserManager.class);
}
}
/**
* Returns the <code>PrincipalManager</code> for the given
* <code>session</code>. If the session does not have a
* <code>PrincipalManager</code> method, a
* <code>UnsupportedRepositoryOperationException</code> is thrown. Otherwise
* the <code>PrincipalManager</code> is returned or if the call fails,
* the respective exception is thrown.
*
* @param session The JCR Session whose <code>PrincipalManager</code> is
* to be returned. If the session is not a <code>JackrabbitSession</code>
* uses reflection to retrive the manager from the repository.
* @return The <code>PrincipalManager</code> of the session.
* @throws AccessDeniedException
* @throws UnsupportedRepositoryOperationException If the session has no
* <code>PrincipalManager</code> method or the exception
* thrown by the method.
* @throws RepositoryException Forwarded from the
* <code>PrincipalManager</code> method call.
*/
public static PrincipalManager getPrincipalManager(Session session)
throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException {
JackrabbitSession jackrabbitSession = getJackrabbitSession(session);
if(jackrabbitSession != null) {
return jackrabbitSession.getPrincipalManager();
} else {
return safeInvokeRepoMethod(session, METHOD_GET_PRINCIPAL_MANAGER, PrincipalManager.class);
}
}
// ---------- AccessControlList methods -----------------------------------------------
/**
* Returns the path of the node <code>AccessControlList</code> acl
* has been created for.
*/
public static String getPath(AccessControlList acl) throws RepositoryException {
return safeInvokeRepoMethod(acl, METHOD_JACKRABBIT_ACL_GET_PATH, String.class);
}
/**
* Returns <code>true</code> if <code>AccessControlList</code> acl
* does not yet define any entries.
*/
public static boolean isEmpty(AccessControlList acl) throws RepositoryException {
return safeInvokeRepoMethod(acl, METHOD_JACKRABBIT_ACL_IS_EMPTY, Boolean.class);
}
/**
* Returns the number of acl entries or 0 if the acl is empty.
*/
public static int size(AccessControlList acl) throws RepositoryException {
return safeInvokeRepoMethod(acl, METHOD_JACKRABBIT_ACL_SIZE, Integer.class);
}
/**
* Same as {@link #addEntry(AccessControlList, Principal, Privilege[], boolean, Map)} using
* some implementation specific restrictions.
*/
@SuppressWarnings("unchecked")
public static boolean addEntry(AccessControlList acl, Principal principal, Privilege privileges[], boolean isAllow)
throws AccessControlException, RepositoryException {
Object[] args = new Object[] {principal, privileges, isAllow};
Class[] types = new Class[] {Principal.class, Privilege[].class, boolean.class};
return safeInvokeRepoMethod(acl, METHOD_JACKRABBIT_ACL_ADD_ENTRY, Boolean.class, args, types);
}
/**
* Adds an access control entry to the acl consisting of the specified
* <code>principal</code>, the specified <code>privileges</code>, the
* <code>isAllow</code> flag and an optional map containing additional
* restrictions.
* <p/>
* This method returns <code>true</code> if this policy was modified,
* <code>false</code> otherwise.
*/
@SuppressWarnings("unchecked")
public static boolean addEntry(AccessControlList acl, Principal principal, Privilege privileges[], boolean isAllow, Map restrictions)
throws UnsupportedRepositoryOperationException, RepositoryException {
Object[] args = new Object[] {principal, privileges, isAllow, restrictions};
Class[] types = new Class[] {Principal.class, Privilege[].class, boolean.class, Map.class};
return safeInvokeRepoMethod(acl, METHOD_JACKRABBIT_ACL_ADD_ENTRY, Boolean.class, args, types);
}
/**
* Replaces existing access control entries in the ACL for the specified
* <code>principal</code> and <code>resourcePath</code>. Any existing granted
* or denied privileges which do not conflict with the specified privileges
* are maintained. Where conflicts exist, existing privileges are dropped.
* The end result will be at most two ACEs for the principal: one for grants
* and one for denies. Aggregate privileges are disaggregated before checking
* for conflicts.
* @param session
* @param resourcePath
* @param principal
* @param grantedPrivilegeNames
* @param deniedPrivilegeNames
* @param removedPrivilegeNames privileges which, if they exist, should be
* removed for this principal and resource
* @throws RepositoryException
* @deprecated use @link {@link #replaceAccessControlEntry(Session, String, Principal, String[], String[], String[], String)} instead.
*/
public static void replaceAccessControlEntry(Session session, String resourcePath, Principal principal,
String[] grantedPrivilegeNames, String[] deniedPrivilegeNames, String[] removedPrivilegeNames)
throws RepositoryException {
replaceAccessControlEntry(session,
resourcePath,
principal,
grantedPrivilegeNames,
deniedPrivilegeNames,
removedPrivilegeNames,
null);
}
/**
* Replaces existing access control entries in the ACL for the specified
* <code>principal</code> and <code>resourcePath</code>. Any existing granted
* or denied privileges which do not conflict with the specified privileges
* are maintained. Where conflicts exist, existing privileges are dropped.
* The end result will be at most two ACEs for the principal: one for grants
* and one for denies. Aggregate privileges are disaggregated before checking
* for conflicts.
* @param session
* @param resourcePath
* @param principal
* @param grantedPrivilegeNames
* @param deniedPrivilegeNames
* @param removedPrivilegeNames privileges which, if they exist, should be
* removed for this principal and resource
* @param order where the access control entry should go in the list.
* Value should be one of these:
* <table>
* <tr><td>null</td><td>If the ACE for the principal doesn't exist add at the end, otherwise leave the ACE at it's current position.</td></tr>
* <tr><td>first</td><td>Place the target ACE as the first amongst its siblings</td></tr>
* <tr><td>last</td><td>Place the target ACE as the last amongst its siblings</td></tr>
* <tr><td>before xyz</td><td>Place the target ACE immediately before the sibling whose name is xyz</td></tr>
* <tr><td>after xyz</td><td>Place the target ACE immediately after the sibling whose name is xyz</td></tr>
* <tr><td>numeric</td><td>Place the target ACE at the specified numeric index</td></tr>
* </table>
* @throws RepositoryException
*/
public static void replaceAccessControlEntry(Session session, String resourcePath, Principal principal,
String[] grantedPrivilegeNames, String[] deniedPrivilegeNames, String[] removedPrivilegeNames,
String order)
throws RepositoryException {
AccessControlManager accessControlManager = getAccessControlManager(session);
Set<String> specifiedPrivilegeNames = new HashSet<String>();
Set<String> newGrantedPrivilegeNames = disaggregateToPrivilegeNames(accessControlManager, grantedPrivilegeNames, specifiedPrivilegeNames);
Set<String> newDeniedPrivilegeNames = disaggregateToPrivilegeNames(accessControlManager, deniedPrivilegeNames, specifiedPrivilegeNames);
disaggregateToPrivilegeNames(accessControlManager, removedPrivilegeNames, specifiedPrivilegeNames);
// Get or create the ACL for the node.
AccessControlList acl = null;
AccessControlPolicy[] policies = accessControlManager.getPolicies(resourcePath);
for (AccessControlPolicy policy : policies) {
if (policy instanceof AccessControlList) {
acl = (AccessControlList) policy;
break;
}
}
if (acl == null) {
AccessControlPolicyIterator applicablePolicies = accessControlManager.getApplicablePolicies(resourcePath);
while (applicablePolicies.hasNext()) {
AccessControlPolicy policy = applicablePolicies.nextAccessControlPolicy();
if (policy instanceof AccessControlList) {
acl = (AccessControlList) policy;
break;
}
}
}
if (acl == null) {
throw new RepositoryException("Could not obtain ACL for resource " + resourcePath);
}
// Used only for logging.
Set<Privilege> oldGrants = null;
Set<Privilege> oldDenies = null;
if (log.isDebugEnabled()) {
oldGrants = new HashSet<Privilege>();
oldDenies = new HashSet<Privilege>();
}
// Combine all existing ACEs for the target principal.
AccessControlEntry[] accessControlEntries = acl.getAccessControlEntries();
for (int i=0; i < accessControlEntries.length; i++) {
AccessControlEntry ace = accessControlEntries[i];
if (principal.equals(ace.getPrincipal())) {
if (log.isDebugEnabled()) {
log.debug("Found Existing ACE for principal {} on resource {}", new Object[] {principal.getName(), resourcePath});
}
if (order == null || order.length() == 0) {
//order not specified, so keep track of the original ACE position.
order = String.valueOf(i);
}
boolean isAllow = isAllow(ace);
Privilege[] privileges = ace.getPrivileges();
if (log.isDebugEnabled()) {
if (isAllow) {
oldGrants.addAll(Arrays.asList(privileges));
} else {
oldDenies.addAll(Arrays.asList(privileges));
}
}
for (Privilege privilege : privileges) {
Set<String> maintainedPrivileges = disaggregateToPrivilegeNames(privilege);
// If there is any overlap with the newly specified privileges, then
// break the existing privilege down; otherwise, maintain as is.
if (!maintainedPrivileges.removeAll(specifiedPrivilegeNames)) {
// No conflicts, so preserve the original.
maintainedPrivileges.clear();
maintainedPrivileges.add(privilege.getName());
}
if (!maintainedPrivileges.isEmpty()) {
if (isAllow) {
newGrantedPrivilegeNames.addAll(maintainedPrivileges);
} else {
newDeniedPrivilegeNames.addAll(maintainedPrivileges);
}
}
}
// Remove the old ACE.
acl.removeAccessControlEntry(ace);
}
}
//add a fresh ACE with the granted privileges
List<Privilege> grantedPrivilegeList = new ArrayList<Privilege>();
for (String name : newGrantedPrivilegeNames) {
Privilege privilege = accessControlManager.privilegeFromName(name);
grantedPrivilegeList.add(privilege);
}
if (grantedPrivilegeList.size() > 0) {
acl.addAccessControlEntry(principal, grantedPrivilegeList.toArray(new Privilege[grantedPrivilegeList.size()]));
}
//add a fresh ACE with the denied privileges
List<Privilege> deniedPrivilegeList = new ArrayList<Privilege>();
for (String name : newDeniedPrivilegeNames) {
Privilege privilege = accessControlManager.privilegeFromName(name);
deniedPrivilegeList.add(privilege);
}
if (deniedPrivilegeList.size() > 0) {
addEntry(acl, principal, deniedPrivilegeList.toArray(new Privilege[deniedPrivilegeList.size()]), false);
}
//order the ACL
reorderAccessControlEntries(acl, principal, order);
accessControlManager.setPolicy(resourcePath, acl);
if (log.isDebugEnabled()) {
List<String> oldGrantedNames = new ArrayList<String>(oldGrants.size());
for (Privilege privilege : oldGrants) {
oldGrantedNames.add(privilege.getName());
}
List<String> oldDeniedNames = new ArrayList<String>(oldDenies.size());
for (Privilege privilege : oldDenies) {
oldDeniedNames.add(privilege.getName());
}
log.debug("Updated ACE for principalName {} for resource {} from grants {}, denies {} to grants {}, denies {}", new Object [] {
principal.getName(), resourcePath, oldGrantedNames, oldDeniedNames, newGrantedPrivilegeNames, newDeniedPrivilegeNames
});
}
}
// ---------- AccessControlEntry methods -----------------------------------------------
/**
* Returns true if the AccessControlEntry represents 'allowed' rights or false
* it it represents 'denied' rights.
*/
public static boolean isAllow(AccessControlEntry ace) throws RepositoryException {
return safeInvokeRepoMethod(ace, METHOD_JACKRABBIT_ACE_IS_ALLOW, Boolean.class);
}
// ---------- internal -----------------------------------------------------
/**
* Use reflection to invoke a repository method.
*/
@SuppressWarnings("unchecked")
private static <T> T safeInvokeRepoMethod(Object target, String methodName, Class<T> returnType, Object[] args, Class[] argsTypes)
throws UnsupportedRepositoryOperationException, RepositoryException {
try {
Method m = target.getClass().getMethod(methodName, argsTypes);
if (!m.isAccessible()) {
m.setAccessible(true);
}
return (T) m.invoke(target, args);
} catch (InvocationTargetException ite) {
// wraps the exception thrown by the method
Throwable t = ite.getCause();
if (t instanceof UnsupportedRepositoryOperationException) {
throw (UnsupportedRepositoryOperationException) t;
} else if (t instanceof AccessDeniedException) {
throw (AccessDeniedException) t;
} else if (t instanceof AccessControlException) {
throw (AccessControlException) t;
} else if (t instanceof RepositoryException) {
throw (RepositoryException) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new RepositoryException(methodName, t);
}
} catch (Throwable t) {
// any other problem is just encapsulated
throw new RepositoryException(methodName, t);
}
}
private static <T> T safeInvokeRepoMethod(Object target, String methodName, Class<T> returnType, Object... args)
throws UnsupportedRepositoryOperationException, RepositoryException {
return safeInvokeRepoMethod(target, methodName, returnType, args, new Class[0]);
}
/**
* Unwrap the jackrabbit session.
*/
private static JackrabbitSession getJackrabbitSession(Session session) {
if (session instanceof JackrabbitSession)
return (JackrabbitSession) session;
else
return null;
}
/**
* Helper routine to transform an input array of privilege names into a set in
* a null-safe way while also adding its disaggregated privileges to an input set.
*/
private static Set<String> disaggregateToPrivilegeNames(AccessControlManager accessControlManager,
String[] privilegeNames, Set<String> disaggregatedPrivilegeNames)
throws RepositoryException {
Set<String> originalPrivilegeNames = new HashSet<String>();
if (privilegeNames != null) {
for (String privilegeName : privilegeNames) {
originalPrivilegeNames.add(privilegeName);
Privilege privilege = accessControlManager.privilegeFromName(privilegeName);
disaggregatedPrivilegeNames.addAll(disaggregateToPrivilegeNames(privilege));
}
}
return originalPrivilegeNames;
}
/**
* Transform an aggregated privilege into a set of disaggregated privilege
* names. If the privilege is not an aggregate, the set will contain the
* original name.
*/
private static Set<String> disaggregateToPrivilegeNames(Privilege privilege) {
Set<String> disaggregatedPrivilegeNames = new HashSet<String>();
if (privilege.isAggregate()) {
Privilege[] privileges = privilege.getAggregatePrivileges();
for (Privilege disaggregate : privileges) {
if (disaggregate.isAggregate()) {
continue; //nested aggregate, so skip it since the privileges are already included.
}
disaggregatedPrivilegeNames.add(disaggregate.getName());
}
} else {
disaggregatedPrivilegeNames.add(privilege.getName());
}
return disaggregatedPrivilegeNames;
}
/**
* Move the ACE(s) for the specified principal to the position specified by the 'order'
* parameter.
*
* @param acl the acl of the node containing the ACE to position
* @param principal the user or group of the ACE to position
* @param order where the access control entry should go in the list.
* Value should be one of these:
* <table>
* <tr><td>first</td><td>Place the target ACE as the first amongst its siblings</td></tr>
* <tr><td>last</td><td>Place the target ACE as the last amongst its siblings</td></tr>
* <tr><td>before xyz</td><td>Place the target ACE immediately before the sibling whose name is xyz</td></tr>
* <tr><td>after xyz</td><td>Place the target ACE immediately after the sibling whose name is xyz</td></tr>
* <tr><td>numeric</td><td>Place the target ACE at the specified index</td></tr>
* </table>
* @throws RepositoryException
* @throws UnsupportedRepositoryOperationException
* @throws AccessControlException
*/
private static void reorderAccessControlEntries(AccessControlList acl,
Principal principal,
String order)
throws RepositoryException {
if (order == null || order.length() == 0) {
return; //nothing to do
}
if (acl instanceof JackrabbitAccessControlList) {
JackrabbitAccessControlList jacl = (JackrabbitAccessControlList)acl;
AccessControlEntry[] accessControlEntries = jacl.getAccessControlEntries();
if (accessControlEntries.length <= 1) {
return; //only one ACE, so nothing to reorder.
}
AccessControlEntry beforeEntry = null;
if ("first".equals(order)) {
beforeEntry = accessControlEntries[0];
} else if ("last".equals(order)) {
beforeEntry = null;
} else if (order.startsWith("before ")) {
String beforePrincipalName = order.substring(7);
//find the index of the ACE of the 'before' principal
for (int i=0; i < accessControlEntries.length; i++) {
if (beforePrincipalName.equals(accessControlEntries[i].getPrincipal().getName())) {
//found it!
beforeEntry = accessControlEntries[i];
break;
}
}
if (beforeEntry == null) {
//didn't find an ACE that matched the 'before' principal
throw new IllegalArgumentException("No ACE was found for the specified principal: " + beforePrincipalName);
}
} else if (order.startsWith("after ")) {
String afterPrincipalName = order.substring(6);
//find the index of the ACE of the 'after' principal
for (int i = accessControlEntries.length - 1; i >= 0; i--) {
if (afterPrincipalName.equals(accessControlEntries[i].getPrincipal().getName())) {
//found it!
// the 'before' ACE is the next one after the 'after' ACE
if (i >= accessControlEntries.length - 1) {
//the after is the last one in the list
beforeEntry = null;
} else {
beforeEntry = accessControlEntries[i + 1];
}
break;
}
}
if (beforeEntry == null) {
//didn't find an ACE that matched the 'after' principal
throw new IllegalArgumentException("No ACE was found for the specified principal: " + afterPrincipalName);
}
} else {
try {
int index = Integer.parseInt(order);
if (index > accessControlEntries.length) {
//invalid index
throw new IndexOutOfBoundsException("Index value is too large: " + index);
}
if (index == 0) {
beforeEntry = accessControlEntries[0];
} else {
//the index value is the index of the principal. A principal may have more
// than one ACEs (deny + grant), so we need to compensate.
Set<Principal> processedPrincipals = new HashSet<Principal>();
for (int i = 0; i < accessControlEntries.length; i++) {
Principal principal2 = accessControlEntries[i].getPrincipal();
if (processedPrincipals.size() == index &&
!processedPrincipals.contains(principal2)) {
//we are now at the correct position in the list
beforeEntry = accessControlEntries[i];
break;
}
processedPrincipals.add(principal2);
}
}
} catch (NumberFormatException nfe) {
//not a number.
throw new IllegalArgumentException("Illegal value for the order parameter: " + order);
}
}
//now loop through the entries to move the affected ACEs to the specified
// position.
for (int i = accessControlEntries.length - 1; i >= 0; i--) {
AccessControlEntry ace = accessControlEntries[i];
if (principal.equals(ace.getPrincipal())) {
//this ACE is for the specified principal.
jacl.orderBefore(ace, beforeEntry);
}
}
} else {
throw new IllegalArgumentException("The acl must be an instance of JackrabbitAccessControlList");
}
}
}
| |
package chav1961.purelib.ui.swing.terminal;
import java.awt.Color;
import java.awt.Rectangle;
import chav1961.purelib.ui.ColorPair;
public class TermUtils {
// U+2500 - U+257F - unicode borders
// U+2580 - U+259F - unicode filling
public static final char SINGLE_HORIZONTAL = '\u2500';
public static final char SINGLE_VERTICAL = '\u2502';
public static final char SINGLE_TOPLEFT = '\u250C';
public static final char SINGLE_TOPRIGHT = '\u2510';
public static final char SINGLE_BOTTOMLEFT = '\u2514';
public static final char SINGLE_BOTTOMRIGHT = '\u2518';
public static final char SINGLE_VERTICAL_RIGHT = '\u251C';
public static final char SINGLE_VERTICAL_LEFT = '\u2524';
public static final char SINGLE_HORIZONTAL_BOTTOM = '\u252C';
public static final char SINGLE_HORIZONTAL_TOP = '\u2534';
public static final char SINGLE_CROSS = '\u253C';
public static final char DOUBLE_HORIZONTAL = '\u2550';
public static final char DOUBLE_VERTICAL = '\u2551';
public static final char DOUBLE_TOPLEFT = '\u2554';
public static final char DOUBLE_TOPRIGHT = '\u2557';
public static final char DOUBLE_BOTTOMLEFT = '\u255A';
public static final char DOUBLE_BOTTOMRIGHT = '\u255D';
public static final char DOUBLE_VERTICAL_RIGHT = '\u2560';
public static final char DOUBLE_VERTICAL_LEFT = '\u2563';
public static final char DOUBLE_HORIZONTAL_BOTTOM = '\u2566';
public static final char DOUBLE_HORIZONTAL_TOP = '\u2569';
public static final char DOUBLE_CROSS = '\u256C';
public static final char SINGLE_TOP_DOUBLE_LEFT = '\u2553';
public static final char SINGLE_BOTTOM_DOUBLE_LEFT = '\u2559';
public static final char SINGLE_TOP_DOUBLE_RIGHT = '\u2556';
public static final char SINGLE_BOTTOM_DOUBLE_RIGHT = '\u255C';
public static final char DOUBLE_TOP_SINGLE_LEFT = '\u2552';
public static final char DOUBLE_BOTTOM_SINGLE_LEFT = '\u2558';
public static final char DOUBLE_TOP_SINGLE_RIGHT = '\u2555';
public static final char DOUBLE_BOTTOM_SINGLE_RIGHT = '\u255B';
private static final char[] SINGLE_BOX= {SINGLE_TOPLEFT, SINGLE_BOTTOMLEFT, SINGLE_TOPRIGHT, SINGLE_BOTTOMRIGHT, SINGLE_VERTICAL, SINGLE_VERTICAL, SINGLE_HORIZONTAL, SINGLE_HORIZONTAL};
private static final char[] DOUBLE_BOX= {DOUBLE_TOPLEFT, DOUBLE_BOTTOMLEFT, DOUBLE_TOPRIGHT, DOUBLE_BOTTOMRIGHT, DOUBLE_VERTICAL, DOUBLE_VERTICAL, DOUBLE_HORIZONTAL, DOUBLE_HORIZONTAL};
private static final char[] SEMIDOUBLE_BOX= {SINGLE_TOPLEFT, DOUBLE_BOTTOM_SINGLE_LEFT, SINGLE_TOP_DOUBLE_RIGHT, DOUBLE_BOTTOMRIGHT, SINGLE_VERTICAL, DOUBLE_VERTICAL, SINGLE_HORIZONTAL, DOUBLE_HORIZONTAL};
private static final char[] SINGLE_VERTICAL_LINE = {SINGLE_VERTICAL, SINGLE_VERTICAL, SINGLE_VERTICAL};
private static final char[] SINGLE_HORIZONTAL_LINE = {SINGLE_HORIZONTAL, SINGLE_HORIZONTAL, SINGLE_HORIZONTAL};
private static final char[] DOUBLE_VERTICAL_LINE = {DOUBLE_VERTICAL, DOUBLE_VERTICAL, DOUBLE_VERTICAL};
private static final char[] DOUBLE_HORIZONTAL_LINE = {DOUBLE_HORIZONTAL, DOUBLE_HORIZONTAL, DOUBLE_HORIZONTAL};
public enum LineStyle {
Single, Double, SemiDouble
}
public static void clear(final PseudoConsole console, final Color color, final Color bkGnd) {
if (console == null) {
throw new NullPointerException("Console can't be null");
}
else if (color == null) {
throw new NullPointerException("Color can't be null");
}
else if (bkGnd == null) {
throw new NullPointerException("Background color can't be null");
}
else {
console.writeAttribute(new Rectangle(1,1,console.getConsoleWidth(),console.getConsoleHeight()),new ColorPair(color,bkGnd));
console.writeContent(new Rectangle(1,1,console.getConsoleWidth(),console.getConsoleHeight()),' ');
}
}
public static void line(final PseudoConsole console, final int xFrom, final int yFrom, final int xTo, final int yTo) {
line(console,xFrom,yFrom,xTo,yTo,LineStyle.Single);
}
public static void line(final PseudoConsole console, final int xFrom, final int yFrom, final int xTo, final int yTo, final LineStyle style) {
if (style == null) {
throw new NullPointerException("Line style can't be null");
}
else {
switch (style) {
case Double :
if (xFrom == xTo) {
line(console,xFrom,yFrom,xTo,yTo,DOUBLE_VERTICAL_LINE);
}
else {
line(console,xFrom,yFrom,xTo,yTo,DOUBLE_HORIZONTAL_LINE);
}
break;
case Single :
if (xFrom == xTo) {
line(console,xFrom,yFrom,xTo,yTo,SINGLE_VERTICAL_LINE);
}
else {
line(console,xFrom,yFrom,xTo,yTo,SINGLE_HORIZONTAL_LINE);
}
break;
default : throw new IllegalArgumentException("Line type ["+style+"] is not supported for ordinal line");
}
}
}
public static void line(final PseudoConsole console, final int xFrom, final int yFrom, final int xTo, final int yTo, final char[] fillers) {
if (console == null) {
throw new NullPointerException("Console to write line to can't be null");
}
else if (xFrom < 1 || xFrom > console.getConsoleWidth()) {
throw new IllegalArgumentException("Start x coordinate ["+xFrom+"] out of range 1.."+console.getConsoleWidth());
}
else if (xTo < 1 || xTo > console.getConsoleWidth()) {
throw new IllegalArgumentException("End x coordinate ["+xTo+"] out of range 1.."+console.getConsoleWidth());
}
else if (yFrom < 1 || yFrom > console.getConsoleHeight()) {
throw new IllegalArgumentException("Start y coordinate ["+yFrom+"] out of range 1.."+console.getConsoleHeight());
}
else if (yTo < 1 || yTo > console.getConsoleHeight()) {
throw new IllegalArgumentException("End y coordinate ["+yTo+"] out of range 1.."+console.getConsoleHeight());
}
else if (fillers == null || fillers.length != 3) {
throw new IllegalArgumentException("Fillers can't be null and must contain exactly 3 chars");
}
else if (xFrom != xTo && yFrom != yTo) {
throw new IllegalArgumentException("Points [,] and [,] describe diagonal line. Only vertical and horizontal lines are available");
}
else if (xFrom > xTo) {
line(console,xTo,yFrom,xFrom,yTo,fillers);
}
else if (yFrom > yTo) {
line(console,xFrom,yTo,xTo,yFrom,fillers);
}
else if (yFrom == yTo) {
for (int index = xFrom; index <= xTo; index++) {
if (index == xFrom) {
console.writeContent(index, yFrom, fillers[0]);
}
else if (index == xTo) {
console.writeContent(index, yFrom, fillers[2]);
}
else {
console.writeContent(index, yFrom, fillers[1]);
}
}
}
else {
for (int index = yFrom; index <= yTo; index++) {
if (index == yFrom) {
console.writeContent(xFrom, index, fillers[0]);
}
else if (index == yTo) {
console.writeContent(xFrom, index, fillers[2]);
}
else {
console.writeContent(xFrom, index, fillers[1]);
}
}
}
}
public static void box(final PseudoConsole console, final int x, final int y, final int width, final int height) {
box(console, x, y, width, height, LineStyle.SemiDouble);
}
public static void box(final PseudoConsole console, final int x, final int y, final int width, final int height, final LineStyle style) {
if (style == null) {
throw new NullPointerException("Box style can't be null");
}
else {
switch (style) {
case Double : box(console, x, y, width, height, DOUBLE_BOX); break;
case SemiDouble : box(console, x, y, width, height, SEMIDOUBLE_BOX); break;
case Single : box(console, x, y, width, height, SINGLE_BOX); break;
default : throw new UnsupportedOperationException("Box style ["+style+"] is not supported yet");
}
}
}
public static void box(final PseudoConsole console, final int x, final int y, final int width, final int height, final char[] fillers) {
if (console == null) {
throw new NullPointerException("Console to fill can't be null");
}
else if (x < 1 || x > console.getConsoleWidth()) {
throw new IllegalArgumentException("X coordinate ["+x+"] out of range 1.."+console.getConsoleWidth());
}
else if (y < 1 || y > console.getConsoleHeight()) {
throw new IllegalArgumentException("Y coordinate ["+y+"] out of range 1.."+console.getConsoleHeight());
}
else if (x+width < 1 || x+width-1 > console.getConsoleWidth()) {
throw new IllegalArgumentException("X coordinate + width ["+(x+width)+"] out of range 1.."+console.getConsoleWidth());
}
else if (y+height < 1 || y+height-1 > console.getConsoleHeight()) {
throw new IllegalArgumentException("Y coordinate + height ["+(y+height)+"] out of range 1.."+console.getConsoleHeight());
}
else if (fillers == null || !(fillers.length == 8 || fillers.length == 9)) {
throw new IllegalArgumentException("Fillers array can't be null and must contain either 8 or 9 elements");
}
else {
for (int xIndex = x; xIndex < x+width; xIndex++) {
for (int yIndex = y; yIndex < y+height; yIndex++) {
if (xIndex == x && yIndex == y) {
console.writeContent(xIndex, yIndex, fillers[0]);
}
else if (xIndex == x && yIndex == y+height-1) {
console.writeContent(xIndex, yIndex, fillers[1]);
}
else if (xIndex == x+width-1 && yIndex == y) {
console.writeContent(xIndex, yIndex, fillers[2]);
}
else if (xIndex == x+width-1 && yIndex == y+height-1) {
console.writeContent(xIndex, yIndex, fillers[3]);
}
else if (xIndex == x) {
console.writeContent(xIndex, yIndex, fillers[4]);
}
else if (xIndex == x+width-1) {
console.writeContent(xIndex, yIndex, fillers[5]);
}
else if (yIndex == y) {
console.writeContent(xIndex, yIndex, fillers[6]);
}
else if (yIndex == y+height-1) {
console.writeContent(xIndex, yIndex, fillers[7]);
}
else if (fillers.length == 9) {
console.writeContent(xIndex, yIndex, fillers[8]);
}
}
}
}
}
}
| |
package controllers.sso.admin.users;
import controllers.sso.filters.AuthenticationFilter;
import controllers.sso.filters.IpAddressFilter;
import controllers.sso.filters.LanguageFilter;
import controllers.sso.web.Controllers;
import controllers.sso.web.UrlBuilder;
import converters.Converter;
import models.sso.Country;
import models.sso.User;
import models.sso.UserConfirmationState;
import models.sso.UserRole;
import models.sso.UserSignInState;
import ninja.Context;
import ninja.Result;
import ninja.session.FlashScope;
import ninja.utils.NinjaProperties;
import ninja.validation.ConstraintViolation;
import ninja.validation.Validation;
import services.sso.CountryService;
import services.sso.UserEventService;
import services.sso.UserService;
import javax.inject.Provider;
import java.util.List;
/**
* Edit user data abstract controller with common method and services.
*
* @param <C> Converter type.
* @param <DTO> Data transfer object type.
*/
public abstract class EditAbstractController<C extends Converter<User, DTO>, DTO> {
/**
* Message id for changed password.
*/
protected static final String USER_DATA_SAVED_MESSAGE = "adminUserDataSaved";
/**
* User service.
*/
protected final UserService userService;
/**
* User event service.
*/
protected final UserEventService userEventService;
/**
* Country service.
*/
protected final CountryService countryService;
/**
* Converter.
*/
protected final C converter;
/**
* URL builder provider for controller. Instance per request.
*/
protected final Provider<UrlBuilder> urlBuilderProvider;
/**
* Html result with secure headers.
*/
private final Provider<Result> htmlAdminSecureHeadersProvider;
/**
* Application properties.
*/
protected final NinjaProperties properties;
/**
* Constructs the controller.
*
* @param userService User service.
* @param userEventService User event service.
* @param countryService Country service.
* @param converter Converter.
* @param urlBuilderProvider Provider for URL builder.
* @param htmlAdminSecureHeadersProvider HTML with secure headers provider for admin.
* @param properties Application properties.
*/
protected EditAbstractController(
UserService userService,
UserEventService userEventService,
CountryService countryService,
C converter,
Provider<UrlBuilder> urlBuilderProvider,
Provider<Result> htmlAdminSecureHeadersProvider,
NinjaProperties properties) {
this.userService = userService;
this.userEventService = userEventService;
this.countryService = countryService;
this.urlBuilderProvider = urlBuilderProvider;
this.htmlAdminSecureHeadersProvider = htmlAdminSecureHeadersProvider;
this.properties = properties;
this.converter = converter;
}
/**
* Provides additional validation for Data Transfer Object.
* <p>
* Return null if the DTO is valid or return violation id for invalid field in DTO/form.
*
* @param user User entity that was updated by this controller.
* @param dto Data Transfer Object for form.
* @return Null if the DTO is valid or violation id for invalid field in DTO/form.
*/
protected abstract String validate(User user, DTO dto);
/**
* Returns absolute URL for a redirect after successful form submission.
*
* @param user User entity that was updated by this controller.
* @param context Application context.
* @return Absolute URL for a redirect after successful form submission.
*/
protected abstract String getSuccessRedirectUrl(User user, Context context);
/**
* Path to application template to be rendered.
*
* @return Path to application template to be rendered.
*/
protected abstract String getTemplate();
/**
* Renders edit user data template for given user, logging access or redirects to the list of users if the given
* user was not found.
*
* @param userId User's id whose data to render.
* @param context Application context.
* @return Result with rendered template or redirection to the list of users if the user was not found.
*/
protected final Result renderUserOrRedirectToList(long userId, Context context) {
User user = userService.get(userId);
if (user == null) {
return Controllers.redirect(urlBuilderProvider.get()
.getAdminUsersUrl(context.getParameter("query"), context.getParameter("page")));
}
User loggedInUser = userService.get((long) context.getAttribute(AuthenticationFilter.USER_ID));
this.logAccess(user, loggedInUser, context);
return createResult(converter.fromEntity(user), user, context, Controllers.noViolations());
}
/**
* Updates user entity with data from given Data Transfer Object (form), logging update or redirects to the list of
* users if the given user was not found.
*
* @param userId User's id whose entity to update.
* @param dto Data Transfer Object to get data from.
* @param context Application context.
* @param flashScope Flash scope.
* @param validation DTO/form validation.
* @return Result with redirect to the URL provided by {@link #getSuccessRedirectUrl(User, Context)} or redirection
* to the list of users if the user was not found.
*/
protected final Result updateUserOrRedirectToList(
long userId,
DTO dto,
Context context,
FlashScope flashScope,
Validation validation) {
// Check existing user.
User user = userService.get(userId);
if (user == null) {
return Controllers.redirect(urlBuilderProvider.get()
.getAdminUsersUrl(context.getParameter("query"), context.getParameter("page")));
}
// Validate all fields.
if (validation.hasViolations()) {
return createResult(dto, user, context, validation);
}
// Validate DTO specifics.
String specificViolation = validate(user, dto);
if (specificViolation != null) {
return createResult(dto, user, context, validation, specificViolation);
}
// Remote IP.
String ip = (String) context.getAttribute(IpAddressFilter.REMOTE_IP);
// Logged in user.
User loggedInUser = userService.get((long) context.getAttribute(AuthenticationFilter.USER_ID));
// Log update event. Must happen before actual data update to fetch data.
this.logUpdate(user, loggedInUser, context);
// Remember old states and roles.
UserRole oldRole = user.getRole();
UserSignInState oldSignInState = user.getSignInState();
UserConfirmationState oldConfirmationState = user.getConfirmationState();
// Map edit DTO to user entity.
converter.update(user, dto);
// Update user.
userService.update(user);
// Produce change events.
UserRole newRole = user.getRole();
UserSignInState newSignInState = user.getSignInState();
UserConfirmationState newConfirmationState = user.getConfirmationState();
if (!oldRole.equals(newRole)) {
userEventService.onRoleChange(user, oldRole, loggedInUser, ip, context.getHeaders());
}
if (!oldSignInState.equals(newSignInState)) {
if (UserSignInState.ENABLED.equals(newSignInState)) {
userEventService.onSignInEnable(user, ip, context.getHeaders());
} else {
userEventService.onSignInEnable(user, ip, context.getHeaders());
}
}
if (!oldConfirmationState.equals(newConfirmationState)
&& UserConfirmationState.CONFIRMED.equals(newConfirmationState)) {
userEventService.onConfirmation(user, ip, context.getHeaders());
}
// Set message.
flashScope.success(USER_DATA_SAVED_MESSAGE);
// Redirect to same form.
return Controllers.redirect(getSuccessRedirectUrl(user, context));
}
/**
* Creates response result with given user, validation and field that lead to error.
*
* @param dto User to use in response.
* @param user Original user entity for read-only data.
* @param ctx Context.
* @param validation Validation.
* @param field Field to report as an error.
* @return Sign up response object.
*/
private Result createResult(DTO dto, User user, Context ctx, Validation validation, String field) {
validation.addViolation(new ConstraintViolation(field, field, field));
return createResult(dto, user, ctx, validation);
}
/**
* Creates response result with given user.
*
* @param user User to use in response.
* @param userEntity Original user entity for read-only data.
* @param ctx Context.
* @param validation Validation.
* @return Sign up response object.
*/
private Result createResult(DTO user, User userEntity, Context ctx, Validation validation) {
User loggedInUser = userService.get((long) ctx.getAttribute(AuthenticationFilter.USER_ID));
String locale = (String) ctx.getAttribute(LanguageFilter.LANG);
List<Country> countries = "en".equals(locale) ?
countryService.getAllSortedByName() : countryService.getAllSortedByNativeName();
return htmlAdminSecureHeadersProvider.get()
.render("context", ctx)
.render("config", properties)
.render("errors", validation)
.render("loggedInUser", loggedInUser)
.render("user", user)
.render("userEntity", userEntity)
.render("countries", countries)
.render("roles", UserRole.values())
.render("signInStates", UserSignInState.values())
.render("confirmationStates", UserConfirmationState.values())
.render("query", ctx.getParameter("query", ""))
.render("page", ctx.getParameterAsInteger("page", 1))
.template(getTemplate());
}
/**
* Log access event.
*
* @param user User who's information is accessed.
* @param loggedInUser Logged-in user.
* @param context Context.
*/
private void logAccess(User user, User loggedInUser, Context context) {
String remoteIp = (String) context.getAttribute(IpAddressFilter.REMOTE_IP);
String currentUrl = urlBuilderProvider.get().getCurrentUrl();
userEventService.onUserDataAccess(loggedInUser, user, currentUrl, remoteIp, context.getHeaders());
}
/**
* Log update event.
*
* @param user User who's information is updated.
* @param loggedInUser Logged-in user.
* @param context Context.
*/
private void logUpdate(User user, User loggedInUser, Context context) {
String remoteIp = (String) context.getAttribute(IpAddressFilter.REMOTE_IP);
String currentUrl = urlBuilderProvider.get().getCurrentUrl();
userEventService.onUserDataUpdate(loggedInUser, user, currentUrl, remoteIp, context.getHeaders());
}
}
| |
package org.zstack.identity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.EventCallback;
import org.zstack.core.cloudbus.EventFacade;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.*;
import org.zstack.core.thread.PeriodicTask;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.header.Component;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.identity.*;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.*;
public class Session implements Component {
private static final CLogger logger = Utils.getLogger(Session.class);
@Autowired
private ThreadFacade thdf;
@Autowired
private DatabaseFacade dbf;
@Autowired
private EventFacade evtf;
private Future<Void> expiredSessionCollector;
private static Map<String, SessionInventory> sessions = new ConcurrentHashMap<>();
public static SessionInventory login(String accountUuid, String userUuid) {
if (IdentityGlobalConfig.ENABLE_UNIQUE_SESSION.value(Boolean.class)) {
List<String> currentSessionUuids = Q.New(SessionVO.class)
.select(SessionVO_.uuid)
.eq(SessionVO_.userUuid, userUuid)
.listValues();
IdentityCanonicalEvents.SessionForceLogoutData data = new IdentityCanonicalEvents.SessionForceLogoutData();
data.setAccountUuid(accountUuid);
data.setUserUuid(userUuid);
PluginRegistry pluginRgty = getComponentLoader().getComponent(PluginRegistry.class);
EventFacade evtf = getComponentLoader().getComponent(EventFacade.class);
for (String sessionUuid : currentSessionUuids) {
logout(sessionUuid);
data.setSessionUuid(sessionUuid);
evtf.fire(IdentityCanonicalEvents.SESSION_FORCE_LOGOUT_PATH, data);
for (ForceLogoutSessionExtensionPoint ext : pluginRgty.getExtensionList(ForceLogoutSessionExtensionPoint.class)) {
ext.afterForceLogoutSession(data);
}
}
}
return new SQLBatchWithReturn<SessionInventory>() {
@Transactional(readOnly = true)
private Timestamp getCurrentSqlDate() {
Query query = databaseFacade.getEntityManager().createNativeQuery("select current_timestamp()");
return (Timestamp) query.getSingleResult();
}
@Override
protected SessionInventory scripts() {
if (q(SessionVO.class).eq(SessionVO_.userUuid, userUuid).count() >= IdentityGlobalConfig.MAX_CONCURRENT_SESSION.value(Integer.class)) {
throw new OperationFailureException(err(IdentityErrors.MAX_CONCURRENT_SESSION_EXCEEDED, "Login sessions hit limit of max allowed concurrent login sessions"));
}
SessionVO vo = new SessionVO();
vo.setUuid(Platform.getUuid());
vo.setAccountUuid(accountUuid);
vo.setUserUuid(userUuid);
long expiredTime = getCurrentSqlDate().getTime() + TimeUnit.SECONDS.toMillis(IdentityGlobalConfig.SESSION_TIMEOUT.value(Long.class));
vo.setExpiredDate(new Timestamp(expiredTime));
persist(vo);
reload(vo);
SessionInventory inv = SessionInventory.valueOf(vo);
sessions.put(inv.getUuid(), inv);
return inv;
}
}.execute();
}
public static SessionInventory renewSession(String uuid, Long extendPeriod) {
errorOnTimeout(uuid);
if (extendPeriod == null) {
extendPeriod = IdentityGlobalConfig.SESSION_TIMEOUT.value(Long.class);
}
Long finalExtendPeriod = extendPeriod;
SessionInventory session = new SQLBatchWithReturn<SessionInventory>() {
@Transactional(readOnly = true)
private Timestamp getCurrentSqlDate() {
Query query = databaseFacade.getEntityManager().createNativeQuery("select current_timestamp()");
return (Timestamp) query.getSingleResult();
}
@Override
protected SessionInventory scripts() {
Timestamp expiredDate = new Timestamp(TimeUnit.SECONDS.toMillis(finalExtendPeriod) + getCurrentSqlDate().getTime());
SessionInventory s = getSession(uuid);
s.setExpiredDate(expiredDate);
sql(SessionVO.class).eq(SessionVO_.uuid, uuid).set(SessionVO_.expiredDate, expiredDate).update();
return s;
}
}.execute();
return session;
}
public static void logout(String uuid) {
new SQLBatch() {
@Override
protected void scripts() {
SessionInventory s = sessions.remove(uuid);
if (s == null) {
SessionVO vo = findByUuid(uuid, SessionVO.class);
s = vo == null ? null : SessionInventory.valueOf(vo);
}
if (s == null) {
return;
}
SessionInventory finalS = s;
getComponentLoader().getComponent(PluginRegistry.class)
.getExtensionList(SessionLogoutExtensionPoint.class)
.forEach(ext -> ext.sessionLogout(finalS));
sql(SessionVO.class).eq(SessionVO_.uuid, uuid).hardDelete();
}
}.execute();
}
/**
* Check if session which matches specific uuid is expired.
* Validate the session store in cache first. if it is expired,
* remove it from cache. And then check the expired date in db,
* if it is expired, logout the session (delete db record)
* @param uuid uuid of a session
* @return if session is expired, return an error code, else return null
*/
public static ErrorCode checkSessionExpired(String uuid) {
return new SQLBatchWithReturn<ErrorCode>() {
@Transactional(readOnly = true)
private Timestamp getCurrentSqlDate() {
Query query = databaseFacade.getEntityManager().createNativeQuery("select current_timestamp()");
return (Timestamp) query.getSingleResult();
}
@Override
protected ErrorCode scripts() {
SessionInventory s = getSession(uuid);
if (s == null) {
return err(IdentityErrors.INVALID_SESSION, "Session expired");
}
Timestamp curr = getCurrentSqlDate();
if (curr.after(s.getExpiredDate())) {
if (logger.isTraceEnabled()) {
logger.debug(String.format("session expired[%s < %s] for account[uuid:%s] in cache", curr,
s.getExpiredDate(), s.getAccountUuid()));
}
SessionVO vo = findByUuid(uuid, SessionVO.class);
if (vo != null && curr.before(vo.getExpiredDate())) {
logger.debug(String.format("session not expired[%s < %s] for account[uuid:%s] in DB, just remove it from session cache", curr,
s.getExpiredDate(), s.getAccountUuid()));
sessions.remove(uuid);
return null;
}
logout(s.getUuid());
return err(IdentityErrors.INVALID_SESSION, "Session expired");
}
return null;
}
}.execute();
}
public static void errorOnTimeout(String uuid) {
ErrorCode errorCode = checkSessionExpired(uuid);
if (errorCode == null) {
return;
}
throw new OperationFailureException(errorCode);
}
public static Map<String, SessionInventory> getSessionsCopy() {
return new HashMap<>(sessions);
}
public static SessionInventory getSession(String uuid) {
SessionInventory s = sessions.get(uuid);
if (s == null) {
SessionVO vo = Q.New(SessionVO.class).eq(SessionVO_.uuid, uuid).find();
if (vo == null) {
return null;
}
s = SessionInventory.valueOf(vo);
sessions.put(s.getUuid(), s);
}
return s;
}
@Override
public boolean start() {
setupGlobalConfig();
startCleanUpStaleSessionTask();
setupCanonicalEvents();
return true;
}
private void setupGlobalConfig() {
IdentityGlobalConfig.SESSION_CLEANUP_INTERVAL.installUpdateExtension((oldConfig, newConfig) -> startCleanUpStaleSessionTask());
}
private void startCleanUpStaleSessionTask() {
if (expiredSessionCollector != null) {
expiredSessionCollector.cancel(true);
}
expiredSessionCollector = thdf.submitPeriodicTask(new PeriodicTask() {
@Transactional
private List<String> deleteExpiredSessions() {
String sql = "select s.uuid from SessionVO s where CURRENT_TIMESTAMP >= s.expiredDate";
TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
List<String> uuids = q.getResultList();
if (!uuids.isEmpty()) {
String dsql = "delete from SessionVO s where s.uuid in :uuids";
Query dq = dbf.getEntityManager().createQuery(dsql);
dq.setParameter("uuids", uuids);
dq.executeUpdate();
}
return uuids;
}
@Transactional(readOnly = true)
private Timestamp getCurrentSqlDate() {
Query query = dbf.getEntityManager().createNativeQuery("select current_timestamp()");
return (Timestamp) query.getSingleResult();
}
private void deleteExpiredCachedSessions() {
Timestamp curr = getCurrentSqlDate();
List<String> staleSessionUuidInCache = sessions.entrySet().stream().filter(entry -> curr.after(entry.getValue().getExpiredDate())).map(entry -> entry.getKey()).collect(Collectors.toList());
for (String uuid : staleSessionUuidInCache) {
logger.debug(String.format("found session[uuid:%s] in cache expired, remove it", uuid));
sessions.remove(uuid);
}
}
@Override
public void run() {
List<String> uuids = deleteExpiredSessions();
for (String uuid : uuids) {
logger.debug(String.format("found session[uuid:%s] expired in DB, also remove it from cache", uuid));
sessions.remove(uuid);
}
deleteExpiredCachedSessions();
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return IdentityGlobalConfig.SESSION_CLEANUP_INTERVAL.value(Long.class);
}
@Override
public String getName() {
return "ExpiredSessionCleanupThread";
}
});
}
@Override
public boolean stop() {
if (expiredSessionCollector != null) {
expiredSessionCollector.cancel(true);
}
return true;
}
private void setupCanonicalEvents() {
evtf.on(IdentityCanonicalEvents.ACCOUNT_DELETED_PATH, new EventCallback() {
@Override
public void run(Map tokens, Object data) {
// as a foreign key would clean SessionVO after account deleted, just clean memory sessions here
removeMemorySessionsAccordingToDB(tokens, data);
removeMemorySessionsAccordingToAccountUuid(tokens, data);
}
private void removeMemorySessionsAccordingToDB(Map tokens, Object data) {
IdentityCanonicalEvents.AccountDeletedData d = (IdentityCanonicalEvents.AccountDeletedData) data;
SimpleQuery<SessionVO> q = dbf.createQuery(SessionVO.class);
q.select(SessionVO_.uuid);
q.add(SessionVO_.accountUuid, SimpleQuery.Op.EQ, d.getAccountUuid());
List<String> suuids = q.listValue();
for (String uuid : suuids) {
logout(uuid);
}
if (!suuids.isEmpty()) {
logger.debug(String.format("successfully removed %s sessions for the deleted account[%s]",
suuids.size(),
d.getAccountUuid()));
}
}
private void removeMemorySessionsAccordingToAccountUuid(Map tokens, Object data) {
IdentityCanonicalEvents.AccountDeletedData d = (IdentityCanonicalEvents.AccountDeletedData) data;
List<String> suuids = sessions.entrySet().stream()
.filter(it -> it.getValue().getAccountUuid().equals(d.getAccountUuid()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
for (String uuid : suuids) {
logout(uuid);
}
if (!suuids.isEmpty()) {
logger.debug(String.format("successfully removed %s sessions for the deleted account[%s]",
suuids.size(),
d.getAccountUuid()));
}
}
});
evtf.on(IdentityCanonicalEvents.USER_DELETED_PATH, new EventCallback() {
@Override
public void run(Map tokens, Object data) {
IdentityCanonicalEvents.UserDeletedData d = (IdentityCanonicalEvents.UserDeletedData) data;
SimpleQuery<SessionVO> q = dbf.createQuery(SessionVO.class);
q.select(SessionVO_.uuid);
q.add(SessionVO_.userUuid, SimpleQuery.Op.EQ, d.getUserUuid());
List<String> suuids = q.listValue();
for (String uuid : suuids) {
logout(uuid);
}
if (!suuids.isEmpty()) {
logger.debug(String.format("successfully removed %s sessions for the deleted user[%s]", suuids.size(),
d.getUserUuid()));
}
}
});
}
}
| |
package com.krishagni.catissueplus.core.biospecimen.services.impl;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.administrative.domain.UserGroup;
import com.krishagni.catissueplus.core.biospecimen.ConfigParams;
import com.krishagni.catissueplus.core.biospecimen.domain.Specimen;
import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenList;
import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenListItem;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenListErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenListFactory;
import com.krishagni.catissueplus.core.biospecimen.events.ShareSpecimenListOp;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenInfo;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenListDetail;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenListSummary;
import com.krishagni.catissueplus.core.biospecimen.events.UpdateListSpecimensOp;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.biospecimen.repository.SpecimenListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.SpecimenListsCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.impl.BiospecimenDaoHelper;
import com.krishagni.catissueplus.core.biospecimen.services.SpecimenListService;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr;
import com.krishagni.catissueplus.core.common.access.SiteCpPair;
import com.krishagni.catissueplus.core.common.domain.Notification;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.EntityQueryCriteria;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.events.UserSummary;
import com.krishagni.catissueplus.core.common.service.ObjectAccessor;
import com.krishagni.catissueplus.core.common.service.StarredItemService;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.EmailUtil;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.NotifUtil;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.de.domain.SavedQuery;
import com.krishagni.catissueplus.core.de.events.ExecuteQueryEventOp;
import com.krishagni.catissueplus.core.de.events.QueryDataExportResult;
import com.krishagni.catissueplus.core.de.services.QueryService;
import com.krishagni.catissueplus.core.de.services.SavedQueryErrorCode;
import com.krishagni.catissueplus.core.query.Column;
import com.krishagni.catissueplus.core.query.ListConfig;
import com.krishagni.catissueplus.core.query.ListService;
import com.krishagni.catissueplus.core.query.ListUtil;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import edu.common.dynamicextensions.query.QueryResultData;
import edu.common.dynamicextensions.query.WideRowMode;
public class SpecimenListServiceImpl implements SpecimenListService, InitializingBean, ObjectAccessor {
private static final Pattern DEF_LIST_NAME_PATTERN = Pattern.compile("\\$\\$\\$\\$user_\\d+");
private SpecimenListFactory specimenListFactory;
private DaoFactory daoFactory;
private ListService listSvc;
private com.krishagni.catissueplus.core.de.repository.DaoFactory deDaoFactory;
private QueryService querySvc;
private StarredItemService starredItemSvc;
public SpecimenListFactory getSpecimenListFactory() {
return specimenListFactory;
}
public void setSpecimenListFactory(SpecimenListFactory specimenListFactory) {
this.specimenListFactory = specimenListFactory;
}
public DaoFactory getDaoFactory() {
return daoFactory;
}
public void setDaoFactory(DaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
public void setListSvc(ListService listSvc) {
this.listSvc = listSvc;
}
public void setDeDaoFactory(com.krishagni.catissueplus.core.de.repository.DaoFactory deDaoFactory) {
this.deDaoFactory = deDaoFactory;
}
public void setQuerySvc(QueryService querySvc) {
this.querySvc = querySvc;
}
public void setStarredItemSvc(StarredItemService starredItemSvc) {
this.starredItemSvc = starredItemSvc;
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenListSummary>> getSpecimenLists(RequestEvent<SpecimenListsCriteria> req) {
try {
List<SpecimenListSummary> lists = new ArrayList<>();
SpecimenListsCriteria crit = addSpecimenListsCriteria(req.getPayload());
if (crit.orderByStarred()) {
List<Long> listIds = daoFactory.getStarredItemDao().getItemIds(getObjectName(), AuthUtil.getCurrentUser().getId());
if (!listIds.isEmpty()) {
crit.ids(listIds);
lists = daoFactory.getSpecimenListDao().getSpecimenLists(crit);
crit.ids(Collections.emptyList()).notInIds(listIds);
lists.forEach(l -> l.setStarred(true));
}
}
if (lists.size() < crit.maxResults()) {
crit.maxResults(crit.maxResults() - lists.size());
lists.addAll(daoFactory.getSpecimenListDao().getSpecimenLists(crit));
}
return ResponseEvent.response(lists);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getSpecimenListsCount(RequestEvent<SpecimenListsCriteria> req) {
try {
SpecimenListsCriteria crit = addSpecimenListsCriteria(req.getPayload());
return ResponseEvent.response(daoFactory.getSpecimenListDao().getSpecimenListsCount(crit));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenListDetail> getSpecimenList(RequestEvent<EntityQueryCriteria> req) {
try {
EntityQueryCriteria crit = req.getPayload();
SpecimenList specimenList = getSpecimenList(crit.getId(), crit.getName());
return ResponseEvent.response(SpecimenListDetail.from(specimenList));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenListDetail> createSpecimenList(RequestEvent<SpecimenListDetail> req) {
try {
SpecimenListDetail listDetails = req.getPayload();
List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps();
if (siteCps != null && siteCps.isEmpty()) {
return ResponseEvent.userError(SpecimenListErrorCode.ACCESS_NOT_ALLOWED);
}
UserSummary owner = new UserSummary();
owner.setId(AuthUtil.getCurrentUser().getId());
listDetails.setOwner(owner);
SpecimenList specimenList = specimenListFactory.createSpecimenList(listDetails);
ensureUniqueName(specimenList);
ensureValidSpecimensAndUsers(listDetails, specimenList, siteCps);
daoFactory.getSpecimenListDao().saveOrUpdate(specimenList);
saveListItems(specimenList, listDetails.getSpecimenIds(), true);
notifyUsersOnCreate(specimenList);
return ResponseEvent.response(SpecimenListDetail.from(specimenList));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenListDetail> updateSpecimenList(RequestEvent<SpecimenListDetail> req) {
return updateSpecimenList(req, false);
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenListDetail> patchSpecimenList(RequestEvent<SpecimenListDetail> req) {
return updateSpecimenList(req, true);
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenListDetail> deleteSpecimenList(RequestEvent<Long> req) {
try {
SpecimenList existing = getSpecimenList(req.getPayload(), null);
//
// copy of deleted list
//
SpecimenList deletedSpecimenList = new SpecimenList();
BeanUtils.copyProperties(existing, deletedSpecimenList);
existing.delete();
daoFactory.getSpecimenListDao().saveOrUpdate(existing);
notifyUsersOnDelete(deletedSpecimenList);
return ResponseEvent.response(SpecimenListDetail.from(existing));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenInfo>> getListSpecimens(RequestEvent<SpecimenListCriteria> req) {
try {
SpecimenListCriteria crit = getListSpecimensCriteria(req.getPayload());
List<Specimen> specimens = daoFactory.getSpecimenDao().getSpecimens(crit);
return ResponseEvent.response(SpecimenInfo.from(specimens));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Integer> getListSpecimensCount(RequestEvent<SpecimenListCriteria> req) {
try {
SpecimenListCriteria crit = getListSpecimensCriteria(req.getPayload());
return ResponseEvent.response(daoFactory.getSpecimenDao().getSpecimensCount(crit));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenInfo>> getListSpecimensSortedByRel(RequestEvent<EntityQueryCriteria> req) {
try {
int maxSpmns = ConfigUtil.getInstance().getIntSetting(ConfigParams.MODULE, ConfigParams.REL_SORTING_MAX_SPMNS, 250);
SpecimenList list = getSpecimenList(req.getPayload().getId(), req.getPayload().getName());
int listSize = daoFactory.getSpecimenListDao().getListSpecimensCount(list.getId());
if (listSize > maxSpmns) {
return ResponseEvent.userError(SpecimenListErrorCode.EXCEEDS_REL_SORT_SIZE, list.getName(), maxSpmns);
}
List<Specimen> specimens = getReadAccessSpecimens(list.getId(), listSize);
return ResponseEvent.response(SpecimenInfo.from(SpecimenList.groupByAncestors(specimens)));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Integer> updateListSpecimens(RequestEvent<UpdateListSpecimensOp> req) {
try {
UpdateListSpecimensOp opDetail = req.getPayload();
if (CollectionUtils.isEmpty(opDetail.getSpecimens())) {
return ResponseEvent.response(0);
}
SpecimenList specimenList = getSpecimenList(opDetail.getListId(), null);
ensureValidSpecimens(opDetail.getSpecimens(), null);
switch (opDetail.getOp()) {
case ADD:
if (specimenList.getId() == null) {
daoFactory.getSpecimenListDao().saveOrUpdate(specimenList);
}
saveListItems(specimenList, opDetail.getSpecimens(), false);
break;
case REMOVE:
if (specimenList.getId() != null) {
deleteListItems(specimenList, opDetail.getSpecimens());
}
break;
}
return ResponseEvent.response(opDetail.getSpecimens().size());
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> addChildSpecimens(RequestEvent<Long> req) {
try {
SpecimenList list = getSpecimenList(req.getPayload(), null);
daoFactory.getSpecimenListDao().addChildSpecimens(list.getId(), ConfigUtil.getInstance().isOracle());
return ResponseEvent.response(Boolean.TRUE);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<UserSummary>> shareSpecimenList(RequestEvent<ShareSpecimenListOp> req) {
try {
ShareSpecimenListOp opDetail = req.getPayload();
SpecimenList specimenList = getSpecimenList(opDetail.getListId(), null);
List<User> users = null;
List<Long> userIds = opDetail.getUserIds();
if (userIds == null || userIds.isEmpty()) {
users = new ArrayList<User>();
} else {
ensureValidUsers(userIds);
users = daoFactory.getUserDao().getUsersByIds(userIds);
}
switch (opDetail.getOp()) {
case ADD:
specimenList.addSharedUsers(users);
break;
case UPDATE:
specimenList.updateSharedUsers(users);
break;
case REMOVE:
specimenList.removeSharedUsers(users);
break;
}
daoFactory.getSpecimenListDao().saveOrUpdate(specimenList);
List<UserSummary> result = new ArrayList<UserSummary>();
for (User user : specimenList.getSharedWith()) {
result.add(UserSummary.from(user));
}
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<QueryDataExportResult> exportSpecimenList(RequestEvent<SpecimenListCriteria> req) {
try {
return ResponseEvent.response(exportSpecimenList0(req.getPayload(), null));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
public void afterPropertiesSet()
throws Exception {
listSvc.registerListConfigurator("cart-specimens-list-view", this::getListSpecimensConfig);
}
@Override
public QueryDataExportResult exportSpecimenList(SpecimenListCriteria crit, BiConsumer<QueryResultData, OutputStream> qdConsumer) {
return exportSpecimenList0(crit, qdConsumer);
}
@Override
@PlusTransactional
public boolean toggleStarredSpecimenList(Long listId, boolean starred) {
try {
SpecimenList list = getSpecimenList(listId, null);
if (starred) {
starredItemSvc.save(getObjectName(), list.getId());
} else {
starredItemSvc.delete(getObjectName(), list.getId());
}
return true;
} catch (Exception e) {
if (e instanceof OpenSpecimenException) {
throw e;
}
throw OpenSpecimenException.serverError(e);
}
}
@Override
public String getObjectName() {
return SpecimenList.getEntityName();
}
@Override
public Map<String, Object> resolveUrl(String key, Object value) {
return Collections.singletonMap("listId", Long.parseLong(value.toString()));
}
@Override
public String getAuditTable() {
return "CARTS_NOT_AUDITED";
}
@Override
public void ensureReadAllowed(Long cartId) {
getSpecimenList(cartId, null);
}
private SpecimenListsCriteria addSpecimenListsCriteria(SpecimenListsCriteria crit) {
if (!AuthUtil.isAdmin()) {
crit.userId(AuthUtil.getCurrentUser().getId());
}
return crit;
}
private int saveListItems(SpecimenList list, List<Long> specimenIds, boolean newList) {
if (CollectionUtils.isEmpty(specimenIds)) {
return 0;
}
if (!newList) {
//
// we could have obtained only those IDs not in specimen list
// but then we will be loosing order in which the specimen labels were inputted
//
List<Long> idsInList = daoFactory.getSpecimenListDao().getSpecimenIdsInList(list.getId(), specimenIds);
specimenIds.removeAll(idsInList);
if (specimenIds.isEmpty()) {
return 0;
}
}
List<SpecimenListItem> items = specimenIds.stream()
.map(specimenId -> {
Specimen spmn = new Specimen();
spmn.setId(specimenId);
SpecimenListItem item = new SpecimenListItem();
item.setList(list);
item.setSpecimen(spmn);
return item;
}).collect(Collectors.toList());
daoFactory.getSpecimenListDao().saveListItems(items);
return items.size();
}
private int deleteListItems(SpecimenList list, List<Long> specimenIds) {
return daoFactory.getSpecimenListDao().deleteListItems(list.getId(), specimenIds);
}
private ResponseEvent<SpecimenListDetail> updateSpecimenList(RequestEvent<SpecimenListDetail> req, boolean partial) {
try {
SpecimenListDetail listDetails = req.getPayload();
SpecimenList existing = getSpecimenList(listDetails.getId(), null);
UserSummary owner = new UserSummary();
owner.setId(existing.getOwner().getId());
listDetails.setOwner(owner);
SpecimenList specimenList = null;
if (partial) {
specimenList = specimenListFactory.createSpecimenList(existing, listDetails);
} else {
specimenList = specimenListFactory.createSpecimenList(listDetails);
}
ensureUniqueName(existing, specimenList);
ensureValidSpecimensAndUsers(listDetails, specimenList, null);
Collection<User> addedUsers = CollectionUtils.subtract(specimenList.getAllSharedUsers(), existing.getAllSharedUsers());
Collection<User> removedUsers = CollectionUtils.subtract(existing.getAllSharedUsers(), specimenList.getAllSharedUsers());
existing.update(specimenList);
daoFactory.getSpecimenListDao().saveOrUpdate(existing);
saveListItems(existing, listDetails.getSpecimenIds(), false);
notifyUsersOnUpdate(existing, addedUsers, removedUsers);
return ResponseEvent.response(SpecimenListDetail.from(existing));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
private SpecimenList getSpecimenList(Long listId, String listName) {
SpecimenList list = null;
Object key = null;
if (listId != null) {
if (listId != 0) {
list = daoFactory.getSpecimenListDao().getSpecimenList(listId);
} else {
list = getDefaultList(AuthUtil.getCurrentUser());
}
key = listId;
} else if (StringUtils.isNotBlank(listName)) {
list = daoFactory.getSpecimenListDao().getSpecimenListByName(listName);
key = listName;
}
if (list == null) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.NOT_FOUND, key);
}
Long userId = AuthUtil.getCurrentUser().getId();
if (!AuthUtil.isAdmin() && !list.canUserAccess(userId)) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.ACCESS_NOT_ALLOWED);
}
return list;
}
private List<Long> getReadAccessSpecimenIds(List<Long> specimenIds, List<SiteCpPair> siteCps) {
if (siteCps == null) {
siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps();
}
if (siteCps != null && siteCps.isEmpty()) {
return Collections.emptyList();
}
SpecimenListCriteria crit = new SpecimenListCriteria().ids(specimenIds).siteCps(siteCps);
return daoFactory.getSpecimenDao().getSpecimenIds(crit);
}
private List<Specimen> getReadAccessSpecimens(Long listId, int size) {
List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps();
if (siteCps != null && siteCps.isEmpty()) {
return Collections.emptyList();
}
SpecimenListCriteria crit = new SpecimenListCriteria()
.specimenListId(listId).siteCps(siteCps)
.maxResults(size).limitItems(true);
return daoFactory.getSpecimenDao().getSpecimens(crit);
}
private SpecimenListCriteria getListSpecimensCriteria(SpecimenListCriteria crit) {
//
// specimen list is retrieved to ensure user has access to the list
//
getSpecimenList(crit.specimenListId(), null);
List<SiteCpPair> siteCpPairs = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps();
if (siteCpPairs != null && siteCpPairs.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
return crit.siteCps(siteCpPairs);
}
private void ensureValidSpecimensAndUsers(SpecimenListDetail details, SpecimenList specimenList, List<SiteCpPair> siteCpPairs) {
if (details.isAttrModified("specimenIds")) {
ensureValidSpecimens(details, siteCpPairs);
}
if (details.isAttrModified("sharedWith")){
ensureValidUsers(specimenList);
}
if (details.isAttrModified("sharedWithGroups")) {
ensureValidGroups(specimenList);
}
}
private void ensureValidSpecimens(SpecimenListDetail details, List<SiteCpPair> siteCpPairs) {
if (CollectionUtils.isEmpty(details.getSpecimenIds())) {
return;
}
ensureValidSpecimens(details.getSpecimenIds(), siteCpPairs);
}
private void ensureValidSpecimens(List<Long> specimenIds, List<SiteCpPair> siteCpPairs) {
List<Long> dbSpmnIds = getReadAccessSpecimenIds(specimenIds, siteCpPairs);
if (dbSpmnIds.size() != specimenIds.size()) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.INVALID_SPECIMENS);
}
}
private void ensureValidUsers(SpecimenList specimenList) {
if (CollectionUtils.isEmpty(specimenList.getSharedWith()) || AuthUtil.isAdmin()) {
return;
}
List<Long> sharedUsers = specimenList.getSharedWith().stream()
.filter(user -> !user.equals(specimenList.getOwner()))
.map(User::getId)
.collect(Collectors.toList());
ensureValidUsers(sharedUsers);
}
private void ensureValidGroups(SpecimenList specimenList) {
if (CollectionUtils.isEmpty(specimenList.getSharedWithGroups()) || AuthUtil.isAdmin()) {
return;
}
for (UserGroup group : specimenList.getSharedWithGroups()) {
if (!group.getInstitute().equals(AuthUtil.getCurrentUserInstitute())) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.INVALID_GROUPS_LIST);
}
}
}
private void ensureValidUsers(List<Long> userIds) {
Long instituteId = null;
if (!AuthUtil.isAdmin()) {
User user = daoFactory.getUserDao().getById(AuthUtil.getCurrentUser().getId());
instituteId = user.getInstitute().getId();
}
List<User> users = daoFactory.getUserDao().getUsersByIdsAndInstitute(userIds, instituteId);
if (userIds.size() != users.size()) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.INVALID_USERS_LIST);
}
}
private void ensureUniqueName(SpecimenList existingList, SpecimenList newList) {
if (existingList != null && existingList.getName().equals(newList.getName())) {
return;
}
ensureUniqueName(newList);
}
private void ensureUniqueName(SpecimenList newList) {
String newListName = newList.getName();
SpecimenList list = daoFactory.getSpecimenListDao().getSpecimenListByName(newListName);
if (list != null) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.DUP_NAME, newListName);
}
if (DEF_LIST_NAME_PATTERN.matcher(newListName).matches()) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.DUP_NAME, newListName);
}
}
private SpecimenList createDefaultList(User user) {
return specimenListFactory.createDefaultSpecimenList(user);
}
private SpecimenList getDefaultList(User user) {
SpecimenList specimenList = daoFactory.getSpecimenListDao().getDefaultSpecimenList(user.getId());
if (specimenList == null) {
specimenList = createDefaultList(user);
}
return specimenList;
}
private QueryDataExportResult exportSpecimenList0(SpecimenListCriteria crit, BiConsumer<QueryResultData, OutputStream> qdConsumer) {
final SpecimenList list = getSpecimenList(crit.specimenListId(), null);
Integer queryId = ConfigUtil.getInstance().getIntSetting("common", "cart_specimens_rpt_query", -1);
if (queryId == -1) {
return null;
}
SavedQuery query = deDaoFactory.getSavedQueryDao().getQuery(queryId.longValue());
if (query == null) {
throw OpenSpecimenException.userError(SavedQueryErrorCode.NOT_FOUND, queryId);
}
String restriction = "Specimen.specimenCarts.name = \"" + list.getName() + "\"";
if (CollectionUtils.isNotEmpty(crit.ids())) {
restriction += " and Specimen.id in (" + StringUtils.join(crit.ids(), ",") + ")";
} else if (CollectionUtils.isNotEmpty(crit.labels())) {
restriction += " and Specimen.label in (" + StringUtils.join(crit.labels(), ",") + ")";
}
List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps();
boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn();
String siteCpRestriction = BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(siteCps, useMrnSites);
if (StringUtils.isNotBlank(siteCpRestriction)) {
restriction += " and " + siteCpRestriction;
}
ExecuteQueryEventOp op = new ExecuteQueryEventOp();
op.setDrivingForm("Participant");
op.setAql(query.getAql(restriction));
op.setWideRowMode(WideRowMode.DEEP.name());
op.setRunType("Export");
if (qdConsumer != null) {
return querySvc.exportQueryData(op, qdConsumer);
}
return querySvc.exportQueryData(op, new QueryService.ExportProcessor() {
@Override
public String filename() {
return "cart_" + list.getId() + "_" + UUID.randomUUID().toString();
}
@Override
public void headers(OutputStream out) {
Map<String, String> headers = new LinkedHashMap<String, String>() {{
put(msg(LIST_NAME), list.isDefaultList() ? msg("specimen_list_default_list", list.getOwner().formattedName()) : list.getName());
put(msg(LIST_DESC), StringUtils.isNotBlank(list.getDescription()) ? list.getDescription() : msg("common_not_specified"));
}};
Utility.writeKeyValuesToCsv(out, headers);
}
});
}
private void notifyUsersOnCreate(SpecimenList specimenList) {
notifyUsersOnListOp(specimenList, specimenList.getAllSharedUsers(), "ADD");
}
private void notifyUsersOnUpdate(SpecimenList existing, Collection<User> addedUsers, Collection<User> removedUsers) {
notifyUsersOnListOp(existing, addedUsers, "ADD");
notifyUsersOnListOp(existing, removedUsers, "REMOVE");
}
private void notifyUsersOnDelete(SpecimenList specimenList) {
notifyUsersOnListOp(specimenList, specimenList.getAllSharedUsers(), "DELETE");
}
private void notifyUsersOnListOp(SpecimenList specimenList, Collection<User> notifyUsers, String op) {
if (CollectionUtils.isEmpty(notifyUsers)) {
return;
}
String notifMsg = getNotifMsg(specimenList, op);
// Send email notification
Map<String, Object> emailProps = new HashMap<>();
emailProps.put("$subject", new String[] { notifMsg });
emailProps.put("emailText", notifMsg);
emailProps.put("specimenList", specimenList);
emailProps.put("currentUser", AuthUtil.getCurrentUser());
emailProps.put("ccAdmin", false);
emailProps.put("op", op);
Set<User> rcpts = new HashSet<>(notifyUsers);
for (User rcpt : rcpts) {
emailProps.put("rcpt", rcpt);
EmailUtil.getInstance().sendEmail(SPECIMEN_LIST_SHARED_TMPL, new String[] { rcpt.getEmailAddress() }, null, emailProps);
}
// UI notification
Notification notif = new Notification();
notif.setEntityType(SpecimenList.getEntityName());
notif.setEntityId(specimenList.getId());
notif.setOperation("UPDATE");
notif.setCreatedBy(AuthUtil.getCurrentUser());
notif.setCreationTime(Calendar.getInstance().getTime());
notif.setMessage(notifMsg);
NotifUtil.getInstance().notify(notif, Collections.singletonMap("specimen-list", rcpts));
}
private String getNotifMsg(SpecimenList specimenList, String op) {
String msgKey = "specimen_list_user_notif_" + op.toLowerCase();
return MessageUtil.getInstance().getMessage(msgKey, new String[] { specimenList.getName() });
}
private ListConfig getListSpecimensConfig(Map<String, Object> listReq) {
Number listId = (Number) listReq.get("listId");
if (listId == null) {
listId = (Number) listReq.get("objectId");
}
SpecimenList list = getSpecimenList(listId != null ? listId.longValue() : null, null);
ListConfig cfg = ListUtil.getSpecimensListConfig("cart-specimens-list-view", true);
ListUtil.addHiddenFieldsOfSpecimen(cfg);
if (cfg == null) {
return null;
}
List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps();
if (siteCps != null && siteCps.isEmpty()) {
throw OpenSpecimenException.userError(SpecimenListErrorCode.ACCESS_NOT_ALLOWED);
}
String restriction = "Specimen.specimenCarts.name = \"" + list.getName() + "\"";
boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn();
String cpSitesCond = BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(siteCps, useMrnSites);
if (StringUtils.isNotBlank(cpSitesCond)) {
restriction += " and " + cpSitesCond;
}
Column orderBy = new Column();
orderBy.setExpr("Specimen.specimenCarts.itemId");
orderBy.setDirection("asc");
cfg.setDrivingForm("Specimen");
cfg.setRestriction(restriction);
cfg.setDistinct(true);
cfg.setOrderBy(Collections.singletonList(orderBy));
return ListUtil.setListLimit(cfg, listReq);
}
private String msg(String code, Object ... params) {
return MessageUtil.getInstance().getMessage(code, params);
}
private static final String LIST_NAME = "specimen_list_name";
private static final String LIST_DESC = "specimen_list_description";
private static final String SPECIMEN_LIST_SHARED_TMPL = "specimen_list_shared";
}
| |
/* Copyright 2018 The TensorFlow 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.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.sparse;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TInt64;
import org.tensorflow.types.family.TNumber;
/**
* Performs sparse-output bin counting for a tf.tensor input.
* Counts the number of times each value occurs in the input.
*
* @param <U> data type for {@code output_values} output
*/
@OpMetadata(
opType = DenseCountSparseOutput.OP_NAME,
inputsClass = DenseCountSparseOutput.Inputs.class
)
public final class DenseCountSparseOutput<U extends TNumber> extends RawOp {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "DenseCountSparseOutput";
private Output<TInt64> outputIndices;
private Output<U> outputValues;
private Output<TInt64> outputDenseShape;
public DenseCountSparseOutput(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
outputIndices = operation.output(outputIdx++);
outputValues = operation.output(outputIdx++);
outputDenseShape = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new DenseCountSparseOutput operation.
*
* @param scope current scope
* @param values Tensor containing data to count.
* @param weights A Tensor of the same shape as indices containing per-index weight values. May
* also be the empty tensor if no weights are used.
* @param binaryOutput Whether to output the number of occurrences of each value or 1.
* @param options carries optional attribute values
* @param <U> data type for {@code DenseCountSparseOutput} output and operands
* @return a new instance of DenseCountSparseOutput
*/
@Endpoint(
describeByClass = true
)
public static <U extends TNumber> DenseCountSparseOutput<U> create(Scope scope,
Operand<? extends TNumber> values, Operand<U> weights, Boolean binaryOutput,
Options... options) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "DenseCountSparseOutput");
opBuilder.addInput(values.asOutput());
opBuilder.addInput(weights.asOutput());
opBuilder.setAttr("binary_output", binaryOutput);
if (options != null) {
for (Options opts : options) {
if (opts.minlength != null) {
opBuilder.setAttr("minlength", opts.minlength);
}
if (opts.maxlength != null) {
opBuilder.setAttr("maxlength", opts.maxlength);
}
}
}
return new DenseCountSparseOutput<>(opBuilder.build());
}
/**
* Sets the minlength option.
*
* @param minlength Minimum value to count. Can be set to -1 for no minimum.
* @return this Options instance.
*/
public static Options minlength(Long minlength) {
return new Options().minlength(minlength);
}
/**
* Sets the maxlength option.
*
* @param maxlength Maximum value to count. Can be set to -1 for no maximum.
* @return this Options instance.
*/
public static Options maxlength(Long maxlength) {
return new Options().maxlength(maxlength);
}
/**
* Gets outputIndices.
* Indices tensor for the resulting sparse tensor object.
* @return outputIndices.
*/
public Output<TInt64> outputIndices() {
return outputIndices;
}
/**
* Gets outputValues.
* Values tensor for the resulting sparse tensor object.
* @return outputValues.
*/
public Output<U> outputValues() {
return outputValues;
}
/**
* Gets outputDenseShape.
* Shape tensor for the resulting sparse tensor object.
* @return outputDenseShape.
*/
public Output<TInt64> outputDenseShape() {
return outputDenseShape;
}
/**
* Optional attributes for {@link org.tensorflow.op.sparse.DenseCountSparseOutput}
*/
public static class Options {
private Long minlength;
private Long maxlength;
private Options() {
}
/**
* Sets the minlength option.
*
* @param minlength Minimum value to count. Can be set to -1 for no minimum.
* @return this Options instance.
*/
public Options minlength(Long minlength) {
this.minlength = minlength;
return this;
}
/**
* Sets the maxlength option.
*
* @param maxlength Maximum value to count. Can be set to -1 for no maximum.
* @return this Options instance.
*/
public Options maxlength(Long maxlength) {
this.maxlength = maxlength;
return this;
}
}
@OpInputsMetadata(
outputsClass = DenseCountSparseOutput.class
)
public static class Inputs<U extends TNumber> extends RawOpInputs<DenseCountSparseOutput<U>> {
/**
* Tensor containing data to count.
*/
public final Operand<? extends TNumber> values;
/**
* A Tensor of the same shape as indices containing per-index weight values. May
* also be the empty tensor if no weights are used.
*/
public final Operand<U> weights;
/**
* Dtype of the input values tensor.
*/
public final DataType T;
/**
* Minimum value to count. Can be set to -1 for no minimum.
*/
public final long minlength;
/**
* Maximum value to count. Can be set to -1 for no maximum.
*/
public final long maxlength;
/**
* Whether to output the number of occurrences of each value or 1.
*/
public final boolean binaryOutput;
/**
* Dtype of the output values tensor.
*/
public final DataType outputType;
public Inputs(GraphOperation op) {
super(new DenseCountSparseOutput<>(op), op, Arrays.asList("T", "minlength", "maxlength", "binary_output", "output_type"));
int inputIndex = 0;
values = (Operand<? extends TNumber>) op.input(inputIndex++);
weights = (Operand<U>) op.input(inputIndex++);
T = op.attributes().getAttrType("T");
minlength = op.attributes().getAttrInt("minlength");
maxlength = op.attributes().getAttrInt("maxlength");
binaryOutput = op.attributes().getAttrBool("binary_output");
outputType = op.attributes().getAttrType("output_type");
}
}
}
| |
/*
* 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.serialization.record;
import org.apache.nifi.serialization.SimpleRecordSchema;
import org.apache.nifi.serialization.record.type.ChoiceDataType;
import org.apache.nifi.serialization.record.type.RecordDataType;
import org.apache.nifi.serialization.record.util.DataTypeUtils;
import org.apache.nifi.serialization.record.util.IllegalTypeConversionException;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.DoubleAdder;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class TestDataTypeUtils {
/**
* This is a unit test to verify conversion java Date objects to Timestamps. Support for this was
* required in order to help the MongoDB packages handle date/time logical types in the Record API.
*/
@Test
public void testDateToTimestamp() {
java.util.Date date = new java.util.Date();
Timestamp ts = DataTypeUtils.toTimestamp(date, null, null);
assertNotNull(ts);
assertEquals("Times didn't match", ts.getTime(), date.getTime());
java.sql.Date sDate = new java.sql.Date(date.getTime());
ts = DataTypeUtils.toTimestamp(date, null, null);
assertNotNull(ts);
assertEquals("Times didn't match", ts.getTime(), sDate.getTime());
}
/*
* This was a bug in NiFi 1.8 where converting from a Timestamp to a Date with the record path API
* would throw an exception.
*/
@Test
public void testTimestampToDate() {
java.util.Date date = new java.util.Date();
Timestamp ts = DataTypeUtils.toTimestamp(date, null, null);
assertNotNull(ts);
java.sql.Date output = DataTypeUtils.toDate(ts, null, null);
assertNotNull(output);
assertEquals("Timestamps didn't match", output.getTime(), ts.getTime());
}
@Test
public void testConvertRecordMapToJavaMap() {
assertNull(DataTypeUtils.convertRecordMapToJavaMap(null, null));
assertNull(DataTypeUtils.convertRecordMapToJavaMap(null, RecordFieldType.MAP.getDataType()));
Map<String,Object> resultMap = DataTypeUtils.convertRecordMapToJavaMap(new HashMap<>(), RecordFieldType.MAP.getDataType());
assertNotNull(resultMap);
assertTrue(resultMap.isEmpty());
int[] intArray = {3,2,1};
Map<String,Object> inputMap = new HashMap<String,Object>() {{
put("field1", "hello");
put("field2", 1);
put("field3", intArray);
}};
resultMap = DataTypeUtils.convertRecordMapToJavaMap(inputMap, RecordFieldType.STRING.getDataType());
assertNotNull(resultMap);
assertFalse(resultMap.isEmpty());
assertEquals("hello", resultMap.get("field1"));
assertEquals(1, resultMap.get("field2"));
assertTrue(resultMap.get("field3") instanceof int[]);
assertNull(resultMap.get("field4"));
}
@Test
public void testConvertRecordArrayToJavaArray() {
assertNull(DataTypeUtils.convertRecordArrayToJavaArray(null, null));
assertNull(DataTypeUtils.convertRecordArrayToJavaArray(null, RecordFieldType.STRING.getDataType()));
String[] stringArray = {"Hello", "World!"};
Object[] resultArray = DataTypeUtils.convertRecordArrayToJavaArray(stringArray, RecordFieldType.STRING.getDataType());
assertNotNull(resultArray);
for(Object o : resultArray) {
assertTrue(o instanceof String);
}
}
@Test
public void testConvertArrayOfRecordsToJavaArray() {
final List<RecordField> fields = new ArrayList<>();
fields.add(new RecordField("stringField", RecordFieldType.STRING.getDataType()));
fields.add(new RecordField("intField", RecordFieldType.INT.getDataType()));
final RecordSchema schema = new SimpleRecordSchema(fields);
final Map<String, Object> values1 = new HashMap<>();
values1.put("stringField", "hello");
values1.put("intField", 5);
final Record inputRecord1 = new MapRecord(schema, values1);
final Map<String, Object> values2 = new HashMap<>();
values2.put("stringField", "world");
values2.put("intField", 50);
final Record inputRecord2 = new MapRecord(schema, values2);
Object[] recordArray = {inputRecord1, inputRecord2};
Object resultObj = DataTypeUtils.convertRecordFieldtoObject(recordArray, RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.RECORD.getRecordDataType(schema)));
assertNotNull(resultObj);
assertTrue(resultObj instanceof Object[]);
Object[] resultArray = (Object[]) resultObj;
for(Object o : resultArray) {
assertTrue(o instanceof Map);
}
}
@Test
@SuppressWarnings("unchecked")
public void testConvertRecordFieldToObject() {
assertNull(DataTypeUtils.convertRecordFieldtoObject(null, null));
assertNull(DataTypeUtils.convertRecordFieldtoObject(null, RecordFieldType.MAP.getDataType()));
final List<RecordField> fields = new ArrayList<>();
fields.add(new RecordField("defaultOfHello", RecordFieldType.STRING.getDataType(), "hello"));
fields.add(new RecordField("noDefault", RecordFieldType.CHOICE.getChoiceDataType(RecordFieldType.STRING.getDataType())));
fields.add(new RecordField("intField", RecordFieldType.INT.getDataType()));
fields.add(new RecordField("intArray", RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.INT.getDataType())));
// Map of Records with Arrays
List<RecordField> nestedRecordFields = new ArrayList<>();
nestedRecordFields.add(new RecordField("a", RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.INT.getDataType())));
nestedRecordFields.add(new RecordField("b", RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.STRING.getDataType())));
RecordSchema nestedRecordSchema = new SimpleRecordSchema(nestedRecordFields);
fields.add(new RecordField("complex", RecordFieldType.MAP.getMapDataType(RecordFieldType.RECORD.getRecordDataType(nestedRecordSchema))));
final RecordSchema schema = new SimpleRecordSchema(fields);
final Map<String, Object> values = new HashMap<>();
values.put("noDefault", "world");
values.put("intField", 5);
values.put("intArray", new Integer[] {3,2,1});
final Map<String, Object> complexValues = new HashMap<>();
final Map<String, Object> complexValueRecord1 = new HashMap<>();
complexValueRecord1.put("a",new Integer[] {3,2,1});
complexValueRecord1.put("b",new Integer[] {5,4,3});
final Map<String, Object> complexValueRecord2 = new HashMap<>();
complexValueRecord2.put("a",new String[] {"hello","world!"});
complexValueRecord2.put("b",new String[] {"5","4","3"});
complexValues.put("complex1", DataTypeUtils.toRecord(complexValueRecord1, nestedRecordSchema, "complex1", StandardCharsets.UTF_8));
complexValues.put("complex2", DataTypeUtils.toRecord(complexValueRecord2, nestedRecordSchema, "complex2", StandardCharsets.UTF_8));
values.put("complex", complexValues);
final Record inputRecord = new MapRecord(schema, values);
Object o = DataTypeUtils.convertRecordFieldtoObject(inputRecord, RecordFieldType.RECORD.getRecordDataType(schema));
assertTrue(o instanceof Map);
Map<String,Object> outputMap = (Map<String,Object>) o;
assertEquals("hello", outputMap.get("defaultOfHello"));
assertEquals("world", outputMap.get("noDefault"));
o = outputMap.get("intField");
assertEquals(5,o);
o = outputMap.get("intArray");
assertTrue(o instanceof Integer[]);
Integer[] intArray = (Integer[])o;
assertEquals(3, intArray.length);
assertEquals((Integer)3, intArray[0]);
o = outputMap.get("complex");
assertTrue(o instanceof Map);
Map<String,Object> nestedOutputMap = (Map<String,Object>)o;
o = nestedOutputMap.get("complex1");
assertTrue(o instanceof Map);
Map<String,Object> complex1 = (Map<String,Object>)o;
o = complex1.get("a");
assertTrue(o instanceof Integer[]);
assertEquals((Integer)2, ((Integer[])o)[1]);
o = complex1.get("b");
assertTrue(o instanceof Integer[]);
assertEquals((Integer)3, ((Integer[])o)[2]);
o = nestedOutputMap.get("complex2");
assertTrue(o instanceof Map);
Map<String,Object> complex2 = (Map<String,Object>)o;
o = complex2.get("a");
assertTrue(o instanceof String[]);
assertEquals("hello", ((String[])o)[0]);
o = complex2.get("b");
assertTrue(o instanceof String[]);
assertEquals("4", ((String[])o)[1]);
}
@Test
public void testToArray() {
final List<String> list = Arrays.asList("Seven", "Eleven", "Thirteen");
final Object[] array = DataTypeUtils.toArray(list, "list", null);
assertEquals(list.size(), array.length);
for (int i = 0; i < list.size(); i++) {
assertEquals(list.get(i), array[i]);
}
}
@Test
public void testStringToBytes() {
Object bytes = DataTypeUtils.convertType("Hello", RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.BYTE.getDataType()),null, StandardCharsets.UTF_8);
assertTrue(bytes instanceof Byte[]);
assertNotNull(bytes);
Byte[] b = (Byte[]) bytes;
assertEquals("Conversion from String to byte[] failed", (long) 72, (long) b[0] ); // H
assertEquals("Conversion from String to byte[] failed", (long) 101, (long) b[1] ); // e
assertEquals("Conversion from String to byte[] failed", (long) 108, (long) b[2] ); // l
assertEquals("Conversion from String to byte[] failed", (long) 108, (long) b[3] ); // l
assertEquals("Conversion from String to byte[] failed", (long) 111, (long) b[4] ); // o
}
@Test
public void testBytesToString() {
Object s = DataTypeUtils.convertType("Hello".getBytes(StandardCharsets.UTF_16), RecordFieldType.STRING.getDataType(),null, StandardCharsets.UTF_16);
assertNotNull(s);
assertTrue(s instanceof String);
assertEquals("Conversion from byte[] to String failed", "Hello", s);
}
@Test
public void testBytesToBytes() {
Object b = DataTypeUtils.convertType("Hello".getBytes(StandardCharsets.UTF_16), RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.BYTE.getDataType()),null, StandardCharsets.UTF_16);
assertNotNull(b);
assertTrue(b instanceof Byte[]);
assertEquals("Conversion from byte[] to String failed at char 0", (Object) "Hello".getBytes(StandardCharsets.UTF_16)[0], ((Byte[]) b)[0]);
}
@Test
public void testConvertToBigDecimalWhenInputIsValid() {
// given
final BigDecimal expectedValue = BigDecimal.valueOf(12L);
// when & then
whenExpectingValidBigDecimalConversion(expectedValue, BigDecimal.valueOf(12L));
whenExpectingValidBigDecimalConversion(expectedValue, (byte) 12);
whenExpectingValidBigDecimalConversion(expectedValue, (short) 12);
whenExpectingValidBigDecimalConversion(expectedValue, 12);
whenExpectingValidBigDecimalConversion(expectedValue, 12L);
whenExpectingValidBigDecimalConversion(expectedValue, BigInteger.valueOf(12L));
whenExpectingValidBigDecimalConversion(expectedValue, 12F);
whenExpectingValidBigDecimalConversion(expectedValue, 12.000F);
whenExpectingValidBigDecimalConversion(expectedValue, 12D);
whenExpectingValidBigDecimalConversion(expectedValue, 12.000D);
whenExpectingValidBigDecimalConversion(expectedValue, "12");
whenExpectingValidBigDecimalConversion(expectedValue, "12.000");
}
@Test
public void testConvertToBigDecimalWhenNullInput() {
assertNull(DataTypeUtils.convertType(null, RecordFieldType.DECIMAL.getDecimalDataType(30, 10), null, StandardCharsets.UTF_8));
}
@Test(expected = IllegalTypeConversionException.class)
public void testConvertToBigDecimalWhenInputStringIsInvalid() {
DataTypeUtils.convertType("test", RecordFieldType.DECIMAL.getDecimalDataType(30, 10), null, StandardCharsets.UTF_8);
}
@Test(expected = IllegalTypeConversionException.class)
public void testConvertToBigDecimalWhenUnsupportedType() {
DataTypeUtils.convertType(new ArrayList<Double>(), RecordFieldType.DECIMAL.getDecimalDataType(30, 10), null, StandardCharsets.UTF_8);
}
@Test(expected = IllegalTypeConversionException.class)
public void testConvertToBigDecimalWhenUnsupportedNumberType() {
DataTypeUtils.convertType(new DoubleAdder(), RecordFieldType.DECIMAL.getDecimalDataType(30, 10), null, StandardCharsets.UTF_8);
}
@Test
public void testCompatibleDataTypeBigDecimal() {
// given
final DataType dataType = RecordFieldType.DECIMAL.getDecimalDataType(30, 10);
// when & then
assertTrue(DataTypeUtils.isCompatibleDataType(new BigDecimal("1.2345678901234567890"), dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(new BigInteger("12345678901234567890"), dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(1234567890123456789L, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(1, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType((byte) 1, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType((short) 1, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType("1.2345678901234567890", dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(3.1F, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(3.0D, dataType));
assertFalse(DataTypeUtils.isCompatibleDataType("1234567XYZ", dataType));
assertFalse(DataTypeUtils.isCompatibleDataType(new Long[]{1L, 2L}, dataType));
}
@Test
public void testInferDataTypeWithBigDecimal() {
assertEquals(RecordFieldType.DECIMAL.getDecimalDataType(3, 1), DataTypeUtils.inferDataType(BigDecimal.valueOf(12.3D), null));
}
@Test
public void testIsBigDecimalTypeCompatible() {
assertTrue(DataTypeUtils.isDecimalTypeCompatible((byte) 13));
assertTrue(DataTypeUtils.isDecimalTypeCompatible((short) 13));
assertTrue(DataTypeUtils.isDecimalTypeCompatible(12));
assertTrue(DataTypeUtils.isDecimalTypeCompatible(12L));
assertTrue(DataTypeUtils.isDecimalTypeCompatible(BigInteger.valueOf(12L)));
assertTrue(DataTypeUtils.isDecimalTypeCompatible(12.123F));
assertTrue(DataTypeUtils.isDecimalTypeCompatible(12.123D));
assertTrue(DataTypeUtils.isDecimalTypeCompatible(BigDecimal.valueOf(12.123D)));
assertTrue(DataTypeUtils.isDecimalTypeCompatible("123"));
assertFalse(DataTypeUtils.isDecimalTypeCompatible(null));
assertFalse(DataTypeUtils.isDecimalTypeCompatible("test"));
assertFalse(DataTypeUtils.isDecimalTypeCompatible(new ArrayList<>()));
// Decimal handling does not support NaN and Infinity as the underlying BigDecimal is unable to parse
assertFalse(DataTypeUtils.isDecimalTypeCompatible("NaN"));
assertFalse(DataTypeUtils.isDecimalTypeCompatible("Infinity"));
}
@Test
public void testGetSQLTypeValueWithBigDecimal() {
assertEquals(Types.NUMERIC, DataTypeUtils.getSQLTypeValue(RecordFieldType.DECIMAL.getDecimalDataType(30, 10)));
}
@Test
public void testChooseDataTypeWhenExpectedIsBigDecimal() {
// GIVEN
final List<DataType> dataTypes = Arrays.asList(
RecordFieldType.FLOAT.getDataType(),
RecordFieldType.DOUBLE.getDataType(),
RecordFieldType.DECIMAL.getDecimalDataType(2, 1),
RecordFieldType.DECIMAL.getDecimalDataType(20, 10)
);
final Object value = new BigDecimal("1.2");
final DataType expected = RecordFieldType.DECIMAL.getDecimalDataType(2, 1);
// WHEN
// THEN
testChooseDataTypeAlsoReverseTypes(value, dataTypes, expected);
}
@Test
public void testFloatingPointCompatibility() {
final String[] prefixes = new String[] {"", "-", "+"};
final String[] exponents = new String[] {"e0", "e1", "e-1", "E0", "E1", "E-1"};
final String[] decimals = new String[] {"", ".0", ".1", "."};
for (final String prefix : prefixes) {
for (final String decimal : decimals) {
for (final String exp : exponents) {
String toTest = prefix + "100" + decimal + exp;
assertTrue(toTest + " not valid float", DataTypeUtils.isFloatTypeCompatible(toTest));
assertTrue(toTest + " not valid double", DataTypeUtils.isDoubleTypeCompatible(toTest));
Double.parseDouble(toTest); // ensure we can actually parse it
Float.parseFloat(toTest);
if (decimal.length() > 1) {
toTest = prefix + decimal + exp;
assertTrue(toTest + " not valid float", DataTypeUtils.isFloatTypeCompatible(toTest));
assertTrue(toTest + " not valid double", DataTypeUtils.isDoubleTypeCompatible(toTest));
Double.parseDouble(toTest); // ensure we can actually parse it
Float.parseFloat(toTest);
}
}
}
}
}
@Test
public void testIsCompatibleDataTypeMap() {
Map<String,Object> testMap = new HashMap<>();
testMap.put("Hello", "World");
assertTrue(DataTypeUtils.isCompatibleDataType(testMap, RecordFieldType.RECORD.getDataType()));
}
@Test
public void testIsCompatibleDataTypeBigint() {
final DataType dataType = RecordFieldType.BIGINT.getDataType();
assertTrue(DataTypeUtils.isCompatibleDataType(new BigInteger("12345678901234567890"), dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(1234567890123456789L, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(1, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType((short) 1, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType("12345678901234567890", dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(3.1f, dataType));
assertTrue(DataTypeUtils.isCompatibleDataType(3.0, dataType));
assertFalse(DataTypeUtils.isCompatibleDataType("1234567XYZ", dataType));
assertFalse(DataTypeUtils.isCompatibleDataType(new Long[]{1L, 2L}, dataType));
}
@Test
public void testConvertDataTypeBigint() {
final Function<Object, BigInteger> toBigInteger = v -> (BigInteger) DataTypeUtils.convertType(v, RecordFieldType.BIGINT.getDataType(), "field");
assertEquals(new BigInteger("12345678901234567890"), toBigInteger.apply(new BigInteger("12345678901234567890")));
assertEquals(new BigInteger("1234567890123456789"), toBigInteger.apply(1234567890123456789L));
assertEquals(new BigInteger("1"), toBigInteger.apply(1));
assertEquals(new BigInteger("1"), toBigInteger.apply((short) 1));
// Decimals are truncated.
assertEquals(new BigInteger("3"), toBigInteger.apply(3.4f));
assertEquals(new BigInteger("3"), toBigInteger.apply(3.9f));
assertEquals(new BigInteger("12345678901234567890"), toBigInteger.apply("12345678901234567890"));
Exception e = null;
try {
toBigInteger.apply("1234567XYZ");
} catch (IllegalTypeConversionException itce) {
e = itce;
}
assertNotNull(e);
}
@Test
public void testFindMostSuitableTypeByStringValueShouldReturnEvenWhenOneTypeThrowsException() {
String valueAsString = "value";
String nonMatchingType = "nonMatchingType";
String throwsExceptionType = "throwsExceptionType";
String matchingType = "matchingType";
List<String> types = Arrays.asList(
nonMatchingType,
throwsExceptionType,
matchingType
);
Optional<String> expected = Optional.of(matchingType);
AtomicBoolean exceptionThrown = new AtomicBoolean(false);
Function<String, DataType> dataTypeMapper = type -> {
if (type.equals(nonMatchingType)) {
return RecordFieldType.BOOLEAN.getDataType();
} else if (type.equals(throwsExceptionType)) {
return new DataType(RecordFieldType.DATE, null) {
@Override
public String getFormat() {
exceptionThrown.set(true);
throw new RuntimeException("maching error");
}
};
} else if (type.equals(matchingType)) {
return RecordFieldType.STRING.getDataType();
}
return null;
};
Optional<String> actual = DataTypeUtils.findMostSuitableTypeByStringValue(valueAsString, types, dataTypeMapper);
assertTrue("Exception not thrown during test as intended.", exceptionThrown.get());
assertEquals(expected, actual);
}
@Test
public void testChooseDataTypeWhenInt_vs_INT_FLOAT_ThenShouldReturnINT() {
// GIVEN
List<DataType> dataTypes = Arrays.asList(
RecordFieldType.INT.getDataType(),
RecordFieldType.FLOAT.getDataType()
);
Object value = 1;
DataType expected = RecordFieldType.INT.getDataType();
// WHEN
// THEN
testChooseDataTypeAlsoReverseTypes(value, dataTypes, expected);
}
@Test
public void testChooseDataTypeWhenFloat_vs_INT_FLOAT_ThenShouldReturnFLOAT() {
// GIVEN
List<DataType> dataTypes = Arrays.asList(
RecordFieldType.INT.getDataType(),
RecordFieldType.FLOAT.getDataType()
);
Object value = 1.5f;
DataType expected = RecordFieldType.FLOAT.getDataType();
// WHEN
// THEN
testChooseDataTypeAlsoReverseTypes(value, dataTypes, expected);
}
@Test
public void testChooseDataTypeWhenHasChoiceThenShouldReturnSingleMatchingFromChoice() {
// GIVEN
List<DataType> dataTypes = Arrays.asList(
RecordFieldType.INT.getDataType(),
RecordFieldType.DOUBLE.getDataType(),
RecordFieldType.CHOICE.getChoiceDataType(
RecordFieldType.FLOAT.getDataType(),
RecordFieldType.STRING.getDataType()
)
);
Object value = 1.5f;
DataType expected = RecordFieldType.FLOAT.getDataType();
// WHEN
// THEN
testChooseDataTypeAlsoReverseTypes(value, dataTypes, expected);
}
private <E> void testChooseDataTypeAlsoReverseTypes(Object value, List<DataType> dataTypes, DataType expected) {
testChooseDataType(dataTypes, value, expected);
Collections.reverse(dataTypes);
testChooseDataType(dataTypes, value, expected);
}
private void testChooseDataType(List<DataType> dataTypes, Object value, DataType expected) {
// GIVEN
ChoiceDataType choiceDataType = (ChoiceDataType) RecordFieldType.CHOICE.getChoiceDataType(dataTypes.toArray(new DataType[dataTypes.size()]));
// WHEN
DataType actual = DataTypeUtils.chooseDataType(value, choiceDataType);
// THEN
assertEquals(expected, actual);
}
@Test
public void testInferTypeWithMapStringKeys() {
Map<String, String> map = new HashMap<>();
map.put("a", "Hello");
map.put("b", "World");
RecordDataType expected = (RecordDataType)RecordFieldType.RECORD.getRecordDataType(new SimpleRecordSchema(Arrays.asList(
new RecordField("a", RecordFieldType.STRING.getDataType()),
new RecordField("b", RecordFieldType.STRING.getDataType())
)));
DataType actual = DataTypeUtils.inferDataType(map, null);
assertEquals(expected, actual);
}
@Test
public void testInferTypeWithMapNonStringKeys() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Hello");
map.put(2, "World");
RecordDataType expected = (RecordDataType)RecordFieldType.RECORD.getRecordDataType(new SimpleRecordSchema(Arrays.asList(
new RecordField("1", RecordFieldType.STRING.getDataType()),
new RecordField("2", RecordFieldType.STRING.getDataType())
)));
DataType actual = DataTypeUtils.inferDataType(map, null);
assertEquals(expected, actual);
}
@Test
public void testFindMostSuitableTypeWithBoolean() {
testFindMostSuitableType(true, RecordFieldType.BOOLEAN.getDataType());
}
@Test
public void testFindMostSuitableTypeWithByte() {
testFindMostSuitableType(Byte.valueOf((byte) 123), RecordFieldType.BYTE.getDataType());
}
@Test
public void testFindMostSuitableTypeWithShort() {
testFindMostSuitableType(Short.valueOf((short) 123), RecordFieldType.SHORT.getDataType());
}
@Test
public void testFindMostSuitableTypeWithInt() {
testFindMostSuitableType(123, RecordFieldType.INT.getDataType());
}
@Test
public void testFindMostSuitableTypeWithLong() {
testFindMostSuitableType(123L, RecordFieldType.LONG.getDataType());
}
@Test
public void testFindMostSuitableTypeWithBigInt() {
testFindMostSuitableType(BigInteger.valueOf(123L), RecordFieldType.BIGINT.getDataType());
}
@Test
public void testFindMostSuitableTypeWithBigDecimal() {
testFindMostSuitableType(BigDecimal.valueOf(123.456D), RecordFieldType.DECIMAL.getDecimalDataType(6, 3));
}
@Test
public void testFindMostSuitableTypeWithFloat() {
testFindMostSuitableType(12.3F, RecordFieldType.FLOAT.getDataType());
}
@Test
public void testFindMostSuitableTypeWithDouble() {
testFindMostSuitableType(12.3, RecordFieldType.DOUBLE.getDataType());
}
@Test
public void testFindMostSuitableTypeWithDate() {
testFindMostSuitableType("1111-11-11", RecordFieldType.DATE.getDataType());
}
@Test
public void testFindMostSuitableTypeWithTime() {
testFindMostSuitableType("11:22:33", RecordFieldType.TIME.getDataType());
}
@Test
public void testFindMostSuitableTypeWithTimeStamp() {
testFindMostSuitableType("1111-11-11 11:22:33", RecordFieldType.TIMESTAMP.getDataType());
}
@Test
public void testFindMostSuitableTypeWithChar() {
testFindMostSuitableType('a', RecordFieldType.CHAR.getDataType());
}
@Test
public void testFindMostSuitableTypeWithStringShouldReturnChar() {
testFindMostSuitableType("abc", RecordFieldType.CHAR.getDataType());
}
@Test
public void testFindMostSuitableTypeWithString() {
testFindMostSuitableType("abc", RecordFieldType.STRING.getDataType(), RecordFieldType.CHAR.getDataType());
}
@Test
public void testFindMostSuitableTypeWithArray() {
testFindMostSuitableType(new int[]{1, 2, 3}, RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.INT.getDataType()));
}
private void testFindMostSuitableType(Object value, DataType expected, DataType... filtered) {
List<DataType> filteredOutDataTypes = Arrays.stream(filtered).collect(Collectors.toList());
// GIVEN
List<DataType> unexpectedTypes = Arrays.stream(RecordFieldType.values())
.flatMap(recordFieldType -> {
Stream<DataType> dataTypeStream;
if (RecordFieldType.ARRAY.equals(recordFieldType)) {
dataTypeStream = Arrays.stream(RecordFieldType.values()).map(elementType -> RecordFieldType.ARRAY.getArrayDataType(elementType.getDataType()));
} else {
dataTypeStream = Stream.of(recordFieldType.getDataType());
}
return dataTypeStream;
})
.filter(dataType -> !dataType.equals(expected))
.filter(dataType -> !filteredOutDataTypes.contains(dataType))
.collect(Collectors.toList());
IntStream.rangeClosed(0, unexpectedTypes.size()).forEach(insertIndex -> {
List<DataType> allTypes = new LinkedList<>(unexpectedTypes);
allTypes.add(insertIndex, expected);
// WHEN
Optional<DataType> actual = DataTypeUtils.findMostSuitableType(value, allTypes, Function.identity());
// THEN
assertEquals(Optional.ofNullable(expected), actual);
});
}
private void whenExpectingValidBigDecimalConversion(final BigDecimal expectedValue, final Object incomingValue) {
// Checking indirect conversion
final String failureMessage = "Conversion from " + incomingValue.getClass().getSimpleName() + " to " + expectedValue.getClass().getSimpleName() + " failed, when ";
final BigDecimal indirectResult = whenExpectingValidConversion(expectedValue, incomingValue, RecordFieldType.DECIMAL.getDecimalDataType(30, 10));
// In some cases, direct equality check comes with false negative as the changing representation brings in
// insignificant changes what might break the comparison. For example 12F will be represented as "12.0"
assertEquals(failureMessage + "indirect", 0, expectedValue.compareTo(indirectResult));
// Checking direct conversion
final BigDecimal directResult = DataTypeUtils.toBigDecimal(incomingValue, "field");
assertEquals(failureMessage + "direct", 0, expectedValue.compareTo(directResult));
}
private <T> T whenExpectingValidConversion(final T expectedValue, final Object incomingValue, final DataType dataType) {
final Object result = DataTypeUtils.convertType(incomingValue, dataType, null, StandardCharsets.UTF_8);
assertNotNull(result);
assertTrue(expectedValue.getClass().isInstance(result));
return (T) result;
}
@Test
public void testIsIntegerFitsToFloat() {
final int maxRepresentableInt = Double.valueOf(Math.pow(2, 24)).intValue();
assertTrue(DataTypeUtils.isIntegerFitsToFloat(0));
assertTrue(DataTypeUtils.isIntegerFitsToFloat(9));
assertTrue(DataTypeUtils.isIntegerFitsToFloat(maxRepresentableInt));
assertTrue(DataTypeUtils.isIntegerFitsToFloat(-1 * maxRepresentableInt));
assertFalse(DataTypeUtils.isIntegerFitsToFloat("test"));
assertFalse(DataTypeUtils.isIntegerFitsToFloat(9L));
assertFalse(DataTypeUtils.isIntegerFitsToFloat(9.0));
assertFalse(DataTypeUtils.isIntegerFitsToFloat(Integer.MAX_VALUE));
assertFalse(DataTypeUtils.isIntegerFitsToFloat(Integer.MIN_VALUE));
assertFalse(DataTypeUtils.isIntegerFitsToFloat(maxRepresentableInt + 1));
assertFalse(DataTypeUtils.isIntegerFitsToFloat(-1 * maxRepresentableInt - 1));
}
@Test
public void testIsLongFitsToFloat() {
final long maxRepresentableLong = Double.valueOf(Math.pow(2, 24)).longValue();
assertTrue(DataTypeUtils.isLongFitsToFloat(0L));
assertTrue(DataTypeUtils.isLongFitsToFloat(9L));
assertTrue(DataTypeUtils.isLongFitsToFloat(maxRepresentableLong));
assertTrue(DataTypeUtils.isLongFitsToFloat(-1L * maxRepresentableLong));
assertFalse(DataTypeUtils.isLongFitsToFloat("test"));
assertFalse(DataTypeUtils.isLongFitsToFloat(9));
assertFalse(DataTypeUtils.isLongFitsToFloat(9.0));
assertFalse(DataTypeUtils.isLongFitsToFloat(Long.MAX_VALUE));
assertFalse(DataTypeUtils.isLongFitsToFloat(Long.MIN_VALUE));
assertFalse(DataTypeUtils.isLongFitsToFloat(maxRepresentableLong + 1L));
assertFalse(DataTypeUtils.isLongFitsToFloat(-1L * maxRepresentableLong - 1L));
}
@Test
public void testIsLongFitsToDouble() {
final long maxRepresentableLong = Double.valueOf(Math.pow(2, 53)).longValue();
assertTrue(DataTypeUtils.isLongFitsToDouble(0L));
assertTrue(DataTypeUtils.isLongFitsToDouble(9L));
assertTrue(DataTypeUtils.isLongFitsToDouble(maxRepresentableLong));
assertTrue(DataTypeUtils.isLongFitsToDouble(-1L * maxRepresentableLong));
assertFalse(DataTypeUtils.isLongFitsToDouble("test"));
assertFalse(DataTypeUtils.isLongFitsToDouble(9));
assertFalse(DataTypeUtils.isLongFitsToDouble(9.0));
assertFalse(DataTypeUtils.isLongFitsToDouble(Long.MAX_VALUE));
assertFalse(DataTypeUtils.isLongFitsToDouble(Long.MIN_VALUE));
assertFalse(DataTypeUtils.isLongFitsToDouble(maxRepresentableLong + 1L));
assertFalse(DataTypeUtils.isLongFitsToDouble(-1L * maxRepresentableLong - 1L));
}
@Test
public void testIsBigIntFitsToFloat() {
final BigInteger maxRepresentableBigInt = BigInteger.valueOf(Double.valueOf(Math.pow(2, 24)).longValue());
assertTrue(DataTypeUtils.isBigIntFitsToFloat(BigInteger.valueOf(0L)));
assertTrue(DataTypeUtils.isBigIntFitsToFloat(BigInteger.valueOf(8L)));
assertTrue(DataTypeUtils.isBigIntFitsToFloat(maxRepresentableBigInt));
assertTrue(DataTypeUtils.isBigIntFitsToFloat(maxRepresentableBigInt.negate()));
assertFalse(DataTypeUtils.isBigIntFitsToFloat("test"));
assertFalse(DataTypeUtils.isBigIntFitsToFloat(9));
assertFalse(DataTypeUtils.isBigIntFitsToFloat(9.0));
assertFalse(DataTypeUtils.isBigIntFitsToFloat(new BigInteger(String.join("", Collections.nCopies(100, "1")))));
assertFalse(DataTypeUtils.isBigIntFitsToFloat(new BigInteger(String.join("", Collections.nCopies(100, "1"))).negate()));
}
@Test
public void testIsBigIntFitsToDouble() {
final BigInteger maxRepresentableBigInt = BigInteger.valueOf(Double.valueOf(Math.pow(2, 53)).longValue());
assertTrue(DataTypeUtils.isBigIntFitsToDouble(BigInteger.valueOf(0L)));
assertTrue(DataTypeUtils.isBigIntFitsToDouble(BigInteger.valueOf(8L)));
assertTrue(DataTypeUtils.isBigIntFitsToDouble(maxRepresentableBigInt));
assertTrue(DataTypeUtils.isBigIntFitsToDouble(maxRepresentableBigInt.negate()));
assertFalse(DataTypeUtils.isBigIntFitsToDouble("test"));
assertFalse(DataTypeUtils.isBigIntFitsToDouble(9));
assertFalse(DataTypeUtils.isBigIntFitsToDouble(9.0));
assertFalse(DataTypeUtils.isBigIntFitsToDouble(new BigInteger(String.join("", Collections.nCopies(100, "1")))));
assertFalse(DataTypeUtils.isBigIntFitsToDouble(new BigInteger(String.join("", Collections.nCopies(100, "1"))).negate()));
}
@Test
public void testIsDoubleWithinFloatInterval() {
assertTrue(DataTypeUtils.isDoubleWithinFloatInterval(0D));
assertTrue(DataTypeUtils.isDoubleWithinFloatInterval(0.1D));
assertTrue(DataTypeUtils.isDoubleWithinFloatInterval((double) Float.MAX_VALUE));
assertTrue(DataTypeUtils.isDoubleWithinFloatInterval((double) Float.MIN_VALUE));
assertTrue(DataTypeUtils.isDoubleWithinFloatInterval((double) -1 * Float.MAX_VALUE));
assertTrue(DataTypeUtils.isDoubleWithinFloatInterval((double) -1 * Float.MIN_VALUE));
assertFalse(DataTypeUtils.isDoubleWithinFloatInterval("test"));
assertFalse(DataTypeUtils.isDoubleWithinFloatInterval(9));
assertFalse(DataTypeUtils.isDoubleWithinFloatInterval(9.0F));
assertFalse(DataTypeUtils.isDoubleWithinFloatInterval(Double.MAX_VALUE));
assertFalse(DataTypeUtils.isDoubleWithinFloatInterval((double) -1 * Double.MAX_VALUE));
}
@Test
public void testIsFittingNumberType() {
// Byte
assertTrue(DataTypeUtils.isFittingNumberType((byte) 9, RecordFieldType.BYTE));
assertFalse(DataTypeUtils.isFittingNumberType((short)9, RecordFieldType.BYTE));
assertFalse(DataTypeUtils.isFittingNumberType(9, RecordFieldType.BYTE));
assertFalse(DataTypeUtils.isFittingNumberType(9L, RecordFieldType.BYTE));
assertFalse(DataTypeUtils.isFittingNumberType(BigInteger.valueOf(9L), RecordFieldType.BYTE));
// Short
assertTrue(DataTypeUtils.isFittingNumberType((byte) 9, RecordFieldType.SHORT));
assertTrue(DataTypeUtils.isFittingNumberType((short)9, RecordFieldType.SHORT));
assertFalse(DataTypeUtils.isFittingNumberType(9, RecordFieldType.SHORT));
assertFalse(DataTypeUtils.isFittingNumberType(9L, RecordFieldType.SHORT));
assertFalse(DataTypeUtils.isFittingNumberType(BigInteger.valueOf(9L), RecordFieldType.SHORT));
// Integer
assertTrue(DataTypeUtils.isFittingNumberType((byte) 9, RecordFieldType.INT));
assertTrue(DataTypeUtils.isFittingNumberType((short)9, RecordFieldType.INT));
assertTrue(DataTypeUtils.isFittingNumberType(9, RecordFieldType.INT));
assertFalse(DataTypeUtils.isFittingNumberType(9L, RecordFieldType.INT));
assertFalse(DataTypeUtils.isFittingNumberType(BigInteger.valueOf(9L), RecordFieldType.INT));
// Long
assertTrue(DataTypeUtils.isFittingNumberType((byte) 9, RecordFieldType.LONG));
assertTrue(DataTypeUtils.isFittingNumberType((short)9, RecordFieldType.LONG));
assertTrue(DataTypeUtils.isFittingNumberType(9, RecordFieldType.LONG));
assertTrue(DataTypeUtils.isFittingNumberType(9L, RecordFieldType.LONG));
assertFalse(DataTypeUtils.isFittingNumberType(BigInteger.valueOf(9L), RecordFieldType.LONG));
// Bigint
assertTrue(DataTypeUtils.isFittingNumberType((byte) 9, RecordFieldType.BIGINT));
assertTrue(DataTypeUtils.isFittingNumberType((short)9, RecordFieldType.BIGINT));
assertTrue(DataTypeUtils.isFittingNumberType(9, RecordFieldType.BIGINT));
assertTrue(DataTypeUtils.isFittingNumberType(9L, RecordFieldType.BIGINT));
assertTrue(DataTypeUtils.isFittingNumberType(BigInteger.valueOf(9L), RecordFieldType.BIGINT));
// Float
assertTrue(DataTypeUtils.isFittingNumberType(9F, RecordFieldType.FLOAT));
assertFalse(DataTypeUtils.isFittingNumberType(9D, RecordFieldType.FLOAT));
assertFalse(DataTypeUtils.isFittingNumberType(9, RecordFieldType.FLOAT));
// Double
assertTrue(DataTypeUtils.isFittingNumberType(9F, RecordFieldType.DOUBLE));
assertTrue(DataTypeUtils.isFittingNumberType(9D, RecordFieldType.DOUBLE));
assertFalse(DataTypeUtils.isFittingNumberType(9, RecordFieldType.DOUBLE));
}
}
| |
/*
* Copyright 2007 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.qrcode.detector;
import com.google.zxing.DecodeHintType;
import com.google.zxing.NotFoundException;
import com.google.zxing.ResultPoint;
import com.google.zxing.ResultPointCallback;
import com.google.zxing.common.BitMatrix;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
* markers at three corners of a QR Code.</p>
*
* <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
*
* @author Sean Owen
*/
public class FinderPatternFinder {
private static final int CENTER_QUORUM = 2;
protected static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
protected static final int MAX_MODULES = 57; // support up to version 10 for mobile clients
private static final int INTEGER_MATH_SHIFT = 8;
private final BitMatrix image;
private final List<FinderPattern> possibleCenters;
private boolean hasSkipped;
private final int[] crossCheckStateCount;
private final ResultPointCallback resultPointCallback;
/**
* <p>Creates a finder that will search the image for three finder patterns.</p>
*
* @param image image to search
*/
public FinderPatternFinder(BitMatrix image) {
this(image, null);
}
public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) {
this.image = image;
this.possibleCenters = new ArrayList<FinderPattern>();
this.crossCheckStateCount = new int[5];
this.resultPointCallback = resultPointCallback;
}
protected final BitMatrix getImage() {
return image;
}
protected final List<FinderPattern> getPossibleCenters() {
return possibleCenters;
}
final FinderPatternInfo find(Map<DecodeHintType,?> hints) throws NotFoundException {
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
int maxI = image.getHeight();
int maxJ = image.getWidth();
// We are looking for black/white/black/white/black modules in
// 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
// image, and then account for the center being 3 modules in size. This gives the smallest
// number of pixels the center could be, so skip this often. When trying harder, look for all
// QR versions regardless of how dense they are.
int iSkip = (3 * maxI) / (4 * MAX_MODULES);
if (iSkip < MIN_SKIP || tryHarder) {
iSkip = MIN_SKIP;
}
boolean done = false;
int[] stateCount = new int[5];
for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {
// Get a row of black/white values
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
stateCount[3] = 0;
stateCount[4] = 0;
int currentState = 0;
for (int j = 0; j < maxJ; j++) {
if (image.get(j, i)) {
// Black pixel
if ((currentState & 1) == 1) { // Counting white pixels
currentState++;
}
stateCount[currentState]++;
} else { // White pixel
if ((currentState & 1) == 0) { // Counting black pixels
if (currentState == 4) { // A winner?
if (foundPatternCross(stateCount)) { // Yes
boolean confirmed = handlePossibleCenter(stateCount, i, j);
if (confirmed) {
// Start examining every other line. Checking each line turned out to be too
// expensive and didn't improve performance.
iSkip = 2;
if (hasSkipped) {
done = haveMultiplyConfirmedCenters();
} else {
int rowSkip = findRowSkip();
if (rowSkip > stateCount[2]) {
// Skip rows between row of lower confirmed center
// and top of presumed third confirmed center
// but back up a bit to get a full chance of detecting
// it, entire width of center of finder pattern
// Skip by rowSkip, but back off by stateCount[2] (size of last center
// of pattern we saw) to be conservative, and also back off by iSkip which
// is about to be re-added
i += rowSkip - stateCount[2] - iSkip;
j = maxJ - 1;
}
}
} else {
stateCount[0] = stateCount[2];
stateCount[1] = stateCount[3];
stateCount[2] = stateCount[4];
stateCount[3] = 1;
stateCount[4] = 0;
currentState = 3;
continue;
}
// Clear state to start looking again
currentState = 0;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
stateCount[3] = 0;
stateCount[4] = 0;
} else { // No, shift counts back by two
stateCount[0] = stateCount[2];
stateCount[1] = stateCount[3];
stateCount[2] = stateCount[4];
stateCount[3] = 1;
stateCount[4] = 0;
currentState = 3;
}
} else {
stateCount[++currentState]++;
}
} else { // Counting white pixels
stateCount[currentState]++;
}
}
}
if (foundPatternCross(stateCount)) {
boolean confirmed = handlePossibleCenter(stateCount, i, maxJ);
if (confirmed) {
iSkip = stateCount[0];
if (hasSkipped) {
// Found a third one
done = haveMultiplyConfirmedCenters();
}
}
}
}
FinderPattern[] patternInfo = selectBestPatterns();
ResultPoint.orderBestPatterns(patternInfo);
return new FinderPatternInfo(patternInfo);
}
/**
* Given a count of black/white/black/white/black pixels just seen and an end position,
* figures the location of the center of this run.
*/
private static float centerFromEnd(int[] stateCount, int end) {
return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
}
/**
* @param stateCount count of black/white/black/white/black pixels just read
* @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
* used by finder patterns to be considered a match
*/
protected static boolean foundPatternCross(int[] stateCount) {
int totalModuleSize = 0;
for (int i = 0; i < 5; i++) {
int count = stateCount[i];
if (count == 0) {
return false;
}
totalModuleSize += count;
}
if (totalModuleSize < 7) {
return false;
}
int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;
int maxVariance = moduleSize / 2;
// Allow less than 50% variance from 1-1-3-1-1 proportions
return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance &&
Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance &&
Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance &&
Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance &&
Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
}
private int[] getCrossCheckStateCount() {
crossCheckStateCount[0] = 0;
crossCheckStateCount[1] = 0;
crossCheckStateCount[2] = 0;
crossCheckStateCount[3] = 0;
crossCheckStateCount[4] = 0;
return crossCheckStateCount;
}
/**
* <p>After a horizontal scan finds a potential finder pattern, this method
* "cross-checks" by scanning down vertically through the center of the possible
* finder pattern to see if the same proportion is detected.</p>
*
* @param startI row where a finder pattern was detected
* @param centerJ center of the section that appears to cross a finder pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @return vertical center of finder pattern, or {@link Float#NaN} if not found
*/
private float crossCheckVertical(int startI, int centerJ, int maxCount,
int originalStateCountTotal) {
BitMatrix image = this.image;
int maxI = image.getHeight();
int[] stateCount = getCrossCheckStateCount();
// Start counting up from center
int i = startI;
while (i >= 0 && image.get(centerJ, i)) {
stateCount[2]++;
i--;
}
if (i < 0) {
return Float.NaN;
}
while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount) {
return Float.NaN;
}
while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image.get(centerJ, i)) {
stateCount[2]++;
i++;
}
if (i == maxI) {
return Float.NaN;
}
while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {
stateCount[3]++;
i++;
}
if (i == maxI || stateCount[3] >= maxCount) {
return Float.NaN;
}
while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {
stateCount[4]++;
i++;
}
if (stateCount[4] >= maxCount) {
return Float.NaN;
}
// If we found a finder-pattern-like section, but its size is more than 40% different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
return Float.NaN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;
}
/**
* <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
* except it reads horizontally instead of vertically. This is used to cross-cross
* check a vertical cross check and locate the real center of the alignment pattern.</p>
*/
private float crossCheckHorizontal(int startJ, int centerI, int maxCount,
int originalStateCountTotal) {
BitMatrix image = this.image;
int maxJ = image.getWidth();
int[] stateCount = getCrossCheckStateCount();
int j = startJ;
while (j >= 0 && image.get(j, centerI)) {
stateCount[2]++;
j--;
}
if (j < 0) {
return Float.NaN;
}
while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {
stateCount[1]++;
j--;
}
if (j < 0 || stateCount[1] > maxCount) {
return Float.NaN;
}
while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {
stateCount[0]++;
j--;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
}
j = startJ + 1;
while (j < maxJ && image.get(j, centerI)) {
stateCount[2]++;
j++;
}
if (j == maxJ) {
return Float.NaN;
}
while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {
stateCount[3]++;
j++;
}
if (j == maxJ || stateCount[3] >= maxCount) {
return Float.NaN;
}
while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {
stateCount[4]++;
j++;
}
if (stateCount[4] >= maxCount) {
return Float.NaN;
}
// If we found a finder-pattern-like section, but its size is significantly different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
return Float.NaN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;
}
/**
* <p>This is called when a horizontal scan finds a possible alignment pattern. It will
* cross check with a vertical scan, and if successful, will, ah, cross-cross-check
* with another horizontal scan. This is needed primarily to locate the real horizontal
* center of the pattern in cases of extreme skew.</p>
*
* <p>If that succeeds the finder pattern location is added to a list that tracks
* the number of times each location has been nearly-matched as a finder pattern.
* Each additional find is more evidence that the location is in fact a finder
* pattern center
*
* @param stateCount reading state module counts from horizontal scan
* @param i row where finder pattern may be found
* @param j end of possible finder pattern in row
* @return true if a finder pattern candidate was found this time
*/
protected final boolean handlePossibleCenter(int[] stateCount, int i, int j) {
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
float centerJ = centerFromEnd(stateCount, j);
float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);
if (!Float.isNaN(centerI)) {
// Re-cross check
centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
if (!Float.isNaN(centerJ)) {
float estimatedModuleSize = (float) stateCountTotal / 7.0f;
boolean found = false;
for (int index = 0; index < possibleCenters.size(); index++) {
FinderPattern center = possibleCenters.get(index);
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
possibleCenters.set(index, center.combineEstimate(centerI, centerJ, estimatedModuleSize));
found = true;
break;
}
}
if (!found) {
FinderPattern point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
possibleCenters.add(point);
if (resultPointCallback != null) {
resultPointCallback.foundPossibleResultPoint(point);
}
}
return true;
}
}
return false;
}
/**
* @return number of rows we could safely skip during scanning, based on the first
* two finder patterns that have been located. In some cases their position will
* allow us to infer that the third pattern must lie below a certain point farther
* down in the image.
*/
private int findRowSkip() {
int max = possibleCenters.size();
if (max <= 1) {
return 0;
}
FinderPattern firstConfirmedCenter = null;
for (FinderPattern center : possibleCenters) {
if (center.getCount() >= CENTER_QUORUM) {
if (firstConfirmedCenter == null) {
firstConfirmedCenter = center;
} else {
// We have two confirmed centers
// How far down can we skip before resuming looking for the next
// pattern? In the worst case, only the difference between the
// difference in the x / y coordinates of the two centers.
// This is the case where you find top left last.
hasSkipped = true;
return (int) (Math.abs(firstConfirmedCenter.getX() - center.getX()) -
Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2;
}
}
}
return 0;
}
/**
* @return true iff we have found at least 3 finder patterns that have been detected
* at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
* candidates is "pretty similar"
*/
private boolean haveMultiplyConfirmedCenters() {
int confirmedCount = 0;
float totalModuleSize = 0.0f;
int max = possibleCenters.size();
for (FinderPattern pattern : possibleCenters) {
if (pattern.getCount() >= CENTER_QUORUM) {
confirmedCount++;
totalModuleSize += pattern.getEstimatedModuleSize();
}
}
if (confirmedCount < 3) {
return false;
}
// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
// and that we need to keep looking. We detect this by asking if the estimated module sizes
// vary too much. We arbitrarily say that when the total deviation from average exceeds
// 5% of the total module size estimates, it's too much.
float average = totalModuleSize / (float) max;
float totalDeviation = 0.0f;
for (FinderPattern pattern : possibleCenters) {
totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);
}
return totalDeviation <= 0.05f * totalModuleSize;
}
/**
* @return the 3 best {@link com.google.zxing.qrcode.detector.FinderPattern}s from our list of candidates. The "best" are
* those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
* size differs from the average among those patterns the least
* @throws NotFoundException if 3 such finder patterns do not exist
*/
private FinderPattern[] selectBestPatterns() throws NotFoundException {
int startSize = possibleCenters.size();
if (startSize < 3) {
// Couldn't find enough finder patterns
throw NotFoundException.getNotFoundInstance();
}
// Filter outlier possibilities whose module size is too different
if (startSize > 3) {
// But we can only afford to do so if we have at least 4 possibilities to choose from
float totalModuleSize = 0.0f;
float square = 0.0f;
for (FinderPattern center : possibleCenters) {
float size = center.getEstimatedModuleSize();
totalModuleSize += size;
square += size * size;
}
float average = totalModuleSize / (float) startSize;
float stdDev = (float) Math.sqrt(square / startSize - average * average);
Collections.sort(possibleCenters, new FurthestFromAverageComparator(average));
float limit = Math.max(0.2f * average, stdDev);
for (int i = 0; i < possibleCenters.size() && possibleCenters.size() > 3; i++) {
FinderPattern pattern = possibleCenters.get(i);
if (Math.abs(pattern.getEstimatedModuleSize() - average) > limit) {
possibleCenters.remove(i);
i--;
}
}
}
if (possibleCenters.size() > 3) {
// Throw away all but those first size candidate points we found.
float totalModuleSize = 0.0f;
for (FinderPattern possibleCenter : possibleCenters) {
totalModuleSize += possibleCenter.getEstimatedModuleSize();
}
float average = totalModuleSize / (float) possibleCenters.size();
Collections.sort(possibleCenters, new CenterComparator(average));
possibleCenters.subList(3, possibleCenters.size()).clear();
}
return new FinderPattern[]{
possibleCenters.get(0),
possibleCenters.get(1),
possibleCenters.get(2)
};
}
/**
* <p>Orders by furthest from average</p>
*/
private static final class FurthestFromAverageComparator implements Comparator<FinderPattern>, Serializable {
private final float average;
private FurthestFromAverageComparator(float f) {
average = f;
}
@Override
public int compare(FinderPattern center1, FinderPattern center2) {
float dA = Math.abs(center2.getEstimatedModuleSize() - average);
float dB = Math.abs(center1.getEstimatedModuleSize() - average);
return dA < dB ? -1 : dA == dB ? 0 : 1;
}
}
/**
* <p>Orders by {@link com.google.zxing.qrcode.detector.FinderPattern#getCount()}, descending.</p>
*/
private static final class CenterComparator implements Comparator<FinderPattern>, Serializable {
private final float average;
private CenterComparator(float f) {
average = f;
}
@Override
public int compare(FinderPattern center1, FinderPattern center2) {
if (center2.getCount() == center1.getCount()) {
float dA = Math.abs(center2.getEstimatedModuleSize() - average);
float dB = Math.abs(center1.getEstimatedModuleSize() - average);
return dA < dB ? 1 : dA == dB ? 0 : -1;
} else {
return center2.getCount() - center1.getCount();
}
}
}
}
| |
/*
* 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 java.math;
import java.util.Arrays;
import java.util.Random;
/**
* Provides primality probabilistic methods.
* @author Intel Middleware Product Division
* @author Instituto Tecnologico de Cordoba
*/
class Primality {
/** Just to denote that this class can't be instantied. */
private Primality() {}
/* Private Fields */
/** All prime numbers with bit length lesser than 10 bits. */
private static final int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467,
479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823,
827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009,
1013, 1019, 1021 };
/** All {@code BigInteger} prime numbers with bit length lesser than 8 bits. */
private static final BigInteger BIprimes[] = new BigInteger[primes.length];
/**
* It encodes how many iterations of Miller-Rabin test are need to get an
* error bound not greater than {@code 2<sup>(-100)</sup>}. For example:
* for a {@code 1000}-bit number we need {@code 4} iterations, since
* {@code BITS[3] < 1000 <= BITS[4]}.
*/
private static final int[] BITS = { 0, 0, 1854, 1233, 927, 747, 627, 543,
480, 431, 393, 361, 335, 314, 295, 279, 265, 253, 242, 232, 223,
216, 181, 169, 158, 150, 145, 140, 136, 132, 127, 123, 119, 114,
110, 105, 101, 96, 92, 87, 83, 78, 73, 69, 64, 59, 54, 49, 44, 38,
32, 26, 1 };
/**
* It encodes how many i-bit primes there are in the table for
* {@code i=2,...,10}. For example {@code offsetPrimes[6]} says that from
* index {@code 11} exists {@code 7} consecutive {@code 6}-bit prime
* numbers in the array.
*/
private static final int[][] offsetPrimes = { null, null, { 0, 2 },
{ 2, 2 }, { 4, 2 }, { 6, 5 }, { 11, 7 }, { 18, 13 }, { 31, 23 },
{ 54, 43 }, { 97, 75 } };
static {// To initialize the dual table of BigInteger primes
for (int i = 0; i < primes.length; i++) {
BIprimes[i] = BigInteger.valueOf(primes[i]);
}
}
/* Package Methods */
/**
* It uses the sieve of Eratosthenes to discard several composite numbers in
* some appropriate range (at the moment {@code [this, this + 1024]}). After
* this process it applies the Miller-Rabin test to the numbers that were
* not discarded in the sieve.
*
* @see BigInteger#nextProbablePrime()
* @see #millerRabin(BigInteger, int)
*/
static BigInteger nextProbablePrime(BigInteger n) {
// PRE: n >= 0
int i, j;
int certainty;
int gapSize = 1024; // for searching of the next probable prime number
int modules[] = new int[primes.length];
boolean isDivisible[] = new boolean[gapSize];
BigInteger startPoint;
BigInteger probPrime;
// If n < "last prime of table" searches next prime in the table
if ((n.numberLength == 1) && (n.digits[0] >= 0)
&& (n.digits[0] < primes[primes.length - 1])) {
for (i = 0; n.digits[0] >= primes[i]; i++) {
;
}
return BIprimes[i];
}
/*
* Creates a "N" enough big to hold the next probable prime Note that: N <
* "next prime" < 2*N
*/
startPoint = new BigInteger(1, n.numberLength,
new int[n.numberLength + 1]);
System.arraycopy(n.digits, 0, startPoint.digits, 0, n.numberLength);
// To fix N to the "next odd number"
if (n.testBit(0)) {
Elementary.inplaceAdd(startPoint, 2);
} else {
startPoint.digits[0] |= 1;
}
// To set the improved certainly of Miller-Rabin
j = startPoint.bitLength();
for (certainty = 2; j < BITS[certainty]; certainty++) {
;
}
// To calculate modules: N mod p1, N mod p2, ... for first primes.
for (i = 0; i < primes.length; i++) {
modules[i] = Division.remainder(startPoint, primes[i]) - gapSize;
}
while (true) {
// At this point, all numbers in the gap are initialized as
// probably primes
Arrays.fill(isDivisible, false);
// To discard multiples of first primes
for (i = 0; i < primes.length; i++) {
modules[i] = (modules[i] + gapSize) % primes[i];
j = (modules[i] == 0) ? 0 : (primes[i] - modules[i]);
for (; j < gapSize; j += primes[i]) {
isDivisible[j] = true;
}
}
// To execute Miller-Rabin for non-divisible numbers by all first
// primes
for (j = 0; j < gapSize; j++) {
if (!isDivisible[j]) {
probPrime = startPoint.copy();
Elementary.inplaceAdd(probPrime, j);
if (millerRabin(probPrime, certainty)) {
return probPrime;
}
}
}
Elementary.inplaceAdd(startPoint, gapSize);
}
}
/**
* A random number is generated until a probable prime number is found.
*
* @see BigInteger#BigInteger(int,int,Random)
* @see BigInteger#probablePrime(int,Random)
* @see #isProbablePrime(BigInteger, int)
*/
static BigInteger consBigInteger(int bitLength, int certainty, Random rnd) {
// PRE: bitLength >= 2;
// For small numbers get a random prime from the prime table
if (bitLength <= 10) {
int rp[] = offsetPrimes[bitLength];
return BIprimes[rp[0] + rnd.nextInt(rp[1])];
}
int shiftCount = (-bitLength) & 31;
int last = (bitLength + 31) >> 5;
BigInteger n = new BigInteger(1, last, new int[last]);
last--;
do {// To fill the array with random integers
for (int i = 0; i < n.numberLength; i++) {
n.digits[i] = rnd.nextInt();
}
// To fix to the correct bitLength
n.digits[last] |= 0x80000000;
n.digits[last] >>>= shiftCount;
// To create an odd number
n.digits[0] |= 1;
} while (!isProbablePrime(n, certainty));
return n;
}
/**
* @see BigInteger#isProbablePrime(int)
* @see #millerRabin(BigInteger, int)
* @ar.org.fitc.ref Optimizations: "A. Menezes - Handbook of applied
* Cryptography, Chapter 4".
*/
static boolean isProbablePrime(BigInteger n, int certainty) {
// PRE: n >= 0;
if ((certainty <= 0) || ((n.numberLength == 1) && (n.digits[0] == 2))) {
return true;
}
// To discard all even numbers
if (!n.testBit(0)) {
return false;
}
// To check if 'n' exists in the table (it fit in 10 bits)
if ((n.numberLength == 1) && ((n.digits[0] & 0XFFFFFC00) == 0)) {
return (Arrays.binarySearch(primes, n.digits[0]) >= 0);
}
// To check if 'n' is divisible by some prime of the table
for (int i = 1; i < primes.length; i++) {
if (Division.remainderArrayByInt(n.digits, n.numberLength,
primes[i]) == 0) {
return false;
}
}
// To set the number of iterations necessary for Miller-Rabin test
int i;
int bitLength = n.bitLength();
for (i = 2; bitLength < BITS[i]; i++) {
;
}
certainty = Math.min(i, 1 + ((certainty - 1) >> 1));
return millerRabin(n, certainty);
}
/* Private Methods */
/**
* The Miller-Rabin primality test.
*
* @param n the input number to be tested.
* @param t the number of trials.
* @return {@code false} if the number is definitely compose, otherwise
* {@code true} with probability {@code 1 - 4<sup>(-t)</sup>}.
* @ar.org.fitc.ref "D. Knuth, The Art of Computer Programming Vo.2, Section
* 4.5.4., Algorithm P"
*/
private static boolean millerRabin(BigInteger n, int t) {
// PRE: n >= 0, t >= 0
BigInteger x; // x := UNIFORM{2...n-1}
BigInteger y; // y := x^(q * 2^j) mod n
BigInteger n_minus_1 = n.subtract(BigInteger.ONE); // n-1
int bitLength = n_minus_1.bitLength(); // ~ log2(n-1)
// (q,k) such that: n-1 = q * 2^k and q is odd
int k = n_minus_1.getLowestSetBit();
BigInteger q = n_minus_1.shiftRight(k);
Random rnd = new Random();
for (int i = 0; i < t; i++) {
// To generate a witness 'x', first it use the primes of table
if (i < primes.length) {
x = BIprimes[i];
} else {/*
* It generates random witness only if it's necesssary. Note
* that all methods would call Miller-Rabin with t <= 50 so
* this part is only to do more robust the algorithm
*/
do {
x = new BigInteger(bitLength, rnd);
} while ((x.compareTo(n) >= BigInteger.EQUALS) || (x.sign == 0)
|| x.isOne());
}
y = x.modPow(q, n);
if (y.isOne() || y.equals(n_minus_1)) {
continue;
}
for (int j = 1; j < k; j++) {
if (y.equals(n_minus_1)) {
continue;
}
y = y.multiply(y).mod(n);
if (y.isOne()) {
return false;
}
}
if (!y.equals(n_minus_1)) {
return false;
}
}
return true;
}
}
| |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util;
import com.facebook.buck.log.Logger;
import com.google.common.base.Preconditions;
import com.zaxxer.nuprocess.NuAbstractProcessHandler;
import com.zaxxer.nuprocess.NuProcess;
import com.zaxxer.nuprocess.NuProcessBuilder;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Replacement for {@link ProcessBuilder} which provides an
* asynchronous callback interface to notify the caller on a
* background thread when a process starts, performs I/O, or exits.
*
* Unlike {@link ProcessExecutor}, this does not automatically forward
* output to {@link Console} formatted with ANSI escapes.
*/
public class ListeningProcessExecutor {
private static final Logger LOG = Logger.get(ListeningProcessExecutor.class);
/**
* Callback API to notify the caller on a background thread when a process
* starts, exits, has stdout or stderr bytes to read, or is ready to receive
* bytes on stdin.
*/
public interface ProcessListener {
/**
* Called just after the process starts.
*/
void onStart(LaunchedProcess process);
/**
* Called just after the process exits.
*/
void onExit(int exitCode);
/**
* Called when the process writes bytes to stdout.
*
* Before this method returns, you must set {@code buffer.position()}
* to indicate how many bytes you have consumed.
*
* If you do not consume the entire buffer, any remaining bytes will
* be passed back to you upon the next invocation (for example, when
* implementing a UTF-8 decoder which might contain a byte sequence
* spanning multiple reads).
*
* If {@code closed} is {@code true}, then stdout has been closed and
* no more bytes will be received.
*/
void onStdout(ByteBuffer buffer, boolean closed);
/**
* Called when the process writes bytes to stderr.
*
* Before this method returns, you must set {@code buffer.position()}
* to indicate how many bytes you have consumed.
*
* If you do not consume the entire buffer, any remaining bytes will
* be passed back to you upon the next invocation (for example, when
* implementing a UTF-8 decoder which might contain a byte sequence
* spanning multiple reads).
*
* If {@code closed} is {@code true}, then stdout has been closed and
* no more bytes will be received.
*/
void onStderr(ByteBuffer buffer, boolean closed);
/**
* Called when the process is ready to receive bytes on stdin.
*
* Before this method returns, you must set the {@code buffer}'s
* {@link ByteBuffer#position() position} and {@link ByteBuffer#limit() limit} (for example, by
* invoking {@link ByteBuffer#flip()}) to indicate how much data is in the buffer
* before returning from this method.
*
* You must first call {@link LaunchedProcess#wantWrite()} at
* least once before this method will be invoked.
*
* If not all of the data needed to be written will fit in {@code buffer},
* you can return {@code true} to indicate that you would like to write more
* data.
*
* Otherwise, return {@code false} if you have no more data to write to
* stdin. (You can always invoke {@link LaunchedProcess#wantWrite()} any
* time in the future.
*/
boolean onStdinReady(ByteBuffer buffer);
}
/**
* Represents a process which was launched by a {@link ListeningProcessExecutor}.
*/
public interface LaunchedProcess {
/**
* The capacity of each I/O buffer, in bytes.
*/
int BUFFER_CAPACITY = NuProcess.BUFFER_CAPACITY;
/**
* Invoke this to indicate you wish to write to the launched process's stdin.
*
* Your {@link ProcessListener#onStdinReady(ByteBuffer)} method will be invoked
* asynchronously when the process is ready to receive data on stdin.
*/
void wantWrite();
/**
* Invoke this to directly write data to the launched process's stdin.
* This method does not block, and will enqueue the buffer to be written
* to the launched process's stdin at a later date.
*
* If you need to be notified when the write to stdin completes, use
* {@link #wantWrite()} and {@link ProcessListener#onStdinReady(ByteBuffer)}
* instead.
*/
void writeStdin(ByteBuffer buffer);
/**
* Closes the stdin of the process. Call this if the process expects stdin
* to be closed before it writes to stdout.
*
* If {@code force} is {@code true}, then pending writes to stdin are
* discarded. Otherwise, waits for pending writes to flush, then closes
* stdin.
*/
void closeStdin(boolean force);
/**
* Returns {@code true} if the process has any data queued to write to stdin,
* {@code false} otherwise.
*/
boolean hasPendingWrites();
/**
* Returns {@code true} if the process is running, {@code false} otherwise.
*/
boolean isRunning();
}
private static class LaunchedProcessImpl implements LaunchedProcess {
public final NuProcess nuProcess;
public final ProcessExecutorParams params;
public LaunchedProcessImpl(NuProcess nuProcess, ProcessExecutorParams params) {
this.nuProcess = nuProcess;
this.params = params;
}
@Override
public void wantWrite() {
nuProcess.wantWrite();
}
@Override
public void writeStdin(ByteBuffer buffer) {
nuProcess.writeStdin(buffer);
}
@Override
public void closeStdin(boolean force) {
nuProcess.closeStdin(force);
}
@Override
public boolean hasPendingWrites() {
return nuProcess.hasPendingWrites();
}
@Override
public boolean isRunning() {
return nuProcess.isRunning();
}
}
private static class ListeningProcessHandler extends NuAbstractProcessHandler {
private final ProcessExecutorParams params;
private final ProcessListener listener;
@Nullable
public LaunchedProcessImpl process;
public ListeningProcessHandler(ProcessListener listener, ProcessExecutorParams params) {
this.listener = listener;
this.params = params;
}
@Override
public void onPreStart(NuProcess process) {
this.process = new LaunchedProcessImpl(process, params);
}
@Override
public void onStart(NuProcess process) {
Preconditions.checkNotNull(this.process);
Preconditions.checkState(this.process.nuProcess == process);
listener.onStart(this.process);
}
@Override
public void onExit(int exitCode) {
listener.onExit(exitCode);
}
@Override
public void onStdout(ByteBuffer buffer, boolean closed) {
listener.onStdout(buffer, closed);
}
@Override
public void onStderr(ByteBuffer buffer, boolean closed) {
listener.onStderr(buffer, closed);
}
@Override
public boolean onStdinReady(ByteBuffer buffer) {
return listener.onStdinReady(buffer);
}
}
/**
* Launches a process and asynchronously sends notifications to {@code listener} on a
* background thread when the process starts, has I/O, or exits.
*/
public LaunchedProcess launchProcess(ProcessExecutorParams params, final ProcessListener listener)
throws IOException {
LOG.debug("Launching process with params %s", params);
ListeningProcessHandler processHandler = new ListeningProcessHandler(listener, params);
// Unlike with Java's ProcessBuilder, we don't need special param escaping for Win32 platforms.
NuProcessBuilder processBuilder = new NuProcessBuilder(processHandler, params.getCommand());
if (params.getEnvironment().isPresent()) {
processBuilder.environment().clear();
processBuilder.environment().putAll(params.getEnvironment().get());
}
if (params.getDirectory().isPresent()) {
processBuilder.setCwd(params.getDirectory().get().toPath());
}
NuProcess process = BgProcessKiller.startProcess(processBuilder);
if (process == null) {
throw new IOException(String.format("Could not start process with params %s", params));
}
LOG.debug("Successfully launched process %s", process);
// This should be set by onPreStart().
Preconditions.checkState(processHandler.process != null);
return processHandler.process;
}
/**
* Blocks the calling thread until either the process exits or the timeout expires,
* whichever is first.
*
* @return {@code Integer.MIN_VALUE} if the timeout expired or the process failed to start,
* or the exit code of the process otherwise.
*/
public int waitForProcess(LaunchedProcess process, long timeout, TimeUnit timeUnit)
throws InterruptedException {
LOG.debug("Waiting for process %s timeout %d %s", process, timeout, timeUnit);
Preconditions.checkArgument(process instanceof LaunchedProcessImpl);
LaunchedProcessImpl processImpl = (LaunchedProcessImpl) process;
int exitCode = processImpl.nuProcess.waitFor(timeout, timeUnit);
LOG.debug("Wait for process returned %d", exitCode);
return exitCode;
}
/**
* Blocks the calling thread until the process exits.
*
* @return the exit code of the process.
* @throws IOException if the process failed to start.
*/
public int waitForProcess(LaunchedProcess process)
throws InterruptedException, IOException {
long infiniteWait = 0;
int exitCode = waitForProcess(process, infiniteWait, TimeUnit.SECONDS);
if (exitCode == Integer.MIN_VALUE) {
// Specifying 0 for timeout guarantees that the wait will not time out. This way we know that
// an exit code equal to Integer.MIN_VALUE must mean that the process failed to start.
Preconditions.checkArgument(process instanceof LaunchedProcessImpl);
LaunchedProcessImpl processImpl = (LaunchedProcessImpl) process;
throw new IOException(
String.format("Failed to start process %s", processImpl.params.getCommand()));
}
return exitCode;
}
/**
* Destroys a process. If {@code force} is {@code true}, then forcibly
* destroys the process in a way it cannot ignore.
*/
public void destroyProcess(LaunchedProcess process, boolean force) {
LOG.debug("Destroying process %s (force %s)", process, force);
Preconditions.checkArgument(process instanceof LaunchedProcessImpl);
LaunchedProcessImpl processImpl = (LaunchedProcessImpl) process;
processImpl.nuProcess.destroy(force);
}
}
| |
/*
* 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 chat;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import org.apache.catalina.CometEvent;
import org.apache.catalina.CometProcessor;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Helper class to implement Comet functionality.
*/
public class ChatServlet
extends HttpServlet implements CometProcessor {
protected ArrayList<HttpServletResponse> connections =
new ArrayList<HttpServletResponse>();
protected MessageSender messageSender = null;
public void init() throws ServletException {
messageSender = new MessageSender();
Thread messageSenderThread =
new Thread(messageSender, "MessageSender[" + getServletContext().getContextPath() + "]");
messageSenderThread.setDaemon(true);
messageSenderThread.start();
}
public void destroy() {
connections.clear();
messageSender.stop();
messageSender = null;
}
/**
* Process the given Comet event.
*
* @param event The Comet event that will be processed
* @throws IOException
* @throws ServletException
*/
public void event(CometEvent event)
throws IOException, ServletException {
// Note: There should really be two servlets in this example, to avoid
// mixing Comet stuff with regular connection processing
HttpServletRequest request = event.getHttpServletRequest();
HttpServletResponse response = event.getHttpServletResponse();
if (event.getEventType() == CometEvent.EventType.BEGIN) {
String action = request.getParameter("action");
if (action != null) {
if ("login".equals(action)) {
String nickname = request.getParameter("nickname");
request.getSession(true).setAttribute("nickname", nickname);
response.sendRedirect("post.jsp");
event.close();
return;
} else {
String nickname = (String) request.getSession(true).getAttribute("nickname");
String message = request.getParameter("message");
messageSender.send(nickname, message);
response.sendRedirect("post.jsp");
event.close();
return;
}
} else {
if (request.getSession(true).getAttribute("nickname") == null) {
// Redirect to "login"
log("Redirect to login for session: " + request.getSession(true).getId());
response.sendRedirect("login.jsp");
event.close();
return;
}
}
begin(event, request, response);
} else if (event.getEventType() == CometEvent.EventType.ERROR) {
error(event, request, response);
} else if (event.getEventType() == CometEvent.EventType.END) {
end(event, request, response);
} else if (event.getEventType() == CometEvent.EventType.READ) {
read(event, request, response);
}
}
protected void begin(CometEvent event, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
log("Begin for session: " + request.getSession(true).getId());
PrintWriter writer = response.getWriter();
writer.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
writer.println("<html><head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
writer.flush();
synchronized(connections) {
connections.add(response);
}
}
protected void end(CometEvent event, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
log("End for session: " + request.getSession(true).getId());
synchronized(connections) {
connections.remove(response);
}
PrintWriter writer = response.getWriter();
writer.println("</body></html>");
event.close();
}
protected void error(CometEvent event, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
log("Error for session: " + request.getSession(true).getId());
synchronized(connections) {
connections.remove(response);
}
event.close();
}
protected void read(CometEvent event, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
InputStream is = request.getInputStream();
byte[] buf = new byte[512];
do {
int n = is.read(buf);
if (n > 0) {
log("Read " + n + " bytes: " + new String(buf, 0, n)
+ " for session: " + request.getSession(true).getId());
} else if (n < 0) {
error(event, request, response);
return;
}
} while (is.available() > 0);
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Compatibility method: equivalent method using the regular connection model
PrintWriter writer = response.getWriter();
writer.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
writer.println("<html><head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
writer.println("Chat example only supports Comet processing");
writer.println("</body></html>");
}
/**
* Poller class.
*/
public class MessageSender implements Runnable {
protected boolean running = true;
protected ArrayList<String> messages = new ArrayList<String>();
public MessageSender() {
}
public void stop() {
running = false;
}
/**
* Add specified socket and associated pool to the poller. The socket will
* be added to a temporary array, and polled first after a maximum amount
* of time equal to pollTime (in most cases, latency will be much lower,
* however).
*
* @param socket to add to the poller
*/
public void send(String user, String message) {
synchronized (messages) {
messages.add("[" + user + "]: " + message);
messages.notify();
}
}
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/
public void run() {
// Loop until we receive a shutdown command
while (running) {
// Loop if endpoint is paused
if (messages.size() == 0) {
try {
synchronized (messages) {
messages.wait();
}
} catch (InterruptedException e) {
// Ignore
}
}
synchronized (connections) {
String[] pendingMessages = null;
synchronized (messages) {
pendingMessages = messages.toArray(new String[0]);
messages.clear();
}
for (int i = 0; i < connections.size(); i++) {
try {
PrintWriter writer = connections.get(i).getWriter();
for (int j = 0; j < pendingMessages.length; j++) {
// FIXME: Add HTML filtering
writer.println(pendingMessages[j] + "<br/>");
}
writer.flush();
} catch (IOException e) {
log("IOExeption sending message", e);
}
}
}
}
}
}
}
| |
/*
* Copyright 2018 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 androidx.biometric;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.Observer;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A fragment that provides a standard prompt UI for fingerprint authentication on versions prior
* to Android 9.0 (API 28).
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class FingerprintDialogFragment extends DialogFragment {
private static final String TAG = "FingerprintFragment";
/**
* The dialog has not been initialized.
*/
static final int STATE_NONE = 0;
/**
* Waiting for the user to authenticate with fingerprint.
*/
static final int STATE_FINGERPRINT = 1;
/**
* An error or failure occurred during fingerprint authentication.
*/
static final int STATE_FINGERPRINT_ERROR = 2;
/**
* The user has successfully authenticated with fingerprint.
*/
static final int STATE_FINGERPRINT_AUTHENTICATED = 3;
/**
* A possible state for the fingerprint dialog.
*/
@IntDef({
STATE_NONE,
STATE_FINGERPRINT,
STATE_FINGERPRINT_ERROR,
STATE_FINGERPRINT_AUTHENTICATED
})
@Retention(RetentionPolicy.SOURCE)
@interface State {}
/**
* Transient errors and help messages will be displayed on the dialog for this amount of time.
*/
private static final int MESSAGE_DISPLAY_TIME_MS = 2000;
/**
* A handler used to post delayed events.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* A runnable that resets the dialog to its default state and appearance.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
final Runnable mResetDialogRunnable = new Runnable() {
@Override
public void run() {
resetDialog();
}
};
/**
* The view model for the ongoing authentication session.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
BiometricViewModel mViewModel;
/**
* The text color used for displaying error messages.
*/
private int mErrorTextColor;
/**
* The text color used for displaying help messages.
*/
private int mNormalTextColor;
/**
* An icon shown on the dialog during authentication.
*/
@Nullable private ImageView mFingerprintIcon;
/**
* Help text shown below the fingerprint icon on the dialog.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
@Nullable
TextView mHelpMessageView;
// Prevent direct instantiation.
private FingerprintDialogFragment() {}
/**
* Creates a new instance of {@link FingerprintDialogFragment}.
*
* @return A {@link FingerprintDialogFragment}.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
@NonNull
static FingerprintDialogFragment newInstance() {
return new FingerprintDialogFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connectViewModel();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mErrorTextColor = getThemedColorFor(Api26Impl.getColorErrorAttr());
} else {
final Context context = getContext();
mErrorTextColor = context != null
? ContextCompat.getColor(context, R.color.biometric_error_color)
: 0;
}
mNormalTextColor = getThemedColorFor(android.R.attr.textColorSecondary);
}
@Override
@NonNull
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle(mViewModel.getTitle());
// We have to use builder.getContext() instead of the usual getContext() in order to get
// the appropriately themed context for this dialog.
final View layout = LayoutInflater.from(builder.getContext())
.inflate(R.layout.fingerprint_dialog_layout, null);
final TextView subtitleView = layout.findViewById(R.id.fingerprint_subtitle);
if (subtitleView != null) {
final CharSequence subtitle = mViewModel.getSubtitle();
if (TextUtils.isEmpty(subtitle)) {
subtitleView.setVisibility(View.GONE);
} else {
subtitleView.setVisibility(View.VISIBLE);
subtitleView.setText(subtitle);
}
}
final TextView descriptionView = layout.findViewById(R.id.fingerprint_description);
if (descriptionView != null) {
final CharSequence description = mViewModel.getDescription();
if (TextUtils.isEmpty(description)) {
descriptionView.setVisibility(View.GONE);
} else {
descriptionView.setVisibility(View.VISIBLE);
descriptionView.setText(description);
}
}
mFingerprintIcon = layout.findViewById(R.id.fingerprint_icon);
mHelpMessageView = layout.findViewById(R.id.fingerprint_error);
final CharSequence negativeButtonText =
AuthenticatorUtils.isDeviceCredentialAllowed(mViewModel.getAllowedAuthenticators())
? getString(R.string.confirm_device_credential_password)
: mViewModel.getNegativeButtonText();
builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mViewModel.setNegativeButtonPressPending(true);
}
});
builder.setView(layout);
Dialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
@Override
public void onResume() {
super.onResume();
mViewModel.setFingerprintDialogPreviousState(STATE_NONE);
mViewModel.setFingerprintDialogState(STATE_FINGERPRINT);
mViewModel.setFingerprintDialogHelpMessage(
getString(R.string.fingerprint_dialog_touch_sensor));
}
@Override
public void onPause() {
super.onPause();
mHandler.removeCallbacksAndMessages(null);
}
@Override
public void onCancel(@NonNull DialogInterface dialog) {
super.onCancel(dialog);
mViewModel.setFingerprintDialogCancelPending(true);
}
/**
* Connects the {@link BiometricViewModel} for the ongoing authentication session to this
* fragment.
*/
private void connectViewModel() {
final Context host = BiometricPrompt.getHostActivityOrContext(this);
if (host == null) {
return;
}
mViewModel = BiometricPrompt.getViewModel(host);
mViewModel.getFingerprintDialogState().observe(this, new Observer<Integer>() {
@Override
public void onChanged(@State Integer state) {
mHandler.removeCallbacks(mResetDialogRunnable);
updateFingerprintIcon(state);
updateHelpMessageColor(state);
mHandler.postDelayed(mResetDialogRunnable, MESSAGE_DISPLAY_TIME_MS);
}
});
mViewModel.getFingerprintDialogHelpMessage().observe(this, new Observer<CharSequence>() {
@Override
public void onChanged(CharSequence helpMessage) {
mHandler.removeCallbacks(mResetDialogRunnable);
updateHelpMessageText(helpMessage);
mHandler.postDelayed(mResetDialogRunnable, MESSAGE_DISPLAY_TIME_MS);
}
});
}
/**
* Updates the fingerprint icon to match the new dialog state, including animating between
* states if necessary.
*
* @param state The new state for the fingerprint dialog.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
void updateFingerprintIcon(@State int state) {
// May be null if we're intentionally suppressing the dialog.
if (mFingerprintIcon == null) {
return;
}
// Devices older than this do not have FP support (and also do not support SVG), so it's
// fine for this to be a no-op. An error is returned immediately and the dialog is not
// shown.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@State final int previousState = mViewModel.getFingerprintDialogPreviousState();
Drawable icon = getAssetForTransition(previousState, state);
if (icon == null) {
return;
}
mFingerprintIcon.setImageDrawable(icon);
if (shouldAnimateForTransition(previousState, state)) {
Api21Impl.startAnimation(icon);
}
mViewModel.setFingerprintDialogPreviousState(state);
}
}
/**
* Updates the color of the help message text to match the new dialog state.
*
* @param state The new state for the fingerprint dialog.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
void updateHelpMessageColor(@State int state) {
if (mHelpMessageView != null) {
final boolean isError = state == STATE_FINGERPRINT_ERROR;
mHelpMessageView.setTextColor(isError ? mErrorTextColor : mNormalTextColor);
}
}
/**
* Changes the help message text shown on the dialog.
*
* @param helpMessage The new help message text for the dialog.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
void updateHelpMessageText(@Nullable CharSequence helpMessage) {
if (mHelpMessageView != null) {
mHelpMessageView.setText(helpMessage);
}
}
/**
* Resets the appearance of the dialog to its initial state (i.e. waiting for authentication).
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
void resetDialog() {
final Context context = getContext();
if (context == null) {
Log.w(TAG, "Not resetting the dialog. Context is null.");
return;
}
mViewModel.setFingerprintDialogState(STATE_FINGERPRINT);
mViewModel.setFingerprintDialogHelpMessage(
context.getString(R.string.fingerprint_dialog_touch_sensor));
}
/**
* Gets the theme color corresponding to a given style attribute.
*
* @param attr The desired attribute.
* @return The theme color for that attribute.
*/
private int getThemedColorFor(int attr) {
final Context context = getContext();
final Context host = BiometricPrompt.getHostActivityOrContext(this);
if (context == null || host == null) {
Log.w(TAG, "Unable to get themed color. Context or activity is null.");
return 0;
}
TypedValue tv = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, tv, true /* resolveRefs */);
TypedArray arr = host.obtainStyledAttributes(tv.data, new int[] {attr});
final int color = arr.getColor(0 /* index */, 0 /* defValue */);
arr.recycle();
return color;
}
/**
* Checks if the fingerprint icon should animate when transitioning between dialog states.
*
* @param previousState The previous state for the fingerprint dialog.
* @param state The new state for the fingerprint dialog.
* @return Whether the fingerprint icon should animate.
*/
private boolean shouldAnimateForTransition(@State int previousState, @State int state) {
if (previousState == STATE_NONE && state == STATE_FINGERPRINT) {
return false;
} else if (previousState == STATE_FINGERPRINT && state == STATE_FINGERPRINT_ERROR) {
return true;
} else if (previousState == STATE_FINGERPRINT_ERROR && state == STATE_FINGERPRINT) {
return true;
} else if (previousState == STATE_FINGERPRINT && state == STATE_FINGERPRINT_AUTHENTICATED) {
// TODO(b/77328470): add animation when fingerprint is authenticated
return false;
}
return false;
}
/**
* Gets the icon or animation asset that should appear when transitioning between dialog states.
*
* @param previousState The previous state for the fingerprint dialog.
* @param state The new state for the fingerprint dialog.
* @return A drawable asset to be used for the fingerprint icon.
*/
private Drawable getAssetForTransition(@State int previousState, @State int state) {
final Context context = getContext();
if (context == null) {
Log.w(TAG, "Unable to get asset. Context is null.");
return null;
}
int iconRes;
if (previousState == STATE_NONE && state == STATE_FINGERPRINT) {
iconRes = R.drawable.fingerprint_dialog_fp_icon;
} else if (previousState == STATE_FINGERPRINT && state == STATE_FINGERPRINT_ERROR) {
iconRes = R.drawable.fingerprint_dialog_error;
} else if (previousState == STATE_FINGERPRINT_ERROR && state == STATE_FINGERPRINT) {
iconRes = R.drawable.fingerprint_dialog_fp_icon;
} else if (previousState == STATE_FINGERPRINT
&& state == STATE_FINGERPRINT_AUTHENTICATED) {
// TODO(b/77328470): add animation when fingerprint is authenticated
iconRes = R.drawable.fingerprint_dialog_fp_icon;
} else {
return null;
}
return ContextCompat.getDrawable(context, iconRes);
}
/**
* Nested class to avoid verification errors for methods introduced in Android 8.0 (API 26).
*/
@RequiresApi(Build.VERSION_CODES.O)
private static class Api26Impl {
// Prevent instantiation.
private Api26Impl() {}
/**
* Gets the resource ID of the {@code colorError} style attribute.
*/
static int getColorErrorAttr() {
return androidx.appcompat.R.attr.colorError;
}
}
/**
* Nested class to avoid verification errors for methods introduced in Android 5.0 (API 21).
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static class Api21Impl {
// Prevent instantiation.
private Api21Impl() {}
/**
* Starts animating the given icon if it is an {@link AnimatedVectorDrawable}.
*
* @param icon A {@link Drawable} icon asset.
*/
static void startAnimation(@NonNull Drawable icon) {
if (icon instanceof AnimatedVectorDrawable) {
((AnimatedVectorDrawable) icon).start();
}
}
}
}
| |
package ua.edu.cdu.fotius.lisun.musicplayer.fragments;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;
import ua.edu.cdu.fotius.lisun.musicplayer.service.MediaPlaybackServiceWrapper;
import ua.edu.cdu.fotius.lisun.musicplayer.R;
import ua.edu.cdu.fotius.lisun.musicplayer.service.ServiceConnectionObserver;
import ua.edu.cdu.fotius.lisun.musicplayer.activities.InfoEditorActivity.AlbumValidatorsSetCreator;
import ua.edu.cdu.fotius.lisun.musicplayer.activities.InfoEditorActivity.ArtistValidatorSetCreator;
import ua.edu.cdu.fotius.lisun.musicplayer.activities.InfoEditorActivity.BaseValidator;
import ua.edu.cdu.fotius.lisun.musicplayer.activities.InfoEditorActivity.EditInfoQueryCreator;
import ua.edu.cdu.fotius.lisun.musicplayer.activities.InfoEditorActivity.TitleValidatorsSetCreator;
import ua.edu.cdu.fotius.lisun.musicplayer.activities.InfoEditorActivity.YearValidatorSetCreator;
import ua.edu.cdu.fotius.lisun.musicplayer.async_tasks.QueryTrackInfoAsyncTask;
import ua.edu.cdu.fotius.lisun.musicplayer.async_tasks.UpdateTrackInfoAsyncTask;
import ua.edu.cdu.fotius.lisun.musicplayer.views.EditTextWithValidation;
//ToDO: maybe extends BaseFragment
public class InfoEditorFragment extends Fragment implements QueryTrackInfoAsyncTask.Callback,
UpdateTrackInfoAsyncTask.Callback, ServiceConnectionObserver {
public static final String TAG = "edit_info";
public static final String TRACK_ID_KEY = "track_id";
private long mTrackId;
private EditInfoQueryCreator mQueryCreator;
private EditTextWithValidation mTitle;
private EditTextWithValidation mAlbum;
private EditTextWithValidation mArtist;
private EditTextWithValidation mYear;
private MediaPlaybackServiceWrapper mServiceWrapper;
public InfoEditorFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Bundle arguments = getArguments();
mTrackId = arguments.getLong(TRACK_ID_KEY);
mQueryCreator = new EditInfoQueryCreator(mTrackId);
mServiceWrapper = MediaPlaybackServiceWrapper.getInstance();
mServiceWrapper.bindToService(getActivity(), this);
}
@Override
public void onDestroy() {
super.onDestroy();
mServiceWrapper.unbindFromService(getActivity(), this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_edit_track_info, container, false);
ImageButton doneEditingButton = (ImageButton) v.findViewById(R.id.done_editing);
doneEditingButton.setOnClickListener(mOnDoneEditingClick);
mTitle = (EditTextWithValidation) v.findViewById(R.id.title_input);
mTitle.setEnabled(false);
mAlbum = (EditTextWithValidation) v.findViewById(R.id.album_input);
mAlbum.setEnabled(false);
mArtist = (EditTextWithValidation) v.findViewById(R.id.artist_input);
mArtist.setEnabled(false);
mYear = (EditTextWithValidation) v.findViewById(R.id.year_input);
mYear.setEnabled(false);
/*Should be called after initializing EditText views*/
if (savedInstanceState == null) {
new QueryTrackInfoAsyncTask(this, mQueryCreator, this).execute();
}
return v;
}
public void doneEditing() {
if (!isAllEnteredTextValid()) return;
ContentValues contentValues = new ContentValues();
if (mTitle.isChanged()) {
contentValues.put(mQueryCreator.getTitleColumn(),
mTitle.getText().toString());
}
if (mAlbum.isChanged()) {
contentValues.put(mQueryCreator.getAlbumColumn(),
mAlbum.getText().toString());
}
if (mArtist.isChanged()) {
contentValues.put(mQueryCreator.getArtistColumn(),
mArtist.getText().toString());
}
if (mYear.isChanged()) {
contentValues.put(mQueryCreator.getYearColumn(),
mYear.getText().toString());
}
if(contentValues.size() == 0) {
getActivity().finish();
return;
}
new UpdateTrackInfoAsyncTask(this, contentValues, mQueryCreator, this).execute();
}
private boolean isAllEnteredTextValid() {
if (!isSpecificEnteredTextValid(mTitle)) {
return false;
}
if (!isSpecificEnteredTextValid(mAlbum)) {
return false;
}
if (!isSpecificEnteredTextValid(mArtist)) {
return false;
}
if (!isSpecificEnteredTextValid(mYear)) {
return false;
}
return true;
}
private boolean isSpecificEnteredTextValid(EditTextWithValidation editText) {
editText.setValidators(new TitleValidatorsSetCreator(getActivity()).create());
BaseValidator.ValidationResult validationResult = new BaseValidator.ValidationResult();
editText.validateInput(validationResult);
if (!validationResult.isSuccessful) {
notifyUserAboutInvalidInput(editText.getContentDescription().toString(),
validationResult.invalidityMessage);
return false;
}
return true;
}
private void notifyUserAboutInvalidInput(String invalidFieldName, String invalidityMessage) {
String message = getActivity().getResources().getString(R.string.invalid_input,
invalidFieldName, invalidityMessage);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private View.OnClickListener mOnDoneEditingClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
doneEditing();
}
};
@Override
public void updateCompleted() {
mServiceWrapper.updateCurrentTrackInfo();
Activity activity = getActivity();
if (activity == null) return;
activity.finish();
}
@Override
public void queryCompleted(Cursor c) {
/*if couldn't retrieve track info*/
if ((c == null) || (!c.moveToFirst())) {
onQueryError();
return;
}
onQuerySucceed(c);
}
private void onQueryError() {
Activity activity = getActivity();
if (activity == null) return;
Toast.makeText(activity, activity.getResources()
.getString(R.string.query_track_info_error), Toast.LENGTH_SHORT).show();
}
private void onQuerySucceed(Cursor c) {
int idx = c.getColumnIndexOrThrow(mQueryCreator.getTitleColumn());
mTitle.setEnabled(true);
String title = c.getString(idx);
mTitle.setInitialText(title);
mTitle.setSelection(title.length());
idx = c.getColumnIndexOrThrow(mQueryCreator.getAlbumColumn());
mAlbum.setEnabled(true);
mAlbum.setInitialText(c.getString(idx));
idx = c.getColumnIndexOrThrow(mQueryCreator.getArtistColumn());
mArtist.setEnabled(true);
mArtist.setInitialText(c.getString(idx));
idx = c.getColumnIndexOrThrow(mQueryCreator.getYearColumn());
mYear.setEnabled(true);
mYear.setInitialText(Integer.toString(c.getInt(idx)));
c.close();
}
@Override
public void ServiceConnected() {
}
@Override
public void ServiceDisconnected() {
}
}
| |
/*
*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.automation.platform.tests.apim.bam;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.*;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.utils.AuthenticateStubUtil;
import org.wso2.carbon.server.admin.stub.ServerAdminException;
import org.wso2.carbon.server.admin.stub.ServerAdminStub;
import org.wso2.carbon.server.admin.stub.types.carbon.ServerData;
import org.wso2.carbon.utils.FileManipulator;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
/*
Note: This test case is not run with default API manager integration tests. To run this test we assume that BAM server
is running with port offset 1 and API Manager is running with offset 500. All the servers should be configured properly.
https://docs.wso2.com/display/AM190/Publishing+API+Runtime+Statistics
BAM
Configure the WSO2AM_STATS_DB data source in BAM
Start BAM server with offset 1 and deploy the API_Manager_Analytics.tbox
AM
Configure the WSO2AM_STATS_DB data source in AM
Copy jag files in resources/artifacts/AM/jaggery to repository/deployment/server/jaggeryapps/testapp
Enable APIUsageTracking in API manager and start the am server
*/
public class APIUsageBAMIntegrationTestCase extends APIMIntegrationBaseTest {
private APIPublisherRestClient apiPublisher;
private APIStoreRestClient apiStore;
private String app1Name;
private String app2Name;
private final String apiName = "UsageTestAPI";
private final String apiNameFaultyAPI = "UsageTestAPIFaultyAPI";
private final String apiVersion = "1.0.0";
private String[] arrayStat;
private int faultCountBefore = 0;
private int apiCountByUserBefore = 0;
private int successRequestCount = 10;
private int faultRequestCount = 10;
private static final Log log = LogFactory.getLog(APIUsageBAMIntegrationTestCase.class);
@BeforeClass(alwaysRun = true)
public void init() throws APIManagerIntegrationTestException {
super.init();
apiPublisher = new APIPublisherRestClient(publisherUrls.getWebAppURLHttp());
apiStore = new APIStoreRestClient(storeUrls.getWebAppURLHttp());
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
HttpResponse httpResponse;
if(app1Name != null) {
httpResponse = apiStore.removeApplication(app1Name);
checkError(httpResponse.getData(), "Error removing application " + app1Name);
}
if(app2Name != null) {
httpResponse = apiStore.removeApplication(app2Name);
checkError(httpResponse.getData(), "Error removing application " + app2Name);
}
httpResponse = apiPublisher.deleteAPI(apiName, apiVersion
, publisherContext.getSuperTenant().getContextUser().getUserName());
checkError(httpResponse.getData(), "Error deleting API " + apiName);
httpResponse = apiPublisher.deleteAPI(apiNameFaultyAPI, apiVersion
, publisherContext.getSuperTenant().getContextUser().getUserName());
checkError(httpResponse.getData(), "Error deleting API " + apiNameFaultyAPI);
super.cleanUp();
}
@Test(groups = {"wso2.am"}, description = "APIM - BAM Integration API Usage statistics analysis test")
public void testGenerateStatistics() throws Exception {
String providerName = user.getUserName();
String password = user.getPassword();
String apiContext = "UsageTestAPI";
String tags = "UsageTestAPI";
String description = "This is test API create by API manager usage integration test";
String visibility = "user";
String url = "http://en.wikipedia.org/w/api.php";
APIRequest apiRequest = new APIRequest(apiName, apiContext, new URL(url));
apiRequest.setTags(tags);
apiRequest.setDescription(description);
apiRequest.setVersion(apiVersion);
apiRequest.setVisibility(visibility);
apiRequest.setProvider(providerName);
HttpResponse response;
response = apiPublisher.login(providerName, password);
checkError(response.getData(), "Error while authenticating to publisher " + providerName);
HttpResponse addApiResponse = apiPublisher.addAPI(apiRequest);
checkError(addApiResponse.getData(), "Error while adding API " + apiName);
APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, providerName,
APILifeCycleState.PUBLISHED);
response = apiPublisher.changeAPILifeCycleStatus(updateRequest);
checkError(response.getData(), "Error while publishing API " + apiName);
// subscribing to api
response = apiStore.login(providerName, password);
checkError(response.getData(), "Error when authenticating to Store " + providerName);
app1Name = "Statistics-Application-" + new Random().nextInt(10000);
response = apiStore.addApplication(app1Name, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test");
checkError(response.getData(), "Error while adding Application " + app1Name);
SubscriptionRequest subscriptionRequest = new SubscriptionRequest(apiName, providerName);
subscriptionRequest.setApplicationName(app1Name);
response = apiStore.subscribe(subscriptionRequest);
checkError(response.getData(), "Error while subscribing fro API " + apiName);
//Here will do 11 faulty invocations
String apiContextFaultyAPI = "UsageTestAPIFaultyAPI";
String tagsFaultyAPI = "youtube, video, media";
//this url should not exists and then it will return with API fault invocation
String urlFaultyAPI = "http://thisiswrong.com/feeds/api/standardfeeds";
String descriptionFaultyAPI = "This is test API create by API manager usage integration test";
app2Name = "Statistics-Application-" + new Random().nextInt(10000);
APIRequest apiRequestFaultyAPI = new APIRequest(apiNameFaultyAPI, apiContextFaultyAPI
, new URL(urlFaultyAPI));
apiRequestFaultyAPI.setTags(tagsFaultyAPI);
apiRequestFaultyAPI.setDescription(descriptionFaultyAPI);
apiRequestFaultyAPI.setVersion(apiVersion);
response = apiPublisher.addAPI(apiRequestFaultyAPI);
checkError(response.getData(), "Error while adding API " + apiNameFaultyAPI);
APILifeCycleStateRequest updateRequestFaultyAPI = new APILifeCycleStateRequest(apiNameFaultyAPI,
providerName,
APILifeCycleState.PUBLISHED);
response = apiPublisher.changeAPILifeCycleStatus(updateRequestFaultyAPI);
checkError(response.getData(), "Error while publishing API " + apiNameFaultyAPI);
SubscriptionRequest subscriptionRequestFaultyAPI = new SubscriptionRequest(apiNameFaultyAPI,
providerName);
subscriptionRequestFaultyAPI.setApplicationName(app2Name);
response = apiStore.addApplication(app2Name, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test");
checkError(response.getData(), "Error while adding application " + app2Name);
response = apiStore.subscribe(subscriptionRequestFaultyAPI);
checkError(response.getData(), "Error while subscribing to API " + apiNameFaultyAPI);
//host object tests
String fileName = "testUsageWithBAM.jag";
String sourcePath = computeJaggeryResourcePath(fileName);
String destinationPath = computeDestinationPath(fileName);
copySampleFile(sourcePath, destinationPath);
//getting api counts before invocation
String finalOutputUsageTest;
finalOutputUsageTest = HttpRequestUtil.doGet(getTestApplicationUsagePublisherServerURLHttp()
, new HashMap<String, String>()).getData();
assert finalOutputUsageTest != null;
String[] array = finalOutputUsageTest.split("==");
if(array.length > 3) {
JSONArray apiCountJsonArray = new JSONArray(array[2]);
if(apiCountJsonArray.length() > 0 && !apiCountJsonArray.isNull(0)) {
apiCountByUserBefore = apiCountJsonArray.getJSONObject(0).getInt("count");
}
JSONArray faultCountJsonArray = new JSONArray(array[0]);
if(faultCountJsonArray.length() > 0 && !faultCountJsonArray.isNull(0)) {
faultCountBefore = faultCountJsonArray.getJSONObject(0).getInt("count");
}
}
//invoking the API UsageTestAPI
APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(app1Name);
String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
JSONObject jsonResponse = new JSONObject(responseString);
String accessToken = jsonResponse.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("Authorization", "Bearer " + accessToken);
HttpResponse apiResponse;
//Here will do 10 successful invocations
for (int i = 0; i < successRequestCount; i++) {
apiResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp("UsageTestAPI", apiVersion)
+ "?format=json&action=query&titles=MainPage" +
"&prop=revisions&rvprop=content",
requestHeaders);
assertEquals(apiResponse.getResponseCode(), HttpStatus.SC_OK, "Response code mismatched");
}
//invoking faulty API UsageTestAPIFaultyAPI
APPKeyRequestGenerator generateAppKeyRequestFaultyAPI = new APPKeyRequestGenerator(app2Name);
String responseStringFaultyAPI = apiStore.generateApplicationKey(generateAppKeyRequestFaultyAPI).getData();
JSONObject responseFaultyAPI = new JSONObject(responseStringFaultyAPI);
String accessTokenFaultyAPI = responseFaultyAPI.getJSONObject("data").getJSONObject("key").
get("accessToken").toString();
Map<String, String> requestHeadersFaultyAPI = new HashMap<String, String>();
requestHeadersFaultyAPI.put("Authorization", "Bearer " + accessTokenFaultyAPI);
HttpResponse apiResponseFaultyAPI;
for (int i = 0; i < faultRequestCount; i++) {
apiResponseFaultyAPI = HttpRequestUtil.doGet(getAPIInvocationURLHttp("UsageTestAPIFaultyAPI", apiVersion)
+ "?format=json&action=query&titles=MainPage" +
"&prop=revisions&rvprop=content"
, requestHeadersFaultyAPI);
assertEquals(apiResponseFaultyAPI.getResponseCode(), HttpStatus.SC_INTERNAL_SERVER_ERROR
, "Response code mismatched");
}
//sleep toolbox to run and populate the result to database
log.info("waiting for hive job to run and populate statics data");
Thread.sleep(240000);
finalOutputUsageTest = HttpRequestUtil.doGet(getTestApplicationUsagePublisherServerURLHttp()
, new HashMap<String, String>()).getData();
assertNotNull(finalOutputUsageTest, "No response from " + getTestApplicationUsagePublisherServerURLHttp());
arrayStat = finalOutputUsageTest.split("==");
log.info(finalOutputUsageTest + "\n");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by APIResponseFaultCount"
, dependsOnMethods = {"testGenerateStatistics"})
public void testAPIResponseFaultCount() throws Exception {
JSONObject element;
log.info("Verifying getAPIResponseFaultCount in publisher");
assertNotNull(arrayStat[0], "API Fault Usage for Subscriber from API publisher host object not found" +
" (getAPIResponseFaultCount)");
element = new JSONArray(arrayStat[0]).getJSONObject(0);
log.info(element.toString() + "\n");
assertEquals((element.getInt("count") - faultCountBefore) ,faultRequestCount
, "API Fault Requests count mismatched");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by APIUsageByResourcePath"
, dependsOnMethods = {"testGenerateStatistics"})
public void testAPIUsageByResourcePath() throws Exception {
JSONObject element;
log.info("Verifying getAPIUsageByResourcePath in publisher");
assertNotNull(arrayStat[1], "API Usage by ResourcePath from API publisher host object " +
"(getAPIUsageByResourcePath)");
element = new JSONArray(arrayStat[1]).getJSONObject(0);
log.info(element.toString() + "\n");
assertTrue(element.getInt("count") > 0, "No API Usage count by Resource Path");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by APIUsageByUser"
, dependsOnMethods = {"testGenerateStatistics"})
public void testAPIUsageByUser() throws Exception {
JSONObject element;
log.info("Verifying getAPIUsageByResourcePath in publisher");
assertNotNull(arrayStat[2], "No API Usage By User Response from API publisher host object " +
"(getAPIUsageByUser)");
element = new JSONArray(arrayStat[2]).getJSONObject(0);
log.info(element.toString() + "\n");
assertEquals((element.getInt("count") - apiCountByUserBefore) , successRequestCount
, "API Usage count by User mismatched");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by AllAPIUsageByProvider"
, dependsOnMethods = {"testGenerateStatistics"})
public void testAllAPIUsageByProvider() throws Exception {
JSONObject element;
log.info("Verifying getAllAPIUsageByProvider in publisher");
assertNotNull(arrayStat[3], "No API Usage by Provider from API publisher host object " +
"(getAllAPIUsageByProvider)");
element = new JSONArray(arrayStat[3]).getJSONObject(0);
log.info(element.toString() + "\n");
assertNotNull(element.get("userName"), "userName not found in API Usage Response by Provider");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by FirstAccessTime"
, dependsOnMethods = {"testGenerateStatistics"})
public void testFirstAccessTime() throws Exception {
JSONObject element;
log.info("Verifying getFirstAccessTime in publisher");
assertNotNull(arrayStat[4], "No First Access Time Response from API publisher host object " +
"(getFirstAccessTime)");
element = new JSONArray(arrayStat[4]).getJSONObject(0);
log.info(element.toString() + "\n");
assertTrue(element.getInt("year") > 0, "No API Usage count by Provider");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by ProviderAPIServiceTime"
, dependsOnMethods = {"testGenerateStatistics"})
public void testProviderAPIServiceTime() throws Exception {
JSONObject element;
log.info("Verifying getProviderAPIServiceTime in publisher");
assertNotNull(arrayStat[5], "No Service Time Response from API publisher host object " +
"(getProviderAPIServiceTime)");
element = new JSONArray(arrayStat[5]).getJSONObject(0);
log.info(element.toString()+ "\n");
assertTrue(element.getDouble("serviceTime") >= 0, "Service Time Not Found in getProviderAPIServiceTime response");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by ProviderAPIUsage"
, dependsOnMethods = {"testGenerateStatistics"})
public void testProviderAPIUsage() throws Exception {
JSONObject element;
log.info("Verifying getProviderAPIUsage in publisher");
assertNotNull(arrayStat[6], "No API Usage By provider Response from API publisher host object " +
"(getProviderAPIUsage)");
element = new JSONArray(arrayStat[6]).getJSONObject(0);
log.info(element.toString() + "\n");
assertTrue(element.getInt("count") > 0, "No API Usage count by Provider");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by ProviderAPIVersionUsage"
, dependsOnMethods = {"testGenerateStatistics"})
public void testProviderAPIVersionUsage() throws Exception {
JSONObject element;
log.info("Verifying getProviderAPIVersionUsage in publisher");
assertNotNull(arrayStat[7], "No API Version Usage By provider Response from API publisher host object " +
"(getProviderAPIVersionUsage)");
element = new JSONArray(arrayStat[7]).getJSONObject(0);
log.info(element.toString() + "\n");
assertTrue(element.getInt("count") > 0, "No API Version Usage count by Provider");
}
@Test(groups = {"wso2.am"}, description = "API Usage statistics by ProviderAPIVersionUserUsage"
, dependsOnMethods = {"testGenerateStatistics"})
public void testProviderAPIVersionUserUsage() throws Exception {
JSONObject element;
log.info("Verifying getProviderAPIVersionUserUsage in publisher");
assertNotNull(arrayStat[8], "No API Version Usage By user Response from API publisher host object " +
"(getProviderAPIVersionUserUsage)");
element = new JSONArray(arrayStat[8]).getJSONObject(0);
log.info(element.toString() + "\n");
assertTrue(element.getInt("count") > 0, "No API Version Usage count by user");
}
private String getTestApplicationUsagePublisherServerURLHttp() {
return storeUrls.getWebAppURLHttp() + "testapp/testUsageWithBAM.jag";
}
private void copySampleFile(String sourcePath, String destinationPath) {
File sourceFile = new File(sourcePath);
File destinationFile = new File(destinationPath);
try {
FileManipulator.copyFile(sourceFile, destinationFile);
} catch (IOException e) {
log.error("Error while copying the other into Jaggery server", e);
}
}
private String computeDestinationPath(String fileName)
throws XPathExpressionException, RemoteException, ServerAdminException {
String deploymentPath = getServerDeploymentDir() + "jaggeryapps" + File.separator + "testapp";
File depFile = new File(deploymentPath);
if (!depFile.exists() && !depFile.mkdir()) {
log.error("Error while creating the deployment folder : "
+ deploymentPath);
}
return deploymentPath + File.separator + fileName;
}
private String getServerDeploymentDir()
throws XPathExpressionException, RemoteException, ServerAdminException {
ServerAdminStub serverAdminStub;
final String serviceName = "ServerAdmin";
String endPoint = publisherContext.getContextUrls().getBackEndUrl() + serviceName;
serverAdminStub = new ServerAdminStub(endPoint);
AuthenticateStubUtil.authenticateStub(user.getUserName(), user.getPassword(), serverAdminStub);
ServerData serverData = serverAdminStub.getServerData();
return serverData.getRepoLocation().substring(serverData.getRepoLocation().indexOf(":") + 1);
}
private String computeJaggeryResourcePath(String fileName) {
return getAMResourceLocation()
+ File.separator + "jaggery" + File.separator + fileName;
}
private void checkError(String jsonString, String message) throws JSONException {
log.info("Response: " + jsonString);
JSONObject jsonObject = new JSONObject(jsonString);
assertFalse(jsonObject.getBoolean(APIMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_ERROR), message);
}
}
| |
/**
* Copyright 2008-2017 Qualogy Solutions B.V.
*
* 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.qualogy.qafe.mgwt.client.vo.functions.execute;
import com.qualogy.qafe.mgwt.client.activities.AbstractActivity;
import com.qualogy.qafe.mgwt.client.activities.WindowActivity;
import com.qualogy.qafe.mgwt.client.places.AbstractPlace;
import com.qualogy.qafe.mgwt.client.places.WindowPlace;
import com.qualogy.qafe.mgwt.client.vo.functions.BuiltInFunctionGVO;
import com.qualogy.qafe.mgwt.client.vo.functions.OpenWindowGVO;
import com.qualogy.qafe.mgwt.shared.QAMLConstants;
public class OpenWindowExecute extends BuiltInExecute {
public void execute(BuiltInFunctionGVO builtInFunctionGVO, AbstractActivity activity) {
if (builtInFunctionGVO instanceof OpenWindowGVO) {
OpenWindowGVO openWindowGVO = (OpenWindowGVO)builtInFunctionGVO;
openWindow(openWindowGVO, activity);
}
FunctionsExecutor.setProcessedBuiltIn(true);
}
private void openWindow(OpenWindowGVO openWindowGVO, AbstractActivity activity) {
String windowId = openWindowGVO.getWindow();
String context = openWindowGVO.getContext();
AbstractPlace currentPlace = resolveCurrentPlace(windowId, context, activity);
AbstractPlace toPlace = new WindowPlace(windowId, context, currentPlace);
activity.goTo(toPlace);
}
private AbstractPlace resolveCurrentPlace(String windowId, String context, AbstractActivity activity) {
if (activity instanceof WindowActivity) {
WindowActivity windowActivity = (WindowActivity)activity;
WindowPlace currentPlace = windowActivity.getPlace();
if (currentPlace.getFromPlace() instanceof WindowPlace) {
WindowPlace fromPlace = (WindowPlace)currentPlace.getFromPlace();
String fromWindowId = fromPlace.getId();
String fromContex = fromPlace.getContext();
if (fromWindowId.equals(windowId) && fromContex.equals(context)) {
currentPlace = (WindowPlace)fromPlace.getFromPlace();
}
}
return currentPlace;
}
return null;
}
// public void execute(BuiltInFunctionGVO builtInFunctionGVO, AbstractActivity activity) {
// if (builtInFunctionGVO instanceof OpenWindowGVO) {
// OpenWindowGVO openWindow = (OpenWindowGVO) builtInFunctionGVO;
// if (openWindow.getWindow() != null && openWindow.getWindow().length() != 0) {
// if (ClientApplicationContext.getInstance().isMDI()) {
// // ClientApplicationContext.getInstance().removeWindow(openWindow.getWindow(), openWindow.getContext(), openWindow.getUuid());
// } else {
// WindowFactory.clearWidgetFromMainPanel();
// }
// MainFactoryActions.getUIByUUID(openWindow.getUuid(), openWindow.getWindow());
// } else if (openWindow.getUrl() != null && openWindow.getUrl().length() != 0) {
// String title = openWindow.getUrl();
// if (openWindow.getTitle() != null) {
// title = openWindow.getTitle();
// title = title.replace(" ", "_");
// }
// int width = 0;
// int height = 0;
// int left = 20;
// int top = 20;
// String menubar = "no";
// String scrollbars = "no";
// String toolbar = "no";
// String status = "no";
// String resize = "yes";
// String modal = "no";
// String features = "";
// if (openWindow.getParams() != null) {
// String[] paramArr = openWindow.getParams().split(",");
// String temp = null;
// for (int i = 0; i < paramArr.length; i++) {
// if (paramArr[i].indexOf("width") > -1) {
// width = Integer.parseInt(paramArr[i].substring(paramArr[i].indexOf("=") + 1));
// } else if (paramArr[i].indexOf("height") > -1) {
// height = Integer.parseInt(paramArr[i].substring(paramArr[i].indexOf("=") + 1));
// } else if (paramArr[i].indexOf("left") > -1) {
// left = Integer.parseInt(paramArr[i].substring(paramArr[i].indexOf("=") + 1));
// } else if (paramArr[i].indexOf("top") > -1) {
// top = Integer.parseInt(paramArr[i].substring(paramArr[i].indexOf("=") + 1));
// } else if (paramArr[i].indexOf("menubar") > -1) {
// temp = paramArr[i].substring(paramArr[i].indexOf("=") + 1);
// if(temp.equalsIgnoreCase("yes") || temp.equalsIgnoreCase("true") || temp.equals("1")){
// menubar = "yes";
// }
// features = features + "menubar=" + menubar + ",";
// } else if (paramArr[i].indexOf("scrollbars") > -1) {
// temp = paramArr[i].substring(paramArr[i].indexOf("=") + 1);
// if(temp.equalsIgnoreCase("yes") || temp.equalsIgnoreCase("true") || temp.equals("1")){
// scrollbars = "yes";
// }
// features = features + "scrollbars=" + scrollbars + ",";
// } else if (paramArr[i].indexOf("toolbar") > -1) {
// temp = paramArr[i].substring(paramArr[i].indexOf("=") + 1);
// if(temp.equalsIgnoreCase("yes") || temp.equalsIgnoreCase("true") || temp.equals("1")){
// toolbar = "yes";
// }
// features = features + "toolbar=" + toolbar + ",";
// } else if (paramArr[i].indexOf("status") > -1) {
// temp = paramArr[i].substring(paramArr[i].indexOf("=") + 1);
// if(temp.equalsIgnoreCase("yes") || temp.equalsIgnoreCase("true") || temp.equals("1")){
// status = "yes";
// }
// features = features + "status=" + status + ",";
// } else if (paramArr[i].indexOf("resizable") > -1) {
// temp = paramArr[i].substring(paramArr[i].indexOf("=") + 1);
// if(temp.equalsIgnoreCase("no") || temp.equalsIgnoreCase("no") || temp.equals("1")){
// resize = "no";
// }
// features = features + "resizable=" + resize + ",";
// } else if (paramArr[i].indexOf("modal") > -1) {
// temp = paramArr[i].substring(paramArr[i].indexOf("=") + 1);
// if(temp.equalsIgnoreCase("yes") || temp.equalsIgnoreCase("true") || temp.equals("1")){
// modal = "yes";
// }
// }
// }
// }
// if(openWindow.getExternal()){
// if (openWindow.getParams() != null) {
// int index = openWindow.getParams().indexOf("left") + openWindow.getParams().indexOf("top") + openWindow.getParams().indexOf("screenX") + openWindow.getParams().indexOf("screenY");
// if (index > -1) {
// Window.open(openWindow.getUrl(), title, openWindow.getParams());
// } else {
//
// ClientApplicationContext.getInstance().externalWindowCount++;
// if (openWindow.getPlacement().equals(OpenWindowGVO.PLACEMENT_CASCADE)) {
// if (ClientApplicationContext.getInstance().externalWindowCount > 1) {
// for (int i = 1; i < ClientApplicationContext.getInstance().externalWindowCount; i++) {
// left = left + 20;
// top = top + 20;
// }
// }
// features = features + ",screenX=" + left + ",screenY=" + top;
// } else if (openWindow.getPlacement().equals(OpenWindowGVO.PLACEMENT_CENTER_CASCADE)) {
// String centerCordinates = centeredWindow(width, height);
// if (ClientApplicationContext.getInstance().externalWindowCount > 1) {
// String[] centerCordinatesArr = centerCordinates.split(",");
// for (int i = 0; i < centerCordinatesArr.length; i++) {
// if (centerCordinatesArr[i].indexOf("screenX") == 0) {
// left = Integer.parseInt(centerCordinatesArr[i].substring(centerCordinatesArr[i].indexOf("=") + 1));
// }
// if (centerCordinatesArr[i].indexOf("screenY") == 0) {
// top = Integer.parseInt(centerCordinatesArr[i].substring(centerCordinatesArr[i].indexOf("=") + 1));
// }
// }
// for (int i = 1; i < ClientApplicationContext.getInstance().externalWindowCount; i++) {
// left = left + 20;
// top = top + 20;
// }
// features = features + ",screenX=" + left + ",screenY=" + top;
// } else {
// features = features + centerCordinates;
// }
// }
// Window.open(openWindow.getUrl(), title, features);
// }
// } else {
// Window.open(openWindow.getUrl(), title, "");
// }
// } else {
// boolean resizable = true;
// boolean isModal = false;
// if(resize.equals("")|| resize.equals("no")){
// resizable = false;
// }
// if(modal.equals("yes")){
// isModal = true;
// }
// boolean centered = false;
// if (openWindow.getPlacement().equals(OpenWindowGVO.PLACEMENT_CASCADE)) {
// if (ClientApplicationContext.getInstance().internalWindowCount > 0) {
// for (int i = 0; i < ClientApplicationContext.getInstance().internalWindowCount; i++) {
// left = left + 20;
// top = top + 20;
// }
// }
// } else if (openWindow.getPlacement().equals(OpenWindowGVO.PLACEMENT_CENTER_CASCADE)) {
// String[] centerCordinatesArr = centeredWindow(width, height).split(",");
// for (int i = 0; i < centerCordinatesArr.length; i++) {
// if (centerCordinatesArr[i].indexOf("screenX") == 0) {
// left = Integer.parseInt(centerCordinatesArr[i].substring(centerCordinatesArr[i].indexOf("=") + 1));
// }
// if (centerCordinatesArr[i].indexOf("screenY") == 0) {
// top = Integer.parseInt(centerCordinatesArr[i].substring(centerCordinatesArr[i].indexOf("=") + 1));
// }
// }
// if (ClientApplicationContext.getInstance().internalWindowCount > 0) {
// for (int i = 0; i < ClientApplicationContext.getInstance().internalWindowCount; i++) {
// left = left + 20;
// top = top + 20;
// }
// }
// } else if (openWindow.getPlacement().equals(OpenWindowGVO.PLACEMENT_TILED)) {
// top = 30;
// left = 0;
// if (ClientApplicationContext.getInstance().internalWindowCount > 0) {
// int row = 1;
// int column = 1;
// boolean makeNextRow = false;
// for (int i = 0; i < ClientApplicationContext.getInstance().internalWindowCount; i++) {
// left = (width * (i + 1));
// if ((left + width) > screenWidth()) {
// left = 0;
// makeNextRow = true;
// if (row > 1) {
// left = (width * column);
// column++;
// if ((left + width) > screenWidth()) {
// makeNextRow = true;
// } else {
// makeNextRow = false;
// }
// }
// if (makeNextRow) {
// left = 0;
// column = 1;
// top = 30 + (height * row);
// row++;
// makeNextRow = false;
// }
// } else {
// top = 30;
// }
// }
// }
// }
// // corrections for the height
// if (width==0){
// width=600;
// }
//
// if (height==0){
// height=450;
// }
// // MainFactory.createWindowWithUrl(title, openWindow.getUrl(), width, height, resizable, centered, top, left, isModal);
// ClientApplicationContext.getInstance().internalWindowCount++;
// }
// }
// FunctionsExecutor.setProcessedBuiltIn(true);
// }
//
// }
//
// public native String centeredWindow(int w, int h) /*-{
// var left = parseInt(((screen.width - w)/2));
// var top = parseInt(((screen.height - h)/2));
// var windowFeatures = ",screenX=" + left + ",screenY=" + top;
// return windowFeatures;
// }-*/;
//
// public native int screenWidth() /*-{
// return screen.width;
// }-*/;
}
| |
/*
* #%L
* %%
* Copyright (C) 2019 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.joynr.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import io.joynr.exceptions.DiscoveryException;
import io.joynr.proxy.CallbackWithModeledError;
import io.joynr.proxy.Future;
import io.joynr.proxy.ProxyBuilder;
import joynr.exceptions.ApplicationException;
import joynr.tests.DefaulttestProvider;
import joynr.tests.testProxy;
import joynr.types.DiscoveryError;
import joynr.types.GlobalDiscoveryEntry;
/**
* Test that errors from global discovery (add, lookup) are reported correctly to the application.
* Errors from global remove are not reported and thus cannot be tested here.
*/
@RunWith(MockitoJUnitRunner.class)
public class MqttMultipleBackendDiscoveryErrorTest extends AbstractMqttMultipleBackendTest {
@Before
public void setUp() throws InterruptedException {
super.setUp();
createJoynrRuntimeWithMockedGcdClient();
}
private void testLookupWithDiscoveryError(String[] gbidsForLookup, DiscoveryError expectedError) {
ProxyBuilder<testProxy> proxyBuilder = joynrRuntime.getProxyBuilder(TESTDOMAIN, testProxy.class);
proxyBuilder.setDiscoveryQos(discoveryQos);
proxyBuilder.setGbids(gbidsForLookup);
testProxy proxy = proxyBuilder.build();
try {
proxy.voidOperation();
fail("Should never get this far.");
} catch (DiscoveryException e) {
String errorMsg = e.getMessage();
assertNotNull(errorMsg);
assertTrue("Error message does not contain \"DiscoveryError\": " + errorMsg,
errorMsg.contains("DiscoveryError"));
assertTrue("Error message does not contain \"" + expectedError + "\": " + errorMsg,
errorMsg.contains(expectedError.name()));
}
}
private void checkGcdClientAddLookupNotCalled() {
verify(gcdClient, times(0)).add(ArgumentMatchers.<CallbackWithModeledError<Void, DiscoveryError>> any(),
any(GlobalDiscoveryEntry.class),
anyLong(),
any(String[].class));
verify(gcdClient,
times(0)).lookup(ArgumentMatchers.<CallbackWithModeledError<GlobalDiscoveryEntry, DiscoveryError>> any(),
any(String.class),
anyLong(),
any(String[].class));
verify(gcdClient,
times(0)).lookup(ArgumentMatchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
any(String[].class),
any(String.class),
anyLong(),
any(String[].class));
}
@Test
public void testLookupWithUnknownGbid_singleGbid() {
testLookupWithDiscoveryError(new String[]{ "unknownGbid" }, DiscoveryError.UNKNOWN_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testLookupWithUnknownGbid_multipleGbids() {
testLookupWithDiscoveryError(new String[]{ TESTGBID1, "unknownGbid" }, DiscoveryError.UNKNOWN_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testLookupWithInvalidGbid_singleGbid_null() {
testLookupWithDiscoveryError(new String[]{ null }, DiscoveryError.INVALID_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testLookupWithInvalidGbid_singleGbid_empty() {
testLookupWithDiscoveryError(new String[]{ "" }, DiscoveryError.INVALID_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testLookupWithInvalidGbid_multipleGbids_null() {
testLookupWithDiscoveryError(new String[]{ TESTGBID1, null }, DiscoveryError.INVALID_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testLookupWithInvalidGbid_multipleGbids_empty() {
testLookupWithDiscoveryError(new String[]{ TESTGBID1, "" }, DiscoveryError.INVALID_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testLookupWithInvalidGbid_multipleGbids_duplicate() {
testLookupWithDiscoveryError(new String[]{ TESTGBID1, TESTGBID2, TESTGBID1 }, DiscoveryError.INVALID_GBID);
checkGcdClientAddLookupNotCalled();
}
/**
* Purpose of test is to check whether JDS error is correctly transmitted to the caller that tries to build a proxy.
*/
private void testLookupWithGlobalDiscoveryError(DiscoveryError expectedError, String[] gbidsForLookup) {
final String[] expectedGbids = gbidsForLookup.clone();
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
@SuppressWarnings("unchecked")
CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError> callback = (CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>) invocation.getArguments()[0];
callback.onFailure(expectedError);
return null;
}
}).when(gcdClient)
.lookup(ArgumentMatchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
any(String[].class),
anyString(),
anyLong(),
any(String[].class));
testLookupWithDiscoveryError(gbidsForLookup, expectedError);
verify(gcdClient).lookup(ArgumentMatchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
eq(new String[]{ TESTDOMAIN }),
eq(testProxy.INTERFACE_NAME),
anyLong(),
eq(expectedGbids));
}
/**
* A locally valid GBID is invalid for the GCD if the GCD implements additional GBID checks which are more restrictive
* than the local (default) checks (null, empty, duplicate).
*/
@Test
public void testLookupWithGloballyInvalidGbid() {
final DiscoveryError expectedError = DiscoveryError.INVALID_GBID;
final String[] gbidsForLookup = new String[]{ TESTGBID1 };
testLookupWithGlobalDiscoveryError(expectedError, gbidsForLookup);
}
/**
* This is a test for bad configuration: the cluster controller has configured GBIDs that are not known to the GCD.
*/
@Test
public void testLookupWithGloballyUnknownGbid() {
final DiscoveryError expectedError = DiscoveryError.UNKNOWN_GBID;
final String[] gbidsForLookup = new String[]{ TESTGBID1 };
testLookupWithGlobalDiscoveryError(expectedError, gbidsForLookup);
}
@Test
public void testLookupWithGcdInternalError() {
final DiscoveryError expectedError = DiscoveryError.INTERNAL_ERROR;
final String[] gbidsForLookup = new String[]{ TESTGBID1 };
testLookupWithGlobalDiscoveryError(expectedError, gbidsForLookup);
}
@Test
public void testLookupForProviderInDifferentBackend() {
final DiscoveryError expectedError = DiscoveryError.NO_ENTRY_FOR_SELECTED_BACKENDS;
final String[] gbidsForLookup = new String[]{ TESTGBID1 };
testLookupWithGlobalDiscoveryError(expectedError, gbidsForLookup);
}
private void testAddWithDiscoveryError(String[] gbidsForAdd, DiscoveryError expectedError) {
Future<Void> registerFuture = joynrRuntime.getProviderRegistrar(TESTDOMAIN, new DefaulttestProvider())
.withProviderQos(providerQos)
.withGbids(gbidsForAdd)
.awaitGlobalRegistration()
.register();
try {
registerFuture.get(10000);
fail("Should never get this far.");
} catch (ApplicationException e) {
assertEquals(expectedError, e.getError());
} catch (Exception e) {
fail("Unexpected exception from registerProvider: " + e);
}
}
private void testAddWithIllegalArgumentException(String[] gbidsForAdd) {
try {
joynrRuntime.getProviderRegistrar(TESTDOMAIN, new DefaulttestProvider())
.withProviderQos(providerQos)
.withGbids(gbidsForAdd)
.awaitGlobalRegistration()
.register();
fail("Should never get this far.");
} catch (IllegalArgumentException e) {
assertEquals("Provided gbid value(s) must not be null or empty!", e.getMessage());
} catch (Exception e) {
fail("Unexpected exception from registerProvider: " + e);
}
}
@Test
public void testAddWithUnknownGbid_singleGbid() {
testAddWithDiscoveryError(new String[]{ "unknownGbid" }, DiscoveryError.UNKNOWN_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testAddWithUnknownGbid_multipleGbids() {
testAddWithDiscoveryError(new String[]{ TESTGBID1, "unknownGbid" }, DiscoveryError.UNKNOWN_GBID);
checkGcdClientAddLookupNotCalled();
}
@Test
public void testAddWithInvalidGbid_singleGbid_null() {
testAddWithIllegalArgumentException(new String[]{ null });
checkGcdClientAddLookupNotCalled();
}
@Test
public void testAddWithInvalidGbid_singleGbid_empty() {
testAddWithIllegalArgumentException(new String[]{ "" });
checkGcdClientAddLookupNotCalled();
}
@Test
public void testAddWithInvalidGbid_multipleGbids_null() {
testAddWithIllegalArgumentException(new String[]{ TESTGBID1, null });
checkGcdClientAddLookupNotCalled();
}
@Test
public void testAddWithInvalidGbid_multipleGbids_empty() {
testAddWithIllegalArgumentException(new String[]{ TESTGBID1, "" });
checkGcdClientAddLookupNotCalled();
}
@Test
public void testAddWithInvalidGbid_multipleGbids_duplicate() {
testAddWithDiscoveryError(new String[]{ TESTGBID1, TESTGBID2, TESTGBID1 }, DiscoveryError.INVALID_GBID);
checkGcdClientAddLookupNotCalled();
}
/**
* Purpose of test is to check whether JDS error is correctly transmitted to the caller that tries to register a provider.
*/
private void testAddWithGlobalDiscoveryError(DiscoveryError expectedError, String[] gbidsForAdd) {
final String[] expectedGbids = gbidsForAdd.clone();
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
@SuppressWarnings("unchecked")
CallbackWithModeledError<Void, DiscoveryError> callback = (CallbackWithModeledError<Void, DiscoveryError>) invocation.getArguments()[0];
callback.onFailure(expectedError);
return null;
}
}).when(gcdClient).add(ArgumentMatchers.<CallbackWithModeledError<Void, DiscoveryError>> any(),
any(GlobalDiscoveryEntry.class),
anyLong(),
any(String[].class));
testAddWithDiscoveryError(gbidsForAdd, expectedError);
ArgumentCaptor<GlobalDiscoveryEntry> gdeCaptor = ArgumentCaptor.forClass(GlobalDiscoveryEntry.class);
verify(gcdClient).add(ArgumentMatchers.<CallbackWithModeledError<Void, DiscoveryError>> any(),
gdeCaptor.capture(),
anyLong(),
eq(expectedGbids));
assertEquals(TESTDOMAIN, gdeCaptor.getValue().getDomain());
assertEquals(testProxy.INTERFACE_NAME, gdeCaptor.getValue().getInterfaceName());
}
/**
* A locally valid GBID is invalid for the GCD if the GCD implements additional GBID checks which are more restrictive
* than the local (default) checks (null, empty, duplicate).
*/
@Test
public void testAddWithGloballyInvalidGbid() {
final DiscoveryError expectedError = DiscoveryError.INVALID_GBID;
final String[] gbidsForAdd = new String[]{ TESTGBID1 };
testAddWithGlobalDiscoveryError(expectedError, gbidsForAdd);
}
/**
* This is a test for bad configuration: the cluster controller has configured GBIDs that are not known to the GCD.
*/
@Test
public void testAddWithGloballyUnknownGbid() {
final DiscoveryError expectedError = DiscoveryError.UNKNOWN_GBID;
final String[] gbidsForAdd = new String[]{ TESTGBID1 };
testAddWithGlobalDiscoveryError(expectedError, gbidsForAdd);
}
@Test
public void testAddWithGcdInternalError() {
final DiscoveryError expectedError = DiscoveryError.INTERNAL_ERROR;
final String[] gbidsForAdd = new String[]{ TESTGBID1 };
testAddWithGlobalDiscoveryError(expectedError, gbidsForAdd);
}
}
| |
package org.cf.simplify.strategy;
import org.cf.simplify.ExecutionGraphManipulator;
import org.cf.smalivm.SideEffect;
import org.cf.smalivm.context.ExecutionContext;
import org.cf.smalivm.context.ExecutionNode;
import org.cf.smalivm.context.MethodState;
import org.cf.smalivm.opcode.*;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderExceptionHandler;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.BuilderTryBlock;
import org.jf.dexlib2.iface.instruction.OffsetInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class DeadRemovalStrategy implements OptimizationStrategy {
private static final Logger log = LoggerFactory.getLogger(DeadRemovalStrategy.class.getSimpleName());
private final ExecutionGraphManipulator manipulator;
private List<Integer> addresses;
private Set<Integer> exceptionHandlingAddresses;
private int unusedAssignmentCount;
private int uselessBranchCount;
private int unvisitedCount;
private int nopCount;
private int unusedResultCount;
private SideEffect.Level sideEffectThreshold = SideEffect.Level.NONE;
public DeadRemovalStrategy(ExecutionGraphManipulator manipulator) {
this.manipulator = manipulator;
addresses = getValidAddresses(manipulator);
exceptionHandlingAddresses = getExceptionHandlerAddresses(manipulator);
unusedAssignmentCount = 0;
uselessBranchCount = 0;
unvisitedCount = 0;
unusedResultCount = 0;
nopCount = 0;
}
private static Set<Integer> getExceptionHandlerAddresses(ExecutionGraphManipulator manipulator) {
int[] allAddresses = manipulator.getAddresses();
Arrays.sort(allAddresses);
int highestAddress = allAddresses[allAddresses.length - 1];
Set<Integer> handlerAddresses = new HashSet<>();
List<BuilderTryBlock> tryBlocks = manipulator.getTryBlocks();
for (BuilderTryBlock tryBlock : tryBlocks) {
List<? extends BuilderExceptionHandler> handlers = tryBlock.getExceptionHandlers();
for (BuilderExceptionHandler handler : handlers) {
int address = handler.getHandlerCodeAddress();
BuilderInstruction instruction = manipulator.getInstruction(address);
while (address < highestAddress) {
// Add all instructions until return, goto, etc.
handlerAddresses.add(address);
address += instruction.getCodeUnits();
instruction = manipulator.getInstruction(address);
if (!instruction.getOpcode().canContinue()) {
break;
}
}
}
}
return handlerAddresses;
}
private static Set<Integer> getNormalRegistersAssigned(MethodState mState) {
Set<Integer> assigned = new HashSet<>();
for (int register : mState.getRegistersAssigned()) {
if (register < 0) {
continue;
}
assigned.add(register);
}
for (int i = 0; i < mState.getParameterCount(); i++) {
int parameterRegister = mState.getParameterStart() + i;
assigned.remove(parameterRegister);
}
return assigned;
}
private static boolean isAnyRegisterUsed(int address, Set<Integer> registers, ExecutionGraphManipulator graph) {
List<ExecutionNode> children = graph.getChildren(address);
for (ExecutionNode child : children) {
Set<Integer> newRegisters = new HashSet<>(registers);
if (isAnyRegisterUsed(address, newRegisters, graph, child)) {
return true;
}
}
return false;
}
/***
* Check if the values in a set of registers is used (read) at or after a certain address.
* @param address
* @param usedRegisters
* @param graph
* @param node
* @return
*/
private static boolean isAnyRegisterUsed(int address, Set<Integer> usedRegisters, ExecutionGraphManipulator graph,
ExecutionNode node) {
ExecutionNode current = node;
Set<Integer> reassignedRegisters = new HashSet<Integer>();
for (; ; ) {
MethodState mState = current.getContext().getMethodState();
for (int register : usedRegisters) {
// Need to check if read before checking if assigned because some ops may read & assign to the same register, e.g. add-int/2addr v0, v0
if (mState.wasRegisterRead(register)) {
if (log.isTraceEnabled()) {
log.trace("r{} read after {} @{} with {}", register, address, current.getAddress(),
current.getOp());
}
return true;
}
// aput mutates an object. Assignment isn't "reassignment" like it is with other ops
if (mState.wasRegisterAssigned(register)) {
if (current.getOp() instanceof APutOp) {
// aput* ops mutate the value at the target register, they don't reassign to a new object, so don't count it as reassignment
continue;
}
if (log.isTraceEnabled()) {
log.trace("r{} assigned after {} @{} with {}", register, address, current.getAddress(),
current.getOp());
}
// This register has been reassigned so the original value isn't accessible from this register anymore.
reassignedRegisters.add(register);
}
}
usedRegisters.removeAll(reassignedRegisters);
if (usedRegisters.isEmpty()) {
return false;
}
List<ExecutionNode> children = current.getChildren();
if (children.size() == 1) {
current = children.get(0);
} else {
for (ExecutionNode child : children) {
Set<Integer> newRegisters = new HashSet<>(usedRegisters);
if (isAnyRegisterUsed(address, newRegisters, graph, child)) {
return true;
}
}
return false;
}
}
}
@Override
public Map<String, Integer> getOptimizationCounts() {
Map<String, Integer> counts = new HashMap<>();
counts.put("dead ops removed", unvisitedCount);
counts.put("dead assignments removed", unusedAssignmentCount);
counts.put("dead results removed", unusedResultCount);
counts.put("useless gotos removed", uselessBranchCount);
counts.put("nops removed", nopCount);
return counts;
}
@Override
public boolean perform() {
// Updated addresses each time because they change outside of this method.
addresses = getValidAddresses(manipulator);
exceptionHandlingAddresses = getExceptionHandlerAddresses(manipulator);
Set<Integer> removeSet = new HashSet<>();
List<Integer> removeAddresses;
removeAddresses = getDeadAddresses();
unvisitedCount += removeAddresses.size();
removeSet.addAll(removeAddresses);
removeAddresses = getDeadAssignmentAddresses();
unusedAssignmentCount += removeAddresses.size();
removeSet.addAll(removeAddresses);
removeAddresses = getDeadResultAddresses();
unusedResultCount += removeAddresses.size();
removeSet.addAll(removeAddresses);
removeAddresses = getUselessBranchAddresses();
uselessBranchCount += removeAddresses.size();
removeSet.addAll(removeAddresses);
removeAddresses = getNopAddresses();
nopCount += removeAddresses.size();
removeSet.addAll(removeAddresses);
List<Integer> deadAddresses = new LinkedList<>(removeSet);
if (deadAddresses.size() > 0) {
manipulator.removeInstructions(deadAddresses);
}
return !removeSet.isEmpty();
}
public void setRemoveWeak(boolean removeWeak) {
if (removeWeak) {
sideEffectThreshold = SideEffect.Level.WEAK;
}
}
List<Integer> getDeadAddresses() {
return addresses.stream().filter(this::isDead).collect(Collectors.toList());
}
List<Integer> getDeadAssignmentAddresses() {
return addresses.stream().filter(this::isDeadAssignment).collect(Collectors.toList());
}
List<Integer> getDeadResultAddresses() {
return addresses.stream().filter(this::isDeadResult).collect(Collectors.toList());
}
List<Integer> getImpotentMethodInvocations() {
return addresses.stream().filter(this::isImpotentMethodInvocation).collect(Collectors.toList());
}
List<Integer> getNopAddresses() {
return addresses.stream().filter(this::isNop).collect(Collectors.toList());
}
List<Integer> getUselessBranchAddresses() {
return addresses.stream().filter(this::isUselessBranch).collect(Collectors.toList());
}
List<Integer> getValidAddresses(ExecutionGraphManipulator manipulator) {
List<Integer> validAddresses = IntStream.of(manipulator.getAddresses()).boxed().collect(Collectors.toList());
List<Integer> invalidAddresses = new LinkedList<>();
// Should never remove the last op. It's either return, goto, or an array payload.
invalidAddresses.add(validAddresses.get(validAddresses.size() - 1));
for (int address : validAddresses) {
if (!manipulator.wasAddressReached(address)) {
// Unreached code is valid for removal
continue;
}
Op op = manipulator.getOp(address);
if (isSideEffectAboveThreshold(op.getSideEffectLevel())) {
invalidAddresses.add(address);
continue;
}
if (op.getName().startsWith("invoke-direct")) {
if (manipulator.getMethod().getSignature().contains(";-><init>(")) {
// Can't remove init method without breaking the object
ExecutionNode node = manipulator.getNodePile(address).get(0);
ExecutionContext context = node.getContext();
MethodState mState = context.getMethodState();
StringBuilder sb = new StringBuilder("invoke-direct {r");
sb.append(mState.getParameterStart() - 1); // p0 for instance method
if (op.toString().startsWith(sb.toString())) {
invalidAddresses.add(address);
continue;
}
}
}
}
validAddresses.removeAll(invalidAddresses);
return validAddresses;
}
private boolean isDead(int address) {
Op op = manipulator.getOp(address);
log.debug("Dead test @{} for: {}", address, op);
if (exceptionHandlingAddresses.contains(address)) {
// If virtual execution was perfect, unvisited exception handling code could safely be removed provided
// you also removed the try/catch but that level of accuracy is difficult. Instead, compromise by not
// removing unvisited code, but try and remove for other reasons such as dead assignment.
return false;
}
if (manipulator.wasAddressReached(address)) {
return false;
}
if (op instanceof GotoOp) {
// These are handled specifically by isUselessBranch
return false;
}
if (op instanceof NopOp) {
int nextAddress = address + op.getLocation().getInstruction().getCodeUnits();
Opcode nextOp = manipulator.getLocation(nextAddress).getInstruction().getOpcode();
if (nextOp == Opcode.ARRAY_PAYLOAD) {
// Necessary nop padding
return false;
}
}
return true;
}
private boolean isDeadAssignment(int address) {
if (!manipulator.wasAddressReached(address)) {
return false;
}
ExecutionNode node = manipulator.getNodePile(address).get(0);
ExecutionContext context = node.getContext();
if (context == null) {
if (log.isWarnEnabled()) {
log.warn("Null execution context @{}. This shouldn't happen!", address);
}
return false;
}
MethodState mState = context.getMethodState();
Set<Integer> assigned = getNormalRegistersAssigned(mState);
if (assigned.isEmpty()) {
// Has no assignments at all
return false;
}
Op op = manipulator.getOp(address);
if (isSideEffectAboveThreshold(op.getSideEffectLevel())) {
return false;
}
if (op instanceof InvokeOp) {
String returnType = ((InvokeOp) op).getReturnType();
if (!"V".equals(returnType)) {
// Handled by dead result
return false;
}
}
log.debug("Dead assignments test @{} for: {}", address, op);
if (isAnyRegisterUsed(address, assigned, manipulator)) {
return false;
}
return true;
}
private boolean isDeadResult(int address) {
if (!manipulator.wasAddressReached(address)) {
return false;
}
Op op = manipulator.getOp(address);
if (!(op instanceof InvokeOp)) {
return false;
}
log.debug("Dead result test @{} for: {}", address, op);
if (isSideEffectAboveThreshold(op.getSideEffectLevel())) {
return false;
}
String returnType = ((InvokeOp) op).getReturnType();
if ("V".equals(returnType)) {
return false;
}
BuilderInstruction instruction = manipulator.getInstruction(address);
int nextAddress = address + instruction.getCodeUnits();
BuilderInstruction nextInstr = manipulator.getInstruction(nextAddress);
if (nextInstr == null) {
return false;
}
if (nextInstr.getOpcode().name.startsWith("move-result")) {
// The result is at least mapped to a normal register
return false;
}
ExecutionNode node = manipulator.getNodePile(address).get(0);
ExecutionContext context = node.getContext();
MethodState mState = context.getMethodState();
Set<Integer> assigned = getNormalRegistersAssigned(mState);
if (0 < assigned.size()) {
if (isAnyRegisterUsed(address, assigned, manipulator)) {
// Result may not be used, but assignments *are* used
return false;
}
}
return true;
}
private boolean isImpotentMethodInvocation(int address) {
return false;
}
private boolean isNop(int address) {
if (!manipulator.wasAddressReached(address)) {
return false;
}
Op op = manipulator.getOp(address);
if (op instanceof NopOp) {
return true;
}
return false;
}
private boolean isSideEffectAboveThreshold(SideEffect.Level level) {
return level.compareTo(sideEffectThreshold) > 0;
}
private boolean isUselessBranch(int address) {
Op op = manipulator.getOp(address);
if (!(op instanceof GotoOp)) {
return false;
}
// Branch is useless if it branches to the next instruction.
OffsetInstruction instruction = (OffsetInstruction) manipulator.getInstruction(address);
int branchOffset = instruction.getCodeOffset();
if (branchOffset != instruction.getCodeUnits()) {
return false;
}
return true;
}
}
| |
package it.unibz.inf.ontop.owlrefplatform.core.reformulation;
/*
* #%L
* ontop-reformulation-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* 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 it.unibz.inf.ontop.ontology.ClassExpression;
import it.unibz.inf.ontop.ontology.OClass;
import it.unibz.inf.ontop.ontology.ObjectPropertyExpression;
import it.unibz.inf.ontop.ontology.ObjectSomeValuesFrom;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.Equivalences;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.Intersection;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.TBoxReasoner;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TreeWitnessGenerator {
private final ObjectPropertyExpression property;
// private final OClass filler;
private final Set<ClassExpression> concepts = new HashSet<ClassExpression>();
private Set<ClassExpression> subconcepts;
private ObjectSomeValuesFrom existsRinv;
private final TBoxReasoner reasoner;
private static final Logger log = LoggerFactory.getLogger(TreeWitnessGenerator.class);
// private static final OntologyFactory ontFactory = OntologyFactoryImpl.getInstance();
public TreeWitnessGenerator(TBoxReasoner reasoner, ObjectPropertyExpression property/*, OClass filler*/) {
this.reasoner = reasoner;
this.property = property;
// this.filler = filler;
}
// tree witness generators of the ontology (i.e., positive occurrences of \exists R.B)
public static Collection<TreeWitnessGenerator> getTreeWitnessGenerators(TBoxReasoner reasoner) {
Map<ClassExpression, TreeWitnessGenerator> gens = new HashMap<ClassExpression, TreeWitnessGenerator>();
// COLLECT GENERATING CONCEPTS (together with their declared subclasses)
// TODO: improve the algorithm
for (Equivalences<ClassExpression> set : reasoner.getClassDAG()) {
Set<Equivalences<ClassExpression>> subClasses = reasoner.getClassDAG().getSub(set);
boolean couldBeGenerating = set.size() > 1 || subClasses.size() > 1;
for (ClassExpression concept : set) {
if (concept instanceof ObjectSomeValuesFrom && couldBeGenerating) {
ObjectSomeValuesFrom some = (ObjectSomeValuesFrom)concept;
TreeWitnessGenerator twg = gens.get(some);
if (twg == null) {
twg = new TreeWitnessGenerator(reasoner, some.getProperty());
gens.put(concept, twg);
}
for (Equivalences<ClassExpression> subClassSet : subClasses) {
for (ClassExpression subConcept : subClassSet) {
if (!subConcept.equals(concept)) {
twg.concepts.add(subConcept);
log.debug("GENERATING CI: {} <= {}", subConcept, some);
}
}
}
}
}
}
return gens.values();
}
public static Set<ClassExpression> getMaximalBasicConcepts(Collection<TreeWitnessGenerator> gens, TBoxReasoner reasoner) {
Set<ClassExpression> concepts = new HashSet<ClassExpression>();
for (TreeWitnessGenerator twg : gens)
concepts.addAll(twg.concepts);
if (concepts.isEmpty())
return concepts;
if (concepts.size() == 1 && concepts.iterator().next() instanceof OClass)
return concepts;
log.debug("MORE THAN ONE GENERATING CONCEPT: {}", concepts);
// add all sub-concepts of all \exists R
Set<ClassExpression> extension = new HashSet<ClassExpression>();
for (ClassExpression b : concepts)
if (b instanceof ObjectSomeValuesFrom)
extension.addAll(reasoner.getClassDAG().getSubRepresentatives(b));
concepts.addAll(extension);
// use all concept names to subsume their sub-concepts
{
boolean modified = true;
while (modified) {
modified = false;
for (ClassExpression b : concepts)
if (b instanceof OClass) {
Set<ClassExpression> bsubconcepts = reasoner.getClassDAG().getSubRepresentatives(b);
Iterator<ClassExpression> i = concepts.iterator();
while (i.hasNext()) {
ClassExpression bp = i.next();
if ((b != bp) && bsubconcepts.contains(bp)) {
i.remove();
modified = true;
}
}
if (modified)
break;
}
}
}
// use all \exists R to subsume their sub-concepts of the form \exists R
{
boolean modified = true;
while (modified) {
modified = false;
for (ClassExpression b : concepts)
if (b instanceof ObjectSomeValuesFrom) {
ObjectSomeValuesFrom some = (ObjectSomeValuesFrom)b;
ObjectPropertyExpression prop = (ObjectPropertyExpression) some.getProperty();
Set<ObjectPropertyExpression> bsubproperties = reasoner.getObjectPropertyDAG().getSubRepresentatives(prop);
Iterator<ClassExpression> i = concepts.iterator();
while (i.hasNext()) {
ClassExpression bp = i.next();
if ((b != bp) && (bp instanceof ObjectSomeValuesFrom)) {
ObjectSomeValuesFrom somep = (ObjectSomeValuesFrom)bp;
ObjectPropertyExpression propp = somep.getProperty();
if (bsubproperties.contains(propp)) {
i.remove();
modified = true;
}
}
}
if (modified)
break;
}
}
}
return concepts;
}
public Set<ClassExpression> getSubConcepts() {
if (subconcepts == null) {
subconcepts = new HashSet<ClassExpression>();
for (ClassExpression con : concepts)
subconcepts.addAll(reasoner.getClassDAG().getSubRepresentatives(con));
}
return subconcepts;
}
public ObjectPropertyExpression getProperty() {
return property;
}
private void ensureExistsRinv() {
if (existsRinv == null) {
if (property instanceof ObjectPropertyExpression) {
ObjectPropertyExpression inv = ((ObjectPropertyExpression)property).getInverse();
existsRinv = inv.getDomain();
}
// else {
// DataPropertyExpression inv = ((DataPropertyExpression)property).getInverse();
// existsRinv = ontFactory.createPropertySomeRestriction(inv);
// }
}
}
public boolean endPointEntailsAnyOf(Set<ClassExpression> subc) {
ensureExistsRinv();
return subc.contains(existsRinv); // || subc.contains(filler);
}
public boolean endPointEntailsAnyOf(Intersection<ClassExpression> subc) {
if (subc.isTop())
return true;
ensureExistsRinv();
return subc.subsumes(existsRinv); // || subc.subsumes(filler);
}
@Override
public String toString() {
return "tw-generator E" + property.toString(); // + "." + filler.toString();
}
@Override
public int hashCode() {
return property.hashCode(); // ^ filler.hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof TreeWitnessGenerator) {
TreeWitnessGenerator o = (TreeWitnessGenerator)other;
return this.property.equals(o.property); // && this.filler.equals(o.filler));
}
return false;
}
}
| |
package parser;
import java.util.HashMap;
import java.util.Map;
public class ExecuteVM {
public static final int CODESIZE = 10000;
public static final int MEMSIZE = 1000;
private HashMap<Integer, Integer> heapReferences = new HashMap<Integer, Integer>();
private HashMap<Integer, HeapBlock> garbageCollector = new HashMap<Integer, HeapBlock>();
private boolean debug = false;
private int[] code;
private int[] memory = new int[MEMSIZE];
private int ip = 0;
private int sp = MEMSIZE;
private int hp = 0;
private int fp = MEMSIZE;
private int ra;
private int rv = -1;
public ExecuteVM(int[] code) {
this.code = code;
}
public ExecuteVM(int[] code, int flags) {
this.code = code;
if ((flags & 1) > 0) {
debug = true;
}
}
public void cpu() {
while (true) {
int bytecode = code[ip++]; // fetch
int v1, v2;
int address;
switch (bytecode) {
case SVMParser.PUSH:
push(code[ip++]);
if (sp < hp) {
//STACKOVERFLOW
System.out.println("STACK OVERFLOW");
System.exit(1);
}
break;
case SVMParser.POP:
pop();
break;
case SVMParser.ADD:
v1 = pop();
v2 = pop();
push(v2 + v1);
break;
case SVMParser.MULT:
v1 = pop();
v2 = pop();
push(v2 * v1);
break;
case SVMParser.DIV:
v1 = pop();
v2 = pop();
if (v1 == 0) {
System.out.println("Division by zero detected.");
System.exit(1);
}
push(v2 / v1);
break;
case SVMParser.SUB:
v1 = pop();
v2 = pop();
push(v2 - v1);
break;
case SVMParser.STOREW: //
address = pop();
int content;
if (heapReferences.get(sp) != null) {
content = popNoGC();
heapReferences.put(address, content);
} else {
content = popNoGC();
}
//if (addReference(content)) {
// heapReferences.put(address, content);
//}
memory[address] = content;
break;
case SVMParser.LOADW: //
int add = pop();
push(memory[add]);
addRefBySP(add);
break;
case SVMParser.BRANCH:
address = code[ip];
ip = address;
break;
case SVMParser.BRANCHEQ: //
address = code[ip++];
v1 = pop();
v2 = pop();
if (v2 == v1)
ip = address;
break;
case SVMParser.BRANCHLESSEQ:
address = code[ip++];
v1 = pop();
v2 = pop();
if (v2 <= v1)
ip = address;
break;
case SVMParser.BRANCHGREATEQ:
address = code[ip++];
v1 = pop();
v2 = pop();
if (v2 >= v1)
ip = address;
break;
case SVMParser.BRANCHLESS:
address = code[ip++];
v1 = pop();
v2 = pop();
if (v2 < v1)
ip = address;
break;
case SVMParser.BRANCHGREAT:
address = code[ip++];
v1 = pop();
v2 = pop();
if (v2 > v1)
ip = address;
break;
case SVMParser.JS: //
address = pop();
ra = ip;
ip = address;
break;
case SVMParser.STORERA: //
ra = pop();
break;
case SVMParser.LOADRA: //
push(ra);
break;
case SVMParser.STORERV: //
heapReferences.remove(sp);
rv = popNoGC();
break;
case SVMParser.LOADRV: //
push(rv);
heapReferences.put(sp, rv);
break;
case SVMParser.LOADFP: //
push(fp);
break;
case SVMParser.STOREFP: //
fp = pop();
break;
case SVMParser.COPYFP: //
fp = sp;
break;
case SVMParser.STOREHP: //
hp = pop();
break;
case SVMParser.LOADHP: //
push(hp);
break;
case SVMParser.MALL: //
int ref = malloc(code[ip++]);
push(ref);
heapReferences.put(sp, ref);
break;
case SVMParser.PRINT:
System.out.println((sp < MEMSIZE) ? memory[sp] : "Empty stack!");
pop();
break;
case SVMParser.HALT:
if (debug == true) {
dumpHeap();
}
return;
}
}
}
private void dumpHeap() {
for (Map.Entry<Integer, HeapBlock> entry : garbageCollector.entrySet()) {
System.out.println("Block of size " + entry.getValue().blockSize + " at address " + entry.getKey() + ".");
}
}
private int malloc(int size) {
int newRef = 0;
HeapBlock block = null;
if (garbageCollector.size() == 0) {
block = new HeapBlock(1, size, newRef);
}
while (block == null) {
boolean room = true;
for (Map.Entry<Integer, HeapBlock> entry : garbageCollector.entrySet()) {
int ref = entry.getKey();
if ((newRef == ref) || (newRef < ref && newRef + size > ref && newRef + size < sp)) {
newRef = ref + entry.getValue().blockSize;
room = false;
break;
}
}
if (room) {
block = new HeapBlock(1, size, newRef);
if (newRef + size >= sp) {
//HEAPOVERFLOW
System.out.println("OUT OF MEMORY.");
System.exit(1);
}
}
}
if (newRef + size > hp) {
hp = newRef + size;
}
if (debug) {
System.out.println("Allocated " + size + " words at " + newRef + ".");
}
garbageCollector.put(newRef, block);
return newRef;
}
private int popNoGC() {
return memory[sp++];
}
private boolean addRefBySP(int add) {
if (heapReferences.get(add) != null) {
if (addReference(heapReferences.get(add))) {
heapReferences.put(sp, heapReferences.get(add));
return true;
} else {
return false;
}
} else {
return false;
}
}
private boolean addReference(int ref) {
HeapBlock block = garbageCollector.get(ref);
if (block == null) {
return false;
}
block.refCount++;
garbageCollector.put(ref, block);
return true;
}
private boolean removeReference(int ref) {
int max;
HeapBlock block = garbageCollector.get(ref);
if (block == null) {
return false;
}
max = ref + block.blockSize;
block.refCount--;
if (block.refCount > 0) {
garbageCollector.put(ref, block);
} else {
if (max == hp) {
hp -= block.blockSize;
}
//garbageCollector.remove(ref);
for (int i = block.address; i < block.address + block.blockSize; i++) {
if (heapReferences.get(i) != null) {
removeReference(memory[i]);
heapReferences.remove(i);
}
}
garbageCollector.remove(block.address);
if (debug == true) {
System.out.println("Deallocated block at " + ref + " of size " + block.blockSize + ".");
}
}
return true;
}
private int pop() {
if (heapReferences.get(sp) != null) {
heapReferences.remove(sp);
if (!removeReference(memory[sp])) {
return memory[sp++];
}
}
return memory[sp++];
}
private void push(int v) {
memory[--sp] = v;
}
private class HeapBlock {
public int refCount;
public int blockSize;
public int address;
public HeapBlock(int count, int size, int add) {
refCount = count;
blockSize = size;
address = add;
}
}
}
| |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/environment.proto
package com.google.cloud.dialogflow.v2beta1;
/**
*
*
* <pre>
* The response message for [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse}
*/
public final class ListEnvironmentsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse)
ListEnvironmentsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListEnvironmentsResponse.newBuilder() to construct.
private ListEnvironmentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEnvironmentsResponse() {
environments_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListEnvironmentsResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ListEnvironmentsResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
environments_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.Environment>();
mutable_bitField0_ |= 0x00000001;
}
environments_.add(
input.readMessage(
com.google.cloud.dialogflow.v2beta1.Environment.parser(), extensionRegistry));
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
nextPageToken_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
environments_ = java.util.Collections.unmodifiableList(environments_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.EnvironmentProto
.internal_static_google_cloud_dialogflow_v2beta1_ListEnvironmentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.EnvironmentProto
.internal_static_google_cloud_dialogflow_v2beta1_ListEnvironmentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.class,
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.Builder.class);
}
public static final int ENVIRONMENTS_FIELD_NUMBER = 1;
private java.util.List<com.google.cloud.dialogflow.v2beta1.Environment> environments_;
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.v2beta1.Environment> getEnvironmentsList() {
return environments_;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder>
getEnvironmentsOrBuilderList() {
return environments_;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
@java.lang.Override
public int getEnvironmentsCount() {
return environments_.size();
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.Environment getEnvironments(int index) {
return environments_.get(index);
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder getEnvironmentsOrBuilder(
int index) {
return environments_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
private volatile java.lang.Object nextPageToken_;
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < environments_.size(); i++) {
output.writeMessage(1, environments_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < environments_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, environments_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse other =
(com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse) obj;
if (!getEnvironmentsList().equals(other.getEnvironmentsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getEnvironmentsCount() > 0) {
hash = (37 * hash) + ENVIRONMENTS_FIELD_NUMBER;
hash = (53 * hash) + getEnvironmentsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response message for [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse)
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.EnvironmentProto
.internal_static_google_cloud_dialogflow_v2beta1_ListEnvironmentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.EnvironmentProto
.internal_static_google_cloud_dialogflow_v2beta1_ListEnvironmentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.class,
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEnvironmentsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (environmentsBuilder_ == null) {
environments_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
environmentsBuilder_.clear();
}
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2beta1.EnvironmentProto
.internal_static_google_cloud_dialogflow_v2beta1_ListEnvironmentsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse
getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse build() {
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse buildPartial() {
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse result =
new com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse(this);
int from_bitField0_ = bitField0_;
if (environmentsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
environments_ = java.util.Collections.unmodifiableList(environments_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.environments_ = environments_;
} else {
result.environments_ = environmentsBuilder_.build();
}
result.nextPageToken_ = nextPageToken_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse) {
return mergeFrom((com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse other) {
if (other
== com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse.getDefaultInstance())
return this;
if (environmentsBuilder_ == null) {
if (!other.environments_.isEmpty()) {
if (environments_.isEmpty()) {
environments_ = other.environments_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureEnvironmentsIsMutable();
environments_.addAll(other.environments_);
}
onChanged();
}
} else {
if (!other.environments_.isEmpty()) {
if (environmentsBuilder_.isEmpty()) {
environmentsBuilder_.dispose();
environmentsBuilder_ = null;
environments_ = other.environments_;
bitField0_ = (bitField0_ & ~0x00000001);
environmentsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getEnvironmentsFieldBuilder()
: null;
} else {
environmentsBuilder_.addAllMessages(other.environments_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.dialogflow.v2beta1.Environment> environments_ =
java.util.Collections.emptyList();
private void ensureEnvironmentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
environments_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.Environment>(environments_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.Environment,
com.google.cloud.dialogflow.v2beta1.Environment.Builder,
com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder>
environmentsBuilder_;
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.v2beta1.Environment> getEnvironmentsList() {
if (environmentsBuilder_ == null) {
return java.util.Collections.unmodifiableList(environments_);
} else {
return environmentsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public int getEnvironmentsCount() {
if (environmentsBuilder_ == null) {
return environments_.size();
} else {
return environmentsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.Environment getEnvironments(int index) {
if (environmentsBuilder_ == null) {
return environments_.get(index);
} else {
return environmentsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder setEnvironments(
int index, com.google.cloud.dialogflow.v2beta1.Environment value) {
if (environmentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEnvironmentsIsMutable();
environments_.set(index, value);
onChanged();
} else {
environmentsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder setEnvironments(
int index, com.google.cloud.dialogflow.v2beta1.Environment.Builder builderForValue) {
if (environmentsBuilder_ == null) {
ensureEnvironmentsIsMutable();
environments_.set(index, builderForValue.build());
onChanged();
} else {
environmentsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder addEnvironments(com.google.cloud.dialogflow.v2beta1.Environment value) {
if (environmentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEnvironmentsIsMutable();
environments_.add(value);
onChanged();
} else {
environmentsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder addEnvironments(
int index, com.google.cloud.dialogflow.v2beta1.Environment value) {
if (environmentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEnvironmentsIsMutable();
environments_.add(index, value);
onChanged();
} else {
environmentsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder addEnvironments(
com.google.cloud.dialogflow.v2beta1.Environment.Builder builderForValue) {
if (environmentsBuilder_ == null) {
ensureEnvironmentsIsMutable();
environments_.add(builderForValue.build());
onChanged();
} else {
environmentsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder addEnvironments(
int index, com.google.cloud.dialogflow.v2beta1.Environment.Builder builderForValue) {
if (environmentsBuilder_ == null) {
ensureEnvironmentsIsMutable();
environments_.add(index, builderForValue.build());
onChanged();
} else {
environmentsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder addAllEnvironments(
java.lang.Iterable<? extends com.google.cloud.dialogflow.v2beta1.Environment> values) {
if (environmentsBuilder_ == null) {
ensureEnvironmentsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, environments_);
onChanged();
} else {
environmentsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder clearEnvironments() {
if (environmentsBuilder_ == null) {
environments_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
environmentsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public Builder removeEnvironments(int index) {
if (environmentsBuilder_ == null) {
ensureEnvironmentsIsMutable();
environments_.remove(index);
onChanged();
} else {
environmentsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.Environment.Builder getEnvironmentsBuilder(
int index) {
return getEnvironmentsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder getEnvironmentsOrBuilder(
int index) {
if (environmentsBuilder_ == null) {
return environments_.get(index);
} else {
return environmentsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder>
getEnvironmentsOrBuilderList() {
if (environmentsBuilder_ != null) {
return environmentsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(environments_);
}
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.Environment.Builder addEnvironmentsBuilder() {
return getEnvironmentsFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.Environment.Builder addEnvironmentsBuilder(
int index) {
return getEnvironmentsFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of agent environments. There will be a maximum number of items
* returned based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.Environment environments = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.v2beta1.Environment.Builder>
getEnvironmentsBuilderList() {
return getEnvironmentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.Environment,
com.google.cloud.dialogflow.v2beta1.Environment.Builder,
com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder>
getEnvironmentsFieldBuilder() {
if (environmentsBuilder_ == null) {
environmentsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.Environment,
com.google.cloud.dialogflow.v2beta1.Environment.Builder,
com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder>(
environments_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
environments_ = null;
}
return environmentsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse)
private static final com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse();
}
public static com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListEnvironmentsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListEnvironmentsResponse>() {
@java.lang.Override
public ListEnvironmentsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListEnvironmentsResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListEnvironmentsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEnvironmentsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.ListEnvironmentsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* 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.openapi.actionSystem.ex;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.UserActivityProviderComponent;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.JBSwingUtilities;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public abstract class ComboBoxAction extends AnAction implements CustomComponentAction {
private static final Icon ARROW_ICON = UIUtil.isUnderDarcula() ? AllIcons.General.ComboArrow : AllIcons.General.ComboBoxButtonArrow;
private static final Icon DISABLED_ARROW_ICON = IconLoader.getDisabledIcon(ARROW_ICON);
private boolean mySmallVariant = true;
private String myPopupTitle;
protected ComboBoxAction() {
}
@Override
public void actionPerformed(AnActionEvent e) {
ComboBoxButton button = (ComboBoxButton)e.getPresentation().getClientProperty(CUSTOM_COMPONENT_PROPERTY);
if (button == null) {
Component contextComponent = e.getData(PlatformDataKeys.CONTEXT_COMPONENT);
JRootPane rootPane = UIUtil.getParentOfType(JRootPane.class, contextComponent);
if (rootPane != null) {
button = (ComboBoxButton)
JBSwingUtilities.uiTraverser().breadthFirstTraversal(rootPane).filter(new Condition<Component>() {
@Override
public boolean value(Component component) {
return component instanceof ComboBoxButton && ((ComboBoxButton)component).getMyAction() == ComboBoxAction.this;
}
}).first();
}
if (button == null) return;
}
if (!button.isShowing()) return;
button.showPopup();
}
@Override
public JComponent createCustomComponent(Presentation presentation) {
JPanel panel = new JPanel(new GridBagLayout());
ComboBoxButton button = createComboBoxButton(presentation);
panel.add(button,
new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.insets(0, 3, 0, 3), 0, 0));
return panel;
}
protected ComboBoxButton createComboBoxButton(Presentation presentation) {
return new ComboBoxButton(presentation);
}
public boolean isSmallVariant() {
return mySmallVariant;
}
public void setSmallVariant(boolean smallVariant) {
mySmallVariant = smallVariant;
}
public void setPopupTitle(String popupTitle) {
myPopupTitle = popupTitle;
}
@Override
public void update(AnActionEvent e) {
}
@NotNull
protected abstract DefaultActionGroup createPopupActionGroup(JComponent button);
protected int getMaxRows() {
return 30;
}
protected int getMinHeight() {
return 1;
}
protected int getMinWidth() {
return 1;
}
protected class ComboBoxButton extends JButton implements UserActivityProviderComponent {
private final Presentation myPresentation;
private boolean myForcePressed = false;
private PropertyChangeListener myButtonSynchronizer;
private boolean myMouseInside = false;
private JBPopup myPopup;
private boolean myForceTransparent = false;
public ComboBoxButton(Presentation presentation) {
myPresentation = presentation;
setEnabled(myPresentation.isEnabled());
setModel(new MyButtonModel());
setHorizontalAlignment(LEFT);
setFocusable(false);
Insets margins = getMargin();
setMargin(JBUI.insets(margins.top, 2, margins.bottom, 2));
if (isSmallVariant()) {
setBorder(JBUI.Borders.empty(0, 2, 0, 2));
if (!UIUtil.isUnderGTKLookAndFeel()) {
setFont(JBUI.Fonts.label(11));
}
}
addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!myForcePressed) {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() {
@Override
public void run() {
showPopup();
}
});
}
}
}
);
//noinspection HardCodedStringLiteral
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
myMouseInside = true;
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
myMouseInside = false;
repaint();
}
@Override
public void mousePressed(final MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
e.consume();
doClick();
}
}
@Override
public void mouseReleased(MouseEvent e) {
dispatchEventToPopup(e);
}
});
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
mouseMoved(new MouseEvent(e.getComponent(),
MouseEvent.MOUSE_MOVED,
e.getWhen(),
e.getModifiers(),
e.getX(),
e.getY(),
e.getClickCount(),
e.isPopupTrigger(),
e.getButton()));
}
@Override
public void mouseMoved(MouseEvent e) {
dispatchEventToPopup(e);
}
});
}
// Event forwarding. We need it if user does press-and-drag gesture for opening popup and choosing item there.
// It works in JComboBox, here we provide the same behavior
private void dispatchEventToPopup(MouseEvent e) {
if (myPopup != null && myPopup.isVisible()) {
JComponent content = myPopup.getContent();
Rectangle rectangle = content.getBounds();
Point location = rectangle.getLocation();
SwingUtilities.convertPointToScreen(location, content);
Point eventPoint = e.getLocationOnScreen();
rectangle.setLocation(location);
if (rectangle.contains(eventPoint)) {
MouseEvent event = SwingUtilities.convertMouseEvent(e.getComponent(), e, myPopup.getContent());
Component component = SwingUtilities.getDeepestComponentAt(content, event.getX(), event.getY());
if (component != null)
component.dispatchEvent(event);
}
}
}
public void setForceTransparent(boolean transparent) {
myForceTransparent = transparent;
}
@NotNull
private Runnable setForcePressed() {
myForcePressed = true;
repaint();
return new Runnable() {
@Override
public void run() {
// give the button a chance to handle action listener
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
myForcePressed = false;
myPopup = null;
}
}, ModalityState.any());
repaint();
fireStateChanged();
}
};
}
@Nullable
@Override
public String getToolTipText() {
return myForcePressed ? null : super.getToolTipText();
}
public void showPopup() {
createPopup(setForcePressed()).showUnderneathOf(this);
}
protected JBPopup createPopup(Runnable onDispose) {
DefaultActionGroup group = createPopupActionGroup(this);
DataContext context = getDataContext();
ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(
myPopupTitle, group, context, false, false, false, onDispose, getMaxRows(), getPreselectCondition());
popup.setMinimumSize(new Dimension(getMinWidth(), getMinHeight()));
return popup;
}
private ComboBoxAction getMyAction() {
return ComboBoxAction.this;
}
protected DataContext getDataContext() {
return DataManager.getInstance().getDataContext(this);
}
@Override
public void removeNotify() {
if (myButtonSynchronizer != null) {
myPresentation.removePropertyChangeListener(myButtonSynchronizer);
myButtonSynchronizer = null;
}
super.removeNotify();
}
@Override
public void addNotify() {
super.addNotify();
if (myButtonSynchronizer == null) {
myButtonSynchronizer = new MyButtonSynchronizer();
myPresentation.addPropertyChangeListener(myButtonSynchronizer);
}
initButton();
}
private void initButton() {
setIcon(myPresentation.getIcon());
setText(myPresentation.getText());
updateTooltipText(myPresentation.getDescription());
updateButtonSize();
}
private void updateTooltipText(String description) {
String tooltip = KeymapUtil.createTooltipText(description, ComboBoxAction.this);
setToolTipText(!tooltip.isEmpty() ? tooltip : null);
}
@Override
public void updateUI() {
super.updateUI();
//if (!UIUtil.isUnderGTKLookAndFeel()) {
// setBorder(UIUtil.getButtonBorder());
//}
//((JComponent)getParent().getParent()).revalidate();
}
protected class MyButtonModel extends DefaultButtonModel {
@Override
public boolean isPressed() {
return myForcePressed || super.isPressed();
}
@Override
public boolean isArmed() {
return myForcePressed || super.isArmed();
}
}
private class MyButtonSynchronizer implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (Presentation.PROP_TEXT.equals(propertyName)) {
setText((String)evt.getNewValue());
updateButtonSize();
}
else if (Presentation.PROP_DESCRIPTION.equals(propertyName)) {
updateTooltipText((String)evt.getNewValue());
}
else if (Presentation.PROP_ICON.equals(propertyName)) {
setIcon((Icon)evt.getNewValue());
updateButtonSize();
}
else if (Presentation.PROP_ENABLED.equals(propertyName)) {
setEnabled(((Boolean)evt.getNewValue()).booleanValue());
}
}
}
@Override
public Insets getInsets() {
final Insets insets = super.getInsets();
return new Insets(insets.top, insets.left, insets.bottom, insets.right + ARROW_ICON.getIconWidth());
}
@Override
public Insets getInsets(Insets insets) {
final Insets result = super.getInsets(insets);
result.right += ARROW_ICON.getIconWidth();
return result;
}
@Override
public boolean isOpaque() {
return !isSmallVariant();
}
@Override
public Dimension getPreferredSize() {
final boolean isEmpty = getIcon() == null && StringUtil.isEmpty(getText());
int width = isEmpty ? JBUI.scale(10) + ARROW_ICON.getIconWidth() : super.getPreferredSize().width;
if (isSmallVariant()) width += JBUI.scale(4);
return new Dimension(width, isSmallVariant() ? JBUI.scale(19) : super.getPreferredSize().height);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(super.getMinimumSize().width, getPreferredSize().height);
}
@Override
public Font getFont() {
return SystemInfo.isMac && isSmallVariant() ? UIUtil.getLabelFont(UIUtil.FontSize.SMALL) : UIUtil.getLabelFont();
}
@Override
public void paint(Graphics g) {
UISettings.setupAntialiasing(g);
final Dimension size = getSize();
final boolean isEmpty = getIcon() == null && StringUtil.isEmpty(getText());
final Color textColor = isEnabled()
? UIManager.getColor("Panel.foreground")
: UIUtil.getInactiveTextColor();
if (myForceTransparent) {
final Icon icon = getIcon();
int x = 7;
if (icon != null) {
icon.paintIcon(this, g, x, (size.height - icon.getIconHeight()) / 2);
x += icon.getIconWidth() + 3;
}
if (!StringUtil.isEmpty(getText())) {
final Font font = getFont();
g.setFont(font);
g.setColor(textColor);
g.drawString(getText(), x, (size.height + font.getSize()) / 2 - 1);
}
} else {
if (isSmallVariant()) {
final Graphics2D g2 = (Graphics2D)g;
g2.setColor(UIUtil.getControlColor());
final int w = getWidth();
final int h = getHeight();
if (getModel().isArmed() && getModel().isPressed()) {
g2.setPaint(UIUtil.getGradientPaint(0, 0, UIUtil.getControlColor(), 0, h, ColorUtil.shift(UIUtil.getControlColor(), 0.8)));
}
else {
if (UIUtil.isUnderDarcula()) {
g2.setPaint(UIUtil.getGradientPaint(0, 0, ColorUtil.shift(UIUtil.getControlColor(), 1.1), 0, h, ColorUtil.shift(UIUtil.getControlColor(), 0.9)));
} else {
g2.setPaint(UIUtil.getGradientPaint(0, 0, new JBColor(SystemInfo.isMac? Gray._226 : Gray._245, Gray._131), 0, h, new JBColor(SystemInfo.isMac? Gray._198 : Gray._208, Gray._128)));
}
}
g2.fillRoundRect(2, 0, w - 2, h, 5, 5);
Color borderColor = myMouseInside ? new JBColor(Gray._111, Gray._118) : new JBColor(Gray._151, Gray._95);
g2.setPaint(borderColor);
g2.drawRoundRect(2, 0, w - 3, h - 1, 5, 5);
final Icon icon = getIcon();
int x = 7;
if (icon != null) {
icon.paintIcon(this, g, x, (size.height - icon.getIconHeight()) / 2);
x += icon.getIconWidth() + 3;
}
if (!StringUtil.isEmpty(getText())) {
final Font font = getFont();
g2.setFont(font);
g2.setColor(textColor);
g2.drawString(getText(), x, (size.height + font.getSize()) / 2 - 1);
}
}
else {
super.paint(g);
}
}
final Insets insets = super.getInsets();
final Icon icon = isEnabled() ? ARROW_ICON : DISABLED_ARROW_ICON;
final int x;
if (isEmpty) {
x = (size.width - icon.getIconWidth()) / 2;
}
else {
if (isSmallVariant()) {
x = size.width - icon.getIconWidth() - insets.right + 1;
}
else {
x = size.width - icon.getIconWidth() - insets.right + (UIUtil.isUnderNimbusLookAndFeel() ? -3 : 2);
}
}
icon.paintIcon(null, g, x, (size.height - icon.getIconHeight()) / 2);
g.setPaintMode();
}
protected void updateButtonSize() {
invalidate();
repaint();
setSize(getPreferredSize());
}
}
protected Condition<AnAction> getPreselectCondition() { return null; }
}
| |
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2010 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.internal.query.processor;
import java.util.*;
import com.db4o.*;
import com.db4o.config.*;
import com.db4o.foundation.*;
import com.db4o.internal.*;
import com.db4o.internal.marshall.*;
import com.db4o.internal.query.*;
import com.db4o.internal.query.SodaQueryComparator.*;
import com.db4o.internal.query.result.*;
import com.db4o.query.*;
import com.db4o.reflect.*;
import com.db4o.types.*;
/**
* QQuery is the users hook on our graph.
*
* A QQuery is defined by it's constraints.
*
* NOTE: This is just a 'partial' base class to allow for variant implementations
* in db4oj and db4ojdk1.2. It assumes that itself is an instance of QQuery
* and should never be used explicitly.
*
* @exclude
*/
public abstract class QQueryBase implements InternalQuery, Unversioned {
transient Transaction _trans;
@decaf.Public
private Collection4 i_constraints = new Collection4();
@decaf.Public
private QQuery i_parent;
@decaf.Public
private String i_field;
private transient QueryEvaluationMode _evaluationMode;
@decaf.Public
private int _prefetchDepth;
@decaf.Public
private int _prefetchCount;
@decaf.Public
private int _evaluationModeAsInt;
@decaf.Public
private QueryComparator _comparator;
private transient final QQuery _this;
@decaf.Public
private List<SodaQueryComparator.Ordering> _orderings;
protected QQueryBase() {
// C/S only
_this = cast(this);
}
protected QQueryBase(Transaction a_trans, QQuery a_parent, String a_field) {
_this = cast(this);
_trans = a_trans;
i_parent = a_parent;
i_field = a_field;
}
public void captureQueryResultConfig() {
final Config4Impl config = _trans.container().config();
_evaluationMode = config.evaluationMode();
_prefetchDepth = config.prefetchDepth();
_prefetchCount = config.prefetchObjectCount();
}
void addConstraint(QCon a_constraint) {
i_constraints.add(a_constraint);
}
private void addConstraint(Collection4 col, Object obj) {
if(attachToExistingConstraints(col, obj, true)){
return;
}
if(attachToExistingConstraints(col, obj, false)){
return;
}
QConObject newConstraint = new QConObject(_trans, null, null, obj);
addConstraint(newConstraint);
col.add(newConstraint);
}
private boolean attachToExistingConstraints(Collection4 newConstraintsCollector, Object obj, boolean onlyForPaths) {
boolean found = false;
final Iterator4 j = iterateConstraints();
while (j.moveNext()) {
QCon existingConstraint = (QCon)j.current();
final BooleanByRef removeExisting = new BooleanByRef(false);
if(! onlyForPaths || (existingConstraint instanceof QConPath) ){
QCon newConstraint = existingConstraint.shareParent(obj, removeExisting);
if (newConstraint != null) {
newConstraintsCollector.add(newConstraint);
addConstraint(newConstraint);
if (removeExisting.value) {
removeConstraint(existingConstraint);
}
found = true;
if(! onlyForPaths){
break;
}
}
}
}
return found;
}
/**
* Search for slot that corresponds to class. <br>If not found add it.
* <br>Constrain it. <br>
*/
public Constraint constrain(Object example) {
synchronized (streamLock()) {
ReflectClass claxx = reflectClassForClass(example);
if (claxx != null) {
return addClassConstraint(claxx);
}
QConEvaluation eval = Platform4.evaluationCreate(_trans, example);
if (eval != null) {
return addEvaluationToAllConstraints(eval);
}
Collection4 constraints = new Collection4();
addConstraint(constraints, example);
return toConstraint(constraints);
}
}
private Constraint addEvaluationToAllConstraints(QConEvaluation eval) {
if(i_constraints.size() == 0){
_trans.container().classCollection().iterateTopLevelClasses(new Visitor4() {
public void visit(Object obj) {
ClassMetadata classMetadata = (ClassMetadata) obj;
QConClass qcc = new QConClass(_trans,classMetadata.classReflector());
addConstraint(qcc);
toConstraint(i_constraints).or(qcc);
}
});
}
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
((QCon)i.current()).addConstraint(eval);
}
// FIXME: should return valid Constraint object
return null;
}
private Constraint addClassConstraint(ReflectClass claxx) {
if (isTheObjectClass(claxx)) {
return null;
}
if (claxx.isInterface()) {
return addInterfaceConstraint(claxx);
}
final Collection4 newConstraints = introduceClassConstrain(claxx);
if (newConstraints.isEmpty()) {
QConClass qcc = new QConClass(_trans,claxx);
addConstraint(qcc);
return qcc;
}
return toConstraint(newConstraints);
}
private Collection4 introduceClassConstrain(ReflectClass claxx) {
final Collection4 newConstraints = new Collection4();
final Iterator4 existingConstraints = iterateConstraints();
while (existingConstraints.moveNext()) {
final QCon existingConstraint = (QConObject)existingConstraints.current();
final BooleanByRef removeExisting = new BooleanByRef(false);
final QCon newConstraint =
existingConstraint.shareParentForClass(claxx, removeExisting);
if (newConstraint != null) {
newConstraints.add(newConstraint);
addConstraint(newConstraint);
if (removeExisting.value) {
removeConstraint(existingConstraint);
}
}
}
return newConstraints;
}
private boolean isTheObjectClass(ReflectClass claxx) {
return claxx.equals(stream()._handlers.ICLASS_OBJECT);
}
private Constraint addInterfaceConstraint(ReflectClass claxx) {
Collection4 classes = stream().classCollection().forInterface(claxx);
if (classes.size() == 0) {
QConClass qcc = new QConClass(_trans, null, null, claxx);
addConstraint(qcc);
return qcc;
}
Iterator4 i = classes.iterator();
Constraint constr = null;
while (i.moveNext()) {
ClassMetadata classMetadata = (ClassMetadata)i.current();
ReflectClass classMetadataClaxx = classMetadata.classReflector();
if(classMetadataClaxx != null){
if(! classMetadataClaxx.isInterface()){
if(constr == null){
constr = constrain(classMetadataClaxx);
}else{
constr = constr.or(constrain(classMetadata.classReflector()));
}
}
}
}
return constr;
}
private ReflectClass reflectClassForClass(Object example) {
if(example instanceof ReflectClass){
return (ReflectClass)example;
}
if(example instanceof Class) {
return _trans.reflector().forClass((Class)example);
}
return null;
}
public Constraints constraints() {
synchronized (streamLock()) {
Constraint[] constraints = new Constraint[i_constraints.size()];
i_constraints.toArray(constraints);
return new QConstraints(_trans, constraints);
}
}
public Query descend(final String a_field) {
synchronized (streamLock()) {
final QQuery query = new QQuery(_trans, _this, a_field);
IntByRef run = new IntByRef(1);
if (!descend1(query, a_field, run)) {
// try to add unparented nodes on the second run,
// if not added in the first run and a descendant
// was not found
if (run.value == 1) {
run.value = 2;
if (!descend1(query, a_field, run)) {
new QConUnconditional(_trans, false).attach(query, a_field);
}
}
}
return query;
}
}
private boolean descend1(final QQuery query, final String fieldName, IntByRef run) {
if (run.value == 2 || i_constraints.size() == 0) {
// On the second run we are really creating a second independant
// query network that is not joined to other higher level
// constraints.
// Let's see how this works out. We may need to join networks.
run.value = 0; // prevent a double run of this code
stream().classCollection().attachQueryNode(fieldName, new Visitor4() {
boolean untypedFieldConstraintCollected = false;
public void visit(Object obj) {
Object[] pair = ((Object[]) obj);
ClassMetadata containingClass = (ClassMetadata)pair[0];
FieldMetadata field = (FieldMetadata)pair[1];
if (isTyped(field)) {
addFieldConstraint(containingClass, field);
return;
}
if (untypedFieldConstraintCollected)
return;
addFieldConstraint(containingClass, field);
untypedFieldConstraintCollected = true;
}
private boolean isTyped(FieldMetadata field) {
return !Handlers4.isUntyped(field.getHandler());
}
private void addFieldConstraint(ClassMetadata containingClass,
FieldMetadata field) {
QConClass qcc =
new QConClass(
_trans,
null,
field.qField(_trans),
containingClass.classReflector());
addConstraint(qcc);
toConstraint(i_constraints).or(qcc);
}
});
}
checkConstraintsEvaluationMode();
final BooleanByRef foundClass = new BooleanByRef(false);
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
if (((QCon)i.current()).attach(query, fieldName)) {
foundClass.value = true;
}
}
return foundClass.value;
}
public ObjectSet execute() {
synchronized (streamLock()) {
return triggeringQueryEvents(new Closure4<ObjectSet>() { public ObjectSet run() {
return new ObjectSetFacade(getQueryResult());
}});
}
}
public void executeLocal(final IdListQueryResult result) {
checkConstraintsEvaluationMode();
CreateCandidateCollectionResult r = createCandidateCollection();
boolean checkDuplicates = r.checkDuplicates;
boolean topLevel = r.topLevel;
List4 candidateCollection = r.candidateCollection;
if (Debug4.queries) {
logConstraints();
}
if (candidateCollection != null) {
final Collection4 executionPath = topLevel ? null : fieldPathFromTop();
Iterator4 i = new Iterator4Impl(candidateCollection);
while (i.moveNext()) {
((QCandidates)i.current()).execute();
}
if (candidateCollection._next != null) {
checkDuplicates = true;
}
if (checkDuplicates) {
result.checkDuplicates();
}
final ObjectContainerBase stream = stream();
i = new Iterator4Impl(candidateCollection);
while (i.moveNext()) {
QCandidates candidates = (QCandidates)i.current();
if (topLevel) {
candidates.traverse(result);
} else {
candidates.traverse(new Visitor4() {
public void visit(Object a_object) {
QCandidate candidate = (QCandidate)a_object;
if (candidate.include()) {
TreeInt ids = new TreeInt(candidate._key);
final ByRef<TreeInt> idsNew = new ByRef<TreeInt>();
Iterator4 itPath = executionPath.iterator();
while (itPath.moveNext()) {
idsNew.value = null;
final String fieldName = (String) (itPath.current());
if (ids != null) {
ids.traverse(new Visitor4() {
public void visit(Object treeInt) {
int id = ((TreeInt)treeInt)._key;
StatefulBuffer reader =
stream.readStatefulBufferById(_trans, id);
if (reader != null) {
ObjectHeader oh = new ObjectHeader(stream, reader);
CollectIdContext context = new CollectIdContext(_trans, oh, reader);
oh.classMetadata().collectIDs(context, fieldName);
Tree.traverse(context.ids(), new Visitor4<TreeInt>() {
public void visit(TreeInt node) {
idsNew.value = TreeInt.add(idsNew.value, node._key);
}
});
}
}
});
}
ids = (TreeInt) idsNew.value;
}
if(ids != null){
ids.traverse(new Visitor4() {
public void visit(Object treeInt) {
result.addKeyCheckDuplicates(((TreeInt)treeInt)._key);
}
});
}
}
}
});
}
}
}
sort(result);
}
private void triggerQueryOnFinished() {
stream().callbacks().queryOnFinished(_trans, cast(this));
}
private void triggerQueryOnStarted() {
stream().callbacks().queryOnStarted(_trans, cast(this));
}
public Iterator4 executeLazy(){
checkConstraintsEvaluationMode();
final CreateCandidateCollectionResult r = createCandidateCollection();
final Collection4 executionPath = executionPath(r);
Iterator4 candidateCollection = new Iterator4Impl(r.candidateCollection);
MappingIterator executeCandidates = new MappingIterator(candidateCollection){
protected Object map(Object current) {
return ((QCandidates)current).executeLazy(executionPath);
}
};
CompositeIterator4 resultingIDs = new CompositeIterator4(executeCandidates);
if(!r.checkDuplicates){
return resultingIDs;
}
return checkDuplicates(resultingIDs);
}
public QueryResult getQueryResult() {
synchronized (streamLock()) {
if(i_constraints.size() == 0){
return executeAllObjectsQuery();
}
QueryResult result = executeClassOnlyQuery();
if(result != null) {
return result;
}
optimizeJoins();
return executeQuery();
}
}
protected final QueryResult executeQuery() {
return stream().executeQuery(_this);
}
private QueryResult executeAllObjectsQuery() {
return stream().queryAllObjects(_trans);
}
protected ObjectContainerBase stream() {
return _trans.container();
}
public InternalObjectContainer container() {
return stream();
}
private QueryResult executeClassOnlyQuery() {
final ClassMetadata clazz = singleClassConstraint();
if (null == clazz) {
return null;
}
QueryResult queryResult = stream().classOnlyQuery(QQueryBase.this, clazz);
sort(queryResult);
return queryResult;
}
private ClassMetadata singleClassConstraint() {
if(requiresSort()) {
return null;
}
QConClass clazzconstr = classConstraint();
if (clazzconstr == null) {
return null;
}
ClassMetadata clazz=clazzconstr._classMetadata;
if(clazz==null) {
return null;
}
if(clazzconstr.hasChildren() || clazz.isArray()) {
return null;
}
return clazz;
}
private QConClass classConstraint() {
if (i_constraints.size()!=1) {
return null;
}
Constraint constr=singleConstraint();
if(constr.getClass()!=QConClass.class) {
return null;
}
return (QConClass)constr;
}
private Constraint singleConstraint() {
return (Constraint)i_constraints.singleElement();
}
public static class CreateCandidateCollectionResult {
public final boolean checkDuplicates;
public final boolean topLevel;
public final List4 candidateCollection;
public CreateCandidateCollectionResult(List4 candidateCollection_, boolean checkDuplicates_, boolean topLevel_) {
candidateCollection = candidateCollection_;
topLevel = topLevel_;
checkDuplicates = checkDuplicates_;
}
}
public Iterator4 executeSnapshot(){
final CreateCandidateCollectionResult r = createCandidateCollection();
final Collection4 executionPath = executionPath(r);
Iterator4 candidatesIterator = new Iterator4Impl(r.candidateCollection);
Collection4 snapshots = new Collection4();
while(candidatesIterator.moveNext()){
QCandidates candidates = (QCandidates) candidatesIterator.current();
snapshots.add( candidates.executeSnapshot(executionPath));
}
Iterator4 snapshotsIterator = snapshots.iterator();
final CompositeIterator4 resultingIDs = new CompositeIterator4(snapshotsIterator);
if(!r.checkDuplicates){
return resultingIDs;
}
return checkDuplicates(resultingIDs);
}
public <T> T triggeringQueryEvents(Closure4<T> closure) {
triggerQueryOnStarted();
try {
return closure.run();
} finally {
triggerQueryOnFinished();
}
}
private Iterator4 checkDuplicates(CompositeIterator4 executeAllCandidates) {
return Iterators.filter(executeAllCandidates, new Predicate4() {
private TreeInt ids = new TreeInt(0);
public boolean match(Object current) {
int id = ((Integer)current).intValue();
if(ids.find(id) != null){
return false;
}
ids = (TreeInt)ids.add(new TreeInt(id));
return true;
}
});
}
private Collection4 executionPath(final CreateCandidateCollectionResult r) {
return r.topLevel ? null : fieldPathFromTop();
}
public void checkConstraintsEvaluationMode() {
Iterator4 constraints = iterateConstraints();
while (constraints.moveNext()) {
((QConObject)constraints.current()).setEvaluationMode();
}
}
private Collection4 fieldPathFromTop(){
QQueryBase q = this;
final Collection4 fieldPath = new Collection4();
while (q.i_parent != null) {
fieldPath.prepend(q.i_field);
q = q.i_parent;
}
return fieldPath;
}
private void logConstraints() {
if (Debug4.queries) {
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
((QCon)i.current()).log("");
}
}
}
public CreateCandidateCollectionResult createCandidateCollection() {
List4 candidatesList = createQCandidatesList();
boolean checkDuplicates = false;
boolean topLevel = true;
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
QCon constraint = (QCon)i.current();
QCon old = constraint;
constraint = constraint.getRoot();
if (constraint != old) {
checkDuplicates = true;
topLevel = false;
}
ClassMetadata classMetadata = constraint.getYapClass();
if (classMetadata == null) {
break;
}
addConstraintToCandidatesList(candidatesList, constraint);
}
return new CreateCandidateCollectionResult(candidatesList, checkDuplicates, topLevel);
}
private void addConstraintToCandidatesList(List4 candidatesList, QCon qcon) {
if (candidatesList == null) {
return;
}
Iterator4 j = new Iterator4Impl(candidatesList);
while (j.moveNext()) {
QCandidates candidates = (QCandidates)j.current();
candidates.addConstraint(qcon);
}
}
private List4 createQCandidatesList(){
List4 candidatesList = null;
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
QCon constraint = (QCon)i.current();
constraint = constraint.getRoot();
ClassMetadata classMetadata = constraint.getYapClass();
if (classMetadata == null) {
continue;
}
if(constraintCanBeAddedToExisting(candidatesList, constraint)){
continue;
}
QCandidates candidates = new QCandidates((LocalTransaction) _trans, classMetadata, null);
candidatesList = new List4(candidatesList, candidates);
}
return candidatesList;
}
private boolean constraintCanBeAddedToExisting(List4 candidatesList, QCon constraint){
Iterator4 j = new Iterator4Impl(candidatesList);
while (j.moveNext()) {
QCandidates candidates = (QCandidates)j.current();
if (candidates.fitsIntoExistingConstraintHierarchy(constraint)) {
return true;
}
}
return false;
}
public final Transaction transaction() {
return _trans;
}
public Iterator4 iterateConstraints(){
// clone the collection first to avoid
// InvalidIteratorException as i_constraints might be
// modified during the execution of callee
return new Collection4(i_constraints).iterator();
}
public Query orderAscending() {
if(i_parent == null) {
throw new IllegalStateException("Cannot apply ordering at top level.");
}
synchronized (streamLock()) {
addOrdering(SodaQueryComparator.Direction.ASCENDING);
return _this;
}
}
public Query orderDescending() {
if(i_parent == null) {
throw new IllegalStateException("Cannot apply ordering at top level.");
}
synchronized (streamLock()) {
addOrdering(SodaQueryComparator.Direction.DESCENDING);
return _this;
}
}
private void addOrdering(Direction direction) {
addOrdering(direction, new ArrayList<String>());
}
protected final void addOrdering(Direction direction, List<String> path) {
if (i_field != null) {
path.add(i_field);
}
if (i_parent != null) {
i_parent.addOrdering(direction, path);
return;
}
final String[] fieldPath = reverseFieldPath(path);
removeExistingOrderingFor(fieldPath);
orderings().add(new SodaQueryComparator.Ordering(direction, fieldPath));
}
private void removeExistingOrderingFor(String[] fieldPath) {
for (Ordering ordering : orderings()) {
if (Arrays.equals(ordering.fieldPath(), fieldPath)) {
orderings().remove(ordering);
break;
}
}
}
/**
* Public so it can be used by the LINQ test cases.
*/
public final List<Ordering> orderings() {
if (null == _orderings) {
_orderings = new ArrayList<SodaQueryComparator.Ordering>();
}
return _orderings;
}
private String[] reverseFieldPath(List<String> path) {
final String[] reversedPath = new String[path.size()];
for (int i = 0; i < reversedPath.length; i++) {
reversedPath[i] = path.get(path.size() - i - 1);
}
return reversedPath;
}
public void marshall() {
checkConstraintsEvaluationMode();
_evaluationModeAsInt = _evaluationMode.asInt();
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
((QCon)i.current()).getRoot().marshall();
}
}
public void unmarshall(final Transaction a_trans) {
_evaluationMode = QueryEvaluationMode.fromInt(_evaluationModeAsInt);
_trans = a_trans;
Iterator4 i = iterateConstraints();
while (i.moveNext()) {
((QCon)i.current()).unmarshall(a_trans);
}
}
void removeConstraint(QCon a_constraint) {
i_constraints.remove(a_constraint);
}
Constraint toConstraint(final Collection4 constraints) {
if (constraints.size() == 1) {
return (Constraint) constraints.singleElement();
} else if (constraints.size() > 0) {
Constraint[] constraintArray = new Constraint[constraints.size()];
constraints.toArray(constraintArray);
return new QConstraints(_trans, constraintArray);
}
return null;
}
protected Object streamLock() {
return stream().lock();
}
public Query sortBy(QueryComparator comparator) {
_comparator=comparator;
return _this;
}
private void sort(QueryResult result) {
if (_orderings != null) {
result.sortIds(newSodaQueryComparator());
}
if(_comparator!=null) {
result.sort(_comparator);
}
}
private IntComparator newSodaQueryComparator() {
return new SodaQueryComparator(
(LocalObjectContainer)this.transaction().container(),
extentType(),
_orderings.toArray(new SodaQueryComparator.Ordering[_orderings.size()]));
}
private ClassMetadata extentType() {
return classConstraint().getYapClass();
}
// cheat emulating '(QQuery)this'
private static QQuery cast(QQueryBase obj) {
return (QQuery)obj;
}
public boolean requiresSort() {
if (_comparator != null || _orderings != null){
return true;
}
return false;
}
public QueryComparator comparator() {
return _comparator;
}
public QueryEvaluationMode evaluationMode(){
return _evaluationMode;
}
public void evaluationMode(QueryEvaluationMode mode){
_evaluationMode = mode;
}
private void optimizeJoins() {
if(!hasOrJoins()) {
removeJoins();
}
}
private boolean hasOrJoins() {
return forEachConstraintRecursively(new Function4() {
public Object apply(Object obj) {
QCon constr = (QCon) obj;
Iterator4 joinIter = constr.iterateJoins();
while(joinIter.moveNext()) {
QConJoin join = (QConJoin) joinIter.current();
if(join.isOr()) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
});
}
private void removeJoins() {
forEachConstraintRecursively(new Function4() {
public Object apply(Object obj) {
QCon constr = (QCon) obj;
constr.i_joins = null;
return Boolean.FALSE;
}
});
}
private boolean forEachConstraintRecursively(Function4 block) {
Queue4 queue = new NoDuplicatesQueue(new NonblockingQueue());
Iterator4 constrIter = iterateConstraints();
while(constrIter.moveNext()) {
queue.add(constrIter.current());
}
while(queue.hasNext()) {
QCon constr = (QCon) queue.next();
Boolean cancel = (Boolean) block.apply(constr);
if(cancel.booleanValue()) {
return true;
}
Iterator4 childIter = constr.iterateChildren();
while(childIter.moveNext()) {
queue.add(childIter.current());
}
Iterator4 joinIter = constr.iterateJoins();
while(joinIter.moveNext()) {
queue.add(joinIter.current());
}
}
return false;
}
public int prefetchDepth() {
return _prefetchDepth;
}
public int prefetchCount() {
return _prefetchCount;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("QQueryBase\n");
Iterator4 i = iterateConstraints();
while(i.moveNext()){
QCon constraint = (QCon) i.current();
sb.append(constraint);
sb.append("\n");
}
return sb.toString();
}
public QQuery parent() {
return i_parent;
}
}
| |
package seedu.address.testutil;
import com.google.common.io.Files;
import guitests.guihandles.TaskCardHandle;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import junit.framework.AssertionFailedError;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxToolkit;
import seedu.address.TestApp;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
import seedu.emeraldo.commons.util.FileUtil;
import seedu.emeraldo.commons.util.XmlUtil;
import seedu.emeraldo.model.Emeraldo;
import seedu.emeraldo.model.tag.Tag;
import seedu.emeraldo.model.tag.UniqueTagList;
import seedu.emeraldo.model.task.*;
import seedu.emeraldo.storage.XmlSerializableEmeraldo;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
/**
* A utility class for test cases.
*/
public class TestUtil {
public static String LS = System.lineSeparator();
public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) {
try {
executable.run();
}
catch (Throwable actualException) {
if (!actualException.getClass().isAssignableFrom(expected)) {
String message = String.format("Expected thrown: %s, actual: %s", expected.getName(),
actualException.getClass().getName());
throw new AssertionFailedError(message);
} else return;
}
throw new AssertionFailedError(
String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName()));
}
/**
* Folder used for temp files created during testing. Ignored by Git.
*/
public static String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/");
public static final Task[] sampleTaskData = getSampleTaskData();
//@@author A0139749L
private static Task[] getSampleTaskData() {
try {
return new Task[]{
new Task(new Description("Complete application form for SEP"), new DateTime("by 22/01/2014, 12:01"), new UniqueTagList()),
new Task(new Description("Fred birthday party"), new DateTime("on 22/02/2014"), new UniqueTagList()),
new Task(new Description("Return book to library"), new DateTime("by 22/01/2014, 12:01"), new UniqueTagList()),
new Task(new Description("Bring food for party"), new DateTime("by 22/03/2014, 12:01"), new UniqueTagList()),
new Task(new Description("Go for a haircut"), new DateTime("by 21/01/2018, 12:01"), new UniqueTagList()),
new Task(new Description("Pay for parking fines"), new DateTime("by 11/01/2015, 12:01"), new UniqueTagList()),
new Task(new Description("Complete tutorial for EE2020"), new DateTime("by 22/01/2014, 12:01"), new UniqueTagList()),
new Task(new Description("Do homework"), new DateTime("from 30/01/2017, 11:00 to 28/02/2018, 12:00"), new UniqueTagList()),
new Task(new Description("Buy groceries for mum"), new DateTime("from 30/05/2017, 13:00 to 06/06/2017, 14:00"), new UniqueTagList())
};
} catch (IllegalValueException e) {
assert false;
//not possible
return null;
}
}
//@@author
public static final Tag[] sampleTagData = getSampleTagData();
private static Tag[] getSampleTagData() {
try {
return new Tag[]{
new Tag("relatives"),
new Tag("friends")
};
} catch (IllegalValueException e) {
assert false;
return null;
//not possible
}
}
public static List<Task> generateSampleTaskData() {
return Arrays.asList(sampleTaskData);
}
/**
* Appends the file name to the sandbox folder path.
* Creates the sandbox folder if it doesn't exist.
* @param fileName
* @return
*/
public static String getFilePathInSandboxFolder(String fileName) {
try {
FileUtil.createDirs(new File(SANDBOX_FOLDER));
} catch (IOException e) {
throw new RuntimeException(e);
}
return SANDBOX_FOLDER + fileName;
}
public static void createDataFileWithSampleData(String filePath) {
createDataFileWithData(generateSampleStorageEmeraldo(), filePath);
}
public static <T> void createDataFileWithData(T data, String filePath) {
try {
File saveFileForTesting = new File(filePath);
FileUtil.createIfMissing(saveFileForTesting);
XmlUtil.saveDataToFile(saveFileForTesting, data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String... s) {
createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING);
}
public static Emeraldo generateEmptyEmeraldo() {
return new Emeraldo(new UniqueTaskList(), new UniqueTagList());
}
public static XmlSerializableEmeraldo generateSampleStorageEmeraldo() {
return new XmlSerializableEmeraldo(generateEmptyEmeraldo());
}
/**
* Tweaks the {@code keyCodeCombination} to resolve the {@code KeyCode.SHORTCUT} to their
* respective platform-specific keycodes
*/
public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) {
List<KeyCode> keys = new ArrayList<>();
if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.ALT);
}
if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.SHIFT);
}
if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.META);
}
if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.CONTROL);
}
keys.add(keyCodeCombination.getCode());
return keys.toArray(new KeyCode[]{});
}
public static boolean isHeadlessEnvironment() {
String headlessProperty = System.getProperty("testfx.headless");
return headlessProperty != null && headlessProperty.equals("true");
}
public static void captureScreenShot(String fileName) {
File file = GuiTest.captureScreenshot();
try {
Files.copy(file, new File(fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String descOnFail(Object... comparedObjects) {
return "Comparison failed \n"
+ Arrays.asList(comparedObjects).stream()
.map(Object::toString)
.collect(Collectors.joining("\n"));
}
public static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException{
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
// ~Modifier.FINAL is used to remove the final modifier from field so that its value is no longer
// final and can be changed
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void initRuntime() throws TimeoutException {
FxToolkit.registerPrimaryStage();
FxToolkit.hideStage();
}
public static void tearDownRuntime() throws Exception {
FxToolkit.cleanupStages();
}
/**
* Gets private method of a class
* Invoke the method using method.invoke(objectInstance, params...)
*
* Caveat: only find method declared in the current Class, not inherited from supertypes
*/
public static Method getPrivateMethod(Class objectClass, String methodName) throws NoSuchMethodException {
Method method = objectClass.getDeclaredMethod(methodName);
method.setAccessible(true);
return method;
}
public static void renameFile(File file, String newFileName) {
try {
Files.copy(file, new File(newFileName));
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* Gets mid point of a node relative to the screen.
* @param node
* @return
*/
public static Point2D getScreenMidPoint(Node node) {
double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x,y);
}
/**
* Gets mid point of a node relative to its scene.
* @param node
* @return
*/
public static Point2D getSceneMidPoint(Node node) {
double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x,y);
}
/**
* Gets the bound of the node relative to the parent scene.
* @param node
* @return
*/
public static Bounds getScenePos(Node node) {
return node.localToScene(node.getBoundsInLocal());
}
public static Bounds getScreenPos(Node node) {
return node.localToScreen(node.getBoundsInLocal());
}
public static double getSceneMaxX(Scene scene) {
return scene.getX() + scene.getWidth();
}
public static double getSceneMaxY(Scene scene) {
return scene.getX() + scene.getHeight();
}
public static Object getLastElement(List<?> list) {
return list.get(list.size() - 1);
}
/**
* Removes a subset from the list of tasks.
* @param tasks The list of tasks
* @param tasksToRemove The subset of tasks.
* @return The modified tasks after removal of the subset from tasks.
*/
public static TestTask[] removeTasksFromList(final TestTask[] tasks, TestTask... tasksToRemove) {
List<TestTask> listOfTasks = asList(tasks);
listOfTasks.removeAll(asList(tasksToRemove));
return listOfTasks.toArray(new TestTask[listOfTasks.size()]);
}
/**
* Returns a copy of the list with the task at specified index removed.
* @param list original list to copy from
* @param targetIndexInOneIndexedFormat e.g. if the first element to be removed, 1 should be given as index.
*/
public static TestTask[] removeTaskFromList(final TestTask[] list, int targetIndexInOneIndexedFormat) {
return removeTasksFromList(list, list[targetIndexInOneIndexedFormat-1]);
}
/**
* Replaces tasks[i] with a task.
* @param tasks The array of tasks.
* @param task The replacement task
* @param index The index of the task to be replaced.
* @return
*/
public static TestTask[] replaceTaskFromList(TestTask[] tasks, TestTask task, int index) {
tasks[index] = task;
return tasks;
}
/**
* Appends tasks to the array of tasks.
* @param tasks A array of tasks.
* @param tasksToAdd The tasks that are to be appended behind the original array.
* @return The modified array of tasks.
*/
public static TestTask[] addTasksToList(final TestTask[] tasks, TestTask... tasksToAdd) {
List<TestTask> listOfTasks = asList(tasks);
listOfTasks.addAll(asList(tasksToAdd));
return listOfTasks.toArray(new TestTask[listOfTasks.size()]);
}
private static <T> List<T> asList(T[] objs) {
List<T> list = new ArrayList<>();
for(T obj : objs) {
list.add(obj);
}
return list;
}
public static boolean compareCardAndTask(TaskCardHandle card, ReadOnlyTask task) {
return card.isSameTask(task);
}
public static Tag[] getTagList(String tags) {
if (tags.equals("")) {
return new Tag[]{};
}
final String[] split = tags.split(", ");
final List<Tag> collect = Arrays.asList(split).stream().map(e -> {
try {
return new Tag(e.replaceFirst("Tag: ", ""));
} catch (IllegalValueException e1) {
//not possible
assert false;
return null;
}
}).collect(Collectors.toList());
return collect.toArray(new Tag[split.length]);
}
}
| |
/*
* Author: atotic
* Created on Mar 23, 2004
* License: Common Public License v1.0
*/
package com.jetbrains.python.debugger.pydev;
import com.google.common.collect.Maps;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.BaseOutputReader;
import com.intellij.xdebugger.frame.XValueChildrenList;
import com.jetbrains.python.console.pydev.PydevCompletionVariant;
import com.jetbrains.python.debugger.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
public class RemoteDebugger implements ProcessDebugger {
private static final int RESPONSE_TIMEOUT = 60000;
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.pydev.remote.RemoteDebugger");
private static final String LOCAL_VERSION = "0.1";
public static final String TEMP_VAR_PREFIX = "__py_debug_temp_var_";
private static final SecureRandom ourRandom = new SecureRandom();
private final IPyDebugProcess myDebugProcess;
@NotNull
private final ServerSocket myServerSocket;
private final int myConnectionTimeout;
private final Object mySocketObject = new Object(); // for synchronization on socket
private Socket mySocket;
private volatile boolean myConnected = false;
private int mySequence = -1;
private final Object mySequenceObject = new Object(); // for synchronization on mySequence
private final Map<String, PyThreadInfo> myThreads = new ConcurrentHashMap<String, PyThreadInfo>();
private final Map<Integer, ProtocolFrame> myResponseQueue = new HashMap<Integer, ProtocolFrame>();
private final TempVarsHolder myTempVars = new TempVarsHolder();
private Map<Pair<String, Integer>, String> myTempBreakpoints = Maps.newHashMap();
private final List<RemoteDebuggerCloseListener> myCloseListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private DebuggerReader myDebuggerReader;
public RemoteDebugger(final IPyDebugProcess debugProcess, @NotNull final ServerSocket serverSocket, final int timeout) {
myDebugProcess = debugProcess;
myServerSocket = serverSocket;
myConnectionTimeout = timeout;
}
public IPyDebugProcess getDebugProcess() {
return myDebugProcess;
}
@Override
public boolean isConnected() {
return myConnected;
}
@Override
public void waitForConnect() throws Exception {
try {
//noinspection SocketOpenedButNotSafelyClosed
myServerSocket.setSoTimeout(myConnectionTimeout);
synchronized (mySocketObject) {
mySocket = myServerSocket.accept();
myConnected = true;
}
}
finally {
//it is closed in close() method on process termination
}
if (myConnected) {
try {
myDebuggerReader = createReader();
}
catch (Exception e) {
synchronized (mySocketObject) {
mySocket.close();
}
throw e;
}
}
}
@Override
public String handshake() throws PyDebuggerException {
final VersionCommand command = new VersionCommand(this, LOCAL_VERSION, SystemInfo.isUnix ? "UNIX" : "WIN");
command.execute();
String version = command.getRemoteVersion();
if (version != null) {
version = version.trim();
}
return version;
}
@Override
public PyDebugValue evaluate(final String threadId,
final String frameId,
final String expression, final boolean execute) throws PyDebuggerException {
return evaluate(threadId, frameId, expression, execute, true);
}
@Override
public PyDebugValue evaluate(final String threadId,
final String frameId,
final String expression,
final boolean execute,
boolean trimResult)
throws PyDebuggerException {
final EvaluateCommand command = new EvaluateCommand(this, threadId, frameId, expression, execute, trimResult);
command.execute();
return command.getValue();
}
@Override
public void consoleExec(String threadId, String frameId, String expression, PyDebugCallback<String> callback) {
final ConsoleExecCommand command = new ConsoleExecCommand(this, threadId, frameId, expression);
command.execute(callback);
}
@Override
public XValueChildrenList loadFrame(final String threadId, final String frameId) throws PyDebuggerException {
final GetFrameCommand command = new GetFrameCommand(this, threadId, frameId);
command.execute();
return command.getVariables();
}
// todo: don't generate temp variables for qualified expressions - just split 'em
@Override
public XValueChildrenList loadVariable(final String threadId, final String frameId, final PyDebugValue var) throws PyDebuggerException {
setTempVariable(threadId, frameId, var);
final GetVariableCommand command = new GetVariableCommand(this, threadId, frameId, var);
command.execute();
return command.getVariables();
}
@Override
public ArrayChunk loadArrayItems(String threadId,
String frameId,
PyDebugValue var,
int rowOffset,
int colOffset,
int rows,
int cols,
String format) throws PyDebuggerException {
final GetArrayCommand command = new GetArrayCommand(this, threadId, frameId, var, rowOffset, colOffset, rows, cols, format);
command.execute();
return command.getArray();
}
@Override
public void loadReferrers(final String threadId,
final String frameId,
final PyReferringObjectsValue var,
final PyDebugCallback<XValueChildrenList> callback) {
RunCustomOperationCommand cmd = new GetReferrersCommand(this, threadId, frameId, var);
cmd.execute(new PyDebugCallback<List<PyDebugValue>>() {
@Override
public void ok(List<PyDebugValue> value) {
XValueChildrenList list = new XValueChildrenList();
for (PyDebugValue v : value) {
list.add(v);
}
callback.ok(list);
}
@Override
public void error(PyDebuggerException exception) {
callback.error(exception);
}
});
}
@Override
public PyDebugValue changeVariable(final String threadId, final String frameId, final PyDebugValue var, final String value)
throws PyDebuggerException {
setTempVariable(threadId, frameId, var);
return doChangeVariable(threadId, frameId, var.getEvaluationExpression(), value);
}
private PyDebugValue doChangeVariable(final String threadId, final String frameId, final String varName, final String value)
throws PyDebuggerException {
final ChangeVariableCommand command = new ChangeVariableCommand(this, threadId, frameId, varName, value);
command.execute();
return command.getNewValue();
}
@Override
@Nullable
public String loadSource(String path) {
LoadSourceCommand command = new LoadSourceCommand(this, path);
try {
command.execute();
return command.getContent();
}
catch (PyDebuggerException e) {
return "#Couldn't load source of file " + path;
}
}
private void cleanUp() {
myThreads.clear();
myResponseQueue.clear();
synchronized (mySequenceObject) {
mySequence = -1;
}
myTempVars.clear();
}
// todo: change variable in lists doesn't work - either fix in pydevd or format var name appropriately
private void setTempVariable(final String threadId, final String frameId, final PyDebugValue var) {
final PyDebugValue topVar = var.getTopParent();
if (!myDebugProcess.canSaveToTemp(topVar.getName())) {
return;
}
if (myTempVars.contains(threadId, frameId, topVar.getTempName())) {
return;
}
topVar.setTempName(generateTempName());
try {
doChangeVariable(threadId, frameId, topVar.getTempName(), topVar.getName());
myTempVars.put(threadId, frameId, topVar.getTempName());
}
catch (PyDebuggerException e) {
LOG.error(e);
topVar.setTempName(null);
}
}
private void clearTempVariables(final String threadId) {
final Map<String, Set<String>> threadVars = myTempVars.get(threadId);
if (threadVars == null || threadVars.size() == 0) return;
for (Map.Entry<String, Set<String>> entry : threadVars.entrySet()) {
final Set<String> frameVars = entry.getValue();
if (frameVars == null || frameVars.size() == 0) continue;
final String expression = "del " + StringUtil.join(frameVars, ",");
try {
evaluate(threadId, entry.getKey(), expression, true);
}
catch (PyDebuggerException e) {
LOG.error(e);
}
}
myTempVars.clear(threadId);
}
private static String generateTempName() {
return TEMP_VAR_PREFIX + ourRandom.nextInt(Integer.MAX_VALUE);
}
@Override
public Collection<PyThreadInfo> getThreads() {
return Collections.unmodifiableCollection(new ArrayList<PyThreadInfo>(myThreads.values()));
}
int getNextSequence() {
synchronized (mySequenceObject) {
mySequence += 2;
return mySequence;
}
}
void placeResponse(final int sequence, final ProtocolFrame response) {
synchronized (myResponseQueue) {
if (response == null || myResponseQueue.containsKey(sequence)) {
myResponseQueue.put(sequence, response);
}
if (response != null) {
myResponseQueue.notifyAll();
}
}
}
@Nullable
ProtocolFrame waitForResponse(final int sequence) {
ProtocolFrame response;
long until = System.currentTimeMillis() + RESPONSE_TIMEOUT;
synchronized (myResponseQueue) {
do {
try {
myResponseQueue.wait(1000);
}
catch (InterruptedException ignore) {
}
response = myResponseQueue.get(sequence);
}
while (response == null && isConnected() && System.currentTimeMillis() < until);
myResponseQueue.remove(sequence);
}
return response;
}
@Override
public void execute(@NotNull final AbstractCommand command) {
if (command instanceof ResumeOrStepCommand) {
final String threadId = ((ResumeOrStepCommand)command).getThreadId();
clearTempVariables(threadId);
}
try {
command.execute();
}
catch (PyDebuggerException e) {
LOG.error(e);
}
}
boolean sendFrame(final ProtocolFrame frame) {
logFrame(frame, true);
try {
final byte[] packed = frame.pack();
synchronized (mySocketObject) {
final OutputStream os = mySocket.getOutputStream();
os.write(packed);
os.flush();
return true;
}
}
catch (SocketException se) {
disconnect();
fireCommunicationError();
}
catch (IOException e) {
LOG.error(e);
}
return false;
}
private static void logFrame(ProtocolFrame frame, boolean out) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("%1$tH:%1$tM:%1$tS.%1$tL %2$s %3$s\n", new Date(), (out ? "<<<" : ">>>"), frame));
}
}
@Override
public void suspendAllThreads() {
for (PyThreadInfo thread : getThreads()) {
suspendThread(thread.getId());
}
}
@Override
public void suspendThread(String threadId) {
final SuspendCommand command = new SuspendCommand(this, threadId);
execute(command);
}
@Override
public void close() {
if (!myServerSocket.isClosed()) {
try {
myServerSocket.close();
}
catch (IOException e) {
LOG.warn("Error closing socket", e);
}
}
if (myDebuggerReader != null) {
myDebuggerReader.stop();
}
fireCloseEvent();
}
@Override
public void disconnect() {
synchronized (mySocketObject) {
myConnected = false;
if (mySocket != null && !mySocket.isClosed()) {
try {
mySocket.close();
}
catch (IOException ignore) {
}
}
}
cleanUp();
}
@Override
public void run() throws PyDebuggerException {
new RunCommand(this).execute();
}
@Override
public void smartStepInto(String threadId, String functionName) {
final SmartStepIntoCommand command = new SmartStepIntoCommand(this, threadId, functionName);
execute(command);
}
@Override
public void resumeOrStep(String threadId, ResumeOrStepCommand.Mode mode) {
final ResumeOrStepCommand command = new ResumeOrStepCommand(this, threadId, mode);
execute(command);
}
@Override
public void setTempBreakpoint(String type, String file, int line) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, type, file, line);
execute(command); // set temp. breakpoint
myTempBreakpoints.put(Pair.create(file, line), type);
}
@Override
public void removeTempBreakpoint(String file, int line) {
String type = myTempBreakpoints.get(Pair.create(file, line));
if (type != null) {
final RemoveBreakpointCommand command = new RemoveBreakpointCommand(this, type, file, line);
execute(command); // remove temp. breakpoint
}
else {
LOG.error("Temp breakpoint not found for " + file + ":" + line);
}
}
@Override
public void setBreakpoint(String typeId, String file, int line, String condition, String logExpression) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, typeId, file, line,
condition,
logExpression);
execute(command);
}
@Override
public void setBreakpointWithFuncName(String typeId, String file, int line, String condition, String logExpression, String funcName) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, typeId, file, line,
condition,
logExpression,
funcName);
execute(command);
}
@Override
public void removeBreakpoint(String typeId, String file, int line) {
final RemoveBreakpointCommand command =
new RemoveBreakpointCommand(this, typeId, file, line);
execute(command);
}
private DebuggerReader createReader() throws IOException {
synchronized (mySocketObject) {
//noinspection IOResourceOpenedButNotSafelyClosed
return new DebuggerReader(mySocket.getInputStream());
}
}
private class DebuggerReader extends BaseOutputReader {
private StringBuilder myTextBuilder = new StringBuilder();
private DebuggerReader(final InputStream stream) throws IOException {
super(stream, CharsetToolkit.UTF8_CHARSET, SleepingPolicy.BLOCKING); //TODO: correct encoding?
start();
}
protected void doRun() {
try {
while (true) {
boolean read = readAvailableBlocking();
if (!read) {
break;
}
else {
if (isStopped) {
break;
}
TimeoutUtil.sleep(mySleepingPolicy.getTimeToSleep(true));
}
}
}
catch (Exception e) {
fireCommunicationError();
}
finally {
close();
fireExitEvent();
}
}
private void processResponse(final String line) {
try {
final ProtocolFrame frame = new ProtocolFrame(line);
logFrame(frame, false);
if (AbstractThreadCommand.isThreadCommand(frame.getCommand())) {
processThreadEvent(frame);
}
else if (AbstractCommand.isWriteToConsole(frame.getCommand())) {
writeToConsole(ProtocolParser.parseIo(frame.getPayload()));
}
else if (AbstractCommand.isExitEvent(frame.getCommand())) {
fireCommunicationError();
}
else if (AbstractCommand.isCallSignatureTrace(frame.getCommand())) {
recordCallSignature(ProtocolParser.parseCallSignature(frame.getPayload()));
}
else if (AbstractCommand.isConcurrencyEvent(frame.getCommand())) {
recordConcurrencyEvent(ProtocolParser.parseConcurrencyEvent(frame.getPayload(), myDebugProcess.getPositionConverter()));
}
else {
placeResponse(frame.getSequence(), frame);
}
}
catch (Throwable t) {
// shouldn't interrupt reader thread
LOG.error(t);
}
}
private void recordCallSignature(PySignature signature) {
myDebugProcess.recordSignature(signature);
}
private void recordConcurrencyEvent(PyConcurrencyEvent event) {
myDebugProcess.recordLogEvent(event);
}
// todo: extract response processing
private void processThreadEvent(ProtocolFrame frame) throws PyDebuggerException {
switch (frame.getCommand()) {
case AbstractCommand.CREATE_THREAD: {
final PyThreadInfo thread = parseThreadEvent(frame);
if (!thread.isPydevThread()) { // ignore pydevd threads
myThreads.put(thread.getId(), thread);
}
break;
}
case AbstractCommand.SUSPEND_THREAD: {
final PyThreadInfo event = parseThreadEvent(frame);
PyThreadInfo thread = myThreads.get(event.getId());
if (thread == null) {
LOG.error("Trying to stop on non-existent thread: " + event.getId() + ", " + event.getStopReason() + ", " + event.getMessage());
myThreads.put(event.getId(), event);
thread = event;
}
thread.updateState(PyThreadInfo.State.SUSPENDED, event.getFrames());
thread.setStopReason(event.getStopReason());
thread.setMessage(event.getMessage());
myDebugProcess.threadSuspended(thread);
break;
}
case AbstractCommand.RESUME_THREAD: {
final String id = ProtocolParser.getThreadId(frame.getPayload());
final PyThreadInfo thread = myThreads.get(id);
if (thread != null) {
thread.updateState(PyThreadInfo.State.RUNNING, null);
myDebugProcess.threadResumed(thread);
}
break;
}
case AbstractCommand.KILL_THREAD: {
final String id = frame.getPayload();
final PyThreadInfo thread = myThreads.get(id);
if (thread != null) {
thread.updateState(PyThreadInfo.State.KILLED, null);
myThreads.remove(id);
}
for (PyThreadInfo threadInfo: myThreads.values()) {
// notify UI of suspended threads left in debugger if one thread finished its work
if ((threadInfo != null) && (threadInfo.getState() == PyThreadInfo.State.SUSPENDED)) {
myDebugProcess.threadResumed(threadInfo);
myDebugProcess.threadSuspended(threadInfo);
}
}
break;
}
case AbstractCommand.SHOW_CONSOLE: {
final PyThreadInfo event = parseThreadEvent(frame);
PyThreadInfo thread = myThreads.get(event.getId());
if (thread == null) {
myThreads.put(event.getId(), event);
thread = event;
}
thread.updateState(PyThreadInfo.State.SUSPENDED, event.getFrames());
thread.setStopReason(event.getStopReason());
thread.setMessage(event.getMessage());
myDebugProcess.showConsole(thread);
break;
}
}
}
private PyThreadInfo parseThreadEvent(ProtocolFrame frame) throws PyDebuggerException {
return ProtocolParser.parseThread(frame.getPayload(), myDebugProcess.getPositionConverter());
}
@NotNull
@Override
protected Future<?> executeOnPooledThread(@NotNull Runnable runnable) {
return ApplicationManager.getApplication().executeOnPooledThread(runnable);
}
@Override
protected void close() {
try {
super.close();
}
catch (IOException e) {
LOG.error(e);
}
}
@Override
public void stop() {
super.stop();
close();
}
@Override
protected void onTextAvailable(@NotNull String text) {
myTextBuilder.append(text);
if (text.contains("\n")) {
String[] lines = myTextBuilder.toString().split("\n");
myTextBuilder = new StringBuilder();
if (!text.endsWith("\n")) {
myTextBuilder.append(lines[lines.length - 1]);
lines = Arrays.copyOfRange(lines, 0, lines.length - 1);
}
for (String line : lines) {
processResponse(line + "\n");
}
}
}
}
private void writeToConsole(PyIo io) {
ConsoleViewContentType contentType;
if (io.getCtx() == 2) {
contentType = ConsoleViewContentType.ERROR_OUTPUT;
}
else {
contentType = ConsoleViewContentType.NORMAL_OUTPUT;
}
myDebugProcess.printToConsole(io.getText(), contentType);
}
private static class TempVarsHolder {
private final Map<String, Map<String, Set<String>>> myData = new HashMap<String, Map<String, Set<String>>>();
public boolean contains(final String threadId, final String frameId, final String name) {
final Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars == null) return false;
final Set<String> frameVars = threadVars.get(frameId);
if (frameVars == null) return false;
return frameVars.contains(name);
}
private void put(final String threadId, final String frameId, final String name) {
Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars == null) myData.put(threadId, (threadVars = new HashMap<String, Set<String>>()));
Set<String> frameVars = threadVars.get(frameId);
if (frameVars == null) threadVars.put(frameId, (frameVars = new HashSet<String>()));
frameVars.add(name);
}
private Map<String, Set<String>> get(final String threadId) {
return myData.get(threadId);
}
private void clear() {
myData.clear();
}
private void clear(final String threadId) {
final Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars != null) {
threadVars.clear();
}
}
}
public void addCloseListener(RemoteDebuggerCloseListener listener) {
myCloseListeners.add(listener);
}
public void removeCloseListener(RemoteDebuggerCloseListener listener) {
myCloseListeners.remove(listener);
}
@Override
public List<PydevCompletionVariant> getCompletions(String threadId, String frameId, String prefix) {
final GetCompletionsCommand command = new GetCompletionsCommand(this, threadId, frameId, prefix);
execute(command);
return command.getCompletions();
}
@Override
public void addExceptionBreakpoint(ExceptionBreakpointCommandFactory factory) {
execute(factory.createAddCommand(this));
}
@Override
public void removeExceptionBreakpoint(ExceptionBreakpointCommandFactory factory) {
execute(factory.createRemoveCommand(this));
}
private void fireCloseEvent() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.closed();
}
}
private void fireCommunicationError() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.communicationError();
}
}
private void fireExitEvent() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.detached();
}
}
}
| |
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
import org.eclipse.gmf.runtime.diagram.ui.commands.DeferredLayoutCommand;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.commands.SetViewMutabilityCommand;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CanonicalEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceEndpointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressEndPointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressingEndpointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AggregateMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BAMMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BeanMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BuilderMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CacheMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CallMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CallTemplateMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CalloutMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ClassMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloneMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloudConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloudConnectorOperationEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CommandMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ConditionalRouterMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DBLookupMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DBReportMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DataMapperMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DefaultEndPointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DropMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EJBMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EnqueueMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EnrichMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EntitlementMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EventMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FailoverEndPointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FaultMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FilterMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HTTPEndpointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HeaderMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.IterateMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoadBalanceEndPointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LogMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoopBackMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.NamedEndpointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.OAuthMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PayloadFactoryMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PropertyMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RMSequenceMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RecipientListEndPointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RespondMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RouterMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RuleMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ScriptMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SendMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequenceEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SmooksMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SpringMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.StoreMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SwitchMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TemplateEndpointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ThrottleMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TransactionMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.URLRewriteMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ValidateMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.WSDLEndPointEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.XQueryMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.XSLTMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbDiagramUpdater;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbNodeDescriptor;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry;
/**
* @generated
*/
public class MediatorFlowMediatorFlowCompartment6CanonicalEditPolicy extends CanonicalEditPolicy {
/**
* @generated
*/
protected void refreshOnActivate() {
// Need to activate editpart children before invoking the canonical refresh for EditParts to add event listeners
List<?> c = getHost().getChildren();
for (int i = 0; i < c.size(); i++) {
((EditPart) c.get(i)).activate();
}
super.refreshOnActivate();
}
/**
* @generated
*/
protected EStructuralFeature getFeatureToSynchronize() {
return EsbPackage.eINSTANCE.getMediatorFlow_Children();
}
/**
* @generated
*/
@SuppressWarnings("rawtypes")
protected List getSemanticChildrenList() {
View viewObject = (View) getHost().getModel();
LinkedList<EObject> result = new LinkedList<EObject>();
List<EsbNodeDescriptor> childDescriptors = EsbDiagramUpdater
.getMediatorFlowMediatorFlowCompartment_7019SemanticChildren(viewObject);
for (EsbNodeDescriptor d : childDescriptors) {
result.add(d.getModelElement());
}
return result;
}
/**
* @generated
*/
protected boolean isOrphaned(Collection<EObject> semanticChildren, final View view) {
return isMyDiagramElement(view) && !semanticChildren.contains(view.getElement());
}
/**
* @generated
*/
private boolean isMyDiagramElement(View view) {
int visualID = EsbVisualIDRegistry.getVisualID(view);
switch (visualID) {
case DropMediatorEditPart.VISUAL_ID:
case PropertyMediatorEditPart.VISUAL_ID:
case ThrottleMediatorEditPart.VISUAL_ID:
case FilterMediatorEditPart.VISUAL_ID:
case LogMediatorEditPart.VISUAL_ID:
case EnrichMediatorEditPart.VISUAL_ID:
case XSLTMediatorEditPart.VISUAL_ID:
case SwitchMediatorEditPart.VISUAL_ID:
case SequenceEditPart.VISUAL_ID:
case EventMediatorEditPart.VISUAL_ID:
case EntitlementMediatorEditPart.VISUAL_ID:
case ClassMediatorEditPart.VISUAL_ID:
case SpringMediatorEditPart.VISUAL_ID:
case ScriptMediatorEditPart.VISUAL_ID:
case FaultMediatorEditPart.VISUAL_ID:
case XQueryMediatorEditPart.VISUAL_ID:
case CommandMediatorEditPart.VISUAL_ID:
case DBLookupMediatorEditPart.VISUAL_ID:
case DBReportMediatorEditPart.VISUAL_ID:
case SmooksMediatorEditPart.VISUAL_ID:
case SendMediatorEditPart.VISUAL_ID:
case HeaderMediatorEditPart.VISUAL_ID:
case CloneMediatorEditPart.VISUAL_ID:
case CacheMediatorEditPart.VISUAL_ID:
case IterateMediatorEditPart.VISUAL_ID:
case CalloutMediatorEditPart.VISUAL_ID:
case TransactionMediatorEditPart.VISUAL_ID:
case RMSequenceMediatorEditPart.VISUAL_ID:
case RuleMediatorEditPart.VISUAL_ID:
case OAuthMediatorEditPart.VISUAL_ID:
case AggregateMediatorEditPart.VISUAL_ID:
case StoreMediatorEditPart.VISUAL_ID:
case BuilderMediatorEditPart.VISUAL_ID:
case CallTemplateMediatorEditPart.VISUAL_ID:
case PayloadFactoryMediatorEditPart.VISUAL_ID:
case EnqueueMediatorEditPart.VISUAL_ID:
case URLRewriteMediatorEditPart.VISUAL_ID:
case ValidateMediatorEditPart.VISUAL_ID:
case RouterMediatorEditPart.VISUAL_ID:
case ConditionalRouterMediatorEditPart.VISUAL_ID:
case BAMMediatorEditPart.VISUAL_ID:
case BeanMediatorEditPart.VISUAL_ID:
case EJBMediatorEditPart.VISUAL_ID:
case DefaultEndPointEditPart.VISUAL_ID:
case AddressEndPointEditPart.VISUAL_ID:
case FailoverEndPointEditPart.VISUAL_ID:
case RecipientListEndPointEditPart.VISUAL_ID:
case WSDLEndPointEditPart.VISUAL_ID:
case NamedEndpointEditPart.VISUAL_ID:
case LoadBalanceEndPointEditPart.VISUAL_ID:
case APIResourceEndpointEditPart.VISUAL_ID:
case AddressingEndpointEditPart.VISUAL_ID:
case HTTPEndpointEditPart.VISUAL_ID:
case TemplateEndpointEditPart.VISUAL_ID:
case CloudConnectorEditPart.VISUAL_ID:
case CloudConnectorOperationEditPart.VISUAL_ID:
case LoopBackMediatorEditPart.VISUAL_ID:
case RespondMediatorEditPart.VISUAL_ID:
case CallMediatorEditPart.VISUAL_ID:
case DataMapperMediatorEditPart.VISUAL_ID:
return true;
}
return false;
}
/**
* @generated
*/
protected void refreshSemantic() {
if (resolveSemanticElement() == null) {
return;
}
LinkedList<IAdaptable> createdViews = new LinkedList<IAdaptable>();
List<EsbNodeDescriptor> childDescriptors = EsbDiagramUpdater
.getMediatorFlowMediatorFlowCompartment_7019SemanticChildren((View) getHost()
.getModel());
LinkedList<View> orphaned = new LinkedList<View>();
// we care to check only views we recognize as ours
LinkedList<View> knownViewChildren = new LinkedList<View>();
for (View v : getViewChildren()) {
if (isMyDiagramElement(v)) {
knownViewChildren.add(v);
}
}
// alternative to #cleanCanonicalSemanticChildren(getViewChildren(), semanticChildren)
//
// iteration happens over list of desired semantic elements, trying to find best matching View, while original CEP
// iterates views, potentially losing view (size/bounds) information - i.e. if there are few views to reference same EObject, only last one
// to answer isOrphaned == true will be used for the domain element representation, see #cleanCanonicalSemanticChildren()
for (Iterator<EsbNodeDescriptor> descriptorsIterator = childDescriptors.iterator(); descriptorsIterator
.hasNext();) {
EsbNodeDescriptor next = descriptorsIterator.next();
String hint = EsbVisualIDRegistry.getType(next.getVisualID());
LinkedList<View> perfectMatch = new LinkedList<View>(); // both semanticElement and hint match that of NodeDescriptor
for (View childView : getViewChildren()) {
EObject semanticElement = childView.getElement();
if (next.getModelElement().equals(semanticElement)) {
if (hint.equals(childView.getType())) {
perfectMatch.add(childView);
// actually, can stop iteration over view children here, but
// may want to use not the first view but last one as a 'real' match (the way original CEP does
// with its trick with viewToSemanticMap inside #cleanCanonicalSemanticChildren
}
}
}
if (perfectMatch.size() > 0) {
descriptorsIterator.remove(); // precise match found no need to create anything for the NodeDescriptor
// use only one view (first or last?), keep rest as orphaned for further consideration
knownViewChildren.remove(perfectMatch.getFirst());
}
}
// those left in knownViewChildren are subject to removal - they are our diagram elements we didn't find match to,
// or those we have potential matches to, and thus need to be recreated, preserving size/location information.
orphaned.addAll(knownViewChildren);
//
ArrayList<CreateViewRequest.ViewDescriptor> viewDescriptors = new ArrayList<CreateViewRequest.ViewDescriptor>(
childDescriptors.size());
for (EsbNodeDescriptor next : childDescriptors) {
String hint = EsbVisualIDRegistry.getType(next.getVisualID());
IAdaptable elementAdapter = new CanonicalElementAdapter(next.getModelElement(), hint);
CreateViewRequest.ViewDescriptor descriptor = new CreateViewRequest.ViewDescriptor(
elementAdapter, Node.class, hint, ViewUtil.APPEND, false, host()
.getDiagramPreferencesHint());
viewDescriptors.add(descriptor);
}
boolean changed = deleteViews(orphaned.iterator());
//
CreateViewRequest request = getCreateViewRequest(viewDescriptors);
Command cmd = getCreateViewCommand(request);
if (cmd != null && cmd.canExecute()) {
SetViewMutabilityCommand.makeMutable(new EObjectAdapter(host().getNotationView()))
.execute();
executeCommand(cmd);
@SuppressWarnings("unchecked")
List<IAdaptable> nl = (List<IAdaptable>) request.getNewObject();
createdViews.addAll(nl);
}
if (changed || createdViews.size() > 0) {
postProcessRefreshSemantic(createdViews);
}
if (createdViews.size() > 1) {
// perform a layout of the container
DeferredLayoutCommand layoutCmd = new DeferredLayoutCommand(host().getEditingDomain(),
createdViews, host());
executeCommand(new ICommandProxy(layoutCmd));
}
makeViewsImmutable(createdViews);
}
}
| |
/*
* 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.cocoon.forms.util;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.Map;
import org.apache.cocoon.components.flow.FlowHelper;
import org.apache.cocoon.components.flow.javascript.JavaScriptFlowHelper;
import org.apache.cocoon.components.flow.javascript.fom.FOM_JavaScriptFlowHelper;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.w3c.dom.Element;
/**
* Helper methods to use JavaScript in various locations of the Cocoon Forms configuration files
* such as event listeners and bindings.
*
* @version $Id$
*/
public class JavaScriptHelper {
/**
* A shared root scope, avoiding to recreate a new one each time.
*/
private static Scriptable _rootScope;
/**
* Build a script with the content of a DOM element.
*
* @param element the element containing the script
* @return the compiled script
* @throws IOException
*/
public static Script buildScript(Element element) throws IOException {
String jsText = DomHelper.getElementText(element);
String sourceName = DomHelper.getSystemIdLocation(element);
Context ctx = Context.enter();
Script script;
try {
script = ctx.compileReader(
// To use rhino1.5r4-continuations-R26.jar as a workaround for COCOON-1579: Uncomment the next line.
// getRootScope(null), //scope
new StringReader(jsText), // in
sourceName == null ? "<unknown>" : sourceName, // sourceName
DomHelper.getLineLocation(element), // lineNo
null // securityDomain
);
} finally {
Context.exit();
}
return script;
}
/**
* Build a function with the content of a DOM element.
*
* @param element the element containing the function body
* @param name the name of the function
* @param argumentNames names of the function arguments
* @return the compiled function
* @throws IOException
*/
public static Function buildFunction(Element element, String name, String[] argumentNames) throws IOException {
// Enclose the script text with a function declaration
StringBuffer buffer = new StringBuffer("function ").append(name).append("(");
for (int i = 0; i < argumentNames.length; i++) {
if (i > 0) {
buffer.append(',');
}
buffer.append(argumentNames[i]);
}
buffer.append(") {\n").append(DomHelper.getElementText(element)).append("\n}");
String jsText = buffer.toString();
String sourceName = DomHelper.getSystemIdLocation(element);
Context ctx = Context.enter();
Function func;
try {
func = ctx.compileFunction(
getRootScope(null), //scope
jsText, // in
sourceName == null ? "<unknown>" : sourceName, // sourceName
DomHelper.getLineLocation(element) - 1, // lineNo, "-1" because we added "function..."
null // securityDomain
);
} finally {
Context.exit();
}
return func;
}
/**
* Get a root scope for building child scopes.
*
* @return an appropriate root scope
*/
public static Scriptable getRootScope(Map objectModel) {
// FIXME: TemplateOMH should be used in 2.2
//return TemplateObjectModelHelper.getScope();
if (_rootScope == null) {
// Create it if never used up to now
Context ctx = Context.enter();
try {
_rootScope = ctx.initStandardObjects(null);
try {
ScriptableObject.defineClass(_rootScope, FOM_SimpleCocoon.class);
} catch (Exception e) {
throw new RuntimeException("Cannot setup a root context with a cocoon object for javascript", e);
}
} finally {
Context.exit();
}
}
if (objectModel == null) {
return _rootScope;
} else {
Context ctx = Context.enter();
try {
Scriptable scope = ctx.newObject(_rootScope);
FOM_SimpleCocoon cocoon = (FOM_SimpleCocoon) ctx.newObject(scope, "FOM_SimpleCocoon", new Object[] { });
cocoon.setObjectModel(objectModel);
cocoon.setParentScope(scope);
scope.put("cocoon", scope, cocoon);
return scope;
} catch (Exception e) {
throw new RuntimeException("Cannot setup a root context with a cocoon object for javascript", e);
} finally {
Context.exit();
}
}
}
/**
* Get a parent scope for building a child scope. The request is searched for an existing scope
* that can be provided by a flowscript higher in the call stack, giving visibility to flowscript
* functions and global (session) variables.
*
* @param objectModel the object model where the flowscript scope will be searched (can be <code>null</code>).
* @return an appropriate parent scope.
*/
public static Scriptable getParentScope(Map objectModel) {
// Try to get the flowscript scope
Scriptable parentScope = null;
if (objectModel != null) {
parentScope = FOM_JavaScriptFlowHelper.getFOM_FlowScope(objectModel);
}
if (parentScope != null) {
return parentScope;
} else {
return getRootScope(objectModel);
}
}
public static Object execScript(Script script, Map values, Map objectModel) throws JavaScriptException {
Context ctx = Context.enter();
try {
Scriptable parentScope = getParentScope(objectModel);
// Create a new local scope
Scriptable scope;
try {
scope = ctx.newObject(parentScope);
} catch (Exception e) {
// Should normally not happen
throw new RuntimeException("Cannot create script scope", e);
}
scope.setParentScope(parentScope);
// Populate the scope
Iterator iter = values.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
String key = (String)entry.getKey();
Object value = entry.getValue();
scope.put(key, scope, Context.toObject(value, scope));
}
if (objectModel != null) {
Object viewData = FlowHelper.getContextObject(objectModel);
if (viewData != null) {
scope.put("viewData", scope, Context.toObject(viewData, scope));
}
}
Object result = script.exec(ctx, scope);
return JavaScriptFlowHelper.unwrap(result);
} finally {
Context.exit();
}
}
public static Object callFunction(Function func, Object thisObject, Object[] arguments, Map objectModel) throws JavaScriptException {
Context ctx = Context.enter();
try {
Scriptable scope = getParentScope(objectModel);
if (objectModel != null) {
// we always add the viewData even it is null (see bug COCOON-1916)
final Object viewData = FlowHelper.getContextObject(objectModel);
// Create a new local scope to hold the view data
final Scriptable newScope;
try {
newScope = ctx.newObject(scope);
} catch (Exception e) {
// Should normally not happen
throw new RuntimeException("Cannot create function scope", e);
}
newScope.setParentScope(scope);
scope = newScope;
if ( viewData != null ) {
scope.put("viewData", scope, Context.toObject(viewData, scope));
} else {
scope.put("viewData", scope, null);
}
}
func.setParentScope(scope);
Object result = func.call(ctx, scope, thisObject == null? null: Context.toObject(thisObject, scope), arguments);
return JavaScriptFlowHelper.unwrap(result);
} finally {
Context.exit();
}
}
}
| |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.dac.explore;
import static com.dremio.common.utils.SqlUtils.stringLiteral;
import static com.dremio.dac.proto.model.dataset.IndexType.INDEX;
import static com.dremio.dac.proto.model.dataset.ReplaceSelectionType.CONTAINS;
import static com.dremio.dac.proto.model.dataset.ReplaceSelectionType.ENDS_WITH;
import static com.dremio.dac.proto.model.dataset.ReplaceSelectionType.EXACT;
import static com.dremio.dac.proto.model.dataset.ReplaceSelectionType.IS_NULL;
import static com.dremio.dac.proto.model.dataset.ReplaceSelectionType.MATCHES;
import static com.dremio.dac.proto.model.dataset.ReplaceSelectionType.STARTS_WITH;
import static java.util.regex.Pattern.quote;
import static org.apache.parquet.Preconditions.checkArgument;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dremio.common.exceptions.UserException;
import com.dremio.dac.explore.PatternMatchUtils.Match;
import com.dremio.dac.explore.model.extract.Selection;
import com.dremio.dac.explore.udfs.MatchPattern;
import com.dremio.dac.proto.model.dataset.DataType;
import com.dremio.dac.proto.model.dataset.ReplacePatternRule;
import com.dremio.dac.proto.model.dataset.ReplaceSelectionType;
import com.dremio.dac.proto.model.dataset.ReplaceType;
import com.google.common.base.Preconditions;
/**
* Replace/Keep only/Exclude transformation recommendation suggestions and generating examples and number of matches
* in sample data for each recommendation.
*/
public class ReplaceRecommender extends Recommender<ReplacePatternRule, Selection> {
private static final Logger logger = LoggerFactory.getLogger(ReplaceRecommender.class);
@Override
public List<ReplacePatternRule> getRules(Selection selection, DataType selColType) {
Preconditions.checkArgument(selColType == DataType.TEXT,
"Cards generation for Replace/Keeponly/Exclude transforms is supported only on TEXT type columns");
List<ReplacePatternRule> rules = new ArrayList<>();
if (selection.getCellText() == null) {
rules.add(new ReplacePatternRule(IS_NULL));
} else {
final int start = selection.getOffset();
final int end = start + selection.getLength();
final String content = selection.getCellText().substring(start, end);
// Applicable only for text type
if (content.length() > 0) {
rules.addAll(casePermutations(CONTAINS, content));
if (start == 0) {
rules.addAll(casePermutations(STARTS_WITH, content));
}
if (end == selection.getCellText().length()) {
rules.addAll(casePermutations(ENDS_WITH, content));
}
List<String> patterns = recommendReplacePattern(selection);
for (String pattern : patterns) {
rules.add(new ReplacePatternRule(MATCHES).setSelectionPattern(pattern));
}
}
if (start == 0 && end == selection.getCellText().length()) {
rules.addAll(casePermutations(EXACT, content));
}
}
return rules;
}
private List<ReplacePatternRule> casePermutations(ReplaceSelectionType selectionType, String pattern) {
/**
* Add case permutations of the rule if the selected text/pattern has no case (such as numbers)
*/
if (!pattern.toUpperCase().equals(pattern.toLowerCase())) {
return Arrays.asList(
new ReplacePatternRule(selectionType).setSelectionPattern(pattern).setIgnoreCase(true),
new ReplacePatternRule(selectionType).setSelectionPattern(pattern).setIgnoreCase(false)
);
}
return Collections.singletonList(
new ReplacePatternRule(selectionType).setSelectionPattern(pattern).setIgnoreCase(false)
);
}
private List<String> recommendReplacePattern(Selection selection) {
List<String> rules = new ArrayList<>();
String cellText = selection.getCellText();
int start = selection.getOffset();
int end = start + selection.getLength();
String selected = cellText.substring(start, end);
boolean startIsCharType = start == 0 ? false : PatternMatchUtils.CharType.DIGIT.isTypeOf(cellText.charAt(start - 1));
boolean endIsCharType = end == cellText.length() ? false : PatternMatchUtils.CharType.DIGIT.isTypeOf(cellText.charAt(end));
boolean selectionIsCharType = PatternMatchUtils.CharType.DIGIT.isTypeOf(selected);
if (!startIsCharType && !endIsCharType && selectionIsCharType) {
Matcher matcher = PatternMatchUtils.CharType.DIGIT.matcher(cellText);
List<Match> matches = PatternMatchUtils.findMatches(matcher, cellText, INDEX);
for (int index = 0; index < matches.size(); index++) {
Match match = matches.get(index);
if (match.start() == start && match.end() == end) {
rules.add(PatternMatchUtils.CharType.DIGIT.pattern());
}
}
}
return rules;
}
public TransformRuleWrapper<ReplacePatternRule> wrapRule(ReplacePatternRule rule) {
return new ReplaceTransformRuleWrapper(rule);
}
private static class ReplaceTransformRuleWrapper extends Recommender.TransformRuleWrapper {
private final ReplacePatternRule rule;
ReplaceTransformRuleWrapper(ReplacePatternRule rule) {
this.rule = rule;
}
@Override
public String getMatchFunctionExpr(String input) {
return getMatchFunction(input);
}
@Override
public boolean canGenerateExamples() {
return rule.getSelectionType() != IS_NULL;
}
@Override
public String getExampleFunctionExpr(String input) {
final boolean ignoreCase = rule.getIgnoreCase() == null ? false : rule.getIgnoreCase();
final String quotedPattern = stringLiteral(rule.getSelectionPattern());
return String.format("%s(%s, '%s', %s, %s)", MatchPattern.GEN_EXAMPLE, input,
rule.getSelectionType().toString(), quotedPattern, ignoreCase);
}
private String getMatchFunction(String expr) {
// Generate the match function
if (rule.getSelectionType() == IS_NULL) {
return String.format("%s IS NULL", expr);
} else if (rule.getSelectionType() == EXACT) {
if (rule.getIgnoreCase() != null && rule.getIgnoreCase()) {
return String.format("lower(%s) = lower(%s)", expr, stringLiteral(rule.getSelectionPattern()));
} else {
return String.format("%s = %s", expr, stringLiteral(rule.getSelectionPattern()));
}
} else {
String patternLiteral = getRegexPatternLiteral(true);
return String.format("regexp_like(%s, %s)", expr, patternLiteral);
}
}
@Override
public String getFunctionExpr(String inputExpr, Object... args) {
checkArgument(args.length >= 1 && args[0] != null, "Expected the replace type as first argument");
ReplaceType replaceType = (ReplaceType) args[0];
String replacementValue = null;
if (replaceType != ReplaceType.NULL) {
checkArgument(args.length == 2 && args[1] != null, "Expected the replacement value as second argument");
replacementValue = stringLiteral((String)args[1]);
}
String matchExpr = getMatchFunction(inputExpr);
switch (replaceType) {
case NULL:
return String.format("CASE WHEN %s THEN NULL ELSE %s END", matchExpr, inputExpr);
case VALUE:
return String.format("CASE WHEN %s THEN %s ELSE %s END", matchExpr, replacementValue, inputExpr);
case SELECTION:
String replace;
switch (rule.getSelectionType()) {
case IS_NULL:
case EXACT:
replace = replacementValue;
break;
case CONTAINS:
case STARTS_WITH:
case ENDS_WITH:
case MATCHES:
replace = String.format("regexp_replace(%s, %s, %s)", inputExpr, getRegexPatternLiteral(false), replacementValue);
break;
default:
throw UserException.unsupportedError()
.message("unsupported selection type: " + rule.getSelectionType().toString())
.build(logger);
}
return String.format("CASE WHEN %s THEN %s ELSE %s END", matchExpr, replace, inputExpr);
default:
throw UserException.unsupportedError()
.message("Unsupported replace type: " + replaceType.toString())
.build(logger);
}
}
@Override
public ReplacePatternRule getRule() {
return rule;
}
private String getRegexPatternLiteral(boolean forMatch) {
final String patternLiteral = rule.getSelectionPattern();
String regexp;
switch (rule.getSelectionType()) {
case CONTAINS:
regexp = regexp(forMatch) + quote(patternLiteral) + regexp(forMatch);
break;
case STARTS_WITH:
regexp = "^" + quote(patternLiteral) + regexp(forMatch);
break;
case ENDS_WITH:
regexp = regexp(forMatch) + quote(patternLiteral) + "$";
break;
case MATCHES:
regexp = regexp(forMatch) + patternLiteral + regexp(forMatch);
break;
default:
throw UserException.unsupportedError()
.message("regexp not available for selection type: " + rule.getSelectionType().toString())
.build(logger);
}
if (rule.getIgnoreCase() != null && rule.getIgnoreCase()) {
// make the pattern case insensitive and unicode case aware
regexp = "(?i)(?u)" + regexp;
}
return stringLiteral(regexp);
}
private static String regexp(boolean forMatch) {
return forMatch ? ".*?" : "";
}
@Override
public String describe() {
String suffix = (rule.getIgnoreCase() != null && rule.getIgnoreCase()) ? " ignore case" : "";
switch (rule.getSelectionType()) {
case CONTAINS:
return String.format("Contains %s", rule.getSelectionPattern()) + suffix;
case ENDS_WITH:
return String.format("Ends with %s", rule.getSelectionPattern()) + suffix;
case EXACT:
return String.format("Exactly matches %s", rule.getSelectionPattern()) + suffix;
case IS_NULL:
return "Is null";
case MATCHES:
return String.format("Matches regex %s", rule.getSelectionPattern()) + suffix;
case STARTS_WITH:
return String.format("Starts with %s", rule.getSelectionPattern()) + suffix;
default:
throw new UnsupportedOperationException(rule.getSelectionType().name());
}
}
}
public static ReplaceMatcher getMatcher(ReplacePatternRule rule) {
final String pattern = rule.getSelectionPattern();
ReplaceSelectionType selectionType = rule.getSelectionType();
if (rule.getIgnoreCase() != null && rule.getIgnoreCase()) {
return new ToLowerReplaceMatcher(getMatcher(pattern.toLowerCase(), selectionType));
} else {
return getMatcher(pattern, selectionType);
}
}
private static ReplaceMatcher getMatcher(final String pattern, ReplaceSelectionType selectionType) {
switch (selectionType) {
case CONTAINS:
return new ReplaceMatcher() {
@Override
public Match matches(String value) {
if (value != null && value.contains(pattern)) {
int start = value.indexOf(pattern);
int end = start + pattern.length();
return new Match(start, end);
}
return null;
}
};
case ENDS_WITH:
return new ReplaceMatcher() {
@Override
public Match matches(String value) {
if (value != null && value.endsWith(pattern)) {
int start = value.length() - pattern.length();
int end = value.length();
return new Match(start, end);
}
return null;
}
};
case EXACT:
return new ReplaceMatcher() {
@Override
public Match matches(String value) {
if (value != null && value.equals(pattern)) {
int start = 0;
int end = value.length();
return new Match(start, end);
}
return null;
}
};
case IS_NULL:
return new ReplaceMatcher() {
@Override
public Match matches(String value) {
if (value == null) {
int start = 0;
int end = 0;
return new Match(start, end);
}
return null;
}
};
case MATCHES:
final Pattern patternC = Pattern.compile(pattern);
return new ReplaceMatcher() {
@Override
public Match matches(String value) {
if (value != null) {
Matcher matcher = patternC.matcher(value);
if (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
return new Match(start, end);
}
}
return null;
}
};
case STARTS_WITH:
return new ReplaceMatcher() {
@Override
public Match matches(String value) {
if (value != null && value.startsWith(pattern)) {
int start = 0;
int end = pattern.length();
return new Match(start, end);
}
return null;
}
};
default:
throw new UnsupportedOperationException(selectionType.name());
}
}
/**
* Selection matcher for replace
*/
public abstract static class ReplaceMatcher {
public abstract Match matches(String value);
}
/**
* turns all input to lower case
*/
public static class ToLowerReplaceMatcher extends ReplaceMatcher {
private final ReplaceMatcher delegate;
public ToLowerReplaceMatcher(ReplaceMatcher delegate) {
super();
this.delegate = delegate;
}
@Override
public Match matches(String value) {
return delegate.matches(value == null ? value : value.toLowerCase());
}
}
}
| |
/*
* 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.directory.server.kerberos.protocol.codec;
import java.nio.ByteBuffer;
import org.apache.directory.server.kerberos.changepwd.exceptions.ChangePasswdErrorType;
import org.apache.directory.server.kerberos.changepwd.exceptions.ChangePasswordException;
import org.apache.directory.api.asn1.DecoderException;
import org.apache.directory.api.asn1.ber.Asn1Container;
import org.apache.directory.api.asn1.ber.Asn1Decoder;
import org.apache.directory.api.asn1.ber.tlv.TLVStateEnum;
import org.apache.directory.shared.kerberos.codec.KerberosMessageContainer;
import org.apache.directory.shared.kerberos.codec.EncKdcRepPart.EncKdcRepPartContainer;
import org.apache.directory.shared.kerberos.codec.apRep.ApRepContainer;
import org.apache.directory.shared.kerberos.codec.apReq.ApReqContainer;
import org.apache.directory.shared.kerberos.codec.authenticator.AuthenticatorContainer;
import org.apache.directory.shared.kerberos.codec.authorizationData.AuthorizationDataContainer;
import org.apache.directory.shared.kerberos.codec.encApRepPart.EncApRepPartContainer;
import org.apache.directory.shared.kerberos.codec.encAsRepPart.EncAsRepPartContainer;
import org.apache.directory.shared.kerberos.codec.encKrbPrivPart.EncKrbPrivPartContainer;
import org.apache.directory.shared.kerberos.codec.encTgsRepPart.EncTgsRepPartContainer;
import org.apache.directory.shared.kerberos.codec.encTicketPart.EncTicketPartContainer;
import org.apache.directory.shared.kerberos.codec.encryptedData.EncryptedDataContainer;
import org.apache.directory.shared.kerberos.codec.encryptionKey.EncryptionKeyContainer;
import org.apache.directory.shared.kerberos.codec.krbPriv.KrbPrivContainer;
import org.apache.directory.shared.kerberos.codec.paEncTsEnc.PaEncTsEncContainer;
import org.apache.directory.shared.kerberos.codec.principalName.PrincipalNameContainer;
import org.apache.directory.shared.kerberos.codec.ticket.TicketContainer;
import org.apache.directory.shared.kerberos.components.AuthorizationData;
import org.apache.directory.shared.kerberos.components.EncKdcRepPart;
import org.apache.directory.shared.kerberos.components.EncKrbPrivPart;
import org.apache.directory.shared.kerberos.components.EncTicketPart;
import org.apache.directory.shared.kerberos.components.EncryptedData;
import org.apache.directory.shared.kerberos.components.EncryptionKey;
import org.apache.directory.shared.kerberos.components.PaEncTsEnc;
import org.apache.directory.shared.kerberos.components.PrincipalName;
import org.apache.directory.shared.kerberos.exceptions.ErrorType;
import org.apache.directory.shared.kerberos.exceptions.KerberosException;
import org.apache.directory.shared.kerberos.messages.ApRep;
import org.apache.directory.shared.kerberos.messages.ApReq;
import org.apache.directory.shared.kerberos.messages.Authenticator;
import org.apache.directory.shared.kerberos.messages.EncApRepPart;
import org.apache.directory.shared.kerberos.messages.EncAsRepPart;
import org.apache.directory.shared.kerberos.messages.EncTgsRepPart;
import org.apache.directory.shared.kerberos.messages.KrbPriv;
import org.apache.directory.shared.kerberos.messages.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class KerberosDecoder
{
/** The logger */
private static Logger LOG = LoggerFactory.getLogger( KerberosDecoder.class );
/** A speedup for logger */
private static final boolean IS_DEBUG = LOG.isDebugEnabled();
public static Object decode( KerberosMessageContainer kerberosMessageContainer, Asn1Decoder asn1Decoder ) throws DecoderException
{
ByteBuffer buf = kerberosMessageContainer.getStream();
if ( kerberosMessageContainer.isTCP() )
{
if ( buf.remaining() > 4 )
{
kerberosMessageContainer.setTcpLength( buf.getInt() );
buf.mark();
}
else
{
return null;
}
}
else
{
buf.mark();
}
while ( buf.hasRemaining() )
{
try
{
asn1Decoder.decode( buf, kerberosMessageContainer );
if ( kerberosMessageContainer.getState() == TLVStateEnum.PDU_DECODED )
{
if ( IS_DEBUG )
{
LOG.debug( "Decoded KerberosMessage : " + kerberosMessageContainer.getMessage() );
buf.mark();
}
return kerberosMessageContainer.getMessage();
}
}
catch ( DecoderException de )
{
LOG.warn( "error while decoding", de );
buf.clear();
kerberosMessageContainer.clean();
throw de;
}
}
return null;
}
/**
* Decode an EncrytedData structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncryptedData
* @throws KerberosException If the decoding fails
*/
public static EncryptedData decodeEncryptedData( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncryptedData Container
Asn1Container encryptedDataContainer = new EncryptedDataContainer();
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncryptedData PDU
try
{
kerberosDecoder.decode( stream, encryptedDataContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncryptedData
EncryptedData encryptedData = ( ( EncryptedDataContainer ) encryptedDataContainer ).getEncryptedData();
return encryptedData;
}
/**
* Decode an PaEncTsEnc structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of PaEncTsEnc
* @throws KerberosException If the decoding fails
*/
public static PaEncTsEnc decodePaEncTsEnc( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a PaEncTsEnc Container
Asn1Container paEncTsEncContainer = new PaEncTsEncContainer();
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the PaEncTsEnc PDU
try
{
kerberosDecoder.decode( stream, paEncTsEncContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded PaEncTsEnc
PaEncTsEnc paEncTsEnc = ( ( PaEncTsEncContainer ) paEncTsEncContainer ).getPaEncTsEnc();
return paEncTsEnc;
}
/**
* Decode an EncApRepPart structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncApRepPart
* @throws KerberosException If the decoding fails
*/
public static EncApRepPart decodeEncApRepPart( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncApRepPart Container
Asn1Container encApRepPartContainer = new EncApRepPartContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncApRepPart PDU
try
{
kerberosDecoder.decode( stream, encApRepPartContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncApRepPart
EncApRepPart encApRepPart = ( ( EncApRepPartContainer ) encApRepPartContainer ).getEncApRepPart();
return encApRepPart;
}
/**
* Decode an EncKdcRepPart structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncKdcRepPart
* @throws KerberosException If the decoding fails
*/
public static EncKdcRepPart decodeEncKdcRepPart( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncKdcRepPart Container
Asn1Container encKdcRepPartContainer = new EncKdcRepPartContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncKdcRepPart PDU
try
{
kerberosDecoder.decode( stream, encKdcRepPartContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncKdcRepPart
EncKdcRepPart encKdcRepPart = ( ( EncKdcRepPartContainer ) encKdcRepPartContainer ).getEncKdcRepPart();
return encKdcRepPart;
}
/**
* Decode an EncKrbPrivPart structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncKrbPrivPart
* @throws KerberosException If the decoding fails
*/
public static EncKrbPrivPart decodeEncKrbPrivPart( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncKrbPrivPart Container
Asn1Container encKrbPrivPartContainer = new EncKrbPrivPartContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncKrbPrivPart PDU
try
{
kerberosDecoder.decode( stream, encKrbPrivPartContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncKrbPrivPart
EncKrbPrivPart encKrbPrivPart = ( ( EncKrbPrivPartContainer ) encKrbPrivPartContainer ).getEncKrbPrivPart();
return encKrbPrivPart;
}
/**
* Decode an EncTicketPart structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncTicketPart
* @throws KerberosException If the decoding fails
*/
public static EncTicketPart decodeEncTicketPart( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncTicketPart Container
Asn1Container encTicketPartContainer = new EncTicketPartContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncTicketPart PDU
try
{
kerberosDecoder.decode( stream, encTicketPartContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncTicketPart
EncTicketPart encTicketPart = ( ( EncTicketPartContainer ) encTicketPartContainer ).getEncTicketPart();
return encTicketPart;
}
/**
* Decode an EncryptionKey structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncryptionKey
* @throws KerberosException If the decoding fails
*/
public static EncryptionKey decodeEncryptionKey( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncryptionKey Container
Asn1Container encryptionKeyContainer = new EncryptionKeyContainer();
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncryptionKey PDU
try
{
kerberosDecoder.decode( stream, encryptionKeyContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncryptionKey
EncryptionKey encryptionKey = ( ( EncryptionKeyContainer ) encryptionKeyContainer ).getEncryptionKey();
return encryptionKey;
}
/**
* Decode an PrincipalName structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of PrincipalName
* @throws KerberosException If the decoding fails
*/
public static PrincipalName decodePrincipalName( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a PrincipalName Container
Asn1Container principalNameContainer = new PrincipalNameContainer();
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the PrincipalName PDU
try
{
kerberosDecoder.decode( stream, principalNameContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded PrincipalName
PrincipalName principalName = ( ( PrincipalNameContainer ) principalNameContainer ).getPrincipalName();
return principalName;
}
/**
* Decode a Ticket structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of Ticket
* @throws KerberosException If the decoding fails
*/
public static Ticket decodeTicket( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a Ticket Container
Asn1Container ticketContainer = new TicketContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the Ticket PDU
try
{
kerberosDecoder.decode( stream, ticketContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded Ticket
Ticket ticket = ( ( TicketContainer ) ticketContainer ).getTicket();
return ticket;
}
/**
* Decode a Authenticator structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of Authenticator
* @throws KerberosException If the decoding fails
*/
public static Authenticator decodeAuthenticator( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a Authenticator Container
Asn1Container authenticatorContainer = new AuthenticatorContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the Ticket PDU
try
{
kerberosDecoder.decode( stream, authenticatorContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded Authenticator
Authenticator authenticator = ( ( AuthenticatorContainer ) authenticatorContainer ).getAuthenticator();
return authenticator;
}
/**
* Decode a AuthorizationData structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of AuthorizationData
* @throws KerberosException If the decoding fails
*/
public static AuthorizationData decodeAuthorizationData( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a AuthorizationData Container
Asn1Container authorizationDataContainer = new AuthorizationDataContainer();
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the Ticket PDU
try
{
kerberosDecoder.decode( stream, authorizationDataContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded AuthorizationData
AuthorizationData authorizationData = ( ( AuthorizationDataContainer ) authorizationDataContainer ).getAuthorizationData();
return authorizationData;
}
/**
* Decode a AP-REP structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of ApRep
* @throws KerberosException If the decoding fails
*/
public static ApRep decodeApRep( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a ApRep Container
Asn1Container apRepContainer = new ApRepContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the ApRep PDU
try
{
kerberosDecoder.decode( stream, apRepContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded ApRep
ApRep apRep = ( ( ApRepContainer ) apRepContainer ).getApRep();
return apRep;
}
/**
* Decode a AP-REQ structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of ApReq
* @throws KerberosException If the decoding fails
*/
public static ApReq decodeApReq( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a ApReq Container
Asn1Container apReqContainer = new ApReqContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the ApReq PDU
try
{
kerberosDecoder.decode( stream, apReqContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded ApReq
ApReq apReq = ( ( ApReqContainer ) apReqContainer ).getApReq();
return apReq;
}
/**
* Decode a KRB-PRIV structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of KrbPriv
* @throws KerberosException If the decoding fails
*/
public static KrbPriv decodeKrbPriv( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a KrbPriv Container
Asn1Container krbPrivContainer = new KrbPrivContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the KrbPriv PDU
try
{
kerberosDecoder.decode( stream, krbPrivContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded KrbPriv
KrbPriv krbPriv = ( ( KrbPrivContainer ) krbPrivContainer ).getKrbPriv();
return krbPriv;
}
/**
* Decode an EncAsRepPart structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncAsRepPart
* @throws KerberosException If the decoding fails
*/
public static EncAsRepPart decodeEncAsRepPart( byte[] data ) throws KerberosException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncAsRepPart Container
Asn1Container encAsRepPartContainer = new EncAsRepPartContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncAsRepPart PDU
try
{
kerberosDecoder.decode( stream, encAsRepPartContainer );
}
catch ( DecoderException de )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, de );
}
// get the decoded EncAsRepPart
EncAsRepPart encAsRepPart = ( ( EncAsRepPartContainer ) encAsRepPartContainer ).getEncAsRepPart();
return encAsRepPart;
}
/**
* Decode an EncTgsRepPart structure
*
* @param data The byte array containing the data structure to decode
* @return An instance of EncTgsRepPart
* @throws KerberosException If the decoding fails
*/
public static EncTgsRepPart decodeEncTgsRepPart( byte[] data ) throws ChangePasswordException
{
ByteBuffer stream = ByteBuffer.allocate( data.length );
stream.put( data );
stream.flip();
// Allocate a EncTgsRepPart Container
Asn1Container encTgsRepPartContainer = new EncTgsRepPartContainer( stream );
Asn1Decoder kerberosDecoder = new Asn1Decoder();
// Decode the EncTgsRepPart PDU
try
{
kerberosDecoder.decode( stream, encTgsRepPartContainer );
}
catch ( DecoderException de )
{
throw new ChangePasswordException( ChangePasswdErrorType.KRB5_KPASSWD_MALFORMED, de );
}
// get the decoded EncTgsRepPart
EncTgsRepPart encTgsRepPart = ( ( EncTgsRepPartContainer ) encTgsRepPartContainer ).getEncTgsRepPart();
return encTgsRepPart;
}
}
| |
package wisdm.cis.fordham.edu.actitracker;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Service that logs data for user determined time.
* Writes data to application directory.
*/
public class PhoneSensorLogService extends Service implements SensorEventListener {
private static final String TAG = "PhoneSensorLogService";
private static final String MINUTES = "MINUTES";
private static final String SAMPLING_RATE = "SAMPLING_RATE";
private static final String TIMED_MODE = "TIMED_MODE";
private static final String USERNAME = "USERNAME";
private static final String ACTIVITY_NAME = "ACTIVITY_NAME";
private static final String PREF_SENSOR_LIST_PHONE = "pref_sensorListPhone";
private SensorManager mSensorManager;
private ArrayList<Integer> mSensorCodes = new ArrayList<Integer>();
private ArrayList<Sensor> mSensors = new ArrayList<Sensor>();
private ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
private ArrayList<ArrayList<SensorRecord>> mRecords = new ArrayList<ArrayList<SensorRecord>>();
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
private String username;
private String activityName;
private boolean timedMode;
private long logDelay = 5000; // TODO: Incorporate into settings.
public PhoneSensorLogService() {
}
@Override
public void onCreate() {
super.onCreate();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
username = intent.getStringExtra(USERNAME);
activityName = intent.getStringExtra(ACTIVITY_NAME);
int minutes = intent.getIntExtra(MINUTES, 0);
int samplingRate = intent.getIntExtra(SAMPLING_RATE, 0);
timedMode = intent.getBooleanExtra(TIMED_MODE, true);
getSensorList();
Log.d(TAG, "Service Started. Username: " + username + ", Activity: " + activityName +
", Sampling Rate: " + samplingRate + ", Minutes: " + minutes);
registerSensorListeners(minutes, samplingRate);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// Write files to disk if manual mode.
if (!timedMode) {
for (Sensor sensor : mSensors) {
mSensorManager.unregisterListener(PhoneSensorLogService.this, sensor);
}
Log.d(TAG, "End: " + System.currentTimeMillis());
writeFiles();
}
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
}
/**
* This method acquires and registers the sensors and the wake lock for sensor sampling.
* Listeners are registered after a delay to allow user to set up phone/watch position if needed.
* Listeners are unregistered after user specified time if in timed mode. Otherwise, waits for
* user to stop service manually via stop button.
*/
private void registerSensorListeners(final int minutes, final int samplingRate){
// Get the accelerometer and gyroscope if available on device
getSensors();
acquireWakeLock();
// Register sensor listener after delay
Log.d(TAG, "Before start: " + System.currentTimeMillis());
exec.schedule(new Runnable() {
@Override
public void run() {
for (Sensor sensor : mSensors) {
mSensorManager.registerListener(PhoneSensorLogService.this, sensor, samplingRate);
}
Log.d(TAG, "Start: " + System.currentTimeMillis());
if (timedMode) {
scheduleLogStop(minutes);
}
}
}, logDelay, TimeUnit.MILLISECONDS);
}
/**
* Unregister sensor listener after specified minutes.
* @param minutes
*/
private void scheduleLogStop(int minutes) {
exec.schedule(new Runnable() {
@Override
public void run() {
for (Sensor sensor : mSensors) {
mSensorManager.unregisterListener(PhoneSensorLogService.this, sensor);
}
Log.d(TAG, "End: " + System.currentTimeMillis());
// Notify user that logging is done
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);
writeFiles();
Log.d(TAG, "Stopping service.");
stopSelf();
}
}, minutes, TimeUnit.MINUTES);
}
/**
* Get selected sensor codes from preference page
*/
private void getSensorList() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Default sensors (accel/gyro) if none are selected. TODO: Handle more gracefully.
Set<String> defaultSensors = new HashSet<String>(Arrays.asList("1", "4"));
List<String> stringList = new ArrayList<String>(sharedPreferences.getStringSet(PREF_SENSOR_LIST_PHONE, defaultSensors));
// Weird bug where default sensors are not referenced
if (stringList.isEmpty()) {
stringList = new ArrayList<String>(defaultSensors);
}
for (String s : stringList) {
if (StringUtils.isNumeric(s)) {
mSensorCodes.add(Integer.valueOf(s));
Log.d(TAG, "code added: " + s);
}
}
}
/**
* Get sensors and create an equal number of ArrayList of SensorRecords
*/
private void getSensors() {
for (Integer i : mSensorCodes) {
mSensors.add(mSensorManager.getDefaultSensor(i));
mRecords.add(new ArrayList<SensorRecord>());
}
}
/**
* Acquire wake lock to sample with the screen off.
*/
private void acquireWakeLock() {
mPowerManager = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.setReferenceCounted(false);
mWakeLock.acquire();
}
/**
* Writes files to internal storage.
* Format: /User/Activity/device_sensor_username_activityName_date_time.txt
*/
private void writeFiles() {
File directory = SensorFileSaver.getDirectory(this, username, activityName);
for (int i = 0; i < mRecords.size(); i++) {
File file = SensorFileSaver.createFile(this, directory, username, activityName,
mSensors.get(i).getName().trim().toLowerCase().replace(" ", "_"));
SensorFileSaver.writeFile(this, file, mRecords.get(i));
}
}
@Override
public void onSensorChanged(SensorEvent event) {
int index = mSensorCodes.indexOf(event.sensor.getType());
mRecords.get(index).add(new SensorRecord(event.timestamp, event.values.clone()));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| |
/*
* Copyright 2015 The Closure Compiler 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.javascript.jscomp;
import static com.google.javascript.jscomp.PolymerPass.POLYMER_DESCRIPTOR_NOT_VALID;
import static com.google.javascript.jscomp.PolymerPass.POLYMER_INVALID_PROPERTY;
import static com.google.javascript.jscomp.PolymerPass.POLYMER_MISSING_IS;
import static com.google.javascript.jscomp.PolymerPass.POLYMER_UNANNOTATED_BEHAVIOR;
import static com.google.javascript.jscomp.PolymerPass.POLYMER_UNEXPECTED_PARAMS;
import static com.google.javascript.jscomp.PolymerPass.POLYMER_UNQUALIFIED_BEHAVIOR;
import static com.google.javascript.jscomp.TypeValidator.TYPE_MISMATCH_WARNING;
import com.google.common.base.Joiner;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
/**
* Unit tests for PolymerPass
* @author jlklein@google.com (Jeremy Klein)
*/
public class PolymerPassTest extends CompilerTestCase {
private static final String EXTERNS = Joiner.on("\n").join(
"/** @constructor */",
"var HTMLElement = function() {};",
"/** @constructor @extends {HTMLElement} */",
"var HTMLInputElement = function() {};",
"/** @constructor @extends {HTMLElement} */",
"var PolymerElement = function() {",
" /** @type {Object} */",
" this.$;",
"};",
"PolymerElement.prototype.created = function() {};",
"PolymerElement.prototype.ready = function() {};",
"PolymerElement.prototype.attached = function() {};",
"PolymerElement.prototype.domReady = function() {};",
"PolymerElement.prototype.detached = function() {};",
"/**",
" * Call the callback after a timeout. Calling job again with the same name",
" * resets the timer but will not result in additional calls to callback.",
" *",
" * @param {string} name",
" * @param {Function} callback",
" * @param {number} timeoutMillis The minimum delay in milliseconds before",
" * calling the callback.",
" */",
"PolymerElement.prototype.job = function(name, callback, timeoutMillis) {};",
"/**",
" * @param a {!Object}",
" * @return {!function()}",
" */",
"var Polymer = function(a) {};",
"var alert = function(msg) {};");
private static final String INPUT_EXTERNS = Joiner.on("\n").join(
"/** @constructor */",
"var HTMLElement = function() {};",
"/** @constructor @extends {HTMLElement} */",
"var HTMLInputElement = function() {};",
"/** @constructor @extends {HTMLElement} */",
"var PolymerElement = function() {",
" /** @type {Object} */",
" this.$;",
"};",
"/** @constructor @extends {HTMLInputElement} */",
"var PolymerInputElement = function() {",
" /** @type {Object} */",
" this.$;",
"};",
"PolymerInputElement.prototype.created = function() {};",
"PolymerInputElement.prototype.ready = function() {};",
"PolymerInputElement.prototype.attached = function() {};",
"PolymerInputElement.prototype.domReady = function() {};",
"PolymerInputElement.prototype.detached = function() {};",
"/**",
" * Call the callback after a timeout. Calling job again with the same name",
" * resets the timer but will not result in additional calls to callback.",
" *",
" * @param {string} name",
" * @param {Function} callback",
" * @param {number} timeoutMillis The minimum delay in milliseconds before",
" * calling the callback.",
" */",
"PolymerInputElement.prototype.job = function(name, callback, timeoutMillis) {};",
"PolymerElement.prototype.created = function() {};",
"PolymerElement.prototype.ready = function() {};",
"PolymerElement.prototype.attached = function() {};",
"PolymerElement.prototype.domReady = function() {};",
"PolymerElement.prototype.detached = function() {};",
"/**",
" * Call the callback after a timeout. Calling job again with the same name",
" * resets the timer but will not result in additional calls to callback.",
" *",
" * @param {string} name",
" * @param {Function} callback",
" * @param {number} timeoutMillis The minimum delay in milliseconds before",
" * calling the callback.",
" */",
"PolymerElement.prototype.job = function(name, callback, timeoutMillis) {};",
"/**",
" * @param a {!Object}",
" * @return {!function()}",
" */",
"var Polymer = function(a) {};",
"var alert = function(msg) {};",
"/** @interface */",
"var PolymerXInputElementInterface = function() {};");
private static final String READONLY_EXTERNS = EXTERNS + Joiner.on("\n").join(
"/** @interface */",
"var Polymera_BInterface = function() {};",
"/** @type {!Array} */",
"Polymera_BInterface.prototype.pets;",
"/** @type {string} */",
"Polymera_BInterface.prototype.name;",
"/** @param {!Array} pets **/",
"Polymera_BInterface.prototype._setPets;");
private static final String BEHAVIOR_READONLY_EXTERNS = EXTERNS + Joiner.on("\n").join(
"/** @interface */",
"var PolymerAInterface = function() {};",
"/** @type {!Array} */",
"PolymerAInterface.prototype.pets;",
"/** @type {string} */",
"PolymerAInterface.prototype.name;",
"/** @type {boolean} */",
"PolymerAInterface.prototype.isFun;",
"/** @param {boolean} isFun **/",
"PolymerAInterface.prototype._setIsFun;");
public PolymerPassTest() {
super(EXTERNS);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new PolymerPass(compiler);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setAcceptedLanguage(LanguageMode.ECMASCRIPT5);
allowExternsChanges(true);
enableTypeCheck(CheckLevel.WARNING);
runTypeCheckAfterProcessing = true;
parseTypeInfo = true;
}
@Override
protected int getNumRepetitions() {
return 1;
}
public void testVarTarget() {
test(Joiner.on("\n").join(
"var X = Polymer({",
" is: 'x-element',",
"});"),
Joiner.on("\n").join(
"/** @constructor @extends {PolymerElement} @implements {PolymerXInterface} */",
"var X = function() {};",
"X = Polymer(/** @lends {X.prototype} */ {",
" is: 'x-element',",
"});"));
}
public void testDefaultTypeNameTarget() {
test(Joiner.on("\n").join(
"Polymer({",
" is: 'x',",
"});"),
Joiner.on("\n").join(
"/**",
" * @implements {PolymerXElementInterface}",
" * @constructor @extends {PolymerElement}",
" */",
"var XElement = function() {};",
"Polymer(/** @lends {XElement.prototype} */ {",
" is: 'x',",
"});"));
}
public void testPathAssignmentTarget() {
test(Joiner.on("\n").join(
"var x = {};",
"x.Z = Polymer({",
" is: 'x-element',",
"});"),
Joiner.on("\n").join(
"var x = {};",
"/** @constructor @extends {PolymerElement} @implements {Polymerx_ZInterface} */",
"x.Z = function() {};",
"x.Z = Polymer(/** @lends {x.Z.prototype} */ {",
" is: 'x-element',",
"});"));
}
/**
* Since 'x' is a global name, the type system understands
* 'x.Z' as a type name, so there is no need to extract the
* type to the global namespace.
*/
public void testIIFEExtractionInGlobalNamespace() {
test(Joiner.on("\n").join(
"var x = {};",
"(function() {",
" x.Z = Polymer({",
" is: 'x-element',",
" sayHi: function() { alert('hi'); },",
" });",
"})()"),
Joiner.on("\n").join(
"var x = {};",
"(function() {",
" /** @constructor @extends {PolymerElement} @implements {Polymerx_ZInterface}*/",
" x.Z = function() {};",
" x.Z = Polymer(/** @lends {x.Z.prototype} */ {",
" is: 'x-element',",
" /** @this {x.Z} */",
" sayHi: function() { alert('hi'); },",
" });",
"})()"));
}
/**
* The definition of XElement is placed in the global namespace,
* outside the IIFE so that the type system will understand that
* XElement is a type.
*/
public void testIIFEExtractionNoAssignmentTarget() {
test(Joiner.on("\n").join(
"(function() {",
" Polymer({",
" is: 'x',",
" sayHi: function() { alert('hi'); },",
" });",
"})()"),
Joiner.on("\n").join(
"/**",
" * @constructor @extends {PolymerElement}",
" * @implements {PolymerXElementInterface}",
" */",
"var XElement = function() {};",
"(function() {",
" Polymer(/** @lends {XElement.prototype} */ {",
" is: 'x',",
" /** @this {XElement} */",
" sayHi: function() { alert('hi'); },",
" });",
"})()"));
}
/**
* The definition of FooThing is placed in the global namespace,
* outside the IIFE so that the type system will understand that
* FooThing is a type.
*/
public void testIIFEExtractionVarTarget() {
test(Joiner.on("\n").join(
"(function() {",
" var FooThing = Polymer({",
" is: 'x',",
" sayHi: function() { alert('hi'); },",
" });",
"})()"),
Joiner.on("\n").join(
"/**",
" * @constructor @extends {PolymerElement}",
" * @implements {PolymerFooThingInterface}",
" */",
"var FooThing = function() {};",
"(function() {",
" FooThing = Polymer(/** @lends {FooThing.prototype} */ {",
" is: 'x',",
" /** @this {FooThing} */",
" sayHi: function() { alert('hi'); },",
" });",
"})()"));
}
public void testConstructorExtraction() {
test(Joiner.on("\n").join(
"var X = Polymer({",
" is: 'x-element',",
" /**",
" * @param {string} name",
" */",
" factoryImpl: function(name) { alert('hi, ' + name); },",
"});"),
Joiner.on("\n").join(
"/**",
" * @param {string} name",
" * @constructor @extends {PolymerElement}",
" * @implements {PolymerXInterface}",
" */",
"var X = function(name) { alert('hi, ' + name); };",
"X = Polymer(/** @lends {X.prototype} */ {",
" is: 'x-element',",
" factoryImpl: function(name) { alert('hi, ' + name); },",
"});"));
}
public void testOtherKeysIgnored() {
test(Joiner.on("\n").join(
"var X = Polymer({",
" is: 'x-element',",
" listeners: {",
" 'click': 'handleClick',",
" },",
"",
" handleClick: function(e) {",
" alert('Thank you for clicking');",
" },",
"});"),
Joiner.on("\n").join(
"/** @constructor @extends {PolymerElement} @implements {PolymerXInterface}*/",
"var X = function() {};",
"X = Polymer(/** @lends {X.prototype} */ {",
" is: 'x-element',",
" listeners: {",
" 'click': 'handleClick',",
" },",
"",
" /** @this {X} */",
" handleClick: function(e) {",
" alert('Thank you for clicking');",
" },",
"});"));
}
public void testNativeElementExtension() {
String js = Joiner.on("\n").join(
"Polymer({",
" is: 'x-input',",
" extends: 'input',",
"});");
test(js,
Joiner.on("\n").join(
"/**",
" * @constructor @extends {PolymerInputElement}",
" * @implements {PolymerXInputElementInterface}",
" */",
"var XInputElement = function() {};",
"Polymer(/** @lends {XInputElement.prototype} */ {",
" is: 'x-input',",
" extends: 'input',",
"});"));
testExternChanges(EXTERNS, js, INPUT_EXTERNS);
}
public void testNativeElementExtensionExternsNotDuplicated() {
String js = Joiner.on("\n").join(
"Polymer({",
" is: 'x-input',",
" extends: 'input',",
"});",
"Polymer({",
" is: 'y-input',",
" extends: 'input',",
"});");
String newExterns = INPUT_EXTERNS + "\n" + Joiner.on("\n").join(
"/** @interface */",
"var PolymerYInputElementInterface = function() {};");
testExternChanges(EXTERNS, js, newExterns);
}
public void testPropertiesAddedToPrototype() {
test(Joiner.on("\n").join(
"/** @constructor */",
"var User = function() {};",
"var a = {};",
"a.B = Polymer({",
" is: 'x-element',",
" properties: {",
" /** @type {!User} @private */",
" user_: Object,",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" thingToDo: Function,",
" },",
"});"),
Joiner.on("\n").join(
"/** @constructor */",
"var User = function() {};",
"var a = {};",
"/** @constructor @extends {PolymerElement} @implements {Polymera_BInterface}*/",
"a.B = function() {};",
"/** @type {!User} @private */",
"a.B.prototype.user_;",
"/** @type {!Array} */",
"a.B.prototype.pets;",
"/** @type {string} */",
"a.B.prototype.name;",
"/** @type {!Function} */",
"a.B.prototype.thingToDo;",
"a.B = Polymer(/** @lends {a.B.prototype} */ {",
" is: 'x-element',",
" properties: {",
" user_: Object,",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" thingToDo: Function,",
" },",
"});"));
}
public void testReadOnlyPropertySetters() {
String js = Joiner.on("\n").join(
"var a = {};",
"a.B = Polymer({",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" readOnly: true,",
" },",
" name: String,",
" },",
"});");
test(js,
Joiner.on("\n").join(
"var a = {};",
"/** @constructor @extends {PolymerElement} @implements {Polymera_BInterface} */",
"a.B = function() {};",
"/** @type {!Array} */",
"a.B.prototype.pets;",
"/** @type {string} */",
"a.B.prototype.name;",
"/** @override */",
"a.B.prototype._setPets = function(pets) {};",
"a.B = Polymer(/** @lends {a.B.prototype} */ {",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" readOnly: true,",
" },",
" name: String,",
" },",
"});"));
testExternChanges(EXTERNS, js, READONLY_EXTERNS);
}
public void testThisTypeAddedToFunctions() {
test(Joiner.on("\n").join(
"var X = Polymer({",
" is: 'x-element',",
" sayHi: function() {",
" alert('hi');",
" },",
" /** @override */",
" created: function() {",
" this.sayHi();",
" this.sayHelloTo_('Tester');",
" },",
" /**",
" * @param {string} name",
" * @private",
" */",
" sayHelloTo_: function(name) {",
" alert('Hello, ' + name);",
" },",
"});"),
Joiner.on("\n").join(
"/** @constructor @extends {PolymerElement} @implements {PolymerXInterface} */",
"var X = function() {};",
"X = Polymer(/** @lends {X.prototype} */ {",
" is: 'x-element',",
" /** @this {X} */",
" sayHi: function() {",
" alert('hi');",
" },",
" /** @override @this {X} */",
" created: function() {",
" this.sayHi();",
" this.sayHelloTo_('Tester');",
" },",
" /**",
" * @param {string} name",
" * @private",
" * @this {X}",
" */",
" sayHelloTo_: function(name) {",
" alert('Hello, ' + name);",
" },",
"});"));
}
public void testDollarSignPropsConvertedToBrackets() {
test(Joiner.on("\n").join(
"/** @constructor */",
"var SomeType = function() {};",
"SomeType.prototype.toggle = function() {};",
"SomeType.prototype.switch = function() {};",
"SomeType.prototype.touch = function() {};",
"var X = Polymer({",
" is: 'x-element',",
" sayHi: function() {",
" this.$.checkbox.toggle();",
" },",
" /** @override */",
" created: function() {",
" this.sayHi();",
" this.$.radioButton.switch();",
" },",
" /**",
" * @param {string} name",
" * @private",
" */",
" sayHelloTo_: function(name) {",
" this.$.otherThing.touch();",
" },",
"});"),
Joiner.on("\n").join(
"/** @constructor */",
"var SomeType = function() {};",
"SomeType.prototype.toggle = function() {};",
"SomeType.prototype.switch = function() {};",
"SomeType.prototype.touch = function() {};",
"/** @constructor @extends {PolymerElement} @implements {PolymerXInterface} */",
"var X = function() {};",
"X = Polymer(/** @lends {X.prototype} */ {",
" is: 'x-element',",
" /** @this {X} */",
" sayHi: function() {",
" this.$['checkbox'].toggle();",
" },",
" /** @override @this {X} */",
" created: function() {",
" this.sayHi();",
" this.$['radioButton'].switch();",
" },",
" /**",
" * @param {string} name",
" * @private",
" * @this {X}",
" */",
" sayHelloTo_: function(name) {",
" this.$['otherThing'].touch();",
" },",
"});"));
}
public void testSimpleBehavior() {
test(Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" /** @type {boolean} */",
" isFun: {",
" type: Boolean,",
" value: true,",
" }",
" },",
" /** @param {string} funAmount */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @override */",
" created: function() {}",
"};",
"var A = Polymer({",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ FunBehavior ],",
"});"),
Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: {",
" type: Boolean,",
" value: true,",
" }",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @suppress {checkTypes|globalThis} */",
" created: function() {}",
"};",
"/** @constructor @extends {PolymerElement} @implements {PolymerAInterface}*/",
"var A = function() {};",
"/** @type {!Array} */",
"A.prototype.pets;",
"/** @type {string} */",
"A.prototype.name;",
"/** @type {boolean} */",
"A.prototype.isFun;",
"/** @param {string} funAmount */",
"A.prototype.doSomethingFun = function(funAmount) {",
" alert('Something ' + funAmount + ' fun!');",
"};",
"A = Polymer(/** @lends {A.prototype} */ {",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ FunBehavior ],",
"});"));
}
public void testArrayBehavior() {
test(Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: Boolean",
" },",
" /** @param {string} funAmount */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @override */",
" created: function() {}",
"};",
"/** @polymerBehavior */",
"var RadBehavior = {",
" properties: {",
" howRad: Number",
" },",
" /** @param {number} radAmount */",
" doSomethingRad: function(radAmount) { alert('Something ' + radAmount + ' rad!'); },",
" /** @override */",
" ready: function() {}",
"};",
"/** @polymerBehavior */",
"var SuperCoolBehaviors = [FunBehavior, RadBehavior];",
"/** @polymerBehavior */",
"var BoringBehavior = {",
" properties: {",
" boringString: String",
" },",
" /** @param {boolean} boredYet */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.boringString); },",
"};",
"var A = Polymer({",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ SuperCoolBehaviors, BoringBehavior ],",
"});"),
Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: Boolean",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @suppress {checkTypes|globalThis} */",
" created: function() {}",
"};",
"/** @polymerBehavior */",
"var RadBehavior = {",
" properties: {",
" howRad: Number",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomethingRad: function(radAmount) { alert('Something ' + radAmount + ' rad!'); },",
" /** @suppress {checkTypes|globalThis} */",
" ready: function() {}",
"};",
"/** @polymerBehavior */",
"var SuperCoolBehaviors = [FunBehavior, RadBehavior];",
"/** @polymerBehavior */",
"var BoringBehavior = {",
" properties: {",
" boringString: String",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.boringString); },",
"};",
"/** @constructor @extends {PolymerElement} @implements {PolymerAInterface}*/",
"var A = function() {};",
"/** @type {!Array} */",
"A.prototype.pets;",
"/** @type {string} */",
"A.prototype.name;",
"/** @type {boolean} */",
"A.prototype.isFun;",
"/** @type {number} */",
"A.prototype.howRad;",
"/** @type {string} */",
"A.prototype.boringString;",
"/** @param {string} funAmount */",
"A.prototype.doSomethingFun = function(funAmount) {",
" alert('Something ' + funAmount + ' fun!');",
"};",
"/** @param {number} radAmount */",
"A.prototype.doSomethingRad = function(radAmount) {",
" alert('Something ' + radAmount + ' rad!');",
"};",
"/** @param {boolean} boredYet */",
"A.prototype.doSomething = function(boredYet) {",
" alert(boredYet + ' ' + this.boringString);",
"};",
"A = Polymer(/** @lends {A.prototype} */ {",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ SuperCoolBehaviors, BoringBehavior ],",
"});"));
}
public void testInlineLiteralBehavior() {
test(Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: Boolean",
" },",
" /** @param {string} funAmount */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @override */",
" created: function() {}",
"};",
"/** @polymerBehavior */",
"var SuperCoolBehaviors = [FunBehavior, {",
" properties: {",
" howRad: Number",
" },",
" /** @param {number} radAmount */",
" doSomethingRad: function(radAmount) { alert('Something ' + radAmount + ' rad!'); },",
" /** @override */",
" ready: function() {}",
"}];",
"var A = Polymer({",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ SuperCoolBehaviors ],",
"});"),
Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: Boolean",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @suppress {checkTypes|globalThis} */",
" created: function() {}",
"};",
"/** @polymerBehavior */",
"var SuperCoolBehaviors = [FunBehavior, {",
" properties: {",
" howRad: Number",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomethingRad: function(radAmount) { alert('Something ' + radAmount + ' rad!'); },",
" /** @suppress {checkTypes|globalThis} */",
" ready: function() {}",
"}];",
"/** @constructor @extends {PolymerElement} @implements {PolymerAInterface}*/",
"var A = function() {};",
"/** @type {!Array} */",
"A.prototype.pets;",
"/** @type {string} */",
"A.prototype.name;",
"/** @type {boolean} */",
"A.prototype.isFun;",
"/** @type {number} */",
"A.prototype.howRad;",
"/** @param {string} funAmount */",
"A.prototype.doSomethingFun = function(funAmount) {",
" alert('Something ' + funAmount + ' fun!');",
"};",
"/** @param {number} radAmount */",
"A.prototype.doSomethingRad = function(radAmount) {",
" alert('Something ' + radAmount + ' rad!');",
"};",
"A = Polymer(/** @lends {A.prototype} */ {",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ SuperCoolBehaviors ],",
"});"));
}
/**
* If an element has two or more behaviors which define the same function, only the last
* behavior's function should be copied over to the element's prototype.
*/
public void testBehaviorFunctionOverriding() {
test(Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: Boolean",
" },",
" /** @param {boolean} boredYet */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.isFun); },",
" /** @override */",
" created: function() {}",
"};",
"/** @polymerBehavior */",
"var RadBehavior = {",
" properties: {",
" howRad: Number",
" },",
" /** @param {boolean} boredYet */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.howRad); },",
" /** @override */",
" ready: function() {}",
"};",
"/** @polymerBehavior */",
"var SuperCoolBehaviors = [FunBehavior, RadBehavior];",
"/** @polymerBehavior */",
"var BoringBehavior = {",
" properties: {",
" boringString: String",
" },",
" /** @param {boolean} boredYet */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.boringString); },",
"};",
"var A = Polymer({",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ SuperCoolBehaviors, BoringBehavior ],",
"});"),
Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: Boolean",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.isFun); },",
" /** @suppress {checkTypes|globalThis} */",
" created: function() {}",
"};",
"/** @polymerBehavior */",
"var RadBehavior = {",
" properties: {",
" howRad: Number",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.howRad); },",
" /** @suppress {checkTypes|globalThis} */",
" ready: function() {}",
"};",
"/** @polymerBehavior */",
"var SuperCoolBehaviors = [FunBehavior, RadBehavior];",
"/** @polymerBehavior */",
"var BoringBehavior = {",
" properties: {",
" boringString: String",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomething: function(boredYet) { alert(boredYet + ' ' + this.boringString); },",
"};",
"/** @constructor @extends {PolymerElement} @implements {PolymerAInterface}*/",
"var A = function() {};",
"/** @type {!Array} */",
"A.prototype.pets;",
"/** @type {string} */",
"A.prototype.name;",
"/** @type {boolean} */",
"A.prototype.isFun;",
"/** @type {number} */",
"A.prototype.howRad;",
"/** @type {string} */",
"A.prototype.boringString;",
"/** @param {boolean} boredYet */",
"A.prototype.doSomething = function(boredYet) {",
" alert(boredYet + ' ' + this.boringString);",
"};",
"A = Polymer(/** @lends {A.prototype} */ {",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ SuperCoolBehaviors, BoringBehavior ],",
"});"));
}
public void testBehaviorReadOnlyProp() {
String js = Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: {",
" type: Boolean,",
" readOnly: true,",
" },",
" },",
" /** @param {string} funAmount */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @override */",
" created: function() {}",
"};",
"var A = Polymer({",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ FunBehavior ],",
"});");
test(js,
Joiner.on("\n").join(
"/** @polymerBehavior */",
"var FunBehavior = {",
" properties: {",
" isFun: {",
" type: Boolean,",
" readOnly: true,",
" },",
" },",
" /** @suppress {checkTypes|globalThis} */",
" doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },",
" /** @suppress {checkTypes|globalThis} */",
" created: function() {}",
"};",
"/** @constructor @extends {PolymerElement} @implements {PolymerAInterface}*/",
"var A = function() {};",
"/** @type {!Array} */",
"A.prototype.pets;",
"/** @type {string} */",
"A.prototype.name;",
"/** @type {boolean} */",
"A.prototype.isFun;",
"/** @param {string} funAmount */",
"A.prototype.doSomethingFun = function(funAmount) {",
" alert('Something ' + funAmount + ' fun!');",
"};",
"/** @override */",
"A.prototype._setIsFun = function(isFun) {};",
"A = Polymer(/** @lends {A.prototype} */ {",
" is: 'x-element',",
" properties: {",
" pets: {",
" type: Array,",
" notify: true,",
" },",
" name: String,",
" },",
" behaviors: [ FunBehavior ],",
"});"));
testExternChanges(EXTERNS, js, BEHAVIOR_READONLY_EXTERNS);
}
public void testInvalid1() {
testSame(
"var x = Polymer();",
POLYMER_DESCRIPTOR_NOT_VALID, true);
testSame(
"var x = Polymer({},'blah');",
POLYMER_UNEXPECTED_PARAMS, true);
testSame(
"var x = Polymer({});",
POLYMER_MISSING_IS, true);
}
public void testInvalidProperties() {
testSame(
Joiner.on("\n").join(
"Polymer({",
" is: 'x-element',",
" properties: {",
" isHappy: true,",
" },",
"});"),
POLYMER_INVALID_PROPERTY, true);
testSame(
Joiner.on("\n").join(
"Polymer({",
" is: 'x-element',",
" properties: {",
" isHappy: {",
" value: true,",
" },",
" },",
"});"),
POLYMER_INVALID_PROPERTY, true);
}
public void testInvalidBehavior() {
testSame(
Joiner.on("\n").join(
"(function() {",
" var isNotGloabl = {};",
" Polymer({",
" is: 'x-element',",
" behaviors: [",
" isNotGlobal",
" ],",
" });",
"})();"),
POLYMER_UNQUALIFIED_BEHAVIOR, true);
testSame(
Joiner.on("\n").join(
"var foo = {};",
"(function() {",
" Polymer({",
" is: 'x-element',",
" behaviors: [",
" foo.IsNotDefined",
" ],",
" });",
"})();"),
POLYMER_UNQUALIFIED_BEHAVIOR, true);
testSame(
Joiner.on("\n").join(
"Polymer({",
" is: 'x-element',",
" behaviors: [",
" DoesNotExist",
" ],",
"});"),
POLYMER_UNQUALIFIED_BEHAVIOR, true);
}
public void testUnannotatedBehavior() {
testError(Joiner.on("\n").join(
"var FunBehavior = {",
" /** @override */",
" created: function() {}",
"};",
"var A = Polymer({",
" is: 'x-element',",
" behaviors: [ FunBehavior ],",
"});"),
POLYMER_UNANNOTATED_BEHAVIOR);
}
public void testInvalidTypeAssignment() {
test(
Joiner.on("\n").join(
"var X = Polymer({",
" is: 'x-element',",
" properties: {",
" isHappy: Boolean,",
" },",
" /** @override */",
" created: function() {",
" this.isHappy = 7;",
" },",
"});"),
Joiner.on("\n").join(
"/** @constructor @extends {PolymerElement} @implements {PolymerXInterface} */",
"var X = function() {};",
"/** @type {boolean} */",
"X.prototype.isHappy;",
"X = Polymer(/** @lends {X.prototype} */ {",
" is: 'x-element',",
" properties: {",
" isHappy: Boolean,",
" },",
" /** @override @this {X} */",
" created: function() {",
" this.isHappy = 7;",
" },",
"});"),
null,
TYPE_MISMATCH_WARNING);
}
}
| |
package org.openntf.bildr;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import javax.faces.context.FacesContext;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.xsp.designer.context.XSPContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.NotesException;
import lotus.domino.View;
import org.openntf.domino.xsp.XspOpenLogUtil;
import lotus.domino.Name;
public class AppController implements Serializable{
private static final long serialVersionUID = 1L;
private static final String startpage = getProperty("startpage");
private ArrayList<JsonJavaObject> profiles;
//The DaoBean contains information where the data database is located e.g. on premise or on bluemix
private static DaoBean dao = new DaoBean();
public AppController() throws NotesException{
// Constructor...
XspOpenLogUtil.logEvent(null, this.getClass().getSimpleName().toString() + ". Constructor started. Debug = " + getDebugMode() + ", user = " + JSFUtil.getCurrentUser().getCanonical(), Level.INFO, null);
}
public Boolean isRegistered() throws NotesException {
writeToConsole(this.getClass().getSimpleName().toString() + ". isRegistered()");
boolean profile = false;
Name name = JSFUtil.getCurrentUser();
if (name.getCommon()=="Anonymous"){
writeToConsole(this.getClass().getSimpleName().toString() + ". isRegistered() - Anonymous user");
profile = false;
}
else{
writeToConsole(this.getClass().getSimpleName().toString() + ". isRegistered() - Welcome " + name.getCommon());
Database dataDB = dao.getDatabase();
View profileView;
try {
profileView = dataDB.getView("$v-profiles");
profileView.refresh();
Document doc = profileView.getDocumentByKey(name.getCanonical());
if (null == doc){
writeToConsole( this.getClass().getSimpleName().toString() + ". isRegistered(). " + name.getCommon() + " is not yet registered.");
profile = false;
}
else{
writeToConsole(this.getClass().getSimpleName().toString() + ". isRegistered() - " + name.getCommon() + " is registered");
profile = true;
doc.recycle();
}
profileView.recycle();
} catch (NotesException e) {
XspOpenLogUtil.logError(null, e, this.getClass().getSimpleName().toString() + ". isRegistered()", Level.SEVERE, null);
}
dataDB.recycle();
}
return profile;
}
public String getObjectType(String id) throws NotesException{
writeToConsole(this.getClass().getSimpleName().toString() + ". getObjectType(id). Id = " + id);
String ObjType = null;
if (id == null){
ObjType = "unknown";
}
else{
Database dataDB = dao.getDatabase();
Document objDoc;
try{
objDoc = dataDB.getDocumentByUNID(id);
String ObjTypeTmp = objDoc.getItemValueString("form");
writeToConsole(this.getClass().getSimpleName().toString() + ". getObjectType(id). Form = " + ObjTypeTmp);
if (ObjTypeTmp.equals("$f-profile")) {
ObjType = "profile";
}
else if(ObjTypeTmp.equals("$f-picture")){
ObjType = "picture";
}
else if(ObjTypeTmp.equals("$f-album")){
ObjType = "album";
}
else{
ObjType = "notavailable";
}
} catch (NotesException e) {
// TODO Auto-generated catch block
XspOpenLogUtil.logError(null, e, this.getClass().getSimpleName().toString() + ". getObjectType(String id)", Level.SEVERE, null);
//e.printStackTrace();
}
}
return ObjType;
}
public String getProfileID() throws NotesException{
writeToConsole(this.getClass().getSimpleName().toString() + ". getProfileID()");
String id = null;
Name name = JSFUtil.getCurrentUser();
if (name.getCommon()=="Anonymous"){
writeToConsole(this.getClass().getSimpleName().toString() + ". getProfileID() - Anonymous user");
id = null;
}
else{
Database dataDB = dao.getDatabase();
View profileView;
try {
profileView = dataDB.getView("$v-profiles");
Document doc = profileView.getDocumentByKey(name.getCanonical());
if (null == doc){
id = "";
}
else{
id = doc.getUniversalID();
doc.recycle();
}
profileView.recycle();
} catch (NotesException e) {
XspOpenLogUtil.logError(null, e, this.getClass().getSimpleName().toString() + ". getProfileID()", Level.SEVERE, null);
}
dataDB.recycle();
}
return id;
}
public static Boolean hasConfiguration() throws NotesException{
writeToConsole("AppController. hasConfiguration()");
boolean configuration = false;
Database dataDB = dao.getDatabase();
View prefView;
try {
prefView = dataDB.getView("$v-preferences");
Document doc = prefView.getFirstDocument();
if (null == doc){
configuration = false;
}
else{
configuration = true;
doc.recycle();
}
prefView.recycle();
} catch (NotesException e) {
// TODO Auto-generated catch block
XspOpenLogUtil.logError(null, e, "AppController. hasConfiguration()", Level.SEVERE, null);
//e.printStackTrace();
}
dataDB.recycle();
return configuration;
}
public static String getConfigurationID(){
writeToConsole("AppController. getConfigurationID()");
String id = null;
Database dataDB = dao.getDatabase();
View prefView;
try {
prefView = dataDB.getView("$v-preferences");
Document doc = prefView.getFirstDocument();
if (null == doc){
id = "";
}
else{
id = doc.getUniversalID();
doc.recycle();
}
prefView.recycle();
dataDB.recycle();
} catch (NotesException e) {
// TODO Auto-generated catch block
XspOpenLogUtil.logError(null, e, "AppController. getConfigurationID()", Level.SEVERE, null);
//e.printStackTrace();
}
return id;
}
// @Deprecated
// public static void writeToLog(String msg, String severity){
// if (getDebugMode() == true){
// OpenLogUtil.logEvent(null, msg, Level.parse(severity) , null);
// }
// }
public static void writeToConsole(String msg){
if (getDebugMode() == true){
System.out.println(msg);
}
}
public ArrayList<JsonJavaObject> getProfiles() {
return profiles;
}
/**
* getting the XSP Contect and redirect
*/
public void redirectToStartPage() {
try {
this.getXSPContext().redirectToPage(startpage);
} catch (Exception e) {
e.printStackTrace();
}
}
public XSPContext getXSPContext() {
return XSPContext.getXSPContext(getFacesContext());
}
public FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
public static Boolean getDebugMode() {
String configval = Configuration.debugMode;
return Boolean.valueOf(configval);
}
private static String getProperty(String prop) {
try {
return getApplicationProperties().getProperty(prop);
} catch (Throwable t) {
XspOpenLogUtil.logError(t);
return null;
}
}
private static Properties getApplicationProperties() throws IOException {
InputStream input = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("application.properties");
Properties props = new Properties();
props.load(input);
return props;
}
}
| |
/*
* Copyright 2013-2018 Ray Tsang
*
* 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.jdeferred2.impl;
import java.util.concurrent.Callable;
import org.jdeferred2.AlwaysPipe;
import org.jdeferred2.DoneCallback;
import org.jdeferred2.DonePipe;
import org.jdeferred2.FailCallback;
import org.jdeferred2.FailPipe;
import org.jdeferred2.Promise;
import org.junit.Test;
public class PipedPromiseTest extends AbstractDeferredTest {
@Test
public void testDoneRewirePipe() {
final ValueHolder<Integer> preRewireValue = new ValueHolder<Integer>();
final ValueHolder<Integer> postRewireValue = new ValueHolder<Integer>();
Callable<Integer> task = new Callable<Integer>() {
public Integer call() {
return 100;
}
};
deferredManager.when(task).pipe(new DonePipe<Integer, Integer, Throwable, Void>() {
@Override
public Promise<Integer, Throwable, Void> pipeDone(Integer result) {
preRewireValue.set(result);
return new DeferredObject<Integer, Throwable, Void>().resolve(1000);
}
}).done(new DoneCallback<Integer>() {
@Override
public void onDone(Integer value) {
postRewireValue.set(value);
}
});
waitForCompletion();
preRewireValue.assertEquals(100);
postRewireValue.assertEquals(1000);
}
@Test
public void testFailRewirePipe() {
final ValueHolder<String> preRewireValue = new ValueHolder<String>();
final ValueHolder<String> postRewireValue = new ValueHolder<String>();
Callable<Integer> task = new Callable<Integer>() {
public Integer call() {
throw new RuntimeException("oops");
}
};
deferredManager.when(task).pipe(null, new FailPipe<Throwable, Integer, String, Void>() {
@Override
public Promise<Integer, String, Void> pipeFail(Throwable result) {
preRewireValue.set(result.getMessage());
return new DeferredObject<Integer, String, Void>().reject("ouch");
}
}).fail(new FailCallback<String>() {
@Override
public void onFail(String result) {
postRewireValue.set(result);
}
});
waitForCompletion();
preRewireValue.assertEquals("oops");
postRewireValue.assertEquals("ouch");
}
@Test
public void testAlwaysRewirePipeResolve() {
final ValueHolder<String> preRewireValue = new ValueHolder<String>();
final ValueHolder<String> postRewireValue = new ValueHolder<String>();
Callable<String> task = new Callable<String>() {
public String call() {
return "done";
}
};
deferredManager.when(task).pipeAlways(new AlwaysPipe<String, Throwable, Object, String, Void>() {
@Override
public Promise<Object, String, Void> pipeAlways(Promise.State state, String resolved, Throwable rejected) {
preRewireValue.set(resolved);
return new DeferredObject<Object, String, Void>().reject("ouch");
}
}).fail(new FailCallback<String>() {
@Override
public void onFail(String result) {
postRewireValue.set(result);
}
});
waitForCompletion();
preRewireValue.assertEquals("done");
postRewireValue.assertEquals("ouch");
}
@Test
public void testAlwaysRewirePipeFail() {
final ValueHolder<String> preRewireValue = new ValueHolder<String>();
final ValueHolder<String> postRewireValue = new ValueHolder<String>();
Callable<Integer> task = new Callable<Integer>() {
public Integer call() {
throw new RuntimeException("oops");
}
};
deferredManager.when(task).pipeAlways(new AlwaysPipe<Integer, Throwable, String, Object, Void>() {
@Override
public Promise<String, Object, Void> pipeAlways(Promise.State state, Integer resolved, Throwable rejected) {
preRewireValue.set(rejected.getMessage());
return new DeferredObject<String, Object, Void>().resolve("done");
}
}).done(new DoneCallback<String>() {
@Override
public void onDone(String result) {
postRewireValue.set(result);
}
});
waitForCompletion();
preRewireValue.assertEquals("oops");
postRewireValue.assertEquals("done");
}
@Test
public void testNullDoneRewirePipe() {
final ValueHolder<Boolean> failed = new ValueHolder<Boolean>(false);
final ValueHolder<Integer> postRewireValue = new ValueHolder<Integer>();
Callable<Integer> task = new Callable<Integer>() {
public Integer call() {
return 100;
}
};
deferredManager.when(task).pipe(null, new FailPipe<Throwable, Integer, String, Void>() {
@Override
public Promise<Integer, String, Void> pipeFail(Throwable result) {
return new DeferredObject<Integer, String, Void>().reject("ouch");
}
}).done(new DoneCallback<Integer>() {
@Override
public void onDone(Integer result) {
postRewireValue.set(result);
}
}).fail(new FailCallback<String>() {
@Override
public void onFail(String result) {
failed.set(true);
}
});
waitForCompletion();
failed.assertEquals(false);
postRewireValue.assertEquals(100);
}
@Test
public void testDoneRewireToFail() {
final ValueHolder<Integer> preRewireValue = new ValueHolder<Integer>();
final ValueHolder<Integer> postRewireValue = new ValueHolder<Integer>();
final ValueHolder<String> failed = new ValueHolder<String>();
deferredManager.when(new Callable<Integer>() {
public Integer call() {
return 10;
}
}).pipe(new DonePipe<Integer, Integer, Throwable, Void>() {
@Override
public Promise<Integer, Throwable, Void> pipeDone(Integer result) {
preRewireValue.set(result);
if (result < 100) {
return new DeferredObject<Integer, Throwable, Void>().reject(new Exception("less than 100"));
} else {
return new DeferredObject<Integer, Throwable, Void>().resolve(result);
}
}
}).done(new DoneCallback<Integer>() {
@Override
public void onDone(Integer result) {
postRewireValue.set(result);
}
}).fail(new FailCallback<Throwable>() {
@Override
public void onFail(Throwable result) {
failed.set(result.getMessage());
}
});
waitForCompletion();
preRewireValue.assertEquals(10);
postRewireValue.assertEquals(null);
failed.assertEquals("less than 100");
}
}
| |
package server;
import Accessors.GameTransactionEccessor;
public class RouletaTable {
private int playerId;
private int gambleAmount;
private String gameResault; // win or lose
private int gambelNumber;
private int Amount;
private int winningNumber;
private String GambleOption; // n or c for numbers and colors
private ScannerManager scanner;
private int balance;
private String gametype; //rouleta
private GameTransactionEccessor gameTransactionEccessor;
private String gambleColor;
private String winningColor;
RouletaWheel rouletaWheel = new RouletaWheel();
public RouletaTable() {
gameTransactionEccessor = new GameTransactionEccessor();
scanner = new ScannerManager();
}
public String getWinningColor() {
return winningColor;
}
public void setWinningColor(String winningColor) {
this.winningColor = winningColor;
}
public String getGambleColor() {
return gambleColor;
}
public void setGambleColor(String gambleColor) {
this.gambleColor = gambleColor;
}
public String getGametype() {
return gametype;
}
public void setGameType(String gametype) {
this.gametype = gametype;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public String getGambleOption() {
return GambleOption;
}
public void setGambleOption(String gambleOption) {
GambleOption = gambleOption;
}
public int getWiningNumber() {
return winningNumber;
}
public void setWiningNumber(int winingNumber) {
this.winningNumber = winingNumber;
}
public int getAmount() {
return Amount;
}
public void setAmount(int Amount) {
this.Amount = Amount;
}
public int getGamblNumber() {
return gambelNumber;
}
public void setGamblNumber(int gamblNumber) {
this.gambelNumber = gamblNumber;
}
public int getPlayerId() {
return playerId;
}
public void setPlayerId(int PlayerId) {
this.playerId = PlayerId;
}
public int getGambleAmount() {
return gambleAmount;
}
public void setGambleAmount(int gambleAmount) {
this.gambleAmount = gambleAmount;
}
public String getGameResault() {
return gameResault;
}
public void setGameResault(String gameResault) {
this.gameResault = gameResault;
}
public void startGame() {
int menu = scanner.getIntValueFromUser("To gamble Enter 1>\nTo go back to " + "'GAME ZONE' enter 2> ");
while (menu != 3) {
if (menu == 1) {
gambleProcces();
} else if (menu == 2) {
} else {
System.out.println("Wrong number, Please chose 1 or 2: ");
}
menu = 3;
}
}
private void gambleProcces() {
int gambleAmount = scanner.getIntValueFromUser("How much are you bringing to the table? ");
Boolean ifBalanceExists = validateBalance(gambleAmount);
if (ifBalanceExists == false) {
startGame();
} else {
setGambleAmount(gambleAmount);
String gambleType = scanner.getStringValueFromUser("Enter \"n\" to gamble on number or \"c\" for color?");// later
// etc..
if (gambleType.equals("n")) {
setGambleOption(gambleType);
int gambleNumber = scanner.getIntValueFromUser("pick a number between 1-36?");
setGamblNumber(gambleNumber);
printRowllingNumbers();
int winingNumber = rouletaWheel.lotteryNumber();
setWiningNumber(winingNumber);
endNumbersRound();
} else if (gambleType.equals("c")) {
setGambleOption(gambleType);
String gambleColor = scanner.getStringValueFromUser("pick \"b\" for black or \"r\" for red:");
if (gambleColor.equals("b")) {
setGambleColor(gambleColor);
printRowllingNumbers();
String winningColor = rouletaWheel.lotteryColor();
setWinningColor(winningColor);
endColorsRound();
} else if (gambleColor.equals("r")) {
setGambleColor(gambleColor);
printRowllingNumbers();
String winningColor = rouletaWheel.lotteryColor();
setWinningColor(winningColor);
endColorsRound();
} else {
System.out.println("Wrong input please type \"r\" or \"b\" ");
gambleType = "c";
gambleProcces();
}
} else {
System.out.println("Wrong input please type \"n\" or \"c\" ");
gambleProcces();
}
}
}
private void endNumbersRound() {
if (this.winningNumber == this.gambelNumber) {
String win = "win";
setGameResault(win);
int winningPrise = gambleAmount * 4;
setAmount(winningPrise);
System.out.println(
"You Won!! Congradulation!! your winning amount is " + winningPrise + " dollar. Luky you!");
setBalance(balance + winningPrise);
gameTransactionEccessor.saveNumberTranHistory(this);
startGame();
} else {
System.out.println(
"The winning number is " + this.winningNumber + " your loss is " + gambleAmount + " dollar");
setAmount(gambleAmount);
setBalance(balance - gambleAmount);
String lose = "lose";
setGameResault(lose);
gameTransactionEccessor.saveNumberTranHistory(this);
startGame();
}
}
private void endColorsRound() {
if (this.winningColor.equals(this.gambleColor)) {
String win = "win";
setGameResault(win);
int winningPrise = gambleAmount * 3;
setAmount(winningPrise);
System.out.println("You Won!! Congradulation!! your winning amount is " + winningPrise + " dollar. Luky you!");
setBalance(balance + winningPrise);
gameTransactionEccessor.saveColorTranHistory(this);
startGame();
} else {
System.out.println("The winning color is " + this.winningColor + " your loss is "
+ gambleAmount + " dollar");
setAmount(gambleAmount);
setBalance(balance - gambleAmount);
String lose = "lose";
setGameResault(lose);
gameTransactionEccessor.saveColorTranHistory(this);
startGame();
}
}
private boolean validateBalance(int gambleAmount) {
if (this.balance < gambleAmount) {
System.out.println("Sorry but you don't have enough chips, please go back to 'GAME ZONE' to buy more chips"
+ "\n********************************************************************************************");
return false;
} else {
return true;
}
}
private void printRowllingNumbers() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
System.out.println("The table is close to gamble... wheel start rolling");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(2);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(15);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(14);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(5);
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(12);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(22);
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(7);
try {
Thread.sleep(70);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(14);
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(24);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(3);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(2);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(".........");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("DONE ROLLING");
System.out.println();
System.out.println();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public long getNumOfWin() {
long winNum = gameTransactionEccessor.getNumOfWin(this);
return winNum;
}
public void getLuckyNum() {
// FindIterable<Document> luckyNum =
gameTransactionEccessor.getLuckyNu(this);
// return luckyNum;
}
public Object getHighlyWinAmount() {
Object highlyWinAmount = gameTransactionEccessor.getHighlyWinAmount(this);
return highlyWinAmount;
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.watcher.actions.hipchat;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.core.watcher.actions.Action;
import org.elasticsearch.xpack.watcher.common.http.HttpProxy;
import org.elasticsearch.xpack.watcher.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.notification.hipchat.HipChatMessage;
import org.elasticsearch.xpack.watcher.notification.hipchat.SentMessages;
import java.io.IOException;
import java.util.Objects;
public class HipChatAction implements Action {
public static final String TYPE = "hipchat";
@Nullable final String account;
@Nullable final HttpProxy proxy;
final HipChatMessage.Template message;
public HipChatAction(@Nullable String account, HipChatMessage.Template message, @Nullable HttpProxy proxy) {
this.account = account;
this.message = message;
this.proxy = proxy;
}
@Override
public String type() {
return TYPE;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HipChatAction that = (HipChatAction) o;
return Objects.equals(account, that.account) &&
Objects.equals(message, that.message) &&
Objects.equals(proxy, that.proxy);
}
@Override
public int hashCode() {
return Objects.hash(account, message, proxy);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (account != null) {
builder.field(Field.ACCOUNT.getPreferredName(), account);
}
if (proxy != null) {
proxy.toXContent(builder, params);
}
builder.field(Field.MESSAGE.getPreferredName(), message);
return builder.endObject();
}
public static HipChatAction parse(String watchId, String actionId, XContentParser parser) throws IOException {
String account = null;
HipChatMessage.Template message = null;
HttpProxy proxy = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.ACCOUNT.match(currentFieldName, parser.getDeprecationHandler())) {
if (token == XContentParser.Token.VALUE_STRING) {
account = parser.text();
} else {
throw new ElasticsearchParseException("failed to parse [{}] action [{}/{}]. expected [{}] to be of type string, but " +
"found [{}] instead", TYPE, watchId, actionId, Field.ACCOUNT.getPreferredName(), token);
}
} else if (Field.PROXY.match(currentFieldName, parser.getDeprecationHandler())) {
proxy = HttpProxy.parse(parser);
} else if (Field.MESSAGE.match(currentFieldName, parser.getDeprecationHandler())) {
try {
message = HipChatMessage.Template.parse(parser);
} catch (Exception e) {
throw new ElasticsearchParseException("failed to parse [{}] action [{}/{}]. failed to parse [{}] field", e, TYPE,
watchId, actionId, Field.MESSAGE.getPreferredName());
}
} else {
throw new ElasticsearchParseException("failed to parse [{}] action [{}/{}]. unexpected token [{}]", TYPE, watchId,
actionId, token);
}
}
if (message == null) {
throw new ElasticsearchParseException("failed to parse [{}] action [{}/{}]. missing required [{}] field", TYPE, watchId,
actionId, Field.MESSAGE.getPreferredName());
}
return new HipChatAction(account, message, proxy);
}
public static Builder builder(String account, TextTemplate body) {
return new Builder(account, body);
}
public interface Result {
class Executed extends Action.Result implements Result {
private final SentMessages sentMessages;
public Executed(SentMessages sentMessages) {
super(TYPE, status(sentMessages));
this.sentMessages = sentMessages;
}
public SentMessages sentMessages() {
return sentMessages;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.field(type, sentMessages, params);
}
static Status status(SentMessages sentMessages) {
boolean hasSuccesses = false;
boolean hasFailures = false;
for (SentMessages.SentMessage message : sentMessages) {
if (message.isSuccess()) {
hasSuccesses = true;
} else {
hasFailures = true;
}
if (hasFailures && hasSuccesses) {
return Status.PARTIAL_FAILURE;
}
}
return hasFailures ? Status.FAILURE : Status.SUCCESS;
}
}
class Simulated extends Action.Result implements Result {
private final HipChatMessage message;
protected Simulated(HipChatMessage message) {
super(TYPE, Status.SIMULATED);
this.message = message;
}
public HipChatMessage getMessage() {
return message;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject(type)
.field(Field.MESSAGE.getPreferredName(), message, params)
.endObject();
}
}
}
public static class Builder implements Action.Builder<HipChatAction> {
final String account;
final HipChatMessage.Template.Builder messageBuilder;
private HttpProxy proxy;
public Builder(String account, TextTemplate body) {
this.account = account;
this.messageBuilder = new HipChatMessage.Template.Builder(body);
}
public Builder addRooms(TextTemplate... rooms) {
messageBuilder.addRooms(rooms);
return this;
}
public Builder addRooms(String... rooms) {
TextTemplate[] templates = new TextTemplate[rooms.length];
for (int i = 0; i < rooms.length; i++) {
templates[i] = new TextTemplate(rooms[i]);
}
return addRooms(templates);
}
public Builder addUsers(TextTemplate... users) {
messageBuilder.addUsers(users);
return this;
}
public Builder addUsers(String... users) {
TextTemplate[] templates = new TextTemplate[users.length];
for (int i = 0; i < users.length; i++) {
templates[i] = new TextTemplate(users[i]);
}
return addUsers(templates);
}
public Builder setFrom(String from) {
messageBuilder.setFrom(from);
return this;
}
public Builder setFormat(HipChatMessage.Format format) {
messageBuilder.setFormat(format);
return this;
}
public Builder setColor(TextTemplate color) {
messageBuilder.setColor(color);
return this;
}
public Builder setColor(HipChatMessage.Color color) {
return setColor(color.asTemplate());
}
public Builder setNotify(boolean notify) {
messageBuilder.setNotify(notify);
return this;
}
public Builder setProxy(HttpProxy proxy) {
this.proxy = proxy;
return this;
}
@Override
public HipChatAction build() {
return new HipChatAction(account, messageBuilder.build(), proxy);
}
}
public interface Field {
ParseField ACCOUNT = new ParseField("account");
ParseField MESSAGE = new ParseField("message");
ParseField PROXY = new ParseField("proxy");
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.testsuite.rest;
import org.jboss.resteasy.annotations.Query;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.adapters.action.LogoutAction;
import org.keycloak.representations.adapters.action.PushNotBeforeAction;
import org.keycloak.representations.adapters.action.TestAvailabilityAction;
import org.keycloak.services.resource.RealmResourceProvider;
import org.keycloak.services.resources.RealmsResource;
import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public class TestApplicationResourceProvider implements RealmResourceProvider {
private KeycloakSession session;
private final BlockingQueue<LogoutAction> adminLogoutActions;
private final BlockingQueue<PushNotBeforeAction> adminPushNotBeforeActions;
private final BlockingQueue<TestAvailabilityAction> adminTestAvailabilityAction;
private final TestApplicationResourceProviderFactory.OIDCClientData oidcClientData;
public TestApplicationResourceProvider(KeycloakSession session, BlockingQueue<LogoutAction> adminLogoutActions,
BlockingQueue<PushNotBeforeAction> adminPushNotBeforeActions,
BlockingQueue<TestAvailabilityAction> adminTestAvailabilityAction, TestApplicationResourceProviderFactory.OIDCClientData oidcClientData) {
this.session = session;
this.adminLogoutActions = adminLogoutActions;
this.adminPushNotBeforeActions = adminPushNotBeforeActions;
this.adminTestAvailabilityAction = adminTestAvailabilityAction;
this.oidcClientData = oidcClientData;
}
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Path("/admin/k_logout")
public void adminLogout(String data) throws JWSInputException {
adminLogoutActions.add(new JWSInput(data).readJsonContent(LogoutAction.class));
}
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Path("/admin/k_push_not_before")
public void adminPushNotBefore(String data) throws JWSInputException {
adminPushNotBeforeActions.add(new JWSInput(data).readJsonContent(PushNotBeforeAction.class));
}
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Path("/admin/k_test_available")
public void testAvailable(String data) throws JWSInputException {
adminTestAvailabilityAction.add(new JWSInput(data).readJsonContent(TestAvailabilityAction.class));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/poll-admin-logout")
public LogoutAction getAdminLogoutAction() throws InterruptedException {
return adminLogoutActions.poll(10, TimeUnit.SECONDS);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/poll-admin-not-before")
public PushNotBeforeAction getAdminPushNotBefore() throws InterruptedException {
return adminPushNotBeforeActions.poll(10, TimeUnit.SECONDS);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/poll-test-available")
public TestAvailabilityAction getTestAvailable() throws InterruptedException {
return adminTestAvailabilityAction.poll(10, TimeUnit.SECONDS);
}
@POST
@Path("/clear-admin-actions")
public Response clearAdminActions() {
adminLogoutActions.clear();
adminPushNotBeforeActions.clear();
return Response.noContent().build();
}
@POST
@Produces(MediaType.TEXT_HTML)
@Path("/{action}")
public String post(@PathParam("action") String action) {
String title = "APP_REQUEST";
if (action.equals("auth")) {
title = "AUTH_RESPONSE";
} else if (action.equals("logout")) {
title = "LOGOUT_REQUEST";
}
StringBuilder sb = new StringBuilder();
sb.append("<html><head><title>" + title + "</title></head><body>");
sb.append("<b>Form parameters: </b><br>");
HttpRequest request = ResteasyProviderFactory.getContextData(HttpRequest.class);
MultivaluedMap<String, String> formParams = request.getDecodedFormParameters();
for (String paramName : formParams.keySet()) {
sb.append(paramName).append(": ").append("<span id=\"").append(paramName).append("\">").append(formParams.getFirst(paramName)).append("</span><br>");
}
sb.append("<br>");
UriBuilder base = UriBuilder.fromUri("http://localhost:8180/auth");
sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>");
sb.append("</body></html>");
return sb.toString();
}
@GET
@Produces(MediaType.TEXT_HTML)
@Path("/{action}")
public String get(@PathParam("action") String action) {
//String requestUri = session.getContext().getUri().getRequestUri().toString();
String title = "APP_REQUEST";
if (action.equals("auth")) {
title = "AUTH_RESPONSE";
} else if (action.equals("logout")) {
title = "LOGOUT_REQUEST";
}
StringBuilder sb = new StringBuilder();
sb.append("<html><head><title>" + title + "</title></head><body>");
UriBuilder base = UriBuilder.fromUri("http://localhost:8180/auth");
sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>");
sb.append("</body></html>");
return sb.toString();
}
@GET
@NoCache
@Produces(MediaType.TEXT_HTML)
@Path("/get-account-profile")
public String getAccountProfile(@QueryParam("token") String token, @QueryParam("account-uri") String accountUri) {
StringBuilder sb = new StringBuilder();
sb.append("function getProfile() {\n");
sb.append(" var req = new XMLHttpRequest();\n");
sb.append(" req.open('GET', '" + accountUri + "', false);\n");
if (token != null) {
sb.append(" req.setRequestHeader('Authorization', 'Bearer " + token + "');\n");
}
sb.append(" req.setRequestHeader('Accept', 'application/json');\n");
sb.append(" req.send(null);\n");
sb.append(" document.getElementById('profileOutput').innerHTML=\"<span id='innerOutput'>\" + req.status + '///' + req.responseText; + \"</span>\"\n");
sb.append("}");
String jsScript = sb.toString();
sb = new StringBuilder();
sb.append("<html><head><title>Account Profile JS Test</title><script>\n")
.append(jsScript)
.append( "</script></head>\n")
.append("<body onload='getProfile()'><div id='profileOutput'></div></body>")
.append("</html>");
return sb.toString();
}
@Path("/oidc-client-endpoints")
public TestingOIDCEndpointsApplicationResource getTestingOIDCClientEndpoints() {
return new TestingOIDCEndpointsApplicationResource(oidcClientData);
}
@Override
public Object getResource() {
return this;
}
@Override
public void close() {
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.rsgroup;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.CacheEvictionStats;
import org.apache.hadoop.hbase.ClusterMetrics;
import org.apache.hadoop.hbase.ClusterMetrics.Option;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.NamespaceNotFoundException;
import org.apache.hadoop.hbase.RegionMetrics;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.BalanceRequest;
import org.apache.hadoop.hbase.client.BalanceResponse;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.CompactType;
import org.apache.hadoop.hbase.client.CompactionState;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.LogEntry;
import org.apache.hadoop.hbase.client.NormalizeTableFilterParams;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.ServerType;
import org.apache.hadoop.hbase.client.SnapshotDescription;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.replication.TableCFs;
import org.apache.hadoop.hbase.client.security.SecurityCapability;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
import org.apache.hadoop.hbase.net.Address;
import org.apache.hadoop.hbase.quotas.QuotaFilter;
import org.apache.hadoop.hbase.quotas.QuotaSettings;
import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshotView;
import org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
import org.apache.hadoop.hbase.replication.SyncReplicationState;
import org.apache.hadoop.hbase.security.access.GetUserPermissionsRequest;
import org.apache.hadoop.hbase.security.access.Permission;
import org.apache.hadoop.hbase.security.access.UserPermission;
import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException;
import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.zookeeper.KeeperException;
import org.apache.hbase.thirdparty.com.google.common.collect.Maps;
import org.apache.hbase.thirdparty.com.google.common.collect.Sets;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupProtos;
@InterfaceAudience.Private
public class VerifyingRSGroupAdmin implements Admin, Closeable {
private final Connection conn;
private final Admin admin;
private final ZKWatcher zkw;
public VerifyingRSGroupAdmin(Configuration conf) throws IOException {
conn = ConnectionFactory.createConnection(conf);
admin = conn.getAdmin();
zkw = new ZKWatcher(conf, this.getClass().getSimpleName(), null);
}
public int getOperationTimeout() {
return admin.getOperationTimeout();
}
public int getSyncWaitTimeout() {
return admin.getSyncWaitTimeout();
}
public void abort(String why, Throwable e) {
admin.abort(why, e);
}
public boolean isAborted() {
return admin.isAborted();
}
public Connection getConnection() {
return admin.getConnection();
}
public boolean tableExists(TableName tableName) throws IOException {
return admin.tableExists(tableName);
}
public List<TableDescriptor> listTableDescriptors() throws IOException {
return admin.listTableDescriptors();
}
public List<TableDescriptor> listTableDescriptors(boolean includeSysTables) throws IOException {
return admin.listTableDescriptors(includeSysTables);
}
public List<TableDescriptor> listTableDescriptors(Pattern pattern, boolean includeSysTables)
throws IOException {
return admin.listTableDescriptors(pattern, includeSysTables);
}
public TableName[] listTableNames() throws IOException {
return admin.listTableNames();
}
public TableName[] listTableNames(Pattern pattern, boolean includeSysTables) throws IOException {
return admin.listTableNames(pattern, includeSysTables);
}
public TableDescriptor getDescriptor(TableName tableName)
throws TableNotFoundException, IOException {
return admin.getDescriptor(tableName);
}
public void createTable(TableDescriptor desc, byte[] startKey, byte[] endKey, int numRegions)
throws IOException {
admin.createTable(desc, startKey, endKey, numRegions);
}
public Future<Void> createTableAsync(TableDescriptor desc) throws IOException {
return admin.createTableAsync(desc);
}
public Future<Void> createTableAsync(TableDescriptor desc, byte[][] splitKeys)
throws IOException {
return admin.createTableAsync(desc, splitKeys);
}
public Future<Void> deleteTableAsync(TableName tableName) throws IOException {
return admin.deleteTableAsync(tableName);
}
public Future<Void> truncateTableAsync(TableName tableName, boolean preserveSplits)
throws IOException {
return admin.truncateTableAsync(tableName, preserveSplits);
}
public Future<Void> enableTableAsync(TableName tableName) throws IOException {
return admin.enableTableAsync(tableName);
}
public Future<Void> disableTableAsync(TableName tableName) throws IOException {
return admin.disableTableAsync(tableName);
}
public boolean isTableEnabled(TableName tableName) throws IOException {
return admin.isTableEnabled(tableName);
}
public boolean isTableDisabled(TableName tableName) throws IOException {
return admin.isTableDisabled(tableName);
}
public boolean isTableAvailable(TableName tableName) throws IOException {
return admin.isTableAvailable(tableName);
}
public Future<Void> addColumnFamilyAsync(TableName tableName, ColumnFamilyDescriptor columnFamily)
throws IOException {
return admin.addColumnFamilyAsync(tableName, columnFamily);
}
public Future<Void> deleteColumnFamilyAsync(TableName tableName, byte[] columnFamily)
throws IOException {
return admin.deleteColumnFamilyAsync(tableName, columnFamily);
}
public Future<Void> modifyColumnFamilyAsync(TableName tableName,
ColumnFamilyDescriptor columnFamily) throws IOException {
return admin.modifyColumnFamilyAsync(tableName, columnFamily);
}
public List<RegionInfo> getRegions(ServerName serverName) throws IOException {
return admin.getRegions(serverName);
}
public void flush(TableName tableName) throws IOException {
admin.flush(tableName);
}
public void flush(TableName tableName, byte[] columnFamily) throws IOException {
admin.flush(tableName, columnFamily);
}
public void flushRegion(byte[] regionName) throws IOException {
admin.flushRegion(regionName);
}
public void flushRegion(byte[] regionName, byte[] columnFamily) throws IOException {
admin.flushRegion(regionName, columnFamily);
}
public void flushRegionServer(ServerName serverName) throws IOException {
admin.flushRegionServer(serverName);
}
public void compact(TableName tableName) throws IOException {
admin.compact(tableName);
}
public void compactRegion(byte[] regionName) throws IOException {
admin.compactRegion(regionName);
}
public void compact(TableName tableName, byte[] columnFamily) throws IOException {
admin.compact(tableName, columnFamily);
}
public void compactRegion(byte[] regionName, byte[] columnFamily) throws IOException {
admin.compactRegion(regionName, columnFamily);
}
public void compact(TableName tableName, CompactType compactType)
throws IOException, InterruptedException {
admin.compact(tableName, compactType);
}
public void compact(TableName tableName, byte[] columnFamily, CompactType compactType)
throws IOException, InterruptedException {
admin.compact(tableName, columnFamily, compactType);
}
public void majorCompact(TableName tableName) throws IOException {
admin.majorCompact(tableName);
}
public void majorCompactRegion(byte[] regionName) throws IOException {
admin.majorCompactRegion(regionName);
}
public void majorCompact(TableName tableName, byte[] columnFamily) throws IOException {
admin.majorCompact(tableName, columnFamily);
}
public void majorCompactRegion(byte[] regionName, byte[] columnFamily) throws IOException {
admin.majorCompactRegion(regionName, columnFamily);
}
public void majorCompact(TableName tableName, CompactType compactType)
throws IOException, InterruptedException {
admin.majorCompact(tableName, compactType);
}
public void majorCompact(TableName tableName, byte[] columnFamily, CompactType compactType)
throws IOException, InterruptedException {
admin.majorCompact(tableName, columnFamily, compactType);
}
public Map<ServerName, Boolean> compactionSwitch(boolean switchState,
List<String> serverNamesList) throws IOException {
return admin.compactionSwitch(switchState, serverNamesList);
}
public void compactRegionServer(ServerName serverName) throws IOException {
admin.compactRegionServer(serverName);
}
public void majorCompactRegionServer(ServerName serverName) throws IOException {
admin.majorCompactRegionServer(serverName);
}
public void move(byte[] encodedRegionName) throws IOException {
admin.move(encodedRegionName);
}
public void move(byte[] encodedRegionName, ServerName destServerName) throws IOException {
admin.move(encodedRegionName, destServerName);
}
public void assign(byte[] regionName) throws IOException {
admin.assign(regionName);
}
public void unassign(byte[] regionName) throws IOException {
admin.unassign(regionName);
}
public void offline(byte[] regionName) throws IOException {
admin.offline(regionName);
}
public boolean balancerSwitch(boolean onOrOff, boolean synchronous) throws IOException {
return admin.balancerSwitch(onOrOff, synchronous);
}
public BalanceResponse balance(BalanceRequest request) throws IOException {
return admin.balance(request);
}
public boolean isBalancerEnabled() throws IOException {
return admin.isBalancerEnabled();
}
public CacheEvictionStats clearBlockCache(TableName tableName) throws IOException {
return admin.clearBlockCache(tableName);
}
@Override
public boolean normalize(NormalizeTableFilterParams ntfp) throws IOException {
return admin.normalize(ntfp);
}
public boolean isNormalizerEnabled() throws IOException {
return admin.isNormalizerEnabled();
}
public boolean normalizerSwitch(boolean on) throws IOException {
return admin.normalizerSwitch(on);
}
public boolean catalogJanitorSwitch(boolean onOrOff) throws IOException {
return admin.catalogJanitorSwitch(onOrOff);
}
public int runCatalogJanitor() throws IOException {
return admin.runCatalogJanitor();
}
public boolean isCatalogJanitorEnabled() throws IOException {
return admin.isCatalogJanitorEnabled();
}
public boolean cleanerChoreSwitch(boolean onOrOff) throws IOException {
return admin.cleanerChoreSwitch(onOrOff);
}
public boolean runCleanerChore() throws IOException {
return admin.runCleanerChore();
}
public boolean isCleanerChoreEnabled() throws IOException {
return admin.isCleanerChoreEnabled();
}
public Future<Void> mergeRegionsAsync(byte[][] nameofRegionsToMerge, boolean forcible)
throws IOException {
return admin.mergeRegionsAsync(nameofRegionsToMerge, forcible);
}
public void split(TableName tableName) throws IOException {
admin.split(tableName);
}
public void split(TableName tableName, byte[] splitPoint) throws IOException {
admin.split(tableName, splitPoint);
}
public Future<Void> splitRegionAsync(byte[] regionName) throws IOException {
return admin.splitRegionAsync(regionName);
}
public Future<Void> splitRegionAsync(byte[] regionName, byte[] splitPoint) throws IOException {
return admin.splitRegionAsync(regionName, splitPoint);
}
public Future<Void> modifyTableAsync(TableDescriptor td) throws IOException {
return admin.modifyTableAsync(td);
}
public void shutdown() throws IOException {
admin.shutdown();
}
public void stopMaster() throws IOException {
admin.stopMaster();
}
public boolean isMasterInMaintenanceMode() throws IOException {
return admin.isMasterInMaintenanceMode();
}
public void stopRegionServer(String hostnamePort) throws IOException {
admin.stopRegionServer(hostnamePort);
}
public ClusterMetrics getClusterMetrics(EnumSet<Option> options) throws IOException {
return admin.getClusterMetrics(options);
}
public List<RegionMetrics> getRegionMetrics(ServerName serverName) throws IOException {
return admin.getRegionMetrics(serverName);
}
public List<RegionMetrics> getRegionMetrics(ServerName serverName, TableName tableName)
throws IOException {
return admin.getRegionMetrics(serverName, tableName);
}
public Configuration getConfiguration() {
return admin.getConfiguration();
}
public Future<Void> createNamespaceAsync(NamespaceDescriptor descriptor) throws IOException {
return admin.createNamespaceAsync(descriptor);
}
public Future<Void> modifyNamespaceAsync(NamespaceDescriptor descriptor) throws IOException {
return admin.modifyNamespaceAsync(descriptor);
}
public Future<Void> deleteNamespaceAsync(String name) throws IOException {
return admin.deleteNamespaceAsync(name);
}
public NamespaceDescriptor getNamespaceDescriptor(String name)
throws NamespaceNotFoundException, IOException {
return admin.getNamespaceDescriptor(name);
}
public String[] listNamespaces() throws IOException {
return admin.listNamespaces();
}
public NamespaceDescriptor[] listNamespaceDescriptors() throws IOException {
return admin.listNamespaceDescriptors();
}
public List<TableDescriptor> listTableDescriptorsByNamespace(byte[] name) throws IOException {
return admin.listTableDescriptorsByNamespace(name);
}
public TableName[] listTableNamesByNamespace(String name) throws IOException {
return admin.listTableNamesByNamespace(name);
}
public List<RegionInfo> getRegions(TableName tableName) throws IOException {
return admin.getRegions(tableName);
}
public void close() {
admin.close();
}
public List<TableDescriptor> listTableDescriptors(List<TableName> tableNames) throws IOException {
return admin.listTableDescriptors(tableNames);
}
public Future<Boolean> abortProcedureAsync(long procId, boolean mayInterruptIfRunning)
throws IOException {
return admin.abortProcedureAsync(procId, mayInterruptIfRunning);
}
public String getProcedures() throws IOException {
return admin.getProcedures();
}
public String getLocks() throws IOException {
return admin.getLocks();
}
public void rollWALWriter(ServerName serverName) throws IOException, FailedLogCloseException {
admin.rollWALWriter(serverName);
}
public CompactionState getCompactionState(TableName tableName) throws IOException {
return admin.getCompactionState(tableName);
}
public CompactionState getCompactionState(TableName tableName, CompactType compactType)
throws IOException {
return admin.getCompactionState(tableName, compactType);
}
public CompactionState getCompactionStateForRegion(byte[] regionName) throws IOException {
return admin.getCompactionStateForRegion(regionName);
}
public long getLastMajorCompactionTimestamp(TableName tableName) throws IOException {
return admin.getLastMajorCompactionTimestamp(tableName);
}
public long getLastMajorCompactionTimestampForRegion(byte[] regionName) throws IOException {
return admin.getLastMajorCompactionTimestampForRegion(regionName);
}
public void snapshot(SnapshotDescription snapshot)
throws IOException, SnapshotCreationException, IllegalArgumentException {
admin.snapshot(snapshot);
}
public Future<Void> snapshotAsync(SnapshotDescription snapshot)
throws IOException, SnapshotCreationException {
return admin.snapshotAsync(snapshot);
}
public boolean isSnapshotFinished(SnapshotDescription snapshot)
throws IOException, HBaseSnapshotException, UnknownSnapshotException {
return admin.isSnapshotFinished(snapshot);
}
public void restoreSnapshot(String snapshotName) throws IOException, RestoreSnapshotException {
admin.restoreSnapshot(snapshotName);
}
public void restoreSnapshot(String snapshotName, boolean takeFailSafeSnapshot, boolean restoreAcl)
throws IOException, RestoreSnapshotException {
admin.restoreSnapshot(snapshotName, takeFailSafeSnapshot, restoreAcl);
}
public Future<Void> cloneSnapshotAsync(String snapshotName, TableName tableName,
boolean restoreAcl, String customSFT)
throws IOException, TableExistsException, RestoreSnapshotException {
return admin.cloneSnapshotAsync(snapshotName, tableName, restoreAcl, customSFT);
}
public void execProcedure(String signature, String instance, Map<String, String> props)
throws IOException {
admin.execProcedure(signature, instance, props);
}
public byte[] execProcedureWithReturn(String signature, String instance,
Map<String, String> props) throws IOException {
return admin.execProcedureWithReturn(signature, instance, props);
}
public boolean isProcedureFinished(String signature, String instance, Map<String, String> props)
throws IOException {
return admin.isProcedureFinished(signature, instance, props);
}
public List<SnapshotDescription> listSnapshots() throws IOException {
return admin.listSnapshots();
}
public List<SnapshotDescription> listSnapshots(Pattern pattern) throws IOException {
return admin.listSnapshots(pattern);
}
public List<SnapshotDescription> listTableSnapshots(Pattern tableNamePattern,
Pattern snapshotNamePattern) throws IOException {
return admin.listTableSnapshots(tableNamePattern, snapshotNamePattern);
}
public void deleteSnapshot(String snapshotName) throws IOException {
admin.deleteSnapshot(snapshotName);
}
public void deleteSnapshots(Pattern pattern) throws IOException {
admin.deleteSnapshots(pattern);
}
public void deleteTableSnapshots(Pattern tableNamePattern, Pattern snapshotNamePattern)
throws IOException {
admin.deleteTableSnapshots(tableNamePattern, snapshotNamePattern);
}
public void setQuota(QuotaSettings quota) throws IOException {
admin.setQuota(quota);
}
public List<QuotaSettings> getQuota(QuotaFilter filter) throws IOException {
return admin.getQuota(filter);
}
public CoprocessorRpcChannel coprocessorService() {
return admin.coprocessorService();
}
public CoprocessorRpcChannel coprocessorService(ServerName serverName) {
return admin.coprocessorService(serverName);
}
public void updateConfiguration(ServerName server) throws IOException {
admin.updateConfiguration(server);
}
public void updateConfiguration() throws IOException {
admin.updateConfiguration();
}
public void updateConfiguration(String groupName) throws IOException {
admin.updateConfiguration(groupName);
}
public List<SecurityCapability> getSecurityCapabilities() throws IOException {
return admin.getSecurityCapabilities();
}
public boolean splitSwitch(boolean enabled, boolean synchronous) throws IOException {
return admin.splitSwitch(enabled, synchronous);
}
public boolean mergeSwitch(boolean enabled, boolean synchronous) throws IOException {
return admin.mergeSwitch(enabled, synchronous);
}
public boolean isSplitEnabled() throws IOException {
return admin.isSplitEnabled();
}
public boolean isMergeEnabled() throws IOException {
return admin.isMergeEnabled();
}
public Future<Void> addReplicationPeerAsync(String peerId, ReplicationPeerConfig peerConfig,
boolean enabled) throws IOException {
return admin.addReplicationPeerAsync(peerId, peerConfig, enabled);
}
public Future<Void> removeReplicationPeerAsync(String peerId) throws IOException {
return admin.removeReplicationPeerAsync(peerId);
}
public Future<Void> enableReplicationPeerAsync(String peerId) throws IOException {
return admin.enableReplicationPeerAsync(peerId);
}
public Future<Void> disableReplicationPeerAsync(String peerId) throws IOException {
return admin.disableReplicationPeerAsync(peerId);
}
public ReplicationPeerConfig getReplicationPeerConfig(String peerId) throws IOException {
return admin.getReplicationPeerConfig(peerId);
}
public Future<Void> updateReplicationPeerConfigAsync(String peerId,
ReplicationPeerConfig peerConfig) throws IOException {
return admin.updateReplicationPeerConfigAsync(peerId, peerConfig);
}
public List<ReplicationPeerDescription> listReplicationPeers() throws IOException {
return admin.listReplicationPeers();
}
public List<ReplicationPeerDescription> listReplicationPeers(Pattern pattern) throws IOException {
return admin.listReplicationPeers(pattern);
}
public Future<Void> transitReplicationPeerSyncReplicationStateAsync(String peerId,
SyncReplicationState state) throws IOException {
return admin.transitReplicationPeerSyncReplicationStateAsync(peerId, state);
}
public void decommissionRegionServers(List<ServerName> servers, boolean offload)
throws IOException {
admin.decommissionRegionServers(servers, offload);
}
public List<ServerName> listDecommissionedRegionServers() throws IOException {
return admin.listDecommissionedRegionServers();
}
public void recommissionRegionServer(ServerName server, List<byte[]> encodedRegionNames)
throws IOException {
admin.recommissionRegionServer(server, encodedRegionNames);
}
public List<TableCFs> listReplicatedTableCFs() throws IOException {
return admin.listReplicatedTableCFs();
}
public void enableTableReplication(TableName tableName) throws IOException {
admin.enableTableReplication(tableName);
}
public void disableTableReplication(TableName tableName) throws IOException {
admin.disableTableReplication(tableName);
}
public void clearCompactionQueues(ServerName serverName, Set<String> queues)
throws IOException, InterruptedException {
admin.clearCompactionQueues(serverName, queues);
}
public List<ServerName> clearDeadServers(List<ServerName> servers) throws IOException {
return admin.clearDeadServers(servers);
}
public void cloneTableSchema(TableName tableName, TableName newTableName, boolean preserveSplits)
throws IOException {
admin.cloneTableSchema(tableName, newTableName, preserveSplits);
}
public boolean switchRpcThrottle(boolean enable) throws IOException {
return admin.switchRpcThrottle(enable);
}
public boolean isRpcThrottleEnabled() throws IOException {
return admin.isRpcThrottleEnabled();
}
public boolean exceedThrottleQuotaSwitch(boolean enable) throws IOException {
return admin.exceedThrottleQuotaSwitch(enable);
}
public Map<TableName, Long> getSpaceQuotaTableSizes() throws IOException {
return admin.getSpaceQuotaTableSizes();
}
public Map<TableName, ? extends SpaceQuotaSnapshotView>
getRegionServerSpaceQuotaSnapshots(ServerName serverName) throws IOException {
return admin.getRegionServerSpaceQuotaSnapshots(serverName);
}
public SpaceQuotaSnapshotView getCurrentSpaceQuotaSnapshot(String namespace) throws IOException {
return admin.getCurrentSpaceQuotaSnapshot(namespace);
}
public SpaceQuotaSnapshotView getCurrentSpaceQuotaSnapshot(TableName tableName)
throws IOException {
return admin.getCurrentSpaceQuotaSnapshot(tableName);
}
public void grant(UserPermission userPermission, boolean mergeExistingPermissions)
throws IOException {
admin.grant(userPermission, mergeExistingPermissions);
}
public void revoke(UserPermission userPermission) throws IOException {
admin.revoke(userPermission);
}
public List<UserPermission>
getUserPermissions(GetUserPermissionsRequest getUserPermissionsRequest) throws IOException {
return admin.getUserPermissions(getUserPermissionsRequest);
}
public List<Boolean> hasUserPermissions(String userName, List<Permission> permissions)
throws IOException {
return admin.hasUserPermissions(userName, permissions);
}
public boolean snapshotCleanupSwitch(boolean on, boolean synchronous) throws IOException {
return admin.snapshotCleanupSwitch(on, synchronous);
}
public boolean isSnapshotCleanupEnabled() throws IOException {
return admin.isSnapshotCleanupEnabled();
}
public void addRSGroup(String groupName) throws IOException {
admin.addRSGroup(groupName);
verify();
}
public RSGroupInfo getRSGroup(String groupName) throws IOException {
return admin.getRSGroup(groupName);
}
public RSGroupInfo getRSGroup(Address hostPort) throws IOException {
return admin.getRSGroup(hostPort);
}
public RSGroupInfo getRSGroup(TableName tableName) throws IOException {
return admin.getRSGroup(tableName);
}
public List<RSGroupInfo> listRSGroups() throws IOException {
return admin.listRSGroups();
}
@Override
public List<TableName> listTablesInRSGroup(String groupName) throws IOException {
return admin.listTablesInRSGroup(groupName);
}
@Override
public Pair<List<String>, List<TableName>>
getConfiguredNamespacesAndTablesInRSGroup(String groupName) throws IOException {
return admin.getConfiguredNamespacesAndTablesInRSGroup(groupName);
}
public void removeRSGroup(String groupName) throws IOException {
admin.removeRSGroup(groupName);
verify();
}
public void removeServersFromRSGroup(Set<Address> servers) throws IOException {
admin.removeServersFromRSGroup(servers);
verify();
}
public void moveServersToRSGroup(Set<Address> servers, String targetGroup) throws IOException {
admin.moveServersToRSGroup(servers, targetGroup);
verify();
}
public void setRSGroup(Set<TableName> tables, String groupName) throws IOException {
admin.setRSGroup(tables, groupName);
verify();
}
public BalanceResponse balanceRSGroup(String groupName, BalanceRequest request) throws IOException {
return admin.balanceRSGroup(groupName, request);
}
@Override
public void renameRSGroup(String oldName, String newName) throws IOException {
admin.renameRSGroup(oldName, newName);
verify();
}
@Override
public void updateRSGroupConfig(String groupName, Map<String, String> configuration)
throws IOException {
admin.updateRSGroupConfig(groupName, configuration);
verify();
}
@Override
public List<LogEntry> getLogEntries(Set<ServerName> serverNames, String logType,
ServerType serverType, int limit, Map<String, Object> filterParams) throws IOException {
return admin.getLogEntries(serverNames, logType, serverType, limit, filterParams);
}
private void verify() throws IOException {
Map<String, RSGroupInfo> groupMap = Maps.newHashMap();
Set<RSGroupInfo> zList = Sets.newHashSet();
List<TableDescriptor> tds = new ArrayList<>();
try (Admin admin = conn.getAdmin()) {
tds.addAll(admin.listTableDescriptors());
tds.addAll(admin.listTableDescriptorsByNamespace(NamespaceDescriptor.SYSTEM_NAMESPACE_NAME));
}
SortedSet<Address> lives = Sets.newTreeSet();
for (ServerName sn : conn.getAdmin().getClusterMetrics().getLiveServerMetrics().keySet()) {
lives.add(sn.getAddress());
}
for (ServerName sn : conn.getAdmin().listDecommissionedRegionServers()) {
lives.remove(sn.getAddress());
}
try (Table table = conn.getTable(RSGroupInfoManagerImpl.RSGROUP_TABLE_NAME);
ResultScanner scanner = table.getScanner(new Scan())) {
for (;;) {
Result result = scanner.next();
if (result == null) {
break;
}
RSGroupProtos.RSGroupInfo proto = RSGroupProtos.RSGroupInfo.parseFrom(result.getValue(
RSGroupInfoManagerImpl.META_FAMILY_BYTES, RSGroupInfoManagerImpl.META_QUALIFIER_BYTES));
RSGroupInfo rsGroupInfo = ProtobufUtil.toGroupInfo(proto);
groupMap.put(proto.getName(), RSGroupUtil.fillTables(rsGroupInfo, tds));
for (Address address : rsGroupInfo.getServers()) {
lives.remove(address);
}
}
}
SortedSet<TableName> tables = Sets.newTreeSet();
for (TableDescriptor td : conn.getAdmin().listTableDescriptors(Pattern.compile(".*"), true)) {
String groupName = td.getRegionServerGroup().orElse(RSGroupInfo.DEFAULT_GROUP);
if (groupName.equals(RSGroupInfo.DEFAULT_GROUP)) {
tables.add(td.getTableName());
}
}
groupMap.put(RSGroupInfo.DEFAULT_GROUP,
new RSGroupInfo(RSGroupInfo.DEFAULT_GROUP, lives, tables));
assertEquals(Sets.newHashSet(groupMap.values()), Sets.newHashSet(admin.listRSGroups()));
try {
String groupBasePath = ZNodePaths.joinZNode(zkw.getZNodePaths().baseZNode, "rsgroup");
for (String znode : ZKUtil.listChildrenNoWatch(zkw, groupBasePath)) {
byte[] data = ZKUtil.getData(zkw, ZNodePaths.joinZNode(groupBasePath, znode));
if (data.length > 0) {
ProtobufUtil.expectPBMagicPrefix(data);
ByteArrayInputStream bis =
new ByteArrayInputStream(data, ProtobufUtil.lengthOfPBMagic(), data.length);
RSGroupInfo rsGroupInfo =
ProtobufUtil.toGroupInfo(RSGroupProtos.RSGroupInfo.parseFrom(bis));
zList.add(RSGroupUtil.fillTables(rsGroupInfo, tds));
}
}
groupMap.remove(RSGroupInfo.DEFAULT_GROUP);
assertEquals(zList.size(), groupMap.size());
for (RSGroupInfo rsGroupInfo : zList) {
assertTrue(groupMap.get(rsGroupInfo.getName()).equals(rsGroupInfo));
}
} catch (KeeperException e) {
throw new IOException("ZK verification failed", e);
} catch (DeserializationException e) {
throw new IOException("ZK verification failed", e);
} catch (InterruptedException e) {
throw new IOException("ZK verification failed", e);
}
}
@Override
public List<Boolean> clearSlowLogResponses(Set<ServerName> serverNames) throws IOException {
return admin.clearSlowLogResponses(serverNames);
}
@Override
public Future<Void> modifyColumnFamilyStoreFileTrackerAsync(TableName tableName, byte[] family,
String dstSFT) throws IOException {
return admin.modifyColumnFamilyStoreFileTrackerAsync(tableName, family, dstSFT);
}
@Override
public Future<Void> modifyTableStoreFileTrackerAsync(TableName tableName, String dstSFT)
throws IOException {
return admin.modifyTableStoreFileTrackerAsync(tableName, dstSFT);
}
}
| |
package com.quakearts.test;
import static org.junit.Assert.*;
import java.io.StringReader;
import static org.hamcrest.core.Is.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.quakearts.webapp.security.jwt.internal.json.Json;
import com.quakearts.webapp.security.jwt.internal.json.JsonObject;
import com.quakearts.webapp.security.jwt.internal.json.JsonValue;
import com.quakearts.webapp.security.jwt.internal.json.ParseException;
import com.quakearts.webapp.security.jwt.internal.json.PrettyPrint;
import com.quakearts.webapp.security.jwt.internal.json.JsonObject.Member;
public class TestJsonInternal {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@SuppressWarnings("unlikely-arg-type")
@Test
public void testValueInt() {
assertThat(Json.value(1).asInt(), is(1));
assertThat(Json.value(1).isNumber(), is(true));
assertThat(Json.value(1).isArray(), is(false));
assertThat(Json.value(1).isBoolean(), is(false));
assertThat(Json.value(1).isFalse(), is(false));
assertThat(Json.value(1).isNull(), is(false));
assertThat(Json.value(1).isObject(), is(false));
assertThat(Json.value(1).isString(), is(false));
assertThat(Json.value(1).isTrue(), is(false));
JsonValue value = Json.value(1);
assertThat(value, is(value));
assertThat(value, is(Json.value(1)));
assertThat(value.hashCode(), is(Json.value(1).hashCode()));
assertThat(Json.value(1).equals(null), is(false));
assertThat(Json.value(1).equals("Test"), is(false));
}
@Test
public void testValueLong() {
assertThat(Json.value(1l).asLong(), is(1l));
assertThat(Json.value(1l).isNumber(), is(true));
}
@Test
public void testValueFloat() {
assertThat(Json.value(1f).asFloat(), is(1f));
assertThat(Json.value(1f).isNumber(), is(true));
}
@Test
public void testValueDouble() {
assertThat(Json.value(1d).asDouble(), is(1d));
assertThat(Json.value(1d).isNumber(), is(true));
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void testValueString() {
assertThat(Json.value("1").asString(), is("1"));
assertThat(Json.value("1").isString(), is(true));
JsonValue jsonValue = Json.value("1");
assertThat(jsonValue, is(jsonValue));
assertThat(jsonValue, is(Json.value("1")));
assertThat(jsonValue.hashCode(), is(Json.value("1").hashCode()));
assertThat(jsonValue.equals(null), is(false));
assertThat(jsonValue.equals("Test"), is(false));
assertThat(Json.value("1").isArray(), is(false));
assertThat(Json.value("1").isBoolean(), is(false));
assertThat(Json.value("1").isFalse(), is(false));
assertThat(Json.value("1").isNull(), is(false));
assertThat(Json.value("1").isObject(), is(false));
assertThat(Json.value("1").isNumber(), is(false));
assertThat(Json.value("1").isTrue(), is(false));
}
@Test
public void testValueBoolean() {
assertThat(Json.value(true).asBoolean(), is(true));
assertThat(Json.value(true).isArray(), is(false));
assertThat(Json.value(false).isFalse(), is(true));
assertThat(Json.value(true).isNull(), is(false));
assertThat(Json.value(true).isObject(), is(false));
assertThat(Json.value(true).isNumber(), is(false));
assertThat(Json.value(true).isString(), is(false));
assertThat(Json.value(true).isTrue(), is(true));
}
@Test
public void testArray() {
assertThat(Json.array("1").get(0).asString(), is("1"));
assertThat(Json.array("1").set(0,Json.value("2")).get(0).asString(), is("2"));
assertThat(Json.array("1","2").remove(0).get(0).asString(), is("2"));
assertThat(Json.array("1","2").equals(Json.array("1","2")), is(true));
JsonValue value = Json.array("1","2");
assertThat(value.equals(value), is(true));
assertThat(value.equals(null), is(false));
assertThat(value.equals(Json.value("[\"1\",\"2\"]")), is(false));
assertThat(Json.array("1","2").hashCode() == Json.array("1","2").hashCode(), is(true));
assertThat(Json.array("1","2").isArray(), is(true));
assertThat(Json.array("1","2").iterator().next().asString(), is("1"));
assertThat(Json.array("1","2").iterator().hasNext(), is(true));
assertThat(Json.array("1","2").size(), is(2));
assertThat(Json.array("1","2").isEmpty(), is(false));
assertThat(Json.array("1","2").toString(), is("[\"1\",\"2\"]"));
expectedException.expect(UnsupportedOperationException.class);
Json.array("1","2").values().add(Json.value("3"));
}
@Test
public void testArrayAdd() {
expectedException.expect(NullPointerException.class);
JsonValue value = null;
Json.array("1","2").add(value);
}
@Test
public void testArraySet() {
expectedException.expect(NullPointerException.class);
JsonValue value = null;
Json.array("1","2").set(1, value);
}
@Test
public void testArrayIteratorRemove() {
expectedException.expect(UnsupportedOperationException.class);
Json.array("1","2").iterator().remove();
}
@Test
public void testArrayIntArray() {
assertThat(Json.array(1,2,3).get(2).asInt(), is(3));
assertThat(Json.array(1,2,3).set(0,5).get(0).asInt(), is(5));
}
@Test
public void testArrayLongArray() {
assertThat(Json.array(1l,2l,3l).get(1).asLong(), is(2l));
assertThat(Json.array(1l,2l,3l).set(0,5l).get(0).asLong(), is(5l));
}
@Test
public void testArrayFloatArray() {
assertThat(Json.array(1f,2f,3f).get(0).asFloat(), is(1f));
assertThat(Json.array(1f,2f,3f).set(0,5f).get(0).asFloat(), is(5f));
}
@Test
public void testArrayDoubleArray() {
assertThat(Json.array(1d,2d,3d).get(0).asDouble(), is(1d));
assertThat(Json.array(1d,2d,3d).set(0,5d).get(0).asDouble(), is(5d));
}
@Test
public void testArrayBooleanArray() {
assertThat(Json.array(true,false,false).get(0).asBoolean(), is(true));
assertThat(Json.array(true,false,false).set(2,true).get(2).asBoolean(), is(true));
}
@Test
public void testArrayStringArray() {
assertThat(Json.array("1","2","3").get(2).asString(), is("3"));
assertThat(Json.array("1","2","3").set(2,"5").get(2).asString(), is("5"));
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void testObject() {
assertThat(Json.object().add("test", "value").toString(), is("{\"test\":\"value\"}"));
assertThat(Json.object().add("test", "value").names().iterator().next(), is("test"));
JsonObject object = Json.object();
object.add("string", "string");
assertThat(object, is(object));
assertThat(object, is(Json.object().add("string", "string")));
assertThat(object.hashCode(), is(Json.object().add("string", "string").hashCode()));
assertThat(object.equals(null), is(false));
assertThat(object.equals(Json.value(false)), is(false));
Member member = Json.object().add("test", "value").iterator().next();
Member member2 = Json.object().add("test", "value").iterator().next();
assertThat(member, is(member));
assertThat(member, is(member2));
assertThat(member.hashCode(), is(member2.hashCode()));
assertThat(member.equals(null), is(false));
assertThat(member.equals("String"), is(false));
assertThat(object.get("string").asString(), is("string"));
object.set("string", "another-string");
assertThat(object.getString("string",""), is("another-string"));
assertThat(object.getString("void", ""), is(""));
object.remove("string");
assertThat(object.size(), is(0));
assertThat(object.isEmpty(), is(true));
object.set("value", 1);
assertThat(object.getInt("value", 0), is(1));
assertThat(object.getInt("void", 0), is(0));
object.set("value", 1l);
assertThat(object.getLong("value", 0), is(1l));
assertThat(object.getLong("void", 0), is(0l));
object.set("value", 1f);
assertThat(object.getFloat("value", 0), is(1f));
assertThat(object.getFloat("void", 0), is(0f));
object.set("value", 1d);
assertThat(object.getDouble("value", 0), is(1d));
assertThat(object.getDouble("void", 0), is(0d));
object.set("value", true);
assertThat(object.getBoolean("value", false), is(true));
assertThat(object.getBoolean("void", false), is(false));
}
@Test
public void testObjectUnmodifiable() throws Exception {
expectedException.expect(UnsupportedOperationException.class);
JsonObject object = Json.object().add("test", "value");
JsonObject unmodifiableObject = JsonObject.unmodifiableObject(object);
unmodifiableObject.add("another", "value");
}
@Test
public void testObjectAddNullName() throws Exception {
expectedException.expect(NullPointerException.class);
Json.object().add(null, "value");
}
@Test
public void testObjectAddNullValue() throws Exception {
expectedException.expect(NullPointerException.class);
JsonValue jsonValue = null;
Json.object().add("test", jsonValue);
}
@Test
public void testUnmodifiableNullValue() throws Exception {
expectedException.expect(NullPointerException.class);
JsonObject jsonValue = null;
JsonObject.unmodifiableObject(jsonValue);
}
@Test
public void testObjectSetNullName() throws Exception {
expectedException.expect(NullPointerException.class);
Json.object().set(null, "value");
}
@Test
public void testObjectRemoveNullName() throws Exception {
expectedException.expect(NullPointerException.class);
Json.object().remove(null);
}
public void testObjectgetNullName() throws Exception {
expectedException.expect(NullPointerException.class);
Json.object().get(null);
}
@Test
public void testObjectSetNullValue() throws Exception {
expectedException.expect(NullPointerException.class);
JsonValue jsonValue = null;
Json.object().set("test", jsonValue);
}
@Test
public void testObjectIteratorRemove() throws Exception {
expectedException.expect(UnsupportedOperationException.class);
Json.object().add("test", "value").iterator().remove();
}
@Test
public void testParseString() {
JsonValue value = Json.parse("{\"string\":\"string\",\"number\":1.0,\"array\":[1,2,3,4,5],\"boolean\":true,\"null\":null}");
assertThat(value.isObject(), is(true));
JsonObject jsonObject = value.asObject();
assertThat(jsonObject.get("string").asString(), is("string"));
assertThat(jsonObject.get("number").asDouble(), is(1.0d));
assertThat(jsonObject.get("array").asArray().get(0).asInt(), is(1));
assertThat(jsonObject.get("boolean").asBoolean(), is(true));
assertThat(jsonObject.get("null").isNull(), is(true));
}
@Test
public void testParseReader() throws Exception {
JsonValue value = Json.parse(new StringReader("{\"string\":\"string\",\"number\":1.0,\"array\":[1,2,3,4,5],\"boolean\":true,\"null\":null}"));
assertThat(value.isObject(), is(true));
JsonObject jsonObject = value.asObject();
assertThat(jsonObject.get("string").asString(), is("string"));
assertThat(jsonObject.get("number").asDouble(), is(1.0d));
assertThat(jsonObject.get("array").asArray().get(0).asInt(), is(1));
assertThat(jsonObject.get("boolean").asBoolean(), is(true));
assertThat(jsonObject.get("null").isNull(), is(true));
}
@Test
public void testReadAndWrite() throws Exception {
JsonObject object = Json.object()
.add("boolean-true", Json.TRUE)
.add("boolean-false", Json.FALSE)
.add("java-boolean", true)
.add("null", Json.NULL)
.add("string", "string")
.add("double", 2d)
.add("float", 1f)
.add("int", 1)
.add("long", 3l)
.add("array", Json.array("a","b","c"));
JsonValue value = Json.parse(object.toString());
JsonObject object2 = value.asObject();
assertThat(object, is(object2));
assertThat(object.toString(PrettyPrint.indentWithTabs()), is("{\n" +
" \"boolean-true\": true,\n" +
" \"boolean-false\": false,\n" +
" \"java-boolean\": true,\n" +
" \"null\": null,\n" +
" \"string\": \"string\",\n" +
" \"double\": 2,\n" +
" \"float\": 1,\n" +
" \"int\": 1,\n" +
" \"long\": 3,\n" +
" \"array\": [\n" +
" \"a\",\n" +
" \"b\",\n" +
" \"c\"\n" +
" ]\n" +
"}"));
assertThat(object.toString(PrettyPrint.indentWithSpaces(3)), is("{\n" +
" \"boolean-true\": true,\n" +
" \"boolean-false\": false,\n" +
" \"java-boolean\": true,\n" +
" \"null\": null,\n" +
" \"string\": \"string\",\n" +
" \"double\": 2,\n" +
" \"float\": 1,\n" +
" \"int\": 1,\n" +
" \"long\": 3,\n" +
" \"array\": [\n" +
" \"a\",\n" +
" \"b\",\n" +
" \"c\"\n" +
" ]\n" +
"}"));
assertThat(object.toString(PrettyPrint.singleLine()),is("{\"boolean-true\": true, \"boolean-false\": false, \"java-boolean\": true, \"null\": null, \"string\": \"string\", \"double\": 2, \"float\": 1, \"int\": 1, \"long\": 3, \"array\": [\"a\", \"b\", \"c\"]}"));
}
@Test
public void testParseExpectation() throws Exception {
expectedException.expect(ParseException.class);
Json.parse("{test}");
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void testParseExpectationLocation() throws Exception {
try {
Json.parse("{test}");
fail("Not thrown");
} catch (ParseException e) {
assertThat(e.getLocation().getLine(), is(1));
assertThat(e.getLocation().getColumn(), is(2));
assertThat(e.getLocation().hashCode(), is(1));
assertThat(e.getLocation(), is(e.getLocation()));
try {
Json.parse("{test}");
fail("Not thrown");
} catch (ParseException e2) {
assertThat(e2.getLocation(), is(e.getLocation()));
}
assertThat(e.getLocation().equals("test"), is(false));
}
}
@Test
public void testWritingEscapeChars() throws Exception {
int CONTROL_CHARACTERS_END = 0x001f+1;
String str = new String(new char[] {(char) CONTROL_CHARACTERS_END});
assertThat(Json.value("\"\r\n\t\\\u2028\u2029\u0012"+str).toString().toCharArray(),
is(new char[]{'\"', '\\', '"', '\\', 'r', '\\', 'n', '\\', 't', '\\',
'\\', '\\', 'u', '2', '0', '2', '8', '\\', 'u', '2', '0', '2', '9',
'\\', 'u', '0', '0', '1', '2',(char) CONTROL_CHARACTERS_END , '"'}));
}
@Test
public void testJSonValues() throws Exception {
try {
Json.value(true).asArray();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(true).asString();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(true).asDouble();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(true).asFloat();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(true).asLong();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(true).asInt();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(1).asObject();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(1).asArray();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(1).asString();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(1).asBoolean();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.value(1).asObject();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asInt();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asString();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asDouble();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asFloat();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asLong();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asBoolean();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.array(1).asObject();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asInt();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asString();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asDouble();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asFloat();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asLong();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asBoolean();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
try {
Json.object().asArray();
fail("Did not throw exception");
} catch (UnsupportedOperationException e) {
}
}
}
| |
/* */ package edu.drexel.cis.dragon.ir.kngbase;
/* */
/* */ import edu.drexel.cis.dragon.ir.index.IRSignature;
/* */ import edu.drexel.cis.dragon.ir.index.IRSignatureIndexList;
/* */ import edu.drexel.cis.dragon.matrix.DoubleSuperSparseMatrix;
/* */ import edu.drexel.cis.dragon.matrix.IntSparseMatrix;
/* */ import edu.drexel.cis.dragon.nlp.Counter;
/* */ import edu.drexel.cis.dragon.nlp.Token;
/* */ import edu.drexel.cis.dragon.util.MathUtil;
/* */ import java.io.File;
/* */ import java.io.PrintStream;
/* */ import java.util.ArrayList;
/* */ import java.util.Date;
/* */ import java.util.HashMap;
/* */ import java.util.Iterator;
/* */ import java.util.Random;
/* */ import java.util.Set;
/* */
/* */ public class TopicSignatureModel
/* */ {
/* */ private IRSignatureIndexList srcIndexList;
/* */ private IRSignatureIndexList destIndexList;
/* */ private IntSparseMatrix srcSignatureDocMatrix;
/* */ private IntSparseMatrix destDocSignatureMatrix;
/* */ private IntSparseMatrix cooccurMatrix;
/* */ private boolean useDocFrequency;
/* */ private boolean useMeanTrim;
/* */ private boolean useEM;
/* */ private double probThreshold;
/* */ private double bkgCoeffi;
/* */ private int[] buf;
/* */ private int iterationNum;
/* */ private int totalDestSignatureNum;
/* */ private int DOC_THRESH;
/* */
/* */ public TopicSignatureModel(IRSignatureIndexList srcIndexList, IntSparseMatrix srcSignatureDocMatrix, IntSparseMatrix destDocSignatureMatrix)
/* */ {
/* 49 */ this.srcIndexList = srcIndexList;
/* 50 */ this.srcSignatureDocMatrix = srcSignatureDocMatrix;
/* 51 */ this.destDocSignatureMatrix = destDocSignatureMatrix;
/* 52 */ this.useDocFrequency = true;
/* 53 */ this.useMeanTrim = true;
/* 54 */ this.probThreshold = 0.001D;
/* 55 */ this.useEM = false;
/* 56 */ this.iterationNum = 15;
/* 57 */ this.bkgCoeffi = 0.5D;
/* 58 */ this.totalDestSignatureNum = destDocSignatureMatrix.columns();
/* */ }
/* */
/* */ public TopicSignatureModel(IRSignatureIndexList srcIndexList, IntSparseMatrix cooccurMatrix)
/* */ {
/* 67 */ this.srcIndexList = srcIndexList;
/* 68 */ this.cooccurMatrix = cooccurMatrix;
/* 69 */ this.useMeanTrim = true;
/* 70 */ this.probThreshold = 0.001D;
/* 71 */ this.useEM = false;
/* 72 */ this.iterationNum = 15;
/* 73 */ this.bkgCoeffi = 0.5D;
/* 74 */ this.totalDestSignatureNum = cooccurMatrix.columns();
/* */ }
/* */
/* */ public TopicSignatureModel(IRSignatureIndexList srcIndexList, IRSignatureIndexList destIndexList, IntSparseMatrix cooccurMatrix)
/* */ {
/* 84 */ this.srcIndexList = srcIndexList;
/* 85 */ this.destIndexList = destIndexList;
/* 86 */ this.cooccurMatrix = cooccurMatrix;
/* 87 */ this.useMeanTrim = true;
/* 88 */ this.probThreshold = 0.001D;
/* 89 */ this.useEM = true;
/* 90 */ this.iterationNum = 15;
/* 91 */ this.bkgCoeffi = 0.5D;
/* 92 */ this.totalDestSignatureNum = cooccurMatrix.columns();
/* */ }
/* */
/* */ public TopicSignatureModel(IRSignatureIndexList srcIndexList, IntSparseMatrix srcSignatureDocMatrix, IRSignatureIndexList destIndexList, IntSparseMatrix destDocSignatureMatrix)
/* */ {
/* 103 */ this.srcIndexList = srcIndexList;
/* 104 */ this.srcSignatureDocMatrix = srcSignatureDocMatrix;
/* 105 */ this.destIndexList = destIndexList;
/* 106 */ this.destDocSignatureMatrix = destDocSignatureMatrix;
/* 107 */ this.useDocFrequency = true;
/* 108 */ this.useMeanTrim = true;
/* 109 */ this.probThreshold = 0.001D;
/* 110 */ this.useEM = true;
/* 111 */ this.iterationNum = 15;
/* 112 */ this.bkgCoeffi = 0.5D;
/* 113 */ this.totalDestSignatureNum = destDocSignatureMatrix.columns();
/* */ }
/* */
/* */ public void setUseEM(boolean option) {
/* 117 */ this.useEM = option;
/* */ }
/* */
/* */ public boolean getUseEM() {
/* 121 */ return this.useEM;
/* */ }
/* */
/* */ public void setEMBackgroundCoefficient(double coeffi) {
/* 125 */ this.bkgCoeffi = coeffi;
/* */ }
/* */
/* */ public double getEMBackgroundCoefficient() {
/* 129 */ return this.bkgCoeffi;
/* */ }
/* */
/* */ public void setEMIterationNum(int iterationNum) {
/* 133 */ this.iterationNum = iterationNum;
/* */ }
/* */
/* */ public int getEMIterationNum() {
/* 137 */ return this.iterationNum;
/* */ }
/* */
/* */ public void setUseDocFrequency(boolean option) {
/* 141 */ this.useDocFrequency = option;
/* */ }
/* */
/* */ public boolean getUseDocFrequency() {
/* 145 */ return this.useDocFrequency;
/* */ }
/* */
/* */ public void setUseMeanTrim(boolean option) {
/* 149 */ this.useMeanTrim = option;
/* */ }
/* */
/* */ public boolean getUseMeanTrim() {
/* 153 */ return this.useMeanTrim;
/* */ }
/* */
/* */ public void setProbThreshold(double threshold) {
/* 157 */ this.probThreshold = threshold;
/* */ }
/* */
/* */ public double getProbThreshold() {
/* 161 */ return this.probThreshold;
/* */ }
/* */
/* */ public boolean genMappingMatrix(int minDocFrequency, String matrixPath, String matrixKey)
/* */ {
/* 174 */ String transIndexFile = matrixPath + "/" + matrixKey + ".index";
/* 175 */ String transMatrixFile = matrixPath + "/" + matrixKey + ".matrix";
/* 176 */ String transTIndexFile = matrixPath + "/" + matrixKey + "t.index";
/* 177 */ String transTMatrixFile = matrixPath + "/" + matrixKey + "t.matrix";
/* 178 */ File file = new File(transMatrixFile);
/* 179 */ if (file.exists()) file.delete();
/* 180 */ file = new File(transIndexFile);
/* 181 */ if (file.exists()) file.delete();
/* 182 */ file = new File(transTMatrixFile);
/* 183 */ if (file.exists()) file.delete();
/* 184 */ file = new File(transTIndexFile);
/* 185 */ if (file.exists()) file.delete();
/* */
/* 187 */ DoubleSuperSparseMatrix outputTransMatrix = new DoubleSuperSparseMatrix(transIndexFile, transMatrixFile, false, false);
/* 188 */ outputTransMatrix.setFlushInterval(2147483647);
/* 189 */ DoubleSuperSparseMatrix outputTransTMatrix = new DoubleSuperSparseMatrix(transTIndexFile, transTMatrixFile, false, false);
/* 190 */ outputTransTMatrix.setFlushInterval(2147483647);
/* 191 */ int cellNum = 0;
/* 192 */ int rowNum = this.srcIndexList.size();
/* 193 */ this.buf = new int[this.totalDestSignatureNum];
/* 194 */ if (this.destDocSignatureMatrix != null) {
/* 195 */ this.DOC_THRESH = computeDocThreshold(this.destDocSignatureMatrix);
/* */ }
/* 197 */ for (int i = 0; i < rowNum; i++) {
/* 198 */ if (i % 1000 == 0) System.out.println(new Date().toString() + " Processing Row#" + i);
/* */
/* 200 */ if ((this.srcIndexList.getIRSignature(i).getDocFrequency() >= minDocFrequency) && (
/* 201 */ (this.cooccurMatrix == null) || (this.cooccurMatrix.getNonZeroNumInRow(i) >= 5)))
/* */ {
/* 203 */ ArrayList tokenList = genSignatureMapping(i);
/* 204 */ for (int j = 0; j < tokenList.size(); j++) {
/* 205 */ Token curToken = (Token)tokenList.get(j);
/* 206 */ outputTransMatrix.add(i, curToken.getIndex(), curToken.getWeight());
/* 207 */ outputTransTMatrix.add(curToken.getIndex(), i, curToken.getWeight());
/* */ }
/* 209 */ cellNum += tokenList.size();
/* 210 */ tokenList.clear();
/* 211 */ if (cellNum >= 5000000) {
/* 212 */ outputTransTMatrix.flush();
/* 213 */ outputTransMatrix.flush();
/* 214 */ cellNum = 0;
/* */ }
/* */ }
/* */ }
/* 217 */ outputTransTMatrix.finalizeData();
/* 218 */ outputTransTMatrix.close();
/* 219 */ outputTransMatrix.finalizeData();
/* 220 */ outputTransMatrix.close();
/* 221 */ return true;
/* */ }
/* */
/* */ public ArrayList genSignatureMapping(int srcSignatureIndex)
/* */ {
/* */ ArrayList tokenList;
/* 228 */ if (this.srcSignatureDocMatrix != null) {
/* 229 */ int[] arrDoc = this.srcSignatureDocMatrix.getNonZeroColumnsInRow(srcSignatureIndex);
/* 230 */ if (arrDoc.length > this.DOC_THRESH)
/* 231 */ tokenList = computeDistributionByArray(arrDoc);
/* */ else
/* 233 */ tokenList = computeDistributionByHash(arrDoc);
/* */ }
/* */ else {
/* 236 */ tokenList = computeDistributionByCooccurMatrix(srcSignatureIndex);
/* */ }
/* 238 */ if (this.useEM)
/* 239 */ tokenList = emTopicSignatureModel(tokenList);
/* 240 */ return tokenList;
/* */ }
/* */
/* */ private int computeDocThreshold(IntSparseMatrix doctermMatrix) {
/* 244 */ return (int)(doctermMatrix.columns() / computeAvgTermNum(doctermMatrix) / 8.0D);
/* */ }
/* */
/* */ private double computeAvgTermNum(IntSparseMatrix doctermMatrix)
/* */ {
/* 252 */ Random random = new Random();
/* 253 */ int num = Math.min(50, doctermMatrix.rows());
/* 254 */ double sum = 0.0D;
/* 255 */ for (int i = 0; i < num; i++) {
/* 256 */ int index = random.nextInt(doctermMatrix.rows());
/* 257 */ sum += doctermMatrix.getNonZeroNumInRow(index);
/* */ }
/* 259 */ return sum / num;
/* */ }
/* */
/* */ private ArrayList computeDistributionByCooccurMatrix(int signatureIndex)
/* */ {
/* 269 */ double rowTotal = 0.0D;
/* 270 */ int[] arrIndex = this.cooccurMatrix.getNonZeroColumnsInRow(signatureIndex);
/* 271 */ int[] arrFreq = this.cooccurMatrix.getNonZeroIntScoresInRow(signatureIndex);
/* 272 */ for (int i = 0; i < arrFreq.length; i++)
/* 273 */ rowTotal += arrFreq[i];
/* */ double mean;
/* 274 */ if (this.useMeanTrim)
/* 275 */ mean = rowTotal / arrFreq.length;
/* */ else
/* 277 */ mean = 0.5D;
/* 278 */ if (mean < rowTotal * getMinInitProb()) {
/* 279 */ mean = rowTotal * getMinInitProb();
/* */ }
/* 281 */ rowTotal = 0.0D;
/* 282 */ ArrayList list = new ArrayList();
/* 283 */ for (int i = 0; i < arrFreq.length; i++) {
/* 284 */ if (arrFreq[i] >= mean) {
/* 285 */ list.add(new Token(arrIndex[i], arrFreq[i]));
/* 286 */ rowTotal += arrFreq[i];
/* */ }
/* */ }
/* 289 */ for (int i = 0; i < list.size(); i++) {
/* 290 */ Token curToken = (Token)list.get(i);
/* 291 */ curToken.setWeight(curToken.getFrequency() / rowTotal);
/* */ }
/* 293 */ return list;
/* */ }
/* */
/* */ private ArrayList computeDistributionByArray(int[] arrDoc)
/* */ {
/* 303 */ double rowTotal = 0.0D;
/* 304 */ if (this.buf == null)
/* 305 */ this.buf = new int[this.totalDestSignatureNum];
/* 306 */ MathUtil.initArray(this.buf, 0);
/* 307 */ for (int j = 0; j < arrDoc.length; j++) {
/* 308 */ int[] arrIndex = this.destDocSignatureMatrix.getNonZeroColumnsInRow(arrDoc[j]);
/* */ int[] arrFreq;
/* 309 */ if (this.useDocFrequency)
/* 310 */ arrFreq = (int[])null;
/* */ else
/* 312 */ arrFreq = this.destDocSignatureMatrix.getNonZeroIntScoresInRow(arrDoc[j]);
/* 313 */ for (int k = 0; k < arrIndex.length; k++) {
/* 314 */ if (this.useDocFrequency)
/* 315 */ this.buf[arrIndex[k]] += 1;
/* */ else {
/* 317 */ this.buf[arrIndex[k]] += arrFreq[k];
/* */ }
/* */ }
/* */ }
/* 321 */ int nonZeroNum = 0;
/* 322 */ for (int i = 0; i < this.buf.length; i++)
/* 323 */ if (this.buf[i] > 0) {
/* 324 */ nonZeroNum++;
/* 325 */ rowTotal += this.buf[i];
/* */ }
/* */ double mean;
/* 328 */ if (this.useMeanTrim)
/* 329 */ mean = rowTotal / nonZeroNum;
/* */ else
/* 331 */ mean = 0.5D;
/* 332 */ if (mean < rowTotal * getMinInitProb()) {
/* 333 */ mean = rowTotal * getMinInitProb();
/* */ }
/* 335 */ rowTotal = 0.0D;
/* 336 */ ArrayList list = new ArrayList();
/* 337 */ for (int i = 0; i < this.buf.length; i++) {
/* 338 */ if (this.buf[i] >= mean) {
/* 339 */ list.add(new Token(i, this.buf[i]));
/* 340 */ rowTotal += this.buf[i];
/* */ }
/* */ }
/* 343 */ for (int i = 0; i < list.size(); i++) {
/* 344 */ Token curToken = (Token)list.get(i);
/* 345 */ curToken.setWeight(curToken.getFrequency() / rowTotal);
/* */ }
/* 347 */ return list;
/* */ }
/* */
/* */ private ArrayList computeDistributionByHash(int[] arrDoc)
/* */ {
/* 356 */ ArrayList tokenList = countTokensByHashMap(arrDoc);
/* 357 */ double rowTotal = 0.0D;
/* 358 */ for (int i = 0; i < tokenList.size(); i++)
/* 359 */ rowTotal += ((Token)tokenList.get(i)).getFrequency();
/* */ ArrayList list;
/* 361 */ if ((this.useMeanTrim) || (rowTotal * getMinInitProb() > 1.0D))
/* */ {
/* */ double mean;
/* 362 */ if (this.useMeanTrim)
/* 363 */ mean = rowTotal / tokenList.size();
/* */ else
/* 365 */ mean = 0.5D;
/* 366 */ if (mean < rowTotal * getMinInitProb())
/* 367 */ mean = rowTotal * getMinInitProb();
/* 368 */ list = new ArrayList();
/* 369 */ rowTotal = 0.0D;
/* 370 */ for (int i = 0; i < tokenList.size(); i++) {
/* 371 */ Token curToken = (Token)tokenList.get(i);
/* 372 */ if (curToken.getFrequency() >= mean) {
/* 373 */ list.add(curToken);
/* 374 */ rowTotal += curToken.getFrequency();
/* */ }
/* */ }
/* 377 */ tokenList.clear();
/* */ }
/* */ else {
/* 380 */ list = tokenList;
/* */ }
/* 382 */ for (int i = 0; i < list.size(); i++) {
/* 383 */ Token curToken = (Token)list.get(i);
/* 384 */ curToken.setWeight(curToken.getFrequency() / rowTotal);
/* */ }
/* 386 */ return list;
/* */ }
/* */
/* */ private ArrayList countTokensByHashMap(int[] arrDoc)
/* */ {
/* 398 */ HashMap hash = new HashMap();
/* 399 */ for (int j = 0; j < arrDoc.length; j++) {
/* 400 */ int termNum = this.destDocSignatureMatrix.getNonZeroNumInRow(arrDoc[j]);
/* 401 */ if (termNum != 0)
/* */ {
/* 403 */ int[] arrTerm = this.destDocSignatureMatrix.getNonZeroColumnsInRow(arrDoc[j]);
/* */ int[] arrFreq;
/* 404 */ if (this.useDocFrequency)
/* 405 */ arrFreq = (int[])null;
/* */ else
/* 407 */ arrFreq = this.destDocSignatureMatrix.getNonZeroIntScoresInRow(arrDoc[j]);
/* 408 */ for (int i = 0; i < termNum; i++)
/* */ {
/* */ Token curToken;
/* 409 */ if (this.useDocFrequency)
/* 410 */ curToken = new Token(arrTerm[i], 1);
/* */ else
/* 412 */ curToken = new Token(arrTerm[i], arrFreq[i]);
/* 413 */ Counter counter = (Counter)hash.get(curToken);
/* 414 */ if (counter == null) {
/* 415 */ counter = new Counter(curToken.getFrequency());
/* 416 */ hash.put(curToken, counter);
/* */ }
/* */ else {
/* 419 */ counter.addCount(curToken.getFrequency());
/* */ }
/* */ }
/* */ }
/* */ }
/* 423 */ ArrayList list = new ArrayList(hash.size());
/* 424 */ Iterator iterator = hash.keySet().iterator();
/* 425 */ while (iterator.hasNext()) {
/* 426 */ Token curToken = (Token)iterator.next();
/* 427 */ Counter counter = (Counter)hash.get(curToken);
/* 428 */ curToken.setFrequency(counter.getCount());
/* 429 */ list.add(curToken);
/* */ }
/* 431 */ hash.clear();
/* 432 */ return list;
/* */ }
/* */
/* */ private double getMinInitProb()
/* */ {
/* 441 */ return this.probThreshold;
/* */ }
/* */
/* */ private ArrayList emTopicSignatureModel(ArrayList list)
/* */ {
/* 451 */ int termNum = list.size();
/* 452 */ double[] arrProb = new double[termNum];
/* */
/* 455 */ double[] arrCollectionProb = new double[termNum];
/* 456 */ double weightSum = 0.0D;
/* 457 */ for (int i = 0; i < termNum; i++) {
/* 458 */ Token curToken = (Token)list.get(i);
/* 459 */ if (this.useDocFrequency)
/* 460 */ arrCollectionProb[i] = this.destIndexList.getIRSignature(curToken.getIndex()).getDocFrequency();
/* */ else
/* 462 */ arrCollectionProb[i] = this.destIndexList.getIRSignature(curToken.getIndex()).getFrequency();
/* 463 */ weightSum += arrCollectionProb[i];
/* */ }
/* 465 */ for (int i = 0; i < termNum; i++) {
/* 466 */ arrCollectionProb[i] /= weightSum;
/* */ }
/* */
/* 469 */ for (int i = 0; i < this.iterationNum; i++) {
/* 470 */ weightSum = 0.0D;
/* 471 */ for (int j = 0; j < termNum; j++) {
/* 472 */ Token curToken = (Token)list.get(j);
/* 473 */ arrProb[j] =
/* 474 */ ((1.0D - this.bkgCoeffi) * curToken.getWeight() / (
/* 474 */ (1.0D - this.bkgCoeffi) * curToken.getWeight() + this.bkgCoeffi * arrCollectionProb[j]) * curToken.getFrequency());
/* 475 */ weightSum += arrProb[j];
/* */ }
/* 477 */ for (int j = 0; j < termNum; j++) {
/* 478 */ Token curToken = (Token)list.get(j);
/* 479 */ curToken.setWeight(arrProb[j] / weightSum);
/* */ }
/* */
/* */ }
/* */
/* 490 */ return list;
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.ir.kngbase.TopicSignatureModel
* JD-Core Version: 0.6.2
*/
| |
/*
* Copyright 2017 Axel Faust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.axelfaust.alfresco.trash.management.repo.behaviour;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.NodeServicePolicies.OnDeleteNodePolicy;
import org.alfresco.repo.node.NodeServicePolicies.OnRestoreNodePolicy;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.policy.Behaviour.NotificationFrequency;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.transaction.TransactionalResourceHelper;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.security.AccessPermission;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.PropertyCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import de.axelfaust.alfresco.trash.management.repo.BetterTrashManagementModel;
/**
* This behaviour ensures that default {@link PermissionService#READ read privileges} are set for the archiving user so that the elements
* can be queried, e.g. via SOLR even if there are no explicitly set permission on the node itself.
*
* @author Axel Faust, <a href="http://acosix.de">Acosix GmbH</a>
*/
public class UserTrashContainer implements InitializingBean, OnRestoreNodePolicy, OnDeleteNodePolicy
{
private static final Logger LOGGER = LoggerFactory.getLogger(UserTrashContainer.class);
protected PolicyComponent policyComponent;
protected NodeService nodeService;
protected NodeArchiveService nodeArchiveService;
protected PermissionService permissionService;
/**
*
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet()
{
PropertyCheck.mandatory(this, "policyComponent", this.policyComponent);
PropertyCheck.mandatory(this, "nodeService", this.nodeService);
PropertyCheck.mandatory(this, "nodeArchiveService", this.nodeArchiveService);
PropertyCheck.mandatory(this, "permissionService", this.permissionService);
this.policyComponent.bindClassBehaviour(OnDeleteNodePolicy.QNAME, this,
new JavaBehaviour(this, "onDeleteNode", NotificationFrequency.EVERY_EVENT));
this.policyComponent.bindClassBehaviour(OnRestoreNodePolicy.QNAME, this,
new JavaBehaviour(this, "onRestoreNode", NotificationFrequency.EVERY_EVENT));
}
/**
* @param policyComponent
* the policyComponent to set
*/
public void setPolicyComponent(final PolicyComponent policyComponent)
{
this.policyComponent = policyComponent;
}
/**
* @param nodeService
* the nodeService to set
*/
public void setNodeService(final NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @param nodeArchiveService
* the nodeArchiveService to set
*/
public void setNodeArchiveService(final NodeArchiveService nodeArchiveService)
{
this.nodeArchiveService = nodeArchiveService;
}
/**
* @param permissionService
* the permissionService to set
*/
public void setPermissionService(final PermissionService permissionService)
{
this.permissionService = permissionService;
}
/**
* {@inheritDoc}
*/
@Override
public void onDeleteNode(final ChildAssociationRef childAssocRef, final boolean isNodeArchived)
{
final NodeRef deletedChildRef = childAssocRef.getChildRef();
if (isNodeArchived)
{
// TODO Report bug: policy parameter isNodeArchive is incorrect in various cases, e.g. set to true if node is moved due to
// restore, though in that case the policy will usually be ignored due to the "storesToIgnorePolicies" list
final NodeRef archiveRootNode = this.nodeArchiveService.getStoreArchiveNode(deletedChildRef.getStoreRef());
if (archiveRootNode != null)
{
final NodeRef archivedNode = this.nodeArchiveService.getArchivedNode(deletedChildRef);
if (this.nodeService.exists(archivedNode))
{
final Map<QName, Serializable> properties = this.nodeService.getProperties(archivedNode);
final String archivedBy = DefaultTypeConverter.INSTANCE.convert(String.class,
properties.get(ContentModel.PROP_ARCHIVED_BY));
// only in this case is it an actual archive-move of a root element (we don't need to handle cascade moves)
if (archivedBy != null)
{
// ensure the archiving user can always query top-level elements
// explicit permissions may be only set to a group from which the user might be removed later on
final Set<AccessPermission> allSetPermissions = this.permissionService.getAllSetPermissions(archivedNode);
final boolean userReadAccessSet = allSetPermissions.stream().anyMatch(setPermission -> {
final boolean readAccessSet = setPermission.getAccessStatus() == AccessStatus.ALLOWED
&& PermissionService.READ.equals(setPermission.getPermission())
&& archivedBy.equals(setPermission.getAuthority());
return readAccessSet;
});
if (!userReadAccessSet)
{
LOGGER.debug("Adding explicit read permission to archived node {} for {} due to inherit=false", archivedNode,
archivedBy);
this.permissionService.setPermission(archivedNode, archivedBy, PermissionService.READ, true);
this.nodeService.addAspect(archivedNode, BetterTrashManagementModel.ASPECT_USER_READ_ACCESS_GRANTED,
Collections.singletonMap(BetterTrashManagementModel.PROP_READ_ACCESS_GRANTED_TO, archivedBy));
}
}
else
{
LOGGER.debug("Not handling deletion of {} as it is not an archive operation", deletedChildRef);
}
}
else
{
LOGGER.warn("Node {} known to have been archived in current txn does not exist", archivedNode);
}
}
else
{
LOGGER.debug("Not handling deletion of {} as it is not an archive operation", deletedChildRef);
}
}
else
{
LOGGER.debug("Not handling deletion of {} as it is not an archive operation", deletedChildRef);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRestoreNode(final ChildAssociationRef childAssocRef)
{
final NodeRef restoredNode = childAssocRef.getChildRef();
final NodeRef archiveRootNode = this.nodeArchiveService.getStoreArchiveNode(restoredNode.getStoreRef());
if (archiveRootNode != null)
{
final NodeRef parentRef = childAssocRef.getParentRef();
final NodeRef potentiallyRestoredParentNode = this.nodeArchiveService.getArchivedNode(parentRef);
final Set<Object> nodesRestoredInTxn = TransactionalResourceHelper
.getSet(UserTrashContainer.class.getName() + "-restoredNodes");
if (!nodesRestoredInTxn.contains(potentiallyRestoredParentNode))
{
if (this.nodeService.hasAspect(restoredNode, BetterTrashManagementModel.ASPECT_USER_READ_ACCESS_GRANTED))
{
final Map<QName, Serializable> properties = this.nodeService.getProperties(restoredNode);
final String readAccessGrantedTo = DefaultTypeConverter.INSTANCE.convert(String.class,
properties.get(BetterTrashManagementModel.PROP_READ_ACCESS_GRANTED_TO));
LOGGER.debug(
"Removing explicit read permission from restored node {} for {} which was granted as part of trash management",
restoredNode, readAccessGrantedTo);
this.permissionService.deletePermission(restoredNode, readAccessGrantedTo, PermissionService.READ);
this.nodeService.removeAspect(restoredNode, BetterTrashManagementModel.ASPECT_USER_READ_ACCESS_GRANTED);
}
nodesRestoredInTxn.add(restoredNode);
}
else
{
LOGGER.debug("Not handling restoration of node {} as it is a cascade-restoration operation", restoredNode);
}
}
else
{
LOGGER.debug("Not handling restoration of {} as it is not an regular restore-from-archive operation", restoredNode);
}
}
}
| |
/*
* Copyright 2018 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 androidx.media3.session;
import static androidx.media3.test.session.common.CommonConstants.SUPPORT_APP_PACKAGE_NAME;
import static androidx.media3.test.session.common.TestUtils.LONG_TIMEOUT_MS;
import static androidx.media3.test.session.common.TestUtils.TIMEOUT_MS;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import androidx.media3.common.DeviceInfo;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaMetadata;
import androidx.media3.common.PlaybackParameters;
import androidx.media3.common.Player;
import androidx.media3.common.TrackSelectionParameters;
import androidx.media3.test.session.common.HandlerThreadTestRule;
import androidx.media3.test.session.common.MainLooperTestRule;
import androidx.media3.test.session.common.TestUtils;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Tests for the underlying {@link Player} of {@link MediaSession}. */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MediaSessionPlayerTest {
@ClassRule public static MainLooperTestRule mainLooperTestRule = new MainLooperTestRule();
@Rule
public final HandlerThreadTestRule threadTestRule =
new HandlerThreadTestRule("MediaSessionPlayerTest");
@Rule
public final RemoteControllerTestRule remoteControllerTestRule = new RemoteControllerTestRule();
private MediaSession session;
private MockPlayer player;
private RemoteMediaController controller;
@Before
public void setUp() throws Exception {
player =
new MockPlayer.Builder()
.setLatchCount(1)
.setApplicationLooper(threadTestRule.getHandler().getLooper())
.setMediaItems(/* itemCount= */ 5)
.build();
session =
new MediaSession.Builder(ApplicationProvider.getApplicationContext(), player)
.setSessionCallback(
new MediaSession.SessionCallback() {
@Override
public MediaSession.ConnectionResult onConnect(
MediaSession session, MediaSession.ControllerInfo controller) {
if (SUPPORT_APP_PACKAGE_NAME.equals(controller.getPackageName())) {
return MediaSession.SessionCallback.super.onConnect(session, controller);
}
return MediaSession.ConnectionResult.reject();
}
})
.build();
// Create a default MediaController in client app.
controller = remoteControllerTestRule.createRemoteController(session.getToken());
}
@After
public void cleanUp() {
if (session != null) {
session.release();
}
}
@Test
public void play() throws Exception {
controller.play();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.playCalled).isTrue();
}
@Test
public void pause() throws Exception {
controller.pause();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.pauseCalled).isTrue();
}
@Test
public void prepare() throws Exception {
controller.prepare();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.prepareCalled).isTrue();
}
@Test
public void stop() throws Exception {
controller.stop();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.stopCalled).isTrue();
}
@Test
public void setPlayWhenReady() throws Exception {
boolean testPlayWhenReady = true;
controller.setPlayWhenReady(testPlayWhenReady);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setPlayWhenReadyCalled).isTrue();
assertThat(player.playWhenReady).isEqualTo(testPlayWhenReady);
}
@Test
public void seekToDefaultPosition() throws Exception {
controller.seekToDefaultPosition();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToDefaultPositionCalled).isTrue();
}
@Test
public void seekToDefaultPosition_withMediaItemIndex() throws Exception {
int mediaItemIndex = 3;
controller.seekToDefaultPosition(mediaItemIndex);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToDefaultPositionWithMediaItemIndexCalled).isTrue();
assertThat(player.seekMediaItemIndex).isEqualTo(mediaItemIndex);
}
@Test
public void seekTo() throws Exception {
long seekPositionMs = 12125L;
controller.seekTo(seekPositionMs);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToCalled).isTrue();
assertThat(player.seekPositionMs).isEqualTo(seekPositionMs);
}
@Test
public void seekTo_withMediaItemIndex() throws Exception {
int mediaItemIndex = 3;
long seekPositionMs = 12125L;
controller.seekTo(mediaItemIndex, seekPositionMs);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToWithMediaItemIndexCalled).isTrue();
assertThat(player.seekMediaItemIndex).isEqualTo(mediaItemIndex);
assertThat(player.seekPositionMs).isEqualTo(seekPositionMs);
}
@Test
public void setPlaybackSpeed() throws Exception {
float testSpeed = 1.5f;
controller.setPlaybackSpeed(testSpeed);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.playbackParameters.speed).isEqualTo(testSpeed);
}
@Test
public void setPlaybackParameters() throws Exception {
PlaybackParameters testPlaybackParameters =
new PlaybackParameters(/* speed= */ 1.4f, /* pitch= */ 2.3f);
controller.setPlaybackParameters(testPlaybackParameters);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setPlaybackParametersCalled).isTrue();
assertThat(player.playbackParameters).isEqualTo(testPlaybackParameters);
}
@Test
public void setMediaItem() throws Exception {
MediaItem item = MediaTestUtils.createMediaItem("setMediaItem");
long startPositionMs = 333L;
boolean resetPosition = true;
player.startPositionMs = startPositionMs;
player.resetPosition = resetPosition;
controller.setMediaItem(item);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemCalled).isTrue();
assertThat(player.mediaItem).isEqualTo(item);
assertThat(player.startPositionMs).isEqualTo(startPositionMs);
assertThat(player.resetPosition).isEqualTo(resetPosition);
}
@Test
public void setMediaItem_withStartPosition() throws Exception {
MediaItem item = MediaTestUtils.createMediaItem("setMediaItem_withStartPosition");
long startPositionMs = 333L;
boolean resetPosition = true;
player.startPositionMs = startPositionMs;
player.resetPosition = resetPosition;
controller.setMediaItem(item);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemCalled).isTrue();
assertThat(player.mediaItem).isEqualTo(item);
assertThat(player.startPositionMs).isEqualTo(startPositionMs);
assertThat(player.resetPosition).isEqualTo(resetPosition);
}
@Test
public void setMediaItem_withResetPosition() throws Exception {
MediaItem item = MediaTestUtils.createMediaItem("setMediaItem_withResetPosition");
long startPositionMs = 333L;
boolean resetPosition = true;
player.startPositionMs = startPositionMs;
player.resetPosition = resetPosition;
controller.setMediaItem(item);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemCalled).isTrue();
assertThat(player.mediaItem).isEqualTo(item);
assertThat(player.startPositionMs).isEqualTo(startPositionMs);
assertThat(player.resetPosition).isEqualTo(resetPosition);
}
@Test
public void setMediaItems() throws Exception {
List<MediaItem> items = MediaTestUtils.createMediaItems(/* size= */ 2);
controller.setMediaItems(items);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemsCalled).isTrue();
assertThat(player.mediaItems).isEqualTo(items);
assertThat(player.resetPosition).isFalse();
}
@Test
public void setMediaItems_withResetPosition() throws Exception {
List<MediaItem> items = MediaTestUtils.createMediaItems(/* size= */ 2);
controller.setMediaItems(items, /* resetPosition= */ true);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemsWithResetPositionCalled).isTrue();
assertThat(player.mediaItems).isEqualTo(items);
assertThat(player.resetPosition).isTrue();
}
@Test
public void setMediaItems_withStartMediaItemIndex() throws Exception {
List<MediaItem> items = MediaTestUtils.createMediaItems(/* size= */ 2);
int startMediaItemIndex = 1;
long startPositionMs = 1234;
controller.setMediaItems(items, startMediaItemIndex, startPositionMs);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemsWithStartIndexCalled).isTrue();
assertThat(player.mediaItems).isEqualTo(items);
assertThat(player.startMediaItemIndex).isEqualTo(startMediaItemIndex);
assertThat(player.startPositionMs).isEqualTo(startPositionMs);
}
@Test
public void setMediaItems_withDuplicatedItems() throws Exception {
int listSize = 4;
List<MediaItem> list = MediaTestUtils.createMediaItems(listSize);
list.set(2, list.get(1));
controller.setMediaItems(list);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemsCalled).isTrue();
assertThat(player.mediaItems.size()).isEqualTo(listSize);
for (int i = 0; i < listSize; i++) {
assertThat(player.mediaItems.get(i).mediaId).isEqualTo(list.get(i).mediaId);
}
}
@Test
public void setMediaItems_withLongPlaylist() throws Exception {
int listSize = 5000;
// Make client app to generate a long list, and call setMediaItems() with it.
controller.createAndSetFakeMediaItems(listSize);
assertThat(player.countDownLatch.await(LONG_TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setMediaItemsCalled).isTrue();
assertThat(player.mediaItems).isNotNull();
assertThat(player.mediaItems.size()).isEqualTo(listSize);
for (int i = 0; i < listSize; i++) {
// Each item's media ID will be same as its index.
assertThat(player.mediaItems.get(i).mediaId).isEqualTo(TestUtils.getMediaIdInFakeTimeline(i));
}
}
@Test
public void setPlaylistMetadata() throws Exception {
MediaMetadata playlistMetadata = new MediaMetadata.Builder().setTitle("title").build();
controller.setPlaylistMetadata(playlistMetadata);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setPlaylistMetadataCalled).isTrue();
assertThat(player.playlistMetadata).isEqualTo(playlistMetadata);
}
@Test
public void addMediaItem() throws Exception {
MediaItem mediaItem = MediaTestUtils.createMediaItem("addMediaItem");
controller.addMediaItem(mediaItem);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.addMediaItemCalled).isTrue();
assertThat(player.mediaItem).isEqualTo(mediaItem);
}
@Test
public void addMediaItem_withIndex() throws Exception {
int index = 2;
MediaItem mediaItem = MediaTestUtils.createMediaItem("addMediaItem_withIndex");
controller.addMediaItem(index, mediaItem);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.addMediaItemWithIndexCalled).isTrue();
assertThat(player.index).isEqualTo(index);
assertThat(player.mediaItem).isEqualTo(mediaItem);
}
@Test
public void addMediaItems() throws Exception {
int size = 2;
List<MediaItem> mediaItems = MediaTestUtils.createMediaItems(size);
controller.addMediaItems(mediaItems);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.addMediaItemsCalled).isTrue();
assertThat(player.mediaItems).isEqualTo(mediaItems);
}
@Test
public void addMediaItems_withIndex() throws Exception {
int index = 0;
int size = 2;
List<MediaItem> mediaItems = MediaTestUtils.createMediaItems(size);
controller.addMediaItems(index, mediaItems);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.addMediaItemsWithIndexCalled).isTrue();
assertThat(player.index).isEqualTo(index);
assertThat(player.mediaItems).isEqualTo(mediaItems);
}
@Test
public void removeMediaItem() throws Exception {
int index = 5;
controller.removeMediaItem(index);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.removeMediaItemCalled).isTrue();
assertThat(player.index).isEqualTo(index);
}
@Test
public void removeMediaItems() throws Exception {
int fromIndex = 0;
int toIndex = 3;
controller.removeMediaItems(fromIndex, toIndex);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.removeMediaItemsCalled).isTrue();
assertThat(player.fromIndex).isEqualTo(fromIndex);
assertThat(player.toIndex).isEqualTo(toIndex);
}
@Test
public void clearMediaItems() throws Exception {
controller.clearMediaItems();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.clearMediaItemsCalled).isTrue();
}
@Test
public void moveMediaItem() throws Exception {
int index = 4;
int newIndex = 1;
controller.moveMediaItem(index, newIndex);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.moveMediaItemCalled).isTrue();
assertThat(player.index).isEqualTo(index);
assertThat(player.newIndex).isEqualTo(newIndex);
}
@Test
public void moveMediaItems() throws Exception {
int fromIndex = 0;
int toIndex = 2;
int newIndex = 1;
controller.moveMediaItems(fromIndex, toIndex, newIndex);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.moveMediaItemsCalled).isTrue();
assertThat(player.fromIndex).isEqualTo(fromIndex);
assertThat(player.toIndex).isEqualTo(toIndex);
assertThat(player.newIndex).isEqualTo(newIndex);
}
@Test
public void seekToPreviousMediaItem() throws Exception {
controller.seekToPreviousMediaItem();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToPreviousMediaItemCalled).isTrue();
}
@Test
public void seekToNextMediaItem() throws Exception {
controller.seekToNextMediaItem();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToNextMediaItemCalled).isTrue();
}
@Test
public void seekToPrevious() throws Exception {
controller.seekToPrevious();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToPreviousCalled).isTrue();
}
@Test
public void seekToNext() throws Exception {
controller.seekToNext();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekToNextCalled).isTrue();
}
@Test
public void setShuffleModeEnabled() throws Exception {
boolean testShuffleModeEnabled = true;
controller.setShuffleModeEnabled(testShuffleModeEnabled);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setShuffleModeCalled).isTrue();
assertThat(player.shuffleModeEnabled).isEqualTo(testShuffleModeEnabled);
}
@Test
public void setRepeatMode() throws Exception {
int testRepeatMode = Player.REPEAT_MODE_ALL;
controller.setRepeatMode(testRepeatMode);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setRepeatModeCalled).isTrue();
assertThat(player.repeatMode).isEqualTo(testRepeatMode);
}
@Test
public void setVolume() throws Exception {
float testVolume = .123f;
controller.setVolume(testVolume);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setVolumeCalled).isTrue();
assertThat(player.volume).isEqualTo(testVolume);
}
@Test
public void setDeviceVolume() throws Exception {
changePlaybackTypeToRemote();
int testVolume = 12;
controller.setDeviceVolume(testVolume);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setDeviceVolumeCalled).isTrue();
assertThat(player.deviceVolume).isEqualTo(testVolume);
}
@Test
public void increaseDeviceVolume() throws Exception {
changePlaybackTypeToRemote();
controller.increaseDeviceVolume();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.increaseDeviceVolumeCalled).isTrue();
}
@Test
public void decreaseDeviceVolume() throws Exception {
changePlaybackTypeToRemote();
controller.decreaseDeviceVolume();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.decreaseDeviceVolumeCalled).isTrue();
}
@Test
public void setDeviceMuted() throws Exception {
player.deviceMuted = false;
controller.setDeviceMuted(true);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setDeviceMutedCalled).isTrue();
assertThat(player.deviceMuted).isTrue();
}
@Test
public void seekBack() throws Exception {
controller.seekBack();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekBackCalled).isTrue();
}
@Test
public void seekForward() throws Exception {
controller.seekForward();
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.seekForwardCalled).isTrue();
}
@Test
public void setTrackSelectionParameters() throws Exception {
TrackSelectionParameters trackSelectionParameters =
TrackSelectionParameters.DEFAULT_WITHOUT_CONTEXT.buildUpon().setMaxAudioBitrate(10).build();
controller.setTrackSelectionParameters(trackSelectionParameters);
assertThat(player.countDownLatch.await(TIMEOUT_MS, MILLISECONDS)).isTrue();
assertThat(player.setTrackSelectionParametersCalled).isTrue();
assertThat(player.trackSelectionParameters).isEqualTo(trackSelectionParameters);
}
private void changePlaybackTypeToRemote() throws Exception {
threadTestRule
.getHandler()
.postAndSync(
() -> {
player.deviceInfo =
new DeviceInfo(
DeviceInfo.PLAYBACK_TYPE_REMOTE, /* minVolume= */ 0, /* maxVolume= */ 100);
player.notifyDeviceInfoChanged();
});
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.guice;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.inject.Binder;
import com.google.inject.Inject;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.util.Types;
import io.druid.guice.annotations.PublicApi;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.util.Properties;
/**
* Provides a singleton value of type {@code <T>} from {@code Properties} bound in guice.
* <br/>
* <h3>Usage</h3>
* To install this provider, bind it in your guice module, like below.
*
* <pre>
* JsonConfigProvider.bind(binder, "druid.server", DruidServerConfig.class);
* </pre>
* <br/>
* In the above case, {@code druid.server} should be a key found in the {@code Properties} bound elsewhere.
* The value of that key should directly relate to the fields in {@code DruidServerConfig.class}.
*
* <h3>Implementation</h3>
* <br/>
* The state of {@code <T>} is defined by the value of the property {@code propertyBase}.
* This value is a json structure, decoded via {@link JsonConfigurator#configurate(Properties, String, Class)}.
* <br/>
*
* An example might be if DruidServerConfig.class were
*
* <pre>
* public class DruidServerConfig
* {
* @JsonProperty @NotNull public String hostname = null;
* @JsonProperty @Min(1025) public int port = 8080;
* }
* </pre>
*
* And your Properties object had in it
*
* <pre>
* druid.server.hostname=0.0.0.0
* druid.server.port=3333
* </pre>
*
* Then this would bind a singleton instance of a DruidServerConfig object with hostname = "0.0.0.0" and port = 3333.
*
* If the port weren't set in the properties, then the default of 8080 would be taken. Essentially, it is the same as
* subtracting the "druid.server" prefix from the properties and building a Map which is then passed into
* ObjectMapper.convertValue()
*
* @param <T> type of config object to provide.
*/
@PublicApi
public class JsonConfigProvider<T> implements Provider<Supplier<T>>
{
@SuppressWarnings("unchecked")
public static <T> void bind(Binder binder, String propertyBase, Class<T> classToProvide)
{
bind(
binder,
propertyBase,
classToProvide,
Key.get(classToProvide),
(Key) Key.get(Types.newParameterizedType(Supplier.class, classToProvide))
);
}
@SuppressWarnings("unchecked")
public static <T> void bind(Binder binder, String propertyBase, Class<T> classToProvide, Annotation annotation)
{
bind(
binder,
propertyBase,
classToProvide,
Key.get(classToProvide, annotation),
(Key) Key.get(Types.newParameterizedType(Supplier.class, classToProvide), annotation)
);
}
@SuppressWarnings("unchecked")
public static <T> void bind(
Binder binder,
String propertyBase,
Class<T> classToProvide,
Class<? extends Annotation> annotation
)
{
bind(
binder,
propertyBase,
classToProvide,
Key.get(classToProvide, annotation),
(Key) Key.get(Types.newParameterizedType(Supplier.class, classToProvide), annotation)
);
}
@SuppressWarnings("unchecked")
public static <T> void bind(
Binder binder,
String propertyBase,
Class<T> clazz,
Key<T> instanceKey,
Key<Supplier<T>> supplierKey
)
{
binder.bind(supplierKey).toProvider((Provider) of(propertyBase, clazz)).in(LazySingleton.class);
binder.bind(instanceKey).toProvider(new SupplierProvider<T>(supplierKey));
}
@SuppressWarnings("unchecked")
public static <T> void bindInstance(
Binder binder,
Key<T> bindKey,
T instance
)
{
binder.bind(bindKey).toInstance(instance);
final ParameterizedType supType = Types.newParameterizedType(Supplier.class, bindKey.getTypeLiteral().getType());
final Key supplierKey;
if (bindKey.getAnnotationType() != null) {
supplierKey = Key.get(supType, bindKey.getAnnotationType());
} else if (bindKey.getAnnotation() != null) {
supplierKey = Key.get(supType, bindKey.getAnnotation());
} else {
supplierKey = Key.get(supType);
}
binder.bind(supplierKey).toInstance(Suppliers.<T>ofInstance(instance));
}
public static <T> JsonConfigProvider<T> of(String propertyBase, Class<T> classToProvide)
{
return new JsonConfigProvider<T>(propertyBase, classToProvide);
}
private final String propertyBase;
private final Class<T> classToProvide;
private Properties props;
private JsonConfigurator configurator;
private Supplier<T> retVal = null;
public JsonConfigProvider(
String propertyBase,
Class<T> classToProvide
)
{
this.propertyBase = propertyBase;
this.classToProvide = classToProvide;
}
@Inject
public void inject(
Properties props,
JsonConfigurator configurator
)
{
this.props = props;
this.configurator = configurator;
}
@Override
public Supplier<T> get()
{
if (retVal != null) {
return retVal;
}
try {
final T config = configurator.configurate(props, propertyBase, classToProvide);
retVal = Suppliers.ofInstance(config);
}
catch (RuntimeException e) {
// When a runtime exception gets thrown out, this provider will get called again if the object is asked for again.
// This will have the same failed result, 'cause when it's called no parameters will have actually changed.
// Guice will then report the same error multiple times, which is pretty annoying. Cache a null supplier and
// return that instead. This is technically enforcing a singleton, but such is life.
retVal = Suppliers.ofInstance(null);
throw e;
}
return retVal;
}
}
| |
/**
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.admindistribution.aspect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import java.math.BigInteger;
import java.util.List;
import javax.activation.DataHandler;
import oasis.names.tc.emergency.edxl.de._1.AnyXMLType;
import oasis.names.tc.emergency.edxl.de._1.ContentObjectType;
import oasis.names.tc.emergency.edxl.de._1.EDXLDistribution;
import oasis.names.tc.emergency.edxl.de._1.NonXMLContentType;
import oasis.names.tc.emergency.edxl.de._1.XmlContentType;
import org.junit.Test;
/**
* @author zmelnick
*
*/
public class EDXLDistributionPayloadSizeExtractorTest {
@Test
public void emptyBuild() {
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
assertNotNull(extractor);
}
@Test
public void testPayloadSizeOnSingleNonXMLPayload() {
EDXLDistribution alert = new EDXLDistribution();
setNonXmlPayloadWithSize(alert, BigInteger.TEN);
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
assertEquals(BigInteger.TEN.toString(), extractor.getPayloadSizes(alert).get(0));
}
@Test
public void testPayloadSizeOnSingleNonXMLEmptyPayload() {
EDXLDistribution alert = new EDXLDistribution();
ContentObjectType payload = new ContentObjectType();
NonXMLContentType payloadContent = createMockNonXmlPayload();
payload.setNonXMLContent(payloadContent);
alert.getContentObject().add(payload);
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
assertTrue(extractor.getPayloadSizes(alert).size() == 1);
assertEquals("0", extractor.getPayloadSizes(alert).get(0));
}
@Test
public void testPayloadSizeMultipleNonXMLPayload() {
EDXLDistribution alert = new EDXLDistribution();
setNonXmlPayloadWithSize(alert, BigInteger.TEN);
alert.getContentObject().add(setNonXmlPayloadObject(BigInteger.TEN));
BigInteger testSize = BigInteger.TEN;
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
assertTrue(extractor.getPayloadSizes(alert).size() == 2);
assertEquals(testSize.toString(), extractor.getPayloadSizes(alert).get(0));
assertEquals(testSize.toString(), extractor.getPayloadSizes(alert).get(1));
}
@Test
public void testPayloadSizeXmlPayload() {
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
EDXLDistribution alert = new EDXLDistribution();
setXmlPayload(alert);
List<String> payloadSizes = extractor.getPayloadSizes(alert);
assertEquals(1, payloadSizes.size());
assertEquals("0", payloadSizes.get(0));
}
@Test
public void testPayloadSizeMixedPayload() {
EDXLDistribution alert = new EDXLDistribution();
setXmlPayload(alert);
setNonXmlPayloadWithSize(alert, BigInteger.TEN);
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
List<String> payloadSizes = extractor.getPayloadSizes(alert);
assertEquals(2, payloadSizes.size());
assertEquals("0", payloadSizes.get(0));
assertEquals("10", payloadSizes.get(1));
}
@Test
public void testPayloadSizeContentXMLbothXMLContentTypesEmpty() {
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
EDXLDistribution alert = new EDXLDistribution();
final List<AnyXMLType> emptyList = mock(List.class);
XmlContentType contentType = new XmlContentType(){
@Override
public List<AnyXMLType> getKeyXMLContent(){
return emptyList;
}
@Override
public List<AnyXMLType> getEmbeddedXMLContent(){
return emptyList;
}
};
when(emptyList.size()).thenReturn(0,0);
ContentObjectType payload = new ContentObjectType();
payload.setXmlContent(contentType);
alert.getContentObject().add(payload);
List<String> payloadSizes = extractor.getPayloadSizes(alert);
assertEquals(1, payloadSizes.size());
assertEquals("0", payloadSizes.get(0));
}
@Test
public void testPayloadSizeContentXMLMixedXMLContentTypeSizes() {
EDXLDistributionPayloadSizeExtractor extractor = new EDXLDistributionPayloadSizeExtractor();
EDXLDistribution alert = new EDXLDistribution();
final List<AnyXMLType> keyList = mock(List.class, "keyList");
final List<AnyXMLType> embeddedList = mock(List.class, "embeddedList");
XmlContentType contentType = new XmlContentType(){
@Override
public List<AnyXMLType> getKeyXMLContent(){
return keyList;
}
@Override
public List<AnyXMLType> getEmbeddedXMLContent(){
return embeddedList;
}
};
when(keyList.size()).thenReturn(4);
when(embeddedList.size()).thenReturn(5);
ContentObjectType payload = new ContentObjectType();
payload.setXmlContent(contentType);
alert.getContentObject().add(payload);
List<String> payloadSizes = extractor.getPayloadSizes(alert);
assertEquals(1, payloadSizes.size());
assertEquals("9", payloadSizes.get(0));
}
/**
* @param alert
*/
private void setXmlPayload(EDXLDistribution alert) {
ContentObjectType payload = new ContentObjectType();
XmlContentType xmlPayload = mock(XmlContentType.class);
payload.setXmlContent(xmlPayload);
alert.getContentObject().add(payload);
}
/**
* @param alert
* the object to set the payload for
*/
private void setNonXmlPayloadWithSize(EDXLDistribution alert, BigInteger... payloadSizes) {
for (BigInteger payloadSize : payloadSizes) {
ContentObjectType payload = new ContentObjectType();
NonXMLContentType payloadContent = createMockNonXmlPayload();
payloadContent.setSize(payloadSize);
payload.setNonXMLContent(payloadContent);
alert.getContentObject().add(payload);
}
}
/**
* @return
*/
private NonXMLContentType createMockNonXmlPayload() {
NonXMLContentType payloadContent = new NonXMLContentType();
payloadContent.setContentData(mock(DataHandler.class));
return payloadContent;
}
private ContentObjectType setNonXmlPayloadObject(BigInteger size) {
ContentObjectType payload = new ContentObjectType();
NonXMLContentType payloadContent = createMockNonXmlPayload();
if (size != null) {
payloadContent.setSize(size);
}
payload.setNonXMLContent(payloadContent);
return payload;
}
}
| |
package gov.va.escreening.controller.dashboard;
import gov.va.escreening.delegate.CreateAssessmentDelegate;
import gov.va.escreening.domain.AssessmentStatusEnum;
import gov.va.escreening.domain.BatteryDto;
import gov.va.escreening.domain.BatterySurveyDto;
import gov.va.escreening.domain.SurveyDto;
import gov.va.escreening.domain.VeteranDto;
import gov.va.escreening.dto.DropDownObject;
import gov.va.escreening.entity.Program;
import gov.va.escreening.entity.User;
import gov.va.escreening.entity.VeteranAssessment;
import gov.va.escreening.form.EditVeteranAssessmentFormBean;
import gov.va.escreening.repository.UserRepository;
import gov.va.escreening.security.CurrentUser;
import gov.va.escreening.security.EscreenUser;
import gov.va.escreening.service.AssessmentAlreadyExistException;
import gov.va.escreening.service.UserService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller("editVeteranAssessmentController")
@RequestMapping(value = "/dashboard")
public class EditVeteranAssessmentController {
private static final Logger logger = LoggerFactory.getLogger(EditVeteranAssessmentController.class);
@Resource(name = "userDetailsService")
UserDetailsService userDetailsService;
private CreateAssessmentDelegate createAssessmentDelegate;
private UserService userService;
public EditVeteranAssessmentController() {
// Default constructor.
}
@Autowired
public void setCreateAssessmentDelegate(
CreateAssessmentDelegate createAssessmentDelegate) {
this.createAssessmentDelegate = createAssessmentDelegate;
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* Returns the backing bean for the form.
*
* @return
*/
@ModelAttribute
public EditVeteranAssessmentFormBean getEditVeteranAssessmentFormBean() {
logger.trace("Creating new EditVeteranAssessmentFormBean");
return new EditVeteranAssessmentFormBean();
}
/**
* Called when the Create Battery page is opened (new or not)
*
* @param model
* @param editVeteranAssessmentFormBean
* @param veteranAssessmentId
* @param veteranId
* @param escreenUser
* @return
*/
@RequestMapping(value = "/editVeteranAssessment", method = RequestMethod.GET)
public String setupPage(
Model model,
@ModelAttribute EditVeteranAssessmentFormBean editVeteranAssessmentFormBean,
@RequestParam(value = "vaid", required = false) Integer veteranAssessmentId,
@RequestParam(value = "vid", required = false) Integer veteranId,
@RequestParam(value = "clinicianId", required = false) Integer clinicianId,
@RequestParam(value = "clinicId", required = false) Integer clinicId,
@RequestParam(value = "noteTitleId", required = false) Integer noteTitleId,
@RequestParam(value = "programId", required = false) Integer programId,
@CurrentUser EscreenUser escreenUser) {
logger.trace("Using the assessment dashboard mapping");
if (veteranId == null && veteranAssessmentId == null) {
throw new IllegalArgumentException("Both Veteran Assessment ID and Veteran ID are missing.");
}
boolean isCreateMode = false;
boolean isReadOnly = false;
String veteranAssessmentStatus = AssessmentStatusEnum.CLEAN.name();
Date dateCreated = null;
Date dateCompleted = null;
// Determine if we should preselect modules.
if (veteranAssessmentId == null) {
isCreateMode = true;
isReadOnly = false;
veteranAssessmentStatus = StringUtils.capitalize(AssessmentStatusEnum.CLEAN.name().toLowerCase());
}
// 1. Get the veteran assessment
VeteranAssessment veteranAssessment = null;
if (veteranAssessmentId != null) {
veteranAssessment = createAssessmentDelegate.getVeteranAssessmentByVeteranAssessmentId(veteranAssessmentId);
if (veteranAssessment == null) {
throw new IllegalArgumentException("Veteran Assessment is null: " + veteranAssessmentId);
}
isReadOnly = createAssessmentDelegate.isVeteranAssessmentReadOnly(veteranAssessmentId);
veteranAssessmentStatus = veteranAssessment.getAssessmentStatus().getName();
dateCreated = veteranAssessment.getDateCreated();
dateCompleted = veteranAssessment.getDateCompleted();
veteranId = veteranAssessment.getVeteran().getVeteranId();
}
model.addAttribute("isCprsVerified", escreenUser.getCprsVerified());
model.addAttribute("isCreateMode", isCreateMode);
model.addAttribute("isReadOnly", isReadOnly);
model.addAttribute("dateCreated", dateCreated);
model.addAttribute("dateCompleted", dateCompleted);
model.addAttribute("veteranAssessmentStatus", veteranAssessmentStatus);
// Set these properties to be used during postback.
editVeteranAssessmentFormBean.setVeteranAssessmentId(veteranAssessmentId);
editVeteranAssessmentFormBean.setVeteranId(veteranId);
// 2. Get veteran
VeteranDto veteranDto = createAssessmentDelegate.getVeteranFromDatabase(veteranId);
model.addAttribute("veteran", veteranDto);
// 4. Get all programs.
List<DropDownObject> programList = createAssessmentDelegate.getProgramList(escreenUser.getProgramIdList());
model.addAttribute("programList", programList);
// // 5. Get all battery list.
// List<DropDownObject> batteryList = createAssessmentDelegate.getBatteryList();
// model.addAttribute("batteryList", batteryList);
//
// Map<String, String> programsMap = createProgramsMap(batteryList);
// model.addAttribute("programsMap", programsMap);
// 6. Get all battery survey list.
List<BatterySurveyDto> batterySurveyList = createAssessmentDelegate.getBatterySurveyList();
model.addAttribute("batterySurveyList", batterySurveyList);
// 7. Get all the modules (surveys) that can be assigned
List<SurveyDto> surveyList = isCreateMode ? createAssessmentDelegate.getSurveyList() : createAssessmentDelegate.getSurveyListUnionAssessment(veteranAssessmentId);
// 8. Populate survey list with list of batteries it is associated with
// to make it easier in view.
for (BatterySurveyDto batterySurvey : batterySurveyList) {
BatteryDto batteryDto = new BatteryDto(batterySurvey.getBatteryId(), batterySurvey.getBatteryName());
for (SurveyDto survey : surveyList) {
if (survey.getSurveyId().intValue() == batterySurvey.getSurveyId().intValue()) {
if (survey.getBatteryList() == null) {
survey.setBatteryList(new ArrayList<BatteryDto>());
}
survey.getBatteryList().add(batteryDto);
break;
}
}
}
model.addAttribute("surveyList", surveyList);
// 9. Get selected program
if (programId != null || (veteranAssessment != null && veteranAssessment.getProgram() != null)) {
Integer pid = programId != null ? programId : veteranAssessment.getProgram().getProgramId();
editVeteranAssessmentFormBean.setSelectedProgramId(pid);
List<DropDownObject> batteryList = createAssessmentDelegate.getBatteryListByProgram(pid);
model.addAttribute("batteryList", batteryList);
// Get all clinic list since we have a program.
List<DropDownObject> clinicList = createAssessmentDelegate.getClinicList(pid);
model.addAttribute("clinicList", clinicList);
editVeteranAssessmentFormBean.setSelectedClinicId(clinicId);
List<DropDownObject> noteTitleList = createAssessmentDelegate.getNoteTitleList(pid);
model.addAttribute("noteTitleList", noteTitleList);
editVeteranAssessmentFormBean.setSelectedNoteTitleId(noteTitleId);
// Get all clinician list since we have a clinic.
List<DropDownObject> clinicianList = createAssessmentDelegate.getClinicianList(pid);
model.addAttribute("clinicianList", clinicianList);
editVeteranAssessmentFormBean.setSelectedClinicianId(clinicianId);
}
// 10. Get selected clinic
if (veteranAssessment != null && veteranAssessment.getClinic() != null) {
editVeteranAssessmentFormBean.setSelectedClinicId(veteranAssessment.getClinic().getClinicId());
}
// 11. Get selected clinician
if (veteranAssessment != null && veteranAssessment.getClinician() != null) {
editVeteranAssessmentFormBean.setSelectedClinicianId(veteranAssessment.getClinician().getUserId());
}
// 12. Get selected note title
if (veteranAssessment != null && veteranAssessment.getNoteTitle() != null) {
editVeteranAssessmentFormBean.setSelectedNoteTitleId(veteranAssessment.getNoteTitle().getNoteTitleId());
}
// 13. Get selected battery
if (veteranAssessment != null && veteranAssessment.getBattery() != null) {
editVeteranAssessmentFormBean.setSelectedBatteryId(veteranAssessment.getBattery().getBatteryId());
}
// 14. Get the full name of the created by user.
if (veteranAssessment != null && veteranAssessment.getCreatedByUser() != null) {
model.addAttribute("createdByUser", userService.getFullName(veteranAssessment.getCreatedByUser()));
}
// 15. Get all the surveys already assigned to this veteran assessment.
List<SurveyDto> veteranAssessmentSurveyList = null;
if (!isCreateMode) {
veteranAssessmentSurveyList = createAssessmentDelegate.getVeteranAssessmentSurveyList(veteranAssessmentId);
}
if (veteranAssessmentSurveyList != null && veteranAssessmentSurveyList.size() > 0) {
for (SurveyDto survey : veteranAssessmentSurveyList) {
editVeteranAssessmentFormBean.getSelectedSurveyIdList().add(survey.getSurveyId());
}
}
// 14. If the veteran has already been mapped to a VistA record, then we
// can look up clinical reminders for the
// veteran. This will pre-select or auto assign modules (surveys).
// the eScreenUser will be changed from the user who is logged in to the clinician. The Notes will be pulled for the clinician
EscreenUser clinicianUser = clinicianId != null ? findEscreenUser(clinicianId) : escreenUser;
if (clinicianUser.getCprsVerified() && StringUtils.isNotBlank(veteranDto.getVeteranIen())) {
Map<Integer, String> autoAssignedSurveyMap = createAssessmentDelegate.getPreSelectedSurveyMap(clinicianUser, veteranDto.getVeteranIen());
// For each survey, pre-select it and also indicate reason in the
// note.
if (autoAssignedSurveyMap != null && !autoAssignedSurveyMap.isEmpty()) {
for (int i = 0; i < surveyList.size(); ++i) {
Integer surveyId = surveyList.get(i).getSurveyId();
// Preselect it and populate note field.
if (autoAssignedSurveyMap.containsKey(surveyId)) {
// Only auto assign for 'create mode'.
if (isCreateMode) {
if (!editVeteranAssessmentFormBean.getSelectedSurveyIdList().contains(surveyId)) {
editVeteranAssessmentFormBean.getSelectedSurveyIdList().add(surveyId);
}
}
surveyList.get(i).setNote(autoAssignedSurveyMap.get(surveyId));
}
}
}
}
return programId != null ? "dashboard/editVeteranAssessmentTail" : "dashboard/editVeteranAssessment";
}
public EscreenUser findEscreenUser(Integer clinicianId) {
User user = userService.findUser(clinicianId);
return (EscreenUser) userDetailsService.loadUserByUsername(user.getLoginId());
}
private Map<String, String> createProgramsMap(
List<DropDownObject> batteryList) {
Map<String, String> pm = new HashMap<String, String>();
for (DropDownObject b : batteryList) {
List<Program> ps = createAssessmentDelegate.getProgramsForBattery(Integer.parseInt(b.getStateId()));
StringBuilder sb = new StringBuilder();
for (Program p : ps) {
sb.append("program_" + p.getProgramId()).append(" ");
}
pm.put(b.getStateId(), sb.toString());
}
return pm;
}
@RequestMapping(value = "/editVeteranAssessment", method = RequestMethod.POST, params = "saveButton")
public String processPage(
Model model,
@Valid @ModelAttribute EditVeteranAssessmentFormBean editVeteranAssessmentFormBean,
BindingResult result,
// RedirectAttributes redirectAttributes,
@RequestParam(value = "vaid", required = false) Integer veteranAssessmentId,
@RequestParam(value = "vid", required = false) Integer veteranId,
@CurrentUser EscreenUser escreenUser) {
logger.trace(editVeteranAssessmentFormBean.toString());
// First check if the Veteran stated taking the assessment while the
// staff member was trying to edit the data.
if (editVeteranAssessmentFormBean.getSelectedProgramId() != null) {
boolean isReadOnly = createAssessmentDelegate.isVeteranAssessmentReadOnly(editVeteranAssessmentFormBean.getVeteranAssessmentId());
if (isReadOnly) {
result.reject("dashboard.createBattery.nolongereditable", "The veteran has started taking the Battery, and this Battery is no longer editable.");
}
}
// If there is an error, return the same view.
if (result.hasErrors()) {
if (veteranId == null && veteranAssessmentId == null) {
throw new IllegalArgumentException("Both Veteran Assessment ID and Veteran ID are missing.");
}
boolean isCreateMode = false;
boolean isReadOnly = false;
String veteranAssessmentStatus = AssessmentStatusEnum.CLEAN.name();
Date dateCreated = null;
Date dateCompleted = null;
// Determine if we should preselect modules.
if (veteranAssessmentId == null) {
isCreateMode = true;
isReadOnly = false;
veteranAssessmentStatus = StringUtils.capitalize(AssessmentStatusEnum.CLEAN.name().toLowerCase());
}
// 1. Get the veteran assessment
VeteranAssessment veteranAssessment = null;
if (veteranAssessmentId != null) {
veteranAssessment = createAssessmentDelegate.getVeteranAssessmentByVeteranAssessmentId(veteranAssessmentId);
if (veteranAssessment == null) {
throw new IllegalArgumentException("Veteran Assessment is null: " + veteranAssessmentId);
}
isReadOnly = createAssessmentDelegate.isVeteranAssessmentReadOnly(veteranAssessmentId);
veteranAssessmentStatus = veteranAssessment.getAssessmentStatus().getName();
dateCreated = veteranAssessment.getDateCreated();
dateCompleted = veteranAssessment.getDateCompleted();
veteranId = veteranAssessment.getVeteran().getVeteranId();
}
resetPage(model, editVeteranAssessmentFormBean, veteranId,
escreenUser, isCreateMode, isReadOnly,
veteranAssessmentStatus, dateCreated, dateCompleted,
veteranAssessment);
return "dashboard/editVeteranAssessment";
}
if (editVeteranAssessmentFormBean.getVeteranAssessmentId() != null) {
boolean isReadOnly = createAssessmentDelegate.isVeteranAssessmentReadOnly(editVeteranAssessmentFormBean.getVeteranAssessmentId());
if (isReadOnly) {
throw new IllegalArgumentException("Veteran Assessment is in a Read Only state but somehow tried to edit : " + editVeteranAssessmentFormBean.getVeteranAssessmentId());
}
// Edit
createAssessmentDelegate.editVeteranAssessment(escreenUser, editVeteranAssessmentFormBean.getVeteranAssessmentId(), editVeteranAssessmentFormBean.getSelectedProgramId(), editVeteranAssessmentFormBean.getSelectedClinicId(), editVeteranAssessmentFormBean.getSelectedClinicianId(), editVeteranAssessmentFormBean.getSelectedNoteTitleId(), editVeteranAssessmentFormBean.getSelectedBatteryId(), editVeteranAssessmentFormBean.getSelectedSurveyIdList());
model.addAttribute("vid", editVeteranAssessmentFormBean.getVeteranId());
return "redirect:/dashboard/veteranDetail";
} else {
// Add
try {
createAssessmentDelegate.createVeteranAssessment(escreenUser, editVeteranAssessmentFormBean.getVeteranId(), editVeteranAssessmentFormBean.getSelectedProgramId(), editVeteranAssessmentFormBean.getSelectedClinicId(), editVeteranAssessmentFormBean.getSelectedClinicianId(), editVeteranAssessmentFormBean.getSelectedNoteTitleId(), editVeteranAssessmentFormBean.getSelectedBatteryId(), editVeteranAssessmentFormBean.getSelectedSurveyIdList());
model.addAttribute("vid", editVeteranAssessmentFormBean.getVeteranId());
model.addAttribute("ibc", true);
return "redirect:/dashboard/veteranDetail";
} catch (AssessmentAlreadyExistException ex) {
result.reject("dashboard.createBattery.alreadyExist", "The Veteran already has an assessment with this program");
resetPage(model, editVeteranAssessmentFormBean, veteranId, escreenUser, true, false,
StringUtils.capitalize(AssessmentStatusEnum.CLEAN.name().toLowerCase()),
null, null, null);
return "dashboard/editVeteranAssessment";
}
}
}
public void resetPage(Model model,
EditVeteranAssessmentFormBean editVeteranAssessmentFormBean,
Integer veteranId, EscreenUser escreenUser, boolean isCreateMode,
boolean isReadOnly, String veteranAssessmentStatus,
Date dateCreated, Date dateCompleted,
VeteranAssessment veteranAssessment) {
model.addAttribute("isCprsVerified", escreenUser.getCprsVerified());
model.addAttribute("isCreateMode", isCreateMode);
model.addAttribute("isReadOnly", isReadOnly);
model.addAttribute("dateCreated", dateCreated);
model.addAttribute("dateCompleted", dateCompleted);
model.addAttribute("veteranAssessmentStatus", veteranAssessmentStatus);
// Set these properties to be used during postback.
// editVeteranAssessmentFormBean.setVeteranAssessmentId(veteranAssessmentId);
// editVeteranAssessmentFormBean.setVeteranId(veteranId);
// 2. Get veteran
VeteranDto veteranDto = createAssessmentDelegate.getVeteranFromDatabase(veteranId);
model.addAttribute("veteran", veteranDto);
// 4. Get all programs.
List<DropDownObject> programList = createAssessmentDelegate.getProgramList(escreenUser.getProgramIdList());
model.addAttribute("programList", programList);
// 5. Get all battery list.
List<DropDownObject> batteryList = createAssessmentDelegate.getBatteryList();
model.addAttribute("batteryList", batteryList);
Map<String, String> programsMap = createProgramsMap(batteryList);
model.addAttribute("programsMap", programsMap);
// 6. Get all battery survey list.
List<BatterySurveyDto> batterySurveyList = createAssessmentDelegate.getBatterySurveyList();
model.addAttribute("batterySurveyList", batterySurveyList);
// 7. Get all the modules (surveys) that can be assigned
List<SurveyDto> surveyList = createAssessmentDelegate.getSurveyList();
// 8. Populate survey list with list of batteries it is associated
// with to make it easier in view.
for (BatterySurveyDto batterySurvey : batterySurveyList) {
BatteryDto batteryDto = new BatteryDto(batterySurvey.getBatteryId(), batterySurvey.getBatteryName());
for (SurveyDto survey : surveyList) {
if (survey.getSurveyId().intValue() == batterySurvey.getSurveyId().intValue()) {
if (survey.getBatteryList() == null) {
survey.setBatteryList(new ArrayList<BatteryDto>());
}
survey.getBatteryList().add(batteryDto);
break;
}
}
}
model.addAttribute("surveyList", surveyList);
// 9. Get selected program
if (editVeteranAssessmentFormBean.getSelectedProgramId() != null) {
// Get all clinic list since we have a program.
List<DropDownObject> clinicList = createAssessmentDelegate.getClinicList(editVeteranAssessmentFormBean.getSelectedProgramId());
model.addAttribute("clinicList", clinicList);
List<DropDownObject> noteTitleList = createAssessmentDelegate.getNoteTitleList(editVeteranAssessmentFormBean.getSelectedProgramId());
model.addAttribute("noteTitleList", noteTitleList);
// Get all clinician list since we have a clinic.
List<DropDownObject> clinicianList = createAssessmentDelegate.getClinicianList(editVeteranAssessmentFormBean.getSelectedProgramId());
model.addAttribute("clinicianList", clinicianList);
}
// 14. Get the full name of the created by user.
if (veteranAssessment != null && veteranAssessment.getCreatedByUser() != null) {
model.addAttribute("createdByUser", userService.getFullName(veteranAssessment.getCreatedByUser()));
}
// 15. If the veteran has already been mapped to a VistA record,
// then we can look up clinical reminders for
// the veteran. This will pre-select or auto assign modules
// (surveys).
if (escreenUser.getCprsVerified() && StringUtils.isNotBlank(veteranDto.getVeteranIen())) {
Map<Integer, String> autoAssignedSurveyMap = createAssessmentDelegate.getPreSelectedSurveyMap(escreenUser, veteranDto.getVeteranIen());
// For each survey, pre-select it and also indicate reason in
// the note.
if (autoAssignedSurveyMap != null && !autoAssignedSurveyMap.isEmpty()) {
for (int i = 0; i < surveyList.size(); ++i) {
Integer surveyId = surveyList.get(i).getSurveyId();
// Preselect it and populate note field.
if (autoAssignedSurveyMap.containsKey(surveyId)) {
surveyList.get(i).setNote(autoAssignedSurveyMap.get(surveyId));
}
}
}
}
}
@RequestMapping(value = "/editVeteranAssessment", method = RequestMethod.POST, params = "cancelButton")
public String processCancelPage(
Model model,
@ModelAttribute EditVeteranAssessmentFormBean editVeteranAssessmentFormBean,
@CurrentUser EscreenUser escreenUser) {
logger.trace(editVeteranAssessmentFormBean.toString());
model.addAttribute("vid", editVeteranAssessmentFormBean.getVeteranId());
return "redirect:/dashboard/veteranDetail";
}
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2011-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.actions;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.openide.util.NbBundle;
import org.openide.util.actions.Presenter;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.casemodule.services.TagsManager;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.TagName;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* An abstract base class for Actions that allow users to tag SleuthKit data
* model objects.
*/
abstract class AddTagAction extends AbstractAction implements Presenter.Popup {
private static final long serialVersionUID = 1L;
private static final String NO_COMMENT = "";
AddTagAction(String menuText) {
super(menuText);
}
@Override
public JMenuItem getPopupPresenter() {
return new TagMenu();
}
/**
* Subclasses of AddTagAction, should not override actionPerformed, but
* instead override addTag.
*
* @param event
*/
@Override
@SuppressWarnings("NoopMethodInAbstractClass")
public void actionPerformed(ActionEvent event) {
}
/**
* Template method to allow derived classes to provide a string for a menu
* item label.
*/
abstract protected String getActionDisplayName();
/**
* Template method to allow derived classes to add the indicated tag and
* comment to one or more SleuthKit data model objects.
*/
abstract protected void addTag(TagName tagName, String comment);
/**
* Instances of this class implement a context menu user interface for
* creating or selecting a tag name for a tag and specifying an optional tag
* comment.
*/
// @@@ This user interface has some significant usability issues and needs
// to be reworked.
private final class TagMenu extends JMenu {
private static final long serialVersionUID = 1L;
TagMenu() {
super(getActionDisplayName());
// Get the current set of tag names.
Map<String, TagName> tagNamesMap = null;
List<String> standardTagNames = TagsManager.getStandardTagNames();
try {
TagsManager tagsManager = Case.getCurrentCaseThrows().getServices().getTagsManager();
tagNamesMap = new TreeMap<>(tagsManager.getDisplayNamesToTagNamesMap());
} catch (TskCoreException | NoCurrentCaseException ex) {
Logger.getLogger(TagsManager.class.getName()).log(Level.SEVERE, "Failed to get tag names", ex); //NON-NLS
}
// Create a menu item for each of the existing and visible tags.
// Selecting one of these menu items adds a tag with the associated tag name.
List<JMenuItem> standardTagMenuitems = new ArrayList<>();
if (null != tagNamesMap && !tagNamesMap.isEmpty()) {
for (Map.Entry<String, TagName> entry : tagNamesMap.entrySet()) {
String tagDisplayName = entry.getKey();
String notableString = entry.getValue().getKnownStatus() == TskData.FileKnown.BAD ? TagsManager.getNotableTagLabel() : "";
JMenuItem tagNameItem = new JMenuItem(tagDisplayName + notableString);
// for the bookmark tag name only, added shortcut label
if (tagDisplayName.equals(NbBundle.getMessage(AddTagAction.class, "AddBookmarkTagAction.bookmark.text"))) {
tagNameItem.setAccelerator(AddBookmarkTagAction.BOOKMARK_SHORTCUT);
}
tagNameItem.addActionListener((ActionEvent e) -> {
getAndAddTag(entry.getKey(), entry.getValue(), NO_COMMENT);
});
// Show custom tags before predefined tags in the menu
if (standardTagNames.contains(tagDisplayName)) {
standardTagMenuitems.add(tagNameItem);
} else {
add(tagNameItem);
}
}
}
if (getItemCount() > 0) {
addSeparator();
}
standardTagMenuitems.forEach((menuItem) -> {
add(menuItem);
});
addSeparator();
// Create a "Choose Tag and Comment..." menu item. Selecting this item initiates
// a dialog that can be used to create or select a tag name with an
// optional comment and adds a tag with the resulting name.
JMenuItem tagAndCommentItem = new JMenuItem(
NbBundle.getMessage(this.getClass(), "AddTagAction.tagAndComment"));
tagAndCommentItem.addActionListener((ActionEvent e) -> {
GetTagNameAndCommentDialog.TagNameAndComment tagNameAndComment = GetTagNameAndCommentDialog.doDialog();
if (null != tagNameAndComment) {
addTag(tagNameAndComment.getTagName(), tagNameAndComment.getComment());
}
});
add(tagAndCommentItem);
// Create a "New Tag..." menu item.
// Selecting this item initiates a dialog that can be used to create
// or select a tag name and adds a tag with the resulting name.
JMenuItem newTagMenuItem = new JMenuItem(NbBundle.getMessage(this.getClass(), "AddTagAction.newTag"));
newTagMenuItem.addActionListener((ActionEvent e) -> {
TagName tagName = GetTagNameDialog.doDialog();
if (null != tagName) {
addTag(tagName, NO_COMMENT);
}
});
add(newTagMenuItem);
}
/**
* Method to add to the action listener for each menu item. Allows a tag
* display name to be added to the menu with an action listener without
* having to instantiate a TagName object for it. When the method is
* called, the TagName object is created here if it doesn't already
* exist.
*
* @param tagDisplayName display name for the tag name
* @param tagName TagName object associated with the tag name,
* may be null
* @param comment comment for the content or artifact tag
*/
private void getAndAddTag(String tagDisplayName, TagName tagName, String comment) {
Case openCase;
try {
openCase = Case.getCurrentCaseThrows();
} catch (NoCurrentCaseException ex) {
Logger.getLogger(AddTagAction.class.getName()).log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
return;
}
if (tagName == null) {
try {
tagName = openCase.getServices().getTagsManager().addTagName(tagDisplayName);
} catch (TagsManager.TagNameAlreadyExistsException ex) {
try {
tagName = openCase.getServices().getTagsManager().getDisplayNamesToTagNamesMap().get(tagDisplayName);
} catch (TskCoreException ex1) {
Logger.getLogger(AddTagAction.class.getName()).log(Level.SEVERE, tagDisplayName + " already exists in database but an error occurred in retrieving it.", ex1); //NON-NLS
}
} catch (TskCoreException ex) {
Logger.getLogger(AddTagAction.class.getName()).log(Level.SEVERE, "Error adding " + tagDisplayName + " tag name", ex); //NON-NLS
}
}
addTag(tagName, comment);
}
}
}
| |
/**
* Copyright 2013 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.bitcoinj.core;
import com.google.common.util.concurrent.*;
import org.bitcoinj.params.*;
import org.bitcoinj.testing.*;
import org.bitcoinj.utils.*;
import org.junit.*;
import org.junit.runner.*;
import org.junit.runners.*;
import java.util.*;
import java.util.concurrent.*;
import static com.google.common.base.Preconditions.*;
import static org.bitcoinj.core.Coin.*;
import static org.junit.Assert.*;
@RunWith(value = Parameterized.class)
public class TransactionBroadcastTest extends TestWithPeerGroup {
@Parameterized.Parameters
public static Collection<ClientType[]> parameters() {
return Arrays.asList(new ClientType[] {ClientType.NIO_CLIENT_MANAGER},
new ClientType[] {ClientType.BLOCKING_CLIENT_MANAGER});
}
public TransactionBroadcastTest(ClientType clientType) {
super(clientType);
}
@Override
@Before
public void setUp() throws Exception {
Utils.setMockClock(); // Use mock clock
super.setUp();
// Fix the random permutation that TransactionBroadcast uses to shuffle the peers.
TransactionBroadcast.random = new Random(0);
peerGroup.setMinBroadcastConnections(2);
peerGroup.start();
}
@Override
@After
public void tearDown() {
super.tearDown();
}
@Test
public void fourPeers() throws Exception {
InboundMessageQueuer[] channels = { connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) };
Transaction tx = new Transaction(params);
tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
TransactionBroadcast broadcast = new TransactionBroadcast(peerGroup, tx);
final AtomicDouble lastProgress = new AtomicDouble();
broadcast.setProgressCallback(new TransactionBroadcast.ProgressCallback() {
@Override
public void onBroadcastProgress(double progress) {
lastProgress.set(progress);
}
});
ListenableFuture<Transaction> future = broadcast.broadcast();
assertFalse(future.isDone());
assertEquals(0.0, lastProgress.get(), 0.0);
// We expect two peers to receive a tx message, and at least one of the others must announce for the future to
// complete successfully.
Message[] messages = {
outbound(channels[0]),
outbound(channels[1]),
outbound(channels[2]),
outbound(channels[3])
};
// 0 and 3 are randomly selected to receive the broadcast.
assertEquals(tx, messages[0]);
assertEquals(tx, messages[3]);
assertNull(messages[1]);
assertNull(messages[2]);
Threading.waitForUserCode();
assertFalse(future.isDone());
assertEquals(0.0, lastProgress.get(), 0.0);
inbound(channels[1], InventoryMessage.with(tx));
future.get();
Threading.waitForUserCode();
assertEquals(1.0, lastProgress.get(), 0.0);
// There is no response from the Peer as it has nothing to do.
assertNull(outbound(channels[1]));
}
@Test
public void lateProgressCallback() throws Exception {
// Check that if we register a progress callback on a broadcast after the broadcast has started, it's invoked
// immediately with the latest state. This avoids API users writing accidentally racy code when they use
// a convenience method like peerGroup.broadcastTransaction.
InboundMessageQueuer[] channels = { connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) };
Transaction tx = FakeTxBuilder.createFakeTx(params, CENT, UnitTestParams.TEST_ADDRESS);
tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
TransactionBroadcast broadcast = peerGroup.broadcastTransaction(tx);
inbound(channels[1], InventoryMessage.with(tx));
pingAndWait(channels[1]);
final AtomicDouble p = new AtomicDouble();
broadcast.setProgressCallback(new TransactionBroadcast.ProgressCallback() {
@Override
public void onBroadcastProgress(double progress) {
p.set(progress);
}
}, Threading.SAME_THREAD);
assertEquals(1.0, p.get(), 0.01);
}
@Test
public void rejectHandling() throws Exception {
InboundMessageQueuer[] channels = { connectPeer(0), connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) };
Transaction tx = new Transaction(params);
TransactionBroadcast broadcast = new TransactionBroadcast(peerGroup, tx);
ListenableFuture<Transaction> future = broadcast.broadcast();
// 0 and 3 are randomly selected to receive the broadcast.
assertEquals(tx, outbound(channels[1]));
assertEquals(tx, outbound(channels[2]));
assertEquals(tx, outbound(channels[4]));
RejectMessage reject = new RejectMessage(params, RejectMessage.RejectCode.DUST, tx.getHash(), "tx", "dust");
inbound(channels[1], reject);
inbound(channels[4], reject);
try {
future.get();
fail();
} catch (ExecutionException e) {
assertEquals(RejectedTransactionException.class, e.getCause().getClass());
}
}
@Test
public void retryFailedBroadcast() throws Exception {
// If we create a spend, it's sent to a peer that swallows it, and the peergroup is removed/re-added then
// the tx should be broadcast again.
InboundMessageQueuer p1 = connectPeer(1);
connectPeer(2);
// Send ourselves a bit of money.
Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address);
inbound(p1, b1);
assertNull(outbound(p1));
assertEquals(FIFTY_COINS, wallet.getBalance());
// Now create a spend, and expect the announcement on p1.
Address dest = new ECKey().toAddress(params);
Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
assertFalse(sendResult.broadcastComplete.isDone());
Transaction t1;
{
Message m;
while (!((m = outbound(p1)) instanceof Transaction));
t1 = (Transaction) m;
}
assertFalse(sendResult.broadcastComplete.isDone());
// p1 eats it :( A bit later the PeerGroup is taken down.
peerGroup.removeWallet(wallet);
peerGroup.addWallet(wallet);
// We want to hear about it again. Now, because we've disabled the randomness for the unit tests it will
// re-appear on p1 again. Of course in the real world it would end up with a different set of peers and
// select randomly so we get a second chance.
Transaction t2 = (Transaction) outbound(p1);
assertEquals(t1, t2);
}
@Test
public void peerGroupWalletIntegration() throws Exception {
// Make sure we can create spends, and that they are announced. Then do the same with offline mode.
// Set up connections and block chain.
VersionMessage ver = new VersionMessage(params, 2);
ver.localServices = VersionMessage.NODE_NETWORK;
InboundMessageQueuer p1 = connectPeer(1, ver);
InboundMessageQueuer p2 = connectPeer(2);
// Send ourselves a bit of money.
Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address);
inbound(p1, b1);
pingAndWait(p1);
assertNull(outbound(p1));
assertEquals(FIFTY_COINS, wallet.getBalance());
// Check that the wallet informs us of changes in confidence as the transaction ripples across the network.
final Transaction[] transactions = new Transaction[1];
wallet.addEventListener(new AbstractWalletEventListener() {
@Override
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) {
transactions[0] = tx;
}
});
// Now create a spend, and expect the announcement on p1.
Address dest = new ECKey().toAddress(params);
Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
assertNotNull(sendResult.tx);
Threading.waitForUserCode();
assertFalse(sendResult.broadcastComplete.isDone());
assertEquals(transactions[0], sendResult.tx);
assertEquals(0, transactions[0].getConfidence().numBroadcastPeers());
transactions[0] = null;
Transaction t1;
{
peerGroup.waitForJobQueue();
Message m = outbound(p1);
// Hack: bloom filters are recalculated asynchronously to sending transactions to avoid lock
// inversion, so we might or might not get the filter/mempool message first or second.
while (!(m instanceof Transaction)) m = outbound(p1);
t1 = (Transaction) m;
}
assertNotNull(t1);
// 49 BTC in change.
assertEquals(valueOf(49, 0), t1.getValueSentToMe(wallet));
// The future won't complete until it's heard back from the network on p2.
InventoryMessage inv = new InventoryMessage(params);
inv.addTransaction(t1);
inbound(p2, inv);
pingAndWait(p2);
Threading.waitForUserCode();
assertTrue(sendResult.broadcastComplete.isDone());
assertEquals(transactions[0], sendResult.tx);
assertEquals(1, transactions[0].getConfidence().numBroadcastPeers());
// Confirm it.
Block b2 = FakeTxBuilder.createFakeBlock(blockStore, t1).block;
inbound(p1, b2);
pingAndWait(p1);
assertNull(outbound(p1));
// Do the same thing with an offline transaction.
peerGroup.removeWallet(wallet);
Wallet.SendRequest req = Wallet.SendRequest.to(dest, valueOf(2, 0));
req.ensureMinRequiredFee = false;
Transaction t3 = checkNotNull(wallet.sendCoinsOffline(req));
assertNull(outbound(p1)); // Nothing sent.
// Add the wallet to the peer group (simulate initialization). Transactions should be announced.
peerGroup.addWallet(wallet);
// Transaction announced to the first peer. No extra Bloom filter because no change address was needed.
assertEquals(t3.getHash(), outbound(p1).getHash());
}
}
| |
package com.cratorsoft.android.frag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.cratorsoft.android.aamain.BuildManager;
import com.cratorsoft.android.aamain.Fargs;
import com.cratorsoft.android.adapter.TTSEngineAdapter;
import com.cratorsoft.android.dialog.DlgInfo;
import com.cratorsoft.android.dialog.DlgTTSEngine;
import com.cratorsoft.android.taskmanager.BUSY;
import com.cratorsoft.android.taskmanager.BusyAsyncTask;
import com.cratorsoft.android.taskmanager.BusyTaskFragment;
import com.cratorsoft.android.ttslanguage.TTSEngine;
import com.earthflare.android.ircradio.Globo;
import com.earthflare.android.ircradio.NavItem;
import com.earthflare.android.ircradio.R;
import com.earthflare.android.notifications.ListNoticeAdapter;
import com.earthflare.android.notifications.Notice;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.lang.ref.WeakReference;
@EFragment
public class FragListTTSEngines extends BusyTaskFragment implements AdapterView.OnItemClickListener {
int mBusyStyle = BUSY.NONMODAL_CONTENT;
private boolean mInitialized = false;
// Misc
// Data
// Views
@ViewById(R.id.noticeListView)
ListView vListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.parseIntent();
loadRefreshDataTask();
loadCreateDataTask();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_listttsengines, container, false);
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
configFrag();
}
@Override
public void onStart() {
super.onStart();
// views bound
}
@Override
public void onResume() {
setTitle();
if (mInitialized) {
loadRefreshDataTask();
}
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (mInitialized) {
stashData();
}
}
// ======================== Fragment Data Lifecycle ====
public void parseIntent(){
}
private void configViews() {
vListView.setOnItemClickListener(this);
}
private void configFrag() {
}
private void stashData() {
}
private void unstashData() {
attachAdapters();
}
private void initAllData() {
attachAdapters();
}
// ======================== Fragment Functions =====
private void setTitle(){
getDrawerDisplayer().setFragTitle(getString(R.string.label_tts), "");
}
// ======================== Fragment Actions =====
// ======================== Fragment Background Tasks =====
public void loadCreateDataTask() {
new BusyAsyncTask<Boolean>(this, mBusyStyle, true) {
protected Boolean doInBackground() {
try {
return true;
} catch (Exception e) {
e.printStackTrace();
BuildManager.INSTANCE.sendCaughtException(e);
return false;
}
}
@Override
protected void onPostExecute(Boolean success) {
if (success) {
// set data vars
initAllData();
configViews();
mInitialized = true;
} else {
abort("DB Error");
}
}
}.execute();
}
public void loadRefreshDataTask() {
cleanupRefreshDBConnections();
new BusyAsyncTask<Boolean>(this, mBusyStyle, true) {
protected Boolean doInBackground() {
try {
return true;
} catch (Exception e) {
e.printStackTrace();
BuildManager.INSTANCE.sendCaughtException(e);
return false;
}
}
@Override
protected void onPostExecute(Boolean success) {
if (success) {
// set data vars
if (mInitialized) {
unstashData();
configViews();
}
} else {
abort("DB Error");
}
}
}.execute();
}
// ======================== Fragment Attach/Populate =====
public void attachAdapters() {
TTSEngineAdapter.Adapter adapter = TTSEngineAdapter.INSTANCE.getAdapter(this.getActivity());
vListView.setAdapter(adapter);
}
//========================= Stash Data =====================
//========================= Fragment Listeners ====================
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TTSEngine engine = (TTSEngine) arg0.getAdapter().getItem(arg2);
DlgTTSEngine dialog = DlgTTSEngine.newInstance(engine);
dialog.show(this.getFragmentManager(), "dialogtts");
}
}
| |
package com.karcompany.models;
/**
* Created by pvkarthik on 2016-12-12.
*
* Generic class (JSON Pojo).
* A Pojo which represents data received from server.
*/
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UserMetaData {
@SerializedName("login")
@Expose
private String login;
@SerializedName("id")
@Expose
private Long id;
@SerializedName("avatar_url")
@Expose
private String avatarUrl;
@SerializedName("gravatar_id")
@Expose
private String gravatarId;
@SerializedName("url")
@Expose
private String url;
@SerializedName("html_url")
@Expose
private String htmlUrl;
@SerializedName("followers_url")
@Expose
private String followersUrl;
@SerializedName("following_url")
@Expose
private String followingUrl;
@SerializedName("gists_url")
@Expose
private String gistsUrl;
@SerializedName("starred_url")
@Expose
private String starredUrl;
@SerializedName("subscriptions_url")
@Expose
private String subscriptionsUrl;
@SerializedName("organizations_url")
@Expose
private String organizationsUrl;
@SerializedName("repos_url")
@Expose
private String reposUrl;
@SerializedName("events_url")
@Expose
private String eventsUrl;
@SerializedName("received_events_url")
@Expose
private String receivedEventsUrl;
@SerializedName("type")
@Expose
private String type;
@SerializedName("site_admin")
@Expose
private Boolean siteAdmin;
/**
*
* @return
* The login
*/
public String getLogin() {
return login;
}
/**
*
* @param login
* The login
*/
public void setLogin(String login) {
this.login = login;
}
/**
*
* @return
* The id
*/
public Long getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Long id) {
this.id = id;
}
/**
*
* @return
* The avatarUrl
*/
public String getAvatarUrl() {
return avatarUrl;
}
/**
*
* @param avatarUrl
* The avatar_url
*/
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
/**
*
* @return
* The gravatarId
*/
public String getGravatarId() {
return gravatarId;
}
/**
*
* @param gravatarId
* The gravatar_id
*/
public void setGravatarId(String gravatarId) {
this.gravatarId = gravatarId;
}
/**
*
* @return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* @return
* The htmlUrl
*/
public String getHtmlUrl() {
return htmlUrl;
}
/**
*
* @param htmlUrl
* The html_url
*/
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
/**
*
* @return
* The followersUrl
*/
public String getFollowersUrl() {
return followersUrl;
}
/**
*
* @param followersUrl
* The followers_url
*/
public void setFollowersUrl(String followersUrl) {
this.followersUrl = followersUrl;
}
/**
*
* @return
* The followingUrl
*/
public String getFollowingUrl() {
return followingUrl;
}
/**
*
* @param followingUrl
* The following_url
*/
public void setFollowingUrl(String followingUrl) {
this.followingUrl = followingUrl;
}
/**
*
* @return
* The gistsUrl
*/
public String getGistsUrl() {
return gistsUrl;
}
/**
*
* @param gistsUrl
* The gists_url
*/
public void setGistsUrl(String gistsUrl) {
this.gistsUrl = gistsUrl;
}
/**
*
* @return
* The starredUrl
*/
public String getStarredUrl() {
return starredUrl;
}
/**
*
* @param starredUrl
* The starred_url
*/
public void setStarredUrl(String starredUrl) {
this.starredUrl = starredUrl;
}
/**
*
* @return
* The subscriptionsUrl
*/
public String getSubscriptionsUrl() {
return subscriptionsUrl;
}
/**
*
* @param subscriptionsUrl
* The subscriptions_url
*/
public void setSubscriptionsUrl(String subscriptionsUrl) {
this.subscriptionsUrl = subscriptionsUrl;
}
/**
*
* @return
* The organizationsUrl
*/
public String getOrganizationsUrl() {
return organizationsUrl;
}
/**
*
* @param organizationsUrl
* The organizations_url
*/
public void setOrganizationsUrl(String organizationsUrl) {
this.organizationsUrl = organizationsUrl;
}
/**
*
* @return
* The reposUrl
*/
public String getReposUrl() {
return reposUrl;
}
/**
*
* @param reposUrl
* The repos_url
*/
public void setReposUrl(String reposUrl) {
this.reposUrl = reposUrl;
}
/**
*
* @return
* The eventsUrl
*/
public String getEventsUrl() {
return eventsUrl;
}
/**
*
* @param eventsUrl
* The events_url
*/
public void setEventsUrl(String eventsUrl) {
this.eventsUrl = eventsUrl;
}
/**
*
* @return
* The receivedEventsUrl
*/
public String getReceivedEventsUrl() {
return receivedEventsUrl;
}
/**
*
* @param receivedEventsUrl
* The received_events_url
*/
public void setReceivedEventsUrl(String receivedEventsUrl) {
this.receivedEventsUrl = receivedEventsUrl;
}
/**
*
* @return
* The type
*/
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* @return
* The siteAdmin
*/
public Boolean getSiteAdmin() {
return siteAdmin;
}
/**
*
* @param siteAdmin
* The site_admin
*/
public void setSiteAdmin(Boolean siteAdmin) {
this.siteAdmin = siteAdmin;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.io.network.partition.consumer;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.metrics.Counter;
import org.apache.flink.runtime.checkpoint.CheckpointException;
import org.apache.flink.runtime.checkpoint.CheckpointFailureReason;
import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter;
import org.apache.flink.runtime.event.AbstractEvent;
import org.apache.flink.runtime.event.TaskEvent;
import org.apache.flink.runtime.execution.CancelTaskException;
import org.apache.flink.runtime.io.network.ConnectionID;
import org.apache.flink.runtime.io.network.ConnectionManager;
import org.apache.flink.runtime.io.network.PartitionRequestClient;
import org.apache.flink.runtime.io.network.api.CheckpointBarrier;
import org.apache.flink.runtime.io.network.api.EventAnnouncement;
import org.apache.flink.runtime.io.network.api.serialization.EventSerializer;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.io.network.buffer.Buffer.DataType;
import org.apache.flink.runtime.io.network.buffer.BufferProvider;
import org.apache.flink.runtime.io.network.partition.PartitionNotFoundException;
import org.apache.flink.runtime.io.network.partition.PrioritizedDeque;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.shaded.guava18.com.google.common.collect.Iterators;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/** An input channel, which requests a remote partition queue. */
public class RemoteInputChannel extends InputChannel {
private static final int NONE = -1;
/** ID to distinguish this channel from other channels sharing the same TCP connection. */
private final InputChannelID id = new InputChannelID();
/** The connection to use to request the remote partition. */
private final ConnectionID connectionId;
/** The connection manager to use connect to the remote partition provider. */
private final ConnectionManager connectionManager;
/**
* The received buffers. Received buffers are enqueued by the network I/O thread and the queue
* is consumed by the receiving task thread.
*/
private final PrioritizedDeque<SequenceBuffer> receivedBuffers = new PrioritizedDeque<>();
/**
* Flag indicating whether this channel has been released. Either called by the receiving task
* thread or the task manager actor.
*/
private final AtomicBoolean isReleased = new AtomicBoolean();
/** Client to establish a (possibly shared) TCP connection and request the partition. */
private volatile PartitionRequestClient partitionRequestClient;
/** The next expected sequence number for the next buffer. */
private int expectedSequenceNumber = 0;
/** The initial number of exclusive buffers assigned to this channel. */
private final int initialCredit;
/** The number of available buffers that have not been announced to the producer yet. */
private final AtomicInteger unannouncedCredit = new AtomicInteger(0);
private final BufferManager bufferManager;
@GuardedBy("receivedBuffers")
private int lastBarrierSequenceNumber = NONE;
@GuardedBy("receivedBuffers")
private long lastBarrierId = NONE;
private final ChannelStatePersister channelStatePersister;
public RemoteInputChannel(
SingleInputGate inputGate,
int channelIndex,
ResultPartitionID partitionId,
ConnectionID connectionId,
ConnectionManager connectionManager,
int initialBackOff,
int maxBackoff,
int networkBuffersPerChannel,
Counter numBytesIn,
Counter numBuffersIn,
ChannelStateWriter stateWriter) {
super(
inputGate,
channelIndex,
partitionId,
initialBackOff,
maxBackoff,
numBytesIn,
numBuffersIn);
this.initialCredit = networkBuffersPerChannel;
this.connectionId = checkNotNull(connectionId);
this.connectionManager = checkNotNull(connectionManager);
this.bufferManager = new BufferManager(inputGate.getMemorySegmentProvider(), this, 0);
this.channelStatePersister = new ChannelStatePersister(stateWriter, getChannelInfo());
}
@VisibleForTesting
void setExpectedSequenceNumber(int expectedSequenceNumber) {
this.expectedSequenceNumber = expectedSequenceNumber;
}
/**
* Setup includes assigning exclusive buffers to this input channel, and this method should be
* called only once after this input channel is created.
*/
@Override
void setup() throws IOException {
checkState(
bufferManager.unsynchronizedGetAvailableExclusiveBuffers() == 0,
"Bug in input channel setup logic: exclusive buffers have already been set for this input channel.");
bufferManager.requestExclusiveBuffers(initialCredit);
}
// ------------------------------------------------------------------------
// Consume
// ------------------------------------------------------------------------
/** Requests a remote subpartition. */
@VisibleForTesting
@Override
public void requestSubpartition(int subpartitionIndex)
throws IOException, InterruptedException {
if (partitionRequestClient == null) {
// Create a client and request the partition
try {
partitionRequestClient =
connectionManager.createPartitionRequestClient(connectionId);
} catch (IOException e) {
// IOExceptions indicate that we could not open a connection to the remote
// TaskExecutor
throw new PartitionConnectionException(partitionId, e);
}
partitionRequestClient.requestSubpartition(partitionId, subpartitionIndex, this, 0);
}
}
/** Retriggers a remote subpartition request. */
void retriggerSubpartitionRequest(int subpartitionIndex) throws IOException {
checkPartitionRequestQueueInitialized();
if (increaseBackoff()) {
partitionRequestClient.requestSubpartition(
partitionId, subpartitionIndex, this, getCurrentBackoff());
} else {
failPartitionRequest();
}
}
@Override
Optional<BufferAndAvailability> getNextBuffer() throws IOException {
checkPartitionRequestQueueInitialized();
final SequenceBuffer next;
final DataType nextDataType;
synchronized (receivedBuffers) {
next = receivedBuffers.poll();
nextDataType =
receivedBuffers.peek() != null
? receivedBuffers.peek().buffer.getDataType()
: DataType.NONE;
}
if (next == null) {
if (isReleased.get()) {
throw new CancelTaskException(
"Queried for a buffer after channel has been released.");
}
return Optional.empty();
}
numBytesIn.inc(next.buffer.getSize());
numBuffersIn.inc();
return Optional.of(
new BufferAndAvailability(next.buffer, nextDataType, 0, next.sequenceNumber));
}
// ------------------------------------------------------------------------
// Task events
// ------------------------------------------------------------------------
@Override
void sendTaskEvent(TaskEvent event) throws IOException {
checkState(
!isReleased.get(),
"Tried to send task event to producer after channel has been released.");
checkPartitionRequestQueueInitialized();
partitionRequestClient.sendTaskEvent(partitionId, event, this);
}
// ------------------------------------------------------------------------
// Life cycle
// ------------------------------------------------------------------------
@Override
public boolean isReleased() {
return isReleased.get();
}
/** Releases all exclusive and floating buffers, closes the partition request client. */
@Override
void releaseAllResources() throws IOException {
if (isReleased.compareAndSet(false, true)) {
final ArrayDeque<Buffer> releasedBuffers;
synchronized (receivedBuffers) {
releasedBuffers =
receivedBuffers.stream()
.map(sb -> sb.buffer)
.collect(Collectors.toCollection(ArrayDeque::new));
receivedBuffers.clear();
}
bufferManager.releaseAllBuffers(releasedBuffers);
// The released flag has to be set before closing the connection to ensure that
// buffers received concurrently with closing are properly recycled.
if (partitionRequestClient != null) {
partitionRequestClient.close(this);
} else {
connectionManager.closeOpenChannelConnections(connectionId);
}
}
}
private void failPartitionRequest() {
setError(new PartitionNotFoundException(partitionId));
}
@Override
public String toString() {
return "RemoteInputChannel [" + partitionId + " at " + connectionId + "]";
}
// ------------------------------------------------------------------------
// Credit-based
// ------------------------------------------------------------------------
/**
* Enqueue this input channel in the pipeline for notifying the producer of unannounced credit.
*/
private void notifyCreditAvailable() throws IOException {
checkPartitionRequestQueueInitialized();
partitionRequestClient.notifyCreditAvailable(this);
}
@VisibleForTesting
public int getNumberOfAvailableBuffers() {
return bufferManager.getNumberOfAvailableBuffers();
}
@VisibleForTesting
public int getNumberOfRequiredBuffers() {
return bufferManager.unsynchronizedGetNumberOfRequiredBuffers();
}
@VisibleForTesting
public int getSenderBacklog() {
return getNumberOfRequiredBuffers() - initialCredit;
}
@VisibleForTesting
boolean isWaitingForFloatingBuffers() {
return bufferManager.unsynchronizedIsWaitingForFloatingBuffers();
}
@VisibleForTesting
public Buffer getNextReceivedBuffer() {
final SequenceBuffer sequenceBuffer = receivedBuffers.poll();
return sequenceBuffer != null ? sequenceBuffer.buffer : null;
}
@VisibleForTesting
BufferManager getBufferManager() {
return bufferManager;
}
@VisibleForTesting
PartitionRequestClient getPartitionRequestClient() {
return partitionRequestClient;
}
/**
* The unannounced credit is increased by the given amount and might notify increased credit to
* the producer.
*/
@Override
public void notifyBufferAvailable(int numAvailableBuffers) throws IOException {
if (numAvailableBuffers > 0 && unannouncedCredit.getAndAdd(numAvailableBuffers) == 0) {
notifyCreditAvailable();
}
}
@Override
public void resumeConsumption() throws IOException {
checkState(!isReleased.get(), "Channel released.");
checkPartitionRequestQueueInitialized();
// notifies the producer that this channel is ready to
// unblock from checkpoint and resume data consumption
partitionRequestClient.resumeConsumption(this);
}
// ------------------------------------------------------------------------
// Network I/O notifications (called by network I/O thread)
// ------------------------------------------------------------------------
/**
* Gets the currently unannounced credit.
*
* @return Credit which was not announced to the sender yet.
*/
public int getUnannouncedCredit() {
return unannouncedCredit.get();
}
/**
* Gets the unannounced credit and resets it to <tt>0</tt> atomically.
*
* @return Credit which was not announced to the sender yet.
*/
public int getAndResetUnannouncedCredit() {
return unannouncedCredit.getAndSet(0);
}
/**
* Gets the current number of received buffers which have not been processed yet.
*
* @return Buffers queued for processing.
*/
public int getNumberOfQueuedBuffers() {
synchronized (receivedBuffers) {
return receivedBuffers.size();
}
}
@Override
public int unsynchronizedGetNumberOfQueuedBuffers() {
return Math.max(0, receivedBuffers.size());
}
public int unsynchronizedGetExclusiveBuffersUsed() {
return Math.max(
0, initialCredit - bufferManager.unsynchronizedGetAvailableExclusiveBuffers());
}
public int unsynchronizedGetFloatingBuffersAvailable() {
return Math.max(0, bufferManager.unsynchronizedGetFloatingBuffersAvailable());
}
public InputChannelID getInputChannelId() {
return id;
}
public int getInitialCredit() {
return initialCredit;
}
public BufferProvider getBufferProvider() throws IOException {
if (isReleased.get()) {
return null;
}
return inputGate.getBufferProvider();
}
/**
* Requests buffer from input channel directly for receiving network data. It should always
* return an available buffer in credit-based mode unless the channel has been released.
*
* @return The available buffer.
*/
@Nullable
public Buffer requestBuffer() {
return bufferManager.requestBuffer();
}
/**
* Receives the backlog from the producer's buffer response. If the number of available buffers
* is less than backlog + initialCredit, it will request floating buffers from the buffer
* manager, and then notify unannounced credits to the producer.
*
* @param backlog The number of unsent buffers in the producer's sub partition.
*/
void onSenderBacklog(int backlog) throws IOException {
int numRequestedBuffers = bufferManager.requestFloatingBuffers(backlog + initialCredit);
if (numRequestedBuffers > 0 && unannouncedCredit.getAndAdd(numRequestedBuffers) == 0) {
notifyCreditAvailable();
}
}
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog) throws IOException {
boolean recycleBuffer = true;
try {
if (expectedSequenceNumber != sequenceNumber) {
onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber));
return;
}
final boolean wasEmpty;
boolean firstPriorityEvent = false;
synchronized (receivedBuffers) {
// Similar to notifyBufferAvailable(), make sure that we never add a buffer
// after releaseAllResources() released all buffers from receivedBuffers
// (see above for details).
if (isReleased.get()) {
return;
}
wasEmpty = receivedBuffers.isEmpty();
SequenceBuffer sequenceBuffer = new SequenceBuffer(buffer, sequenceNumber);
DataType dataType = buffer.getDataType();
if (dataType.hasPriority()) {
firstPriorityEvent = addPriorityBuffer(sequenceBuffer);
} else {
receivedBuffers.add(sequenceBuffer);
if (dataType.requiresAnnouncement()) {
firstPriorityEvent = addPriorityBuffer(announce(sequenceBuffer));
}
}
channelStatePersister
.checkForBarrier(sequenceBuffer.buffer)
.filter(id -> id > lastBarrierId)
.ifPresent(
id -> {
// checkpoint was not yet started by task thread,
// so remember the numbers of buffers to spill for the time when
// it will be started
lastBarrierId = id;
lastBarrierSequenceNumber = sequenceBuffer.sequenceNumber;
});
channelStatePersister.maybePersist(buffer);
++expectedSequenceNumber;
}
recycleBuffer = false;
if (firstPriorityEvent) {
notifyPriorityEvent(sequenceNumber);
}
if (wasEmpty) {
notifyChannelNonEmpty();
}
if (backlog >= 0) {
onSenderBacklog(backlog);
}
} finally {
if (recycleBuffer) {
buffer.recycleBuffer();
}
}
}
/** @return {@code true} if this was first priority buffer added. */
private boolean addPriorityBuffer(SequenceBuffer sequenceBuffer) {
receivedBuffers.addPriorityElement(sequenceBuffer);
return receivedBuffers.getNumPriorityElements() == 1;
}
private SequenceBuffer announce(SequenceBuffer sequenceBuffer) throws IOException {
checkState(
!sequenceBuffer.buffer.isBuffer(),
"Only a CheckpointBarrier can be announced but found %s",
sequenceBuffer.buffer);
checkAnnouncedOnlyOnce(sequenceBuffer);
AbstractEvent event =
EventSerializer.fromBuffer(sequenceBuffer.buffer, getClass().getClassLoader());
checkState(
event instanceof CheckpointBarrier,
"Only a CheckpointBarrier can be announced but found %s",
sequenceBuffer.buffer);
CheckpointBarrier barrier = (CheckpointBarrier) event;
return new SequenceBuffer(
EventSerializer.toBuffer(
new EventAnnouncement(barrier, sequenceBuffer.sequenceNumber), true),
sequenceBuffer.sequenceNumber);
}
private void checkAnnouncedOnlyOnce(SequenceBuffer sequenceBuffer) {
Iterator<SequenceBuffer> iterator = receivedBuffers.iterator();
int count = 0;
while (iterator.hasNext()) {
if (iterator.next().sequenceNumber == sequenceBuffer.sequenceNumber) {
count++;
}
}
checkState(
count == 1,
"Before enqueuing the announcement there should be exactly single occurrence of the buffer, but found [%d]",
count);
}
/**
* Spills all queued buffers on checkpoint start. If barrier has already been received (and
* reordered), spill only the overtaken buffers.
*/
public void checkpointStarted(CheckpointBarrier barrier) throws CheckpointException {
synchronized (receivedBuffers) {
channelStatePersister.startPersisting(
barrier.getId(), getInflightBuffersUnsafe(barrier.getId()));
}
}
public void checkpointStopped(long checkpointId) {
synchronized (receivedBuffers) {
channelStatePersister.stopPersisting(checkpointId);
if (lastBarrierId == checkpointId) {
lastBarrierId = NONE;
lastBarrierSequenceNumber = NONE;
}
}
}
@VisibleForTesting
List<Buffer> getInflightBuffers(long checkpointId) throws CheckpointException {
synchronized (receivedBuffers) {
return getInflightBuffersUnsafe(checkpointId);
}
}
@Override
public void convertToPriorityEvent(int sequenceNumber) throws IOException {
boolean firstPriorityEvent;
synchronized (receivedBuffers) {
checkState(channelStatePersister.hasBarrierReceived());
int numPriorityElementsBeforeRemoval = receivedBuffers.getNumPriorityElements();
SequenceBuffer toPrioritize =
receivedBuffers.getAndRemove(
sequenceBuffer -> sequenceBuffer.sequenceNumber == sequenceNumber);
checkState(lastBarrierSequenceNumber == sequenceNumber);
checkState(!toPrioritize.buffer.isBuffer());
checkState(
numPriorityElementsBeforeRemoval == receivedBuffers.getNumPriorityElements(),
"Attempted to convertToPriorityEvent an event [%s] that has already been prioritized [%s]",
toPrioritize,
numPriorityElementsBeforeRemoval);
// set the priority flag (checked on poll)
// don't convert the barrier itself (barrier controller might not have been switched
// yet)
AbstractEvent e =
EventSerializer.fromBuffer(
toPrioritize.buffer, this.getClass().getClassLoader());
toPrioritize.buffer.setReaderIndex(0);
toPrioritize =
new SequenceBuffer(
EventSerializer.toBuffer(e, true), toPrioritize.sequenceNumber);
firstPriorityEvent =
addPriorityBuffer(
toPrioritize); // note that only position of the element is changed
// converting the event itself would require switching the controller sooner
}
if (firstPriorityEvent) {
notifyPriorityEventForce(); // forcibly notify about the priority event
// instead of passing barrier SQN to be checked
// because this SQN might have be seen by the input gate during the announcement
}
}
private void notifyPriorityEventForce() {
inputGate.notifyPriorityEventForce(this);
}
/**
* Returns a list of buffers, checking the first n non-priority buffers, and skipping all
* events.
*/
private List<Buffer> getInflightBuffersUnsafe(long checkpointId) throws CheckpointException {
assert Thread.holdsLock(receivedBuffers);
if (checkpointId < lastBarrierId) {
throw new CheckpointException(
String.format(
"Sequence number for checkpoint %d is not known (it was likely been overwritten by a newer checkpoint %d)",
checkpointId, lastBarrierId),
CheckpointFailureReason
.CHECKPOINT_SUBSUMED); // currently, at most one active unaligned
// checkpoint is possible
}
final List<Buffer> inflightBuffers = new ArrayList<>();
Iterator<SequenceBuffer> iterator = receivedBuffers.iterator();
// skip all priority events (only buffers are stored anyways)
Iterators.advance(iterator, receivedBuffers.getNumPriorityElements());
while (iterator.hasNext()) {
SequenceBuffer sequenceBuffer = iterator.next();
if (sequenceBuffer.buffer.isBuffer()) {
if (shouldBeSpilled(sequenceBuffer.sequenceNumber)) {
inflightBuffers.add(sequenceBuffer.buffer.retainBuffer());
} else {
break;
}
}
}
return inflightBuffers;
}
/**
* @return if given {@param sequenceNumber} should be spilled given {@link
* #lastBarrierSequenceNumber}. We might not have yet received {@link CheckpointBarrier} and
* we might need to spill everything. If we have already received it, there is a bit nasty
* corner case of {@link SequenceBuffer#sequenceNumber} overflowing that needs to be handled
* as well.
*/
private boolean shouldBeSpilled(int sequenceNumber) {
if (lastBarrierSequenceNumber == NONE) {
return true;
}
checkState(
receivedBuffers.size() < Integer.MAX_VALUE / 2,
"Too many buffers for sequenceNumber overflow detection code to work correctly");
boolean possibleOverflowAfterOvertaking = Integer.MAX_VALUE / 2 < lastBarrierSequenceNumber;
boolean possibleOverflowBeforeOvertaking =
lastBarrierSequenceNumber < -Integer.MAX_VALUE / 2;
if (possibleOverflowAfterOvertaking) {
return sequenceNumber < lastBarrierSequenceNumber && sequenceNumber > 0;
} else if (possibleOverflowBeforeOvertaking) {
return sequenceNumber < lastBarrierSequenceNumber || sequenceNumber > 0;
} else {
return sequenceNumber < lastBarrierSequenceNumber;
}
}
public void onEmptyBuffer(int sequenceNumber, int backlog) throws IOException {
boolean success = false;
synchronized (receivedBuffers) {
if (!isReleased.get()) {
if (expectedSequenceNumber == sequenceNumber) {
expectedSequenceNumber++;
success = true;
} else {
onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber));
}
}
}
if (success && backlog >= 0) {
onSenderBacklog(backlog);
}
}
public void onFailedPartitionRequest() {
inputGate.triggerPartitionStateCheck(partitionId);
}
public void onError(Throwable cause) {
setError(cause);
}
private void checkPartitionRequestQueueInitialized() throws IOException {
checkError();
checkState(
partitionRequestClient != null,
"Bug: partitionRequestClient is not initialized before processing data and no error is detected.");
}
private static class BufferReorderingException extends IOException {
private static final long serialVersionUID = -888282210356266816L;
private final int expectedSequenceNumber;
private final int actualSequenceNumber;
BufferReorderingException(int expectedSequenceNumber, int actualSequenceNumber) {
this.expectedSequenceNumber = expectedSequenceNumber;
this.actualSequenceNumber = actualSequenceNumber;
}
@Override
public String getMessage() {
return String.format(
"Buffer re-ordering: expected buffer with sequence number %d, but received %d.",
expectedSequenceNumber, actualSequenceNumber);
}
}
private static final class SequenceBuffer {
final Buffer buffer;
final int sequenceNumber;
private SequenceBuffer(Buffer buffer, int sequenceNumber) {
this.buffer = buffer;
this.sequenceNumber = sequenceNumber;
}
@Override
public String toString() {
return String.format(
"SequenceBuffer(isEvent = %s, dataType = %s, sequenceNumber = %s)",
!buffer.isBuffer(), buffer.getDataType(), sequenceNumber);
}
}
}
| |
/////////////////////////////////////////////////
// Project : WSFramework
// Package : co.mindie.wsframework.resolver
// AbstractModelConverterManager.java
//
// Author : Simon CORSIN <simoncorsin@gmail.com>
// File created on Feb 13, 2014 at 1:16:25 PM
////////
package co.mindie.cindy.webservice.resolver;
import co.mindie.cindy.core.annotation.Core;
import co.mindie.cindy.core.annotation.Load;
import co.mindie.cindy.core.component.metadata.ComponentMetadata;
import co.mindie.cindy.core.component.metadata.ComponentMetadataManager;
import co.mindie.cindy.core.tools.Initializable;
import co.mindie.cindy.webservice.annotation.Resolver;
import co.mindie.cindy.webservice.exception.ResolverException;
import me.corsin.javatools.reflect.ReflectionUtils;
import org.apache.log4j.Logger;
import java.util.*;
@Load(creationPriority = -1)
public class ResolverManager implements Initializable {
////////////////////////
// VARIABLES
////////////////
private static final Logger LOGGER = Logger.getLogger(ResolverManager.class);
// Kinda hacky. Didn't find a clean solution to dynamicaly provide the input and output class
// on generated resolver classes yet. (See HibernateDAO)
public static final String COMPONENT_CONFIG_INPUT_CLASS = "cindy.resolver_manager.managed_input_class";
public static final String COMPONENT_CONFIG_OUTPUT_CLASS = "cindy.resolver_manager.managed_output_class";
private Map<Class<?>, ResolverEntry> resolverEntriesByInputClass;
@Core
private ComponentMetadataManager metadataManager;
////////////////////////
// CONSTRUCTORS
////////////////
public ResolverManager() {
this.resolverEntriesByInputClass = new HashMap<>();
}
////////////////////////
// METHODS
////////////////
@Override
public void init() {
for (ComponentMetadata metadata : this.metadataManager.getLoadedComponentsWithAnnotation(Resolver.class)) {
this.addConverter(metadata.getComponentClass());
}
}
public void removeAllConverters() {
this.resolverEntriesByInputClass.clear();
}
public void addConverter(Class<?> resolverClass) {
ComponentMetadata metadata = this.metadataManager.getComponentMetadata(resolverClass);
if (metadata == null) {
throw new IllegalArgumentException("Component " + resolverClass + " not loaded.");
}
Resolver annotation = metadata.getAnnotation(Resolver.class);
Class<?>[] managedInputClasses = annotation != null ? annotation.managedInputClasses() : new Class[0];
Class<?>[] managedOutputClasses = annotation != null ? annotation.managedOutputClasses() : new Class[0];
boolean defaultForInputTypes = annotation != null && annotation.isDefaultForInputTypes();
if (managedInputClasses.length == 0) {
Class<?> inputCls = (Class<?>)metadata.getConfig(COMPONENT_CONFIG_INPUT_CLASS, false);
if (inputCls == null) {
inputCls = ReflectionUtils.getGenericTypeParameter(metadata.getComponentClass(), IResolver.class, 0);
}
if (inputCls == null) {
throw new ResolverException("Unable to add resolver " + resolverClass + ": unable to detect managed input class");
}
managedInputClasses = new Class[] { inputCls };
}
if (managedOutputClasses.length == 0) {
Class<?> outputCls = (Class<?>)metadata.getConfig(COMPONENT_CONFIG_OUTPUT_CLASS, false);
if (outputCls == null) {
outputCls = ReflectionUtils.getGenericTypeParameter(metadata.getComponentClass(), IResolver.class, 1);
}
if (outputCls == null) {
throw new ResolverException("Unable to add resolver " + resolverClass + ": unable to detect managed output class");
}
managedOutputClasses = new Class[] { outputCls };
}
// System.out.println(Strings.getObjectDescription(managedInputClasses));
// System.out.println(Strings.getObjectDescription(managedOutputClasses));
for (Class<?> inputClass : managedInputClasses) {
for (Class<?> outputClass : managedOutputClasses) {
this.addConverter(metadata.getComponentClass(), inputClass, outputClass, defaultForInputTypes, metadata.getCreationPriority());
}
}
}
public void addConverter(Class<?> modelConverterClass, Class<?> inputClass, Class<?> outputClass, boolean isDefault, int priority) {
LOGGER.trace("Registering resolver with class=" + modelConverterClass + " for input type=" + inputClass + " and output type=" + outputClass);
ResolverEntry entry = this.resolverEntriesByInputClass.get(inputClass);
if (entry == null) {
entry = new ResolverEntry(inputClass);
this.resolverEntriesByInputClass.put(inputClass, entry);
}
entry.addConverter(modelConverterClass, outputClass, isDefault, priority);
}
////////////////////////
// GETTERS/SETTERS
////////////////
public ResolverBuilder getDefaultResolverOutputForInputClass(Class<?> inputClass) {
ResolverEntry entry = this.getResolverEntry(inputClass);
return entry != null ? entry.getDefaultConverterOutput() : null;
}
public IResolverBuilder getDefaultResolverOutputForInput(Object inputObject) {
if (inputObject == null) {
return null;
}
return this.getDefaultResolverOutputForInputClass(inputObject.getClass());
}
private ResolverEntry getResolverEntry(Class<?> inputClass) {
ResolverEntry entry = null;
while (entry == null && inputClass != null) {
entry = this.resolverEntriesByInputClass.get(inputClass);
if (entry == null) {
inputClass = inputClass.getSuperclass();
}
}
return entry;
}
public IResolverBuilder getResolverOutput(Class<?> inputClass, Class<?> outputClass) {
ResolverEntry firstEntry = this.getResolverEntry(inputClass);
if (firstEntry == null) {
return null;
}
Deque<ResolverEntry> q = new ArrayDeque<>();
Set<ResolverEntry> v = new HashSet<>();
Map<ResolverEntry, ResolverEntry> childToParent = new HashMap<>();
q.add(firstEntry);
v.add(firstEntry);
ResolverEntry outputEntry = null;
while (!q.isEmpty()) {
ResolverEntry t = q.poll();
if (t.getConverterOutput(outputClass) != null) {
outputEntry = t;
break;
} else {
Class<?>[] outputClasses = t.getOutputClasses();
for (Class<?> tOutputClass : outputClasses) {
ResolverEntry tEntry = this.getResolverEntry(tOutputClass);
if (tEntry != null) {
if (!v.contains(tEntry)) {
childToParent.put(tEntry, t);
v.add(tEntry);
q.add(tEntry);
}
}
}
}
}
if (outputEntry == null) {
return null;
}
Class<?> currentOutputClass = outputClass;
List<IResolverBuilder> outputs = new ArrayList<>();
while (outputEntry != null) {
outputs.add(0, outputEntry.getConverterOutput(currentOutputClass));
currentOutputClass = outputEntry.getInputClass();
if (outputEntry != firstEntry) {
outputEntry = childToParent.get(outputEntry);
} else {
outputEntry = null;
}
}
IResolverBuilder output = null;
if (outputs.size() == 1) {
output = outputs.get(0);
} else {
output = new ChainedResolverBuilder(outputs);
}
return output;
}
public Class<?> getDefaultOutputTypeForInputObject(Object object) {
if (object == null) {
return null;
}
ResolverEntry entry = this.resolverEntriesByInputClass.get(object.getClass());
return entry != null ? entry.getDefaultConverterOutput().getOutputClass() : null;
}
public Class<?>[] getManagedOutputTypesForInputObject(Object object) {
if (object == null) {
return null;
}
ResolverEntry entry = this.resolverEntriesByInputClass.get(object.getClass());
return entry != null ? entry.getOutputClasses() : null;
}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.codeInsight;
import com.intellij.JavaTestUtil;
import com.intellij.application.options.CodeStyle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.testFramework.EditorActionTestCase;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.annotations.NotNull;
@TestDataPath("$CONTENT_ROOT/testData")
public class CompleteStatementTest extends EditorActionTestCase {
private CodeStyleSettings mySettings;
private CommonCodeStyleSettings myJavaSettings;
@Override
protected String getActionId() {
return IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT;
}
@NotNull
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath() + "/codeInsight/completeStatement/";
}
@Override
protected void setUp() throws Exception {
super.setUp();
mySettings = CodeStyle.getSettings(getProject());
myJavaSettings = mySettings.getCommonSettings(JavaLanguage.INSTANCE);
}
public void testAddMissingSemicolon() { doTest(); }
public void testAddMissingSemicolonToPackageStatement() { doTest(); }
public void testAddMissingSemicolonAfterAnonymous() { doTest(); }
public void testAddMissingParen() { doTest(); }
public void testCompleteIf() { doTest(); }
public void testCompleteIfKeyword() { doTest(); }
public void testCompleteIfStatementGoesToThen() { doTest(); }
public void testAddBracesToIfAndElse() { doTest(); }
public void testAddBracesToIfThenOneLiner() { doTest(); }
public void testCompleteIfKeywordStatementGoesToThen() { doTest(); }
public void testIndentation() { doTest(); }
public void testErrorNavigation() { doTest(); }
public void testStringLiteral() { doTest(); }
public void testCompleteCatch() { doTest(); }
public void testCompleteCatchLParen() { doTest(); }
public void testAlreadyCompleteCatch() { myJavaSettings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE; doTest(); }
public void testNoBlockReformat() { doTest(); }
public void testCompleteCatchWithExpression() { doTest(); }
public void testCompleteCatchBody() { doTest(); }
public void testSCR11147() { doTest(); }
public void testNoErrors() { doTest(); }
public void testThrow() { doTest(); }
public void testReturn() { doTest(); }
public void testEmptyLine() { doTest(); }
public void testBlock() { doTest(); }
public void testTwoStatementsInLine() { doTest(); }
public void testFor() { doTest(); }
public void testEmptyFor() { doTest(); }
public void testForEach() { doTest(); }
public void testForBlock() { doTest(); }
public void testForIncrementExpressionAndBody() { doTest(); }
public void testEmptyBeforeReturn() { doTest(); }
public void testIf() { doTest(); }
public void testIfWithoutParentheses() { doTest(); }
public void testBeforeStatement() { doTest(); }
public void testTry1() { doTest(); }
public void testInsideResourceVariable() { doTest(); }
public void testBlock1() { doTest(); }
public void testAfterFor() { doTest(); }
public void testBeforeFor() { doTest(); }
public void testAtBlockEnd() { doTest(); }
public void testForceBlock() { doTest(); }
public void testElseIf() { doTest(); }
public void testBlockBeforeElseIf() { doTest(); }
public void testIncompleteElseIf() { doTest(); }
public void testField() { doTest(); }
public void testMethod() { doTest(); }
public void testClass() { doTest(); }
public void testInnerEnumBeforeMethod() { doTest(); }
public void testInnerEnumBeforeMethodWithSpace() { doTest(); }
public void testCompleteElseIf() { doTest(); }
public void testReformatElseIf() { doTest(); }
public void testCompleteStringLiteral() { doTest(); }
public void testNonAbstractMethodWithSemicolon() { doTest(); }
public void testReturnFromNonVoid() { doTest(); }
public void testReturnFromVoid() { doTest(); }
public void testIncompleteCall() { doTest(); }
public void testCompleteCall() { doTest(); }
public void testStartNewBlock() { doTest(); }
public void testInPrecedingBlanks() { doTest(); }
public void testNoBlockReturn() { doTest(); }
public void testInComment() { doTest(); }
public void testInComment2() { doTest(); }
public void testInComment3() { doTest(); }
public void testInComment4() { doTest(); }
public void testSCR22904() { doTest(); }
public void testSCR30227() { doTest(); }
public void testFieldWithInitializer() { doTest(); }
public void testFieldBeforeAnnotation() { doTest(); }
public void testMethodBeforeAnnotation() { doTest(); }
public void testMethodBeforeCommentField() { doTest(); }
public void testMethodBeforeCommentMethod() { doTest(); }
public void testCloseAnnotationWithArrayInitializer() { doTest(); }
public void testParenthesized() { doTest(); }
public void testCompleteBreak() { doTest(); }
public void testCompleteIfNextLineBraceStyle() { myJavaSettings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE; doTest(); }
public void testCompleteIfNextLineBraceStyle2() { myJavaSettings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE; doTest(); }
public void testSCR36110() { doTest(); }
public void testSCR37331() { doTest(); }
public void testIDEADEV434() {
mySettings.getCommonSettings(JavaLanguage.INSTANCE).KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true;
doTest();
mySettings.getCommonSettings(JavaLanguage.INSTANCE).KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false;
doTest();
}
public void testIDEADEV1093() { doTest(); }
public void testIDEADEV1710() { doTest(); }
public void testInterfaceMethodSemicolon() { doTest(); }
public void testSynchronized() { doTest(); }
public void testCdrEndlessLoop() { doTest(); }
public void testFollowedByComment() { doTest(); }
public void testBraceFixNewLine() { doTest(); }
public void testSwitchKeyword() { doTest(); }
public void testSwitchKeywordWithCondition() { doTest(); }
public void testSwitchBraces() { doTest(); }
public void testCaseColon() { doTest(); }
public void testDefaultColon() { doTest(); }
public void testNewInParentheses() { doTest(); }
public void testIDEADEV20713() { doTest(); }
public void testIDEA22125() { doTest(); }
public void testIDEA22385() { doTest(); }
public void testIDEADEV40479() { doTest(); }
public void testMultilineReturn() { doTest(); }
public void testMultilineCall() { doTest(); }
public void testVarargCall() { doTest(); }
public void testOverloadedCall() { doTest(); }
public void testIDEADEV13019() { doTestBracesNextLineStyle(); }
public void testIDEA25139() { doTestBracesNextLineStyle(); }
public void testClassBracesNextLine() { doTestBracesNextLineStyle(); }
public void testBeforeIfRBrace() { mySettings.getCommonSettings(JavaLanguage.INSTANCE).KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true; doTest(); }
public void testNoUnnecessaryEmptyLineAtCodeBlock() { doTest(); }
public void testForStatementGeneration() { doTest(); }
public void testSpaceAfterSemicolon() { mySettings.getCommonSettings(JavaLanguage.INSTANCE).SPACE_AFTER_SEMICOLON = true; doTest(); }
public void testNoSpaceAfterSemicolon() { myJavaSettings.SPACE_AFTER_SEMICOLON = false; doTest(); }
public void testForUpdateGeneration() { doTest(); }
public void testReformatForHeader() { doTest(); }
public void testValidCodeBlock() { doTest(); }
public void testValidCodeBlockWithEmptyLineAfterIt() { doTest(); }
public void testFromJavadocParameterDescriptionEndToNextParameter() { doTest(); }
public void testFromJavadocParameterDescriptionMiddleToNextParameter() { doTest(); }
public void testLastJavadocParameterDescription() { doTest(); }
public void testLastJavadocParameterDescriptionToReturn() { doTest(); }
public void testCompleteMethodCallAtReturn() { doTest(); }
public void testGenericMethodBody() { doTest(); }
public void testDefaultMethodBody() { doTest(); }
public void testStaticInterfaceMethodBody() { doTest(); }
public void testPrivateInterfaceMethodBody() { doTest(); }
public void testAddMethodBodyFromInsideAnnotation() { doTest(); }
public void testArrayInitializerRBracket() { doTest(); }
public void testArrayInitializerRBrace() { doTest(); }
public void testArrayInitializerRBrace2() { doTest(); }
public void testMultiArrayInitializerRBrace() { doTest(); }
public void testMultiArrayInitializerRBrace2() { doTest(); }
public void testArrayInitializerSeveralLines() { doTest(); }
public void testReturnInLambda() { doTest(); }
public void testSemicolonAfterLambda() { doTest(); }
public void testModuleInfo() { doTest(); }
public void testDoubleFieldDeclaration() { doTest(); }
public void testAddTernaryColon() { doTest(); }
public void testRecord() { doTest(); }
public void testRecordWithComponent() { doTest(); }
public void testRecordWithComponentNoBody() { doTest(); }
public void testVarargMethod() { doTest(); }
public void testVarargMethod2() { doTest(); }
public void testVarargMethod3() { doTest(); }
public void testSemicolonAfterSwitchExpression() { doTest(); }
public void testOverloadedMethod() { doTest(); }
public void testOverloadedMethodNoCaretHint() { doTest(); }
public void testOverloadedMethodOneOrThree() { doTest(); }
public void testOverloadedMethodOneOrThree2() { doTest(); }
public void testOverloadedMethodOneOrThree3() { doTest(); }
public void testMissingComma() { doTest(); }
public void testInInjection() { doTest(); }
public void testNativeMethod() {
doTest();
}
public void testNativePrivateMethod() {
doTest();
}
public void testReturnSwitchExpression() {
doTest();
}
public void testReturnSwitchExpression2() {
doTest();
}
public void testReturnSwitchExpression3() {
doTest();
}
public void testSwitchAtTheEndOfClass() { doTest(); }
private void doTestBracesNextLineStyle() {
myJavaSettings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE;
myJavaSettings.METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE;
myJavaSettings.CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE;
doTest();
}
private void doTest() {
String name = getTestName(false);
doFileTest(name + ".java", name + "_after.java", 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.jmeter.gui;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import org.apache.jmeter.gui.action.UndoCommand;
import org.apache.jmeter.gui.tree.JMeterTreeModel;
import org.apache.jmeter.gui.tree.JMeterTreeNode;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
* This class serves storing Test Tree state and navigating through it
* to give the undo/redo ability for test plan changes
*
* @since 2.12
*/
public class UndoHistory implements TreeModelListener, Serializable {
/**
*
*/
private static final long serialVersionUID = -974269825492906010L;
/**
* Interface to be implemented by components interested in UndoHistory
*/
public interface HistoryListener {
void notifyChangeInHistory(UndoHistory history);
}
/**
* Avoid storing too many elements
*
* @param <T> Class that should be held in this container
*/
private static class LimitedArrayList<T> extends ArrayList<T> {
/**
*
*/
private static final long serialVersionUID = -6574380490156356507L;
private int limit;
public LimitedArrayList(int limit) {
this.limit = limit;
}
@Override
public boolean add(T item) {
if (this.size() + 1 > limit) {
this.remove(0);
}
return super.add(item);
}
}
private static final Logger log = LoggingManager.getLoggerForClass();
/**
* temporary storage for GUI tree expansion state
*/
private ArrayList<Integer> savedExpanded = new ArrayList<Integer>();
/**
* temporary storage for GUI tree selected row
*/
private int savedSelected = 0;
private static final int INITIAL_POS = -1;
private int position = INITIAL_POS;
private static final int HISTORY_SIZE = JMeterUtils.getPropDefault("undo.history.size", 0);
private List<UndoHistoryItem> history = new LimitedArrayList<UndoHistoryItem>(HISTORY_SIZE);
/**
* flag to prevent recursive actions
*/
private boolean working = false;
/**
* History listeners
*/
private List<HistoryListener> listeners = new ArrayList<UndoHistory.HistoryListener>();
public UndoHistory() {
}
/**
* Clears the undo history
*/
public void clear() {
if (working) {
return;
}
log.debug("Clearing undo history");
history.clear();
position = INITIAL_POS;
notifyListeners();
}
/**
* Add tree model copy to the history
* <p>
* This method relies on the rule that the record in history made AFTER
* change has been made to test plan
*
* @param treeModel JMeterTreeModel
* @param comment String
*/
public void add(JMeterTreeModel treeModel, String comment) {
if(!isEnabled()) {
log.debug("undo.history.size is set to 0, undo/redo feature is disabled");
return;
}
// don't add element if we are in the middle of undo/redo or a big loading
if (working) {
log.debug("Not adding history because of noop");
return;
}
JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
if (root.getChildCount() < 1) {
log.debug("Not adding history because of no children");
return;
}
String name = root.getName();
log.debug("Adding history element " + name + ": " + comment);
working = true;
// get test plan tree
HashTree tree = treeModel.getCurrentSubTree((JMeterTreeNode) treeModel.getRoot());
// first clone to not convert original tree
tree = (HashTree) tree.getTree(tree.getArray()[0]).clone();
position++;
while (history.size() > position) {
log.debug("Removing further record, position: " + position + ", size: " + history.size());
history.remove(history.size() - 1);
}
// cloning is required because we need to immute stored data
HashTree copy = UndoCommand.convertAndCloneSubTree(tree);
history.add(new UndoHistoryItem(copy, comment));
log.debug("Added history element, position: " + position + ", size: " + history.size());
working = false;
notifyListeners();
}
/**
* Goes through undo history, changing GUI
*
* @param offset the direction to go to, usually -1 for undo or 1 for redo
* @param acceptorModel TreeModel to accept the changes
*/
public void moveInHistory(int offset, JMeterTreeModel acceptorModel) {
log.debug("Moving history from position " + position + " with step " + offset + ", size is " + history.size());
if (offset < 0 && !canUndo()) {
log.warn("Can't undo, we're already on the last record");
return;
}
if (offset > 0 && !canRedo()) {
log.warn("Can't redo, we're already on the first record");
return;
}
if (history.isEmpty()) {
log.warn("Can't proceed, the history is empty");
return;
}
position += offset;
final GuiPackage guiInstance = GuiPackage.getInstance();
// save tree expansion and selection state before changing the tree
saveTreeState(guiInstance);
// load the tree
loadHistoricalTree(acceptorModel, guiInstance);
// load tree UI state
restoreTreeState(guiInstance);
log.debug("Current position " + position + ", size is " + history.size());
// refresh the all ui
guiInstance.updateCurrentGui();
guiInstance.getMainFrame().repaint();
notifyListeners();
}
/**
* Load the undo item into acceptorModel tree
*
* @param acceptorModel tree to accept the data
* @param guiInstance {@link GuiPackage} to be used
*/
private void loadHistoricalTree(JMeterTreeModel acceptorModel, GuiPackage guiInstance) {
HashTree newModel = history.get(position).getTree();
acceptorModel.removeTreeModelListener(this);
working = true;
try {
guiInstance.getTreeModel().clearTestPlan();
guiInstance.addSubTree(newModel);
} catch (Exception ex) {
log.error("Failed to load from history", ex);
}
acceptorModel.addTreeModelListener(this);
working = false;
}
/**
* @return true if remaing items
*/
public boolean canRedo() {
return position < history.size() - 1;
}
/**
* @return true if not at first element
*/
public boolean canUndo() {
return position > INITIAL_POS + 1;
}
/**
* Record the changes in the node as the undo step
*
* @param tme {@link TreeModelEvent} with event details
*/
@Override
public void treeNodesChanged(TreeModelEvent tme) {
String name = ((JMeterTreeNode) tme.getTreePath().getLastPathComponent()).getName();
log.debug("Nodes changed " + name);
final JMeterTreeModel sender = (JMeterTreeModel) tme.getSource();
add(sender, "Node changed " + name);
}
/**
* Record adding nodes as the undo step
*
* @param tme {@link TreeModelEvent} with event details
*/
@Override
public void treeNodesInserted(TreeModelEvent tme) {
String name = ((JMeterTreeNode) tme.getTreePath().getLastPathComponent()).getName();
log.debug("Nodes inserted " + name);
final JMeterTreeModel sender = (JMeterTreeModel) tme.getSource();
add(sender, "Add " + name);
}
/**
* Record deleting nodes as the undo step
*
* @param tme {@link TreeModelEvent} with event details
*/
@Override
public void treeNodesRemoved(TreeModelEvent tme) {
String name = ((JMeterTreeNode) tme.getTreePath().getLastPathComponent()).getName();
log.debug("Nodes removed: " + name);
add((JMeterTreeModel) tme.getSource(), "Remove " + name);
}
/**
* Record some other change
*
* @param tme {@link TreeModelEvent} with event details
*/
@Override
public void treeStructureChanged(TreeModelEvent tme) {
log.debug("Nodes struct changed");
add((JMeterTreeModel) tme.getSource(), "Complex Change");
}
/**
* Save tree expanded and selected state
*
* @param guiPackage {@link GuiPackage} to be used
*/
private void saveTreeState(GuiPackage guiPackage) {
savedExpanded.clear();
MainFrame mainframe = guiPackage.getMainFrame();
if (mainframe != null) {
final JTree tree = mainframe.getTree();
savedSelected = tree.getMinSelectionRow();
for (int rowN = 0; rowN < tree.getRowCount(); rowN++) {
if (tree.isExpanded(rowN)) {
savedExpanded.add(rowN);
}
}
}
}
/**
* Restore tree expanded and selected state
*
* @param guiInstance GuiPackage to be used
*/
private void restoreTreeState(GuiPackage guiInstance) {
final JTree tree = guiInstance.getMainFrame().getTree();
if (savedExpanded.size() > 0) {
for (int rowN : savedExpanded) {
tree.expandRow(rowN);
}
} else {
tree.expandRow(0);
}
tree.setSelectionRow(savedSelected);
}
/**
*
* @return true if history is enabled
*/
boolean isEnabled() {
return HISTORY_SIZE > 0;
}
/**
* Register HistoryListener
* @param listener to add to our listeners
*/
public void registerHistoryListener(HistoryListener listener) {
listeners.add(listener);
}
/**
* Notify listener
*/
private void notifyListeners() {
for (HistoryListener listener : listeners) {
listener.notifyChangeInHistory(this);
}
}
}
| |
/*
* Copyright (c) 2003, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.sql.SQLException;
import java.util.List;
/**
* Test cases for the Parser.
* @author Jeremy Whiting jwhiting@redhat.com
*/
public class ParserTest {
/**
* Test to make sure delete command is detected by parser and detected via
* api. Mix up the case of the command to check detection continues to work.
*/
@Test
public void testDeleteCommandParsing() {
char[] command = new char[6];
"DELETE".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse upper case command.", Parser.parseDeleteKeyword(command, 0));
"DelEtE".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseDeleteKeyword(command, 0));
"deleteE".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseDeleteKeyword(command, 0));
"delete".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse lower case command.", Parser.parseDeleteKeyword(command, 0));
"Delete".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseDeleteKeyword(command, 0));
}
/**
* Test UPDATE command parsing.
*/
@Test
public void testUpdateCommandParsing() {
char[] command = new char[6];
"UPDATE".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse upper case command.", Parser.parseUpdateKeyword(command, 0));
"UpDateE".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseUpdateKeyword(command, 0));
"updatE".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseUpdateKeyword(command, 0));
"Update".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseUpdateKeyword(command, 0));
"update".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse lower case command.", Parser.parseUpdateKeyword(command, 0));
}
/**
* Test MOVE command parsing.
*/
@Test
public void testMoveCommandParsing() {
char[] command = new char[4];
"MOVE".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse upper case command.", Parser.parseMoveKeyword(command, 0));
"mOVe".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseMoveKeyword(command, 0));
"movE".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseMoveKeyword(command, 0));
"Move".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseMoveKeyword(command, 0));
"move".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse lower case command.", Parser.parseMoveKeyword(command, 0));
}
/**
* Test WITH command parsing.
*/
@Test
public void testWithCommandParsing() {
char[] command = new char[4];
"WITH".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse upper case command.", Parser.parseWithKeyword(command, 0));
"wITh".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseWithKeyword(command, 0));
"witH".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseWithKeyword(command, 0));
"With".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseWithKeyword(command, 0));
"with".getChars(0, 4, command, 0);
assertTrue("Failed to correctly parse lower case command.", Parser.parseWithKeyword(command, 0));
}
/**
* Test SELECT command parsing.
*/
@Test
public void testSelectCommandParsing() {
char[] command = new char[6];
"SELECT".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse upper case command.", Parser.parseSelectKeyword(command, 0));
"sELect".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseSelectKeyword(command, 0));
"selecT".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseSelectKeyword(command, 0));
"Select".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse mixed case command.", Parser.parseSelectKeyword(command, 0));
"select".getChars(0, 6, command, 0);
assertTrue("Failed to correctly parse lower case command.", Parser.parseSelectKeyword(command, 0));
}
@Test
public void testEscapeProcessing() throws Exception {
assertEquals("DATE '1999-01-09'", Parser.replaceProcessing("{d '1999-01-09'}", true, false));
assertEquals("DATE '1999-01-09'", Parser.replaceProcessing("{D '1999-01-09'}", true, false));
assertEquals("TIME '20:00:03'", Parser.replaceProcessing("{t '20:00:03'}", true, false));
assertEquals("TIME '20:00:03'", Parser.replaceProcessing("{T '20:00:03'}", true, false));
assertEquals("TIMESTAMP '1999-01-09 20:11:11.123455'", Parser.replaceProcessing("{ts '1999-01-09 20:11:11.123455'}", true, false));
assertEquals("TIMESTAMP '1999-01-09 20:11:11.123455'", Parser.replaceProcessing("{Ts '1999-01-09 20:11:11.123455'}", true, false));
assertEquals("user", Parser.replaceProcessing("{fn user()}", true, false));
assertEquals("cos(1)", Parser.replaceProcessing("{fn cos(1)}", true, false));
assertEquals("extract(week from DATE '2005-01-24')", Parser.replaceProcessing("{fn week({d '2005-01-24'})}", true, false));
assertEquals("\"T1\" LEFT OUTER JOIN t2 ON \"T1\".id = t2.id",
Parser.replaceProcessing("{oj \"T1\" LEFT OUTER JOIN t2 ON \"T1\".id = t2.id}", true, false));
assertEquals("ESCAPE '_'", Parser.replaceProcessing("{escape '_'}", true, false));
// nothing should be changed in that case, no valid escape code
assertEquals("{obj : 1}", Parser.replaceProcessing("{obj : 1}", true, false));
}
@Test
public void testModifyJdbcCall() throws SQLException {
assertEquals("select * from pack_getValue(?) as result", Parser.modifyJdbcCall("{ ? = call pack_getValue}", true, ServerVersion.v9_6.getVersionNum(), 3).getSql());
assertEquals("select * from pack_getValue(?,?) as result", Parser.modifyJdbcCall("{ ? = call pack_getValue(?) }", true, ServerVersion.v9_6.getVersionNum(), 3).getSql());
assertEquals("select * from pack_getValue(?) as result", Parser.modifyJdbcCall("{ ? = call pack_getValue()}", true, ServerVersion.v9_6.getVersionNum(), 3).getSql());
assertEquals("select * from pack_getValue(?,?,?,?) as result", Parser.modifyJdbcCall("{ ? = call pack_getValue(?,?,?) }", true, ServerVersion.v9_6.getVersionNum(), 3).getSql());
assertEquals("select * from lower(?,?) as result", Parser.modifyJdbcCall("{ ? = call lower(?)}", true, ServerVersion.v9_6.getVersionNum(), 3).getSql());
}
@Test
public void testUnterminatedEscape() throws Exception {
assertEquals("{oj ", Parser.replaceProcessing("{oj ", true, false));
}
@Test
@Ignore(value = "returning in the select clause is hard to distinguish from insert ... returning *")
public void insertSelectFakeReturning() throws SQLException {
String query =
"insert test(id, name) select 1, 'value' as RETURNING from test2";
List<NativeQuery> qry =
Parser.parseJdbcSql(
query, true, true, true, true);
boolean returningKeywordPresent = qry.get(0).command.isReturningKeywordPresent();
Assert.assertFalse("Query does not have returning clause " + query, returningKeywordPresent);
}
@Test
public void insertSelectReturning() throws SQLException {
String query =
"insert test(id, name) select 1, 'value' from test2 RETURNING id";
List<NativeQuery> qry =
Parser.parseJdbcSql(
query, true, true, true, true);
boolean returningKeywordPresent = qry.get(0).command.isReturningKeywordPresent();
Assert.assertTrue("Query has a returning clause " + query, returningKeywordPresent);
}
@Test
public void insertReturningInWith() throws SQLException {
String query =
"with x as (insert into mytab(x) values(1) returning x) insert test(id, name) select 1, 'value' from test2";
List<NativeQuery> qry =
Parser.parseJdbcSql(
query, true, true, true, true);
boolean returningKeywordPresent = qry.get(0).command.isReturningKeywordPresent();
Assert.assertFalse("There's no top-level <<returning>> clause " + query, returningKeywordPresent);
}
@Test
public void insertBatchedReWriteOnConflict() throws SQLException {
String query = "insert into test(id, name) values (:id,:name) ON CONFLICT (id) DO NOTHING";
List<NativeQuery> qry = Parser.parseJdbcSql(query, true, true, true, true);
SqlCommand command = qry.get(0).getCommand();
Assert.assertEquals(34, command.getBatchRewriteValuesBraceOpenPosition());
Assert.assertEquals(44, command.getBatchRewriteValuesBraceClosePosition());
}
@Test
public void insertBatchedReWriteOnConflictUpdateBind() throws SQLException {
String query = "insert into test(id, name) values (?,?) ON CONFLICT (id) UPDATE SET name=?";
List<NativeQuery> qry = Parser.parseJdbcSql(query, true, true, true, true);
SqlCommand command = qry.get(0).getCommand();
Assert.assertFalse("update set name=? is NOT compatible with insert rewrite", command.isBatchedReWriteCompatible());
}
@Test
public void insertBatchedReWriteOnConflictUpdateConstant() throws SQLException {
String query = "insert into test(id, name) values (?,?) ON CONFLICT (id) UPDATE SET name='default'";
List<NativeQuery> qry = Parser.parseJdbcSql(query, true, true, true, true);
SqlCommand command = qry.get(0).getCommand();
Assert.assertTrue("update set name='default' is compatible with insert rewrite", command.isBatchedReWriteCompatible());
}
@Test
public void insertMultiInsert() throws SQLException {
String query =
"insert into test(id, name) values (:id,:name),(:id,:name) ON CONFLICT (id) DO NOTHING";
List<NativeQuery> qry = Parser.parseJdbcSql(query, true, true, true, true);
SqlCommand command = qry.get(0).getCommand();
Assert.assertEquals(34, command.getBatchRewriteValuesBraceOpenPosition());
Assert.assertEquals(56, command.getBatchRewriteValuesBraceClosePosition());
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.cxf;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.xml.ws.WebFault;
import org.w3c.dom.Element;
import org.apache.camel.AsyncCallback;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultConsumer;
import org.apache.camel.util.ObjectHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.continuations.Continuation;
import org.apache.cxf.continuations.ContinuationProvider;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.service.invoker.Invoker;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.version.Version;
/**
* A Consumer of exchanges for a service in CXF. CxfConsumer acts a CXF
* service to receive requests, convert them, and forward them to Camel
* route for processing. It is also responsible for converting and sending
* back responses to CXF client.
*
* @version $Revision$
*/
public class CxfConsumer extends DefaultConsumer {
private static final Log LOG = LogFactory.getLog(CxfConsumer.class);
private Server server;
public CxfConsumer(final CxfEndpoint endpoint, Processor processor) throws Exception {
super(endpoint, processor);
// create server
ServerFactoryBean svrBean = endpoint.createServerFactoryBean();
svrBean.setInvoker(new Invoker() {
// we receive a CXF request when this method is called
public Object invoke(Exchange cxfExchange, Object o) {
if (LOG.isTraceEnabled()) {
LOG.trace("Received CXF Request: " + cxfExchange);
}
Continuation continuation = getContinuation(cxfExchange);
// Only calling the continuation API for CXF 2.3.x
if (continuation != null && !endpoint.isSynchronous() && Version.getCurrentVersion().startsWith("2.3")) {
if (LOG.isTraceEnabled()) {
LOG.trace("Calling the Camel async processors.");
}
return asyncInvoke(cxfExchange, continuation);
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Calling the Camel sync processors.");
}
return syncInvoke(cxfExchange);
}
}
// NOTE this code cannot work with CXF 2.2.x
private Object asyncInvoke(Exchange cxfExchange, final Continuation continuation) {
synchronized (continuation) {
if (continuation.isNew()) {
final org.apache.camel.Exchange camelExchange = perpareCamelExchange(cxfExchange);
// Now we don't set up the timeout value
if (LOG.isTraceEnabled()) {
LOG.trace("Suspending continuation of exchangeId: " + camelExchange.getExchangeId());
}
// TODO Support to set the timeout in case the Camel can't send the response back on time.
// The continuation could be called before the suspend is called
continuation.suspend(0);
// use the asynchronous API to process the exchange
getAsyncProcessor().process(camelExchange, new AsyncCallback() {
public void done(boolean doneSync) {
// make sure the continuation resume will not be called before the suspend method in other thread
synchronized (continuation) {
if (LOG.isTraceEnabled()) {
LOG.trace("Resuming continuation of exchangeId: "
+ camelExchange.getExchangeId());
}
// resume processing after both, sync and async callbacks
continuation.setObject(camelExchange);
continuation.resume();
}
}
});
}
if (continuation.isResumed()) {
org.apache.camel.Exchange camelExchange = (org.apache.camel.Exchange)continuation
.getObject();
setResponseBack(cxfExchange, camelExchange);
}
}
return null;
}
private Continuation getContinuation(Exchange cxfExchange) {
ContinuationProvider provider =
(ContinuationProvider)cxfExchange.getInMessage().get(ContinuationProvider.class.getName());
return provider == null ? null : provider.getContinuation();
}
private Object syncInvoke(Exchange cxfExchange) {
org.apache.camel.Exchange camelExchange = perpareCamelExchange(cxfExchange);
// send Camel exchange to the target processor
if (LOG.isTraceEnabled()) {
LOG.trace("Processing +++ START +++");
}
try {
getProcessor().process(camelExchange);
} catch (Exception e) {
throw new Fault(e);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Processing +++ END +++");
}
setResponseBack(cxfExchange, camelExchange);
// response should have been set in outMessage's content
return null;
}
private org.apache.camel.Exchange perpareCamelExchange(Exchange cxfExchange) {
// get CXF binding
CxfEndpoint endpoint = (CxfEndpoint)getEndpoint();
CxfBinding binding = endpoint.getCxfBinding();
// create a Camel exchange
org.apache.camel.Exchange camelExchange = endpoint.createExchange();
DataFormat dataFormat = endpoint.getDataFormat();
BindingOperationInfo boi = cxfExchange.getBindingOperationInfo();
// make sure the "boi" is remained as wrapped in PAYLOAD mode
if (dataFormat == DataFormat.PAYLOAD && boi.isUnwrapped()) {
boi = boi.getWrappedOperation();
cxfExchange.put(BindingOperationInfo.class, boi);
}
if (boi != null) {
camelExchange.setProperty(BindingOperationInfo.class.getName(), boi);
if (LOG.isTraceEnabled()) {
LOG.trace("Set exchange property: BindingOperationInfo: " + boi);
}
}
// set data format mode in Camel exchange
camelExchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, dataFormat);
if (LOG.isTraceEnabled()) {
LOG.trace("Set Exchange property: " + DataFormat.class.getName()
+ "=" + dataFormat);
}
camelExchange.setProperty(Message.MTOM_ENABLED, String.valueOf(endpoint.isMtomEnabled()));
// bind the CXF request into a Camel exchange
binding.populateExchangeFromCxfRequest(cxfExchange, camelExchange);
// extract the javax.xml.ws header
Map<String, Object> context = new HashMap<String, Object>();
binding.extractJaxWsContext(cxfExchange, context);
// put the context into camelExchange
camelExchange.setProperty(CxfConstants.JAXWS_CONTEXT, context);
return camelExchange;
}
@SuppressWarnings("unchecked")
private void setResponseBack(Exchange cxfExchange, org.apache.camel.Exchange camelExchange) {
CxfEndpoint endpoint = (CxfEndpoint)getEndpoint();
CxfBinding binding = endpoint.getCxfBinding();
checkFailure(camelExchange);
// bind the Camel response into a CXF response
if (camelExchange.getPattern().isOutCapable()) {
binding.populateCxfResponseFromExchange(camelExchange, cxfExchange);
}
// check failure again as fault could be discovered by converter
checkFailure(camelExchange);
// copy the headers javax.xml.ws header back
binding.copyJaxWsContext(cxfExchange, (Map<String, Object>)camelExchange.getProperty(CxfConstants.JAXWS_CONTEXT));
}
private void checkFailure(org.apache.camel.Exchange camelExchange) throws Fault {
final Throwable t;
if (camelExchange.isFailed()) {
t = (camelExchange.hasOut() && camelExchange.getOut().isFault()) ? camelExchange.getOut()
.getBody(Throwable.class) : camelExchange.getException();
if (t instanceof Fault) {
throw (Fault)t;
} else if (t != null) {
// This is not a CXF Fault. Build the CXF Fault manuallly.
Fault fault = new Fault(t);
if (fault.getMessage() == null) {
// The Fault has no Message. This is the case if t had
// no message, for
// example was a NullPointerException.
fault.setMessage(t.getClass().getSimpleName());
}
WebFault faultAnnotation = t.getClass().getAnnotation(WebFault.class);
Object faultInfo = null;
try {
Method method = t.getClass().getMethod("getFaultInfo", new Class[0]);
faultInfo = method.invoke(t, new Object[0]);
} catch (Exception e) {
// do nothing here
}
if (faultAnnotation != null && faultInfo == null) {
// t has a JAX-WS WebFault annotation, which describes
// in detail the Web Service Fault that should be thrown. Add the
// detail.
Element detail = fault.getOrCreateDetail();
Element faultDetails = detail.getOwnerDocument()
.createElementNS(faultAnnotation.targetNamespace(), faultAnnotation.name());
detail.appendChild(faultDetails);
}
throw fault;
}
}
}
});
server = svrBean.create();
if (ObjectHelper.isNotEmpty(endpoint.getPublishedEndpointUrl())) {
server.getEndpoint().getEndpointInfo().setProperty("publishedEndpointUrl", endpoint.getPublishedEndpointUrl());
}
}
@Override
protected void doStart() throws Exception {
super.doStart();
server.start();
}
@Override
protected void doStop() throws Exception {
server.stop();
super.doStop();
}
public Server getServer() {
return server;
}
}
| |
/*
* Copyright 2017-2022 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.workmail.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/GetAccessControlEffect" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetAccessControlEffectResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The rule effect.
* </p>
*/
private String effect;
/**
* <p>
* The rules that match the given parameters, resulting in an effect.
* </p>
*/
private java.util.List<String> matchedRules;
/**
* <p>
* The rule effect.
* </p>
*
* @param effect
* The rule effect.
* @see AccessControlRuleEffect
*/
public void setEffect(String effect) {
this.effect = effect;
}
/**
* <p>
* The rule effect.
* </p>
*
* @return The rule effect.
* @see AccessControlRuleEffect
*/
public String getEffect() {
return this.effect;
}
/**
* <p>
* The rule effect.
* </p>
*
* @param effect
* The rule effect.
* @return Returns a reference to this object so that method calls can be chained together.
* @see AccessControlRuleEffect
*/
public GetAccessControlEffectResult withEffect(String effect) {
setEffect(effect);
return this;
}
/**
* <p>
* The rule effect.
* </p>
*
* @param effect
* The rule effect.
* @return Returns a reference to this object so that method calls can be chained together.
* @see AccessControlRuleEffect
*/
public GetAccessControlEffectResult withEffect(AccessControlRuleEffect effect) {
this.effect = effect.toString();
return this;
}
/**
* <p>
* The rules that match the given parameters, resulting in an effect.
* </p>
*
* @return The rules that match the given parameters, resulting in an effect.
*/
public java.util.List<String> getMatchedRules() {
return matchedRules;
}
/**
* <p>
* The rules that match the given parameters, resulting in an effect.
* </p>
*
* @param matchedRules
* The rules that match the given parameters, resulting in an effect.
*/
public void setMatchedRules(java.util.Collection<String> matchedRules) {
if (matchedRules == null) {
this.matchedRules = null;
return;
}
this.matchedRules = new java.util.ArrayList<String>(matchedRules);
}
/**
* <p>
* The rules that match the given parameters, resulting in an effect.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setMatchedRules(java.util.Collection)} or {@link #withMatchedRules(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param matchedRules
* The rules that match the given parameters, resulting in an effect.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetAccessControlEffectResult withMatchedRules(String... matchedRules) {
if (this.matchedRules == null) {
setMatchedRules(new java.util.ArrayList<String>(matchedRules.length));
}
for (String ele : matchedRules) {
this.matchedRules.add(ele);
}
return this;
}
/**
* <p>
* The rules that match the given parameters, resulting in an effect.
* </p>
*
* @param matchedRules
* The rules that match the given parameters, resulting in an effect.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetAccessControlEffectResult withMatchedRules(java.util.Collection<String> matchedRules) {
setMatchedRules(matchedRules);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEffect() != null)
sb.append("Effect: ").append(getEffect()).append(",");
if (getMatchedRules() != null)
sb.append("MatchedRules: ").append(getMatchedRules());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetAccessControlEffectResult == false)
return false;
GetAccessControlEffectResult other = (GetAccessControlEffectResult) obj;
if (other.getEffect() == null ^ this.getEffect() == null)
return false;
if (other.getEffect() != null && other.getEffect().equals(this.getEffect()) == false)
return false;
if (other.getMatchedRules() == null ^ this.getMatchedRules() == null)
return false;
if (other.getMatchedRules() != null && other.getMatchedRules().equals(this.getMatchedRules()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEffect() == null) ? 0 : getEffect().hashCode());
hashCode = prime * hashCode + ((getMatchedRules() == null) ? 0 : getMatchedRules().hashCode());
return hashCode;
}
@Override
public GetAccessControlEffectResult clone() {
try {
return (GetAccessControlEffectResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/**
* Copyright 2016 OpenSemantics.IO
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opensemantics.semiotics.model.assessment.provider;
import io.opensemantics.semiotics.model.assessment.Assessment;
import io.opensemantics.semiotics.model.assessment.AssessmentFactory;
import io.opensemantics.semiotics.model.assessment.AssessmentPackage;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link io.opensemantics.semiotics.model.assessment.Assessment} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class AssessmentItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AssessmentItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addLabelPropertyDescriptor(object);
addNotesPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Label feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addLabelPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Label_label_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Label_label_feature", "_UI_Label_type"),
AssessmentPackage.Literals.LABEL__LABEL,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Notes feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addNotesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Notes_notes_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Notes_notes_feature", "_UI_Notes_type"),
AssessmentPackage.Literals.NOTES__NOTES,
true,
true,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(AssessmentPackage.Literals.ASSESSMENT__APPLICATIONS);
childrenFeatures.add(AssessmentPackage.Literals.ASSESSMENT__FINDINGS);
childrenFeatures.add(AssessmentPackage.Literals.ASSESSMENT__TASKS);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns Assessment.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("famfamfam/silk/rainbow.png"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public String getText(Object object) {
String label = ((Assessment)object).getLabel();
return label == null || label.length() == 0 ?
getString("_UI_Assessment_type") : label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(Assessment.class)) {
case AssessmentPackage.ASSESSMENT__LABEL:
case AssessmentPackage.ASSESSMENT__NOTES:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case AssessmentPackage.ASSESSMENT__APPLICATIONS:
case AssessmentPackage.ASSESSMENT__FINDINGS:
case AssessmentPackage.ASSESSMENT__TASKS:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(AssessmentPackage.Literals.ASSESSMENT__APPLICATIONS,
AssessmentFactory.eINSTANCE.createApplications()));
newChildDescriptors.add
(createChildParameter
(AssessmentPackage.Literals.ASSESSMENT__FINDINGS,
AssessmentFactory.eINSTANCE.createFindings()));
newChildDescriptors.add
(createChildParameter
(AssessmentPackage.Literals.ASSESSMENT__TASKS,
AssessmentFactory.eINSTANCE.createTasks()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return AssessmentEditPlugin.INSTANCE;
}
}
| |
package com.xiaomi.infra.galaxy.sds.examples.stream;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xiaomi.infra.galaxy.rpc.thrift.GrantType;
import com.xiaomi.infra.galaxy.rpc.thrift.Grantee;
import com.xiaomi.infra.galaxy.sds.client.ClientFactory;
import com.xiaomi.infra.galaxy.sds.thrift.AdminService;
import com.xiaomi.infra.galaxy.sds.thrift.CommonConstants;
import com.xiaomi.infra.galaxy.sds.thrift.Credential;
import com.xiaomi.infra.galaxy.sds.thrift.Datum;
import com.xiaomi.infra.galaxy.sds.thrift.IncrementRequest;
import com.xiaomi.infra.galaxy.sds.thrift.PointInTimeRecovery;
import com.xiaomi.infra.galaxy.sds.thrift.PutRequest;
import com.xiaomi.infra.galaxy.sds.thrift.PutResult;
import com.xiaomi.infra.galaxy.sds.thrift.RemoveRequest;
import com.xiaomi.infra.galaxy.sds.thrift.RemoveResult;
import com.xiaomi.infra.galaxy.sds.thrift.StreamCheckpoint;
import com.xiaomi.infra.galaxy.sds.thrift.StreamSpec;
import com.xiaomi.infra.galaxy.sds.thrift.StreamViewType;
import com.xiaomi.infra.galaxy.sds.thrift.TableInfo;
import com.xiaomi.infra.galaxy.sds.thrift.TableSchema;
import com.xiaomi.infra.galaxy.sds.thrift.TableService;
import com.xiaomi.infra.galaxy.sds.thrift.TableSnapshots;
import com.xiaomi.infra.galaxy.sds.thrift.TableSpec;
import com.xiaomi.infra.galaxy.sds.thrift.UserType;
import com.xiaomi.infra.galaxy.talos.admin.TalosAdmin;
import com.xiaomi.infra.galaxy.talos.client.TalosClientConfig;
import com.xiaomi.infra.galaxy.talos.client.TalosClientConfigKeys;
import com.xiaomi.infra.galaxy.talos.thrift.CreateTopicRequest;
import com.xiaomi.infra.galaxy.talos.thrift.CreateTopicResponse;
import com.xiaomi.infra.galaxy.talos.thrift.Permission;
import com.xiaomi.infra.galaxy.talos.thrift.TopicAttribute;
import com.xiaomi.infra.galaxy.talos.thrift.TopicInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
/**
* Copyright 2015, Xiaomi.
* All rights reserved.
* Author: qiankai@xiaomi.com
*/
public class PitrDemo {
private static final Logger LOG = LoggerFactory.getLogger(StreamDemo.class);
static Random rand = new Random(0);
static final int PARTITAL_DELETE_NUMBER = 2;
static final int ADMIN_CONN_TIMEOUT = 3000;
static final int ADMIN_SOCKET_TIMEOUT = 50000;
static final int TABLE_CONN_TIMEOUT = 3000;
static final int TABLE_SOCKET_TIMEOUT = 10000;
private Credential createSdsCredential(String secretKeyId, String secretKey, UserType userType) {
return new Credential()
.setSecretKeyId(secretKeyId)
.setSecretKey(secretKey)
.setType(userType);
}
private com.xiaomi.infra.galaxy.rpc.thrift.Credential createTalosCredential(String secretKeyId,
String secretKey, com.xiaomi.infra.galaxy.rpc.thrift.UserType userType) {
return new com.xiaomi.infra.galaxy.rpc.thrift.Credential()
.setSecretKeyId(secretKeyId)
.setSecretKey(secretKey)
.setType(userType);
}
private AdminService.Iface createAdminClient(String endpoint, Credential credential) {
ClientFactory clientFactory = new ClientFactory().setCredential(credential);
return clientFactory.newAdminClient(endpoint + CommonConstants.ADMIN_SERVICE_PATH,
ADMIN_SOCKET_TIMEOUT, ADMIN_CONN_TIMEOUT);
}
private TableService.Iface createTableClient(String endpoint, Credential credential) {
ClientFactory clientFactory = new ClientFactory().setCredential(credential);
return clientFactory.newTableClient(endpoint + CommonConstants.TABLE_SERVICE_PATH,
TABLE_SOCKET_TIMEOUT, TABLE_CONN_TIMEOUT);
}
private void initSdsClient() {
Credential credential = createSdsCredential(accountKey, accountSecret, UserType.DEV_XIAOMI);
adminClient = createAdminClient(sdsServiceEndpoint, credential);
credential = createSdsCredential(appKey, appSecret, UserType.APP_SECRET);
tableClient = createTableClient(sdsServiceEndpoint, credential);
}
private void initTalosClient() {
Properties pro = new Properties();
pro.setProperty(TalosClientConfigKeys.GALAXY_TALOS_SERVICE_ENDPOINT, talosServiceEndpoint);
TalosClientConfig talosClientConfig = new TalosClientConfig(pro);
com.xiaomi.infra.galaxy.rpc.thrift.Credential credential = createTalosCredential(
accountKey, accountSecret, com.xiaomi.infra.galaxy.rpc.thrift.UserType.DEV_XIAOMI);
talosAdmin = new TalosAdmin(talosClientConfig, credential);
}
public PitrDemo() {
initSdsClient();
initTalosClient();
}
private boolean shouldDo() {
return rand.nextBoolean();
}
public void listSnapshots() throws Exception {
TableSnapshots tableSnapshots = adminClient.listSnapshots(tableName);
LOG.info("table " + tableName + " snapshots are " + tableSnapshots);
}
public StreamCheckpoint getLatestCheckpoint() throws Exception {
return adminClient.getLatestStreamCheckpoint(tableName, topicName);
}
public void produceData()
throws Exception {
LOG.info("Begin to produce data for table " + tableName);
for (int i = 0; i < 1000; i++) {
Map<String, Datum> record = DataProvider.randomRecord(
DataProvider.attributesDef(enableEntityGroup));
Map<String, Datum> keys = DataProvider.getRecordKeys(tableSchema, record);
Map<String, Datum> dataRecord = Maps.difference(record, keys).entriesOnlyOnLeft();
// put
PutRequest put = new PutRequest();
put.setTableName(tableName)
.setRecord(record);
PutResult putResult = tableClient.put(put);
Preconditions.checkArgument(putResult.isSuccess());
// increment
if (shouldDo()) {
Map<String, Datum> amounts = DataProvider.randomIncrementAmounts(tableSchema,
dataRecord.keySet());
IncrementRequest increment = new IncrementRequest();
increment.setTableName(tableName)
.setKeys(keys)
.setAmounts(amounts);
tableClient.increment(increment);
}
// partial delete
if (shouldDo()) {
List<String> attributes = DataProvider.randomSelect(dataRecord.keySet(),
PARTITAL_DELETE_NUMBER);
RemoveRequest remove = new RemoveRequest();
remove.setTableName(tableName)
.setAttributes(attributes)
.setKeys(keys);
RemoveResult removeResult = tableClient.remove(remove);
Preconditions.checkArgument(removeResult.isSuccess());
}
}
LOG.info("Produce data finished for table " + tableName);
}
public TableSchema createSrcTable()
throws Exception {
Map<String, StreamSpec> streamSpecs = new HashMap<String, StreamSpec>();
streamSpecs.put(topicName, streamSpec);
TableSpec tableSpec = DataProvider.createTableSpec(appId, enableEntityGroup,
enableEntityGroupHash, streamSpecs, pitr);
TableInfo tableInfo = adminClient.createTable(tableName, tableSpec);
LOG.info("Src table " + tableName + " is created");
return tableInfo.getSpec().getSchema();
}
private TopicInfo createTopic() throws Exception {
CreateTopicRequest createTopicRequest = new CreateTopicRequest();
createTopicRequest.setTopicName(topicName);
Map<Grantee,Permission> aclMap = new HashMap<Grantee, Permission>();
Grantee grantee = new Grantee();
grantee.setIdentifier(appId)
.setType(GrantType.APP_ROOT);
aclMap.put(grantee, Permission.TOPIC_READ_AND_MESSAGE_FULL_CONTROL);
createTopicRequest.setAclMap(aclMap);
TopicAttribute topicAttribute = new TopicAttribute();
topicAttribute.setPartitionNumber(topicPartitionNumber);
createTopicRequest.setTopicAttribute(topicAttribute);
CreateTopicResponse createTopicResponse = talosAdmin.createTopic(createTopicRequest);
LOG.info("Topic " + topicName + " is created");
return createTopicResponse.getTopicInfo();
}
private StreamSpec createStreamSpec() throws Exception {
StreamSpec streamSpec = new StreamSpec();
streamSpec.setViewType(streamViewType)
.setAttributes(Lists.newArrayList(DataProvider.columnsDef().keySet()))
.setEnableStream(true);
LOG.info("Stream " + streamSpec + " is created");
return streamSpec;
}
private PointInTimeRecovery createPitr() {
PointInTimeRecovery pitr = new PointInTimeRecovery();
pitr.setEnablePointInTimeRecovery(true);
pitr.setTopicName(topicName);
pitr.setSnapshotPeriod(86400); // 1 day
pitr.setTtl(604800); // 1 week
return pitr;
}
public void createTable() throws Exception {
topicInfo = createTopic();
streamSpec = createStreamSpec();
pitr = createPitr();
tableSchema = createSrcTable();
}
public void recoverTable(long timestamp) throws Exception {
adminClient.recoverTable(tableName, destTableName, topicName, timestamp);
}
// sds config
private static final String sdsServiceEndpoint = "$sdsServiceEndpoint";
private static final String tableName = "pitrDemoTable";
private static final String destTableName = "destPitrDemoTable";
private static final boolean enableEntityGroup = true;
private static final boolean enableEntityGroupHash = true;
private static final StreamViewType streamViewType = StreamViewType.MUTATE_LOG;
private static final String accountKey = "$your_accountKey";
private static final String accountSecret = "$your_accountSecret";
private static final String appId = "$your_appId";
private static final String appKey = "$your_appKey";
private static final String appSecret = "$your_appSecret";
private static AdminService.Iface adminClient;
private static TableService.Iface tableClient;
private static TableSchema tableSchema;
private static StreamSpec streamSpec;
private static PointInTimeRecovery pitr;
// talos config
private static final String talosServiceEndpoint = "$talosServiceEndpoint";
private static final String topicName = "pitrDemoTopic";
private static final int topicPartitionNumber = 8;
private static TalosAdmin talosAdmin;
private static TopicInfo topicInfo;
public static void main(String[] args) throws Exception {
PitrDemo pitrDemo = new PitrDemo();
pitrDemo.createTable();
pitrDemo.produceData();
Thread.sleep(120000);
pitrDemo.produceData();
pitrDemo.listSnapshots();
StreamCheckpoint latestCheckpoint = pitrDemo.getLatestCheckpoint();
pitrDemo.recoverTable(latestCheckpoint.getTimestamp() - 10);
}
}
| |
package alien4cloud.tosca.container.validation;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.junit.Assert;
import org.junit.Test;
import alien4cloud.model.components.PropertyConstraint;
import alien4cloud.tosca.normative.ToscaType;
import alien4cloud.model.components.PropertyDefinition;
import alien4cloud.model.components.constraints.EqualConstraint;
import alien4cloud.model.components.constraints.GreaterOrEqualConstraint;
import alien4cloud.model.components.constraints.GreaterThanConstraint;
import alien4cloud.model.components.constraints.InRangeConstraint;
import alien4cloud.model.components.constraints.LengthConstraint;
import alien4cloud.model.components.constraints.LessOrEqualConstraint;
import alien4cloud.model.components.constraints.LessThanConstraint;
import alien4cloud.model.components.constraints.MaxLengthConstraint;
import alien4cloud.model.components.constraints.MinLengthConstraint;
import alien4cloud.model.components.constraints.PatternConstraint;
import alien4cloud.model.components.constraints.ValidValuesConstraint;
import com.google.common.collect.Lists;
public class TocsaPropertyDefaultValueConstraintsValidatorTest {
private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();;
private PropertyDefinition createDefinitions(String propertyType, PropertyConstraint constraint, String defaultValue) {
PropertyDefinition propertyDefinition = new PropertyDefinition();
propertyDefinition.setType(propertyType);
propertyDefinition.setDefault(defaultValue);
propertyDefinition.setConstraints(Lists.newArrayList(constraint));
return propertyDefinition;
}
private PropertyDefinition createEqualDefinition(String propertyType, String constraintValue, String defaultValue) {
EqualConstraint constraint = new EqualConstraint();
constraint.setEqual(constraintValue);
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createGreaterOrEqualDefinition(String propertyType, Comparable<?> constraintValue, String defaultValue) {
GreaterOrEqualConstraint constraint = new GreaterOrEqualConstraint();
constraint.setGreaterOrEqual(String.valueOf(constraintValue));
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createGreaterThanDefinition(String propertyType, Comparable<?> constraintValue, String defaultValue) {
GreaterThanConstraint constraint = new GreaterThanConstraint();
constraint.setGreaterThan(String.valueOf(constraintValue));
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createInRangeDefinition(String propertyType, Comparable minConstraintValue, Comparable maxConstraintValue, String defaultValue) {
InRangeConstraint constraint = new InRangeConstraint();
constraint.setInRange(Lists.newArrayList(String.valueOf(minConstraintValue), String.valueOf(maxConstraintValue)));
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createLenghtDefinition(String propertyType, int constraintValue, String defaultValue) {
LengthConstraint constraint = new LengthConstraint();
constraint.setLength(constraintValue);
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createLessOrEqualDefinition(String propertyType, Comparable<?> constraintValue, String defaultValue) {
LessOrEqualConstraint constraint = new LessOrEqualConstraint();
constraint.setLessOrEqual(String.valueOf(constraintValue));
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createLessDefinition(String propertyType, Comparable<?> constraintValue, String defaultValue) {
LessThanConstraint constraint = new LessThanConstraint();
constraint.setLessThan(String.valueOf(constraintValue));
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createMaxLenghtDefinition(String propertyType, int constraintValue, String defaultValue) {
MaxLengthConstraint constraint = new MaxLengthConstraint();
constraint.setMaxLength(constraintValue);
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createMinLenghtDefinition(String propertyType, int constraintValue, String defaultValue) {
MinLengthConstraint constraint = new MinLengthConstraint();
constraint.setMinLength(constraintValue);
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createPatternDefinition(String propertyType, String constraintValue, String defaultValue) {
PatternConstraint constraint = new PatternConstraint();
constraint.setPattern(constraintValue);
return createDefinitions(propertyType, constraint, defaultValue);
}
private PropertyDefinition createValidValuesDefinition(String propertyType, List<String> constraintValue, String defaultValue) {
ValidValuesConstraint constraint = new ValidValuesConstraint();
constraint.setValidValues(constraintValue);
return createDefinitions(propertyType, constraint, defaultValue);
}
// Equals tests
@Test
public void validStringEqualsShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(
createEqualDefinition(ToscaType.STRING.toString(), "constrainted value", "constrainted value"), ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidStringEqualsShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(
createEqualDefinition(ToscaType.STRING.toString(), "constrainted value", "not matching value"), ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
@Test
public void validIntegerEqualsShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createEqualDefinition(ToscaType.INTEGER.toString(), "10", "10"),
ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidIntegerEqualsShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createEqualDefinition(ToscaType.INTEGER.toString(), "10", "40"),
ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
@Test
public void validFloatEqualsShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createEqualDefinition(ToscaType.FLOAT.toString(), "10.56", "10.56"),
ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidFloatEqualsShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createEqualDefinition(ToscaType.FLOAT.toString(), "10.56", "40.56"),
ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
@Test
public void validBooleanEqualsShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createEqualDefinition(ToscaType.BOOLEAN.toString(), "true", "true"),
ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidBooleanEqualsShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createEqualDefinition(ToscaType.BOOLEAN.toString(), "true", "false"),
ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
// Greater Or Equal
@Test
public void validIntegerGreaterOrEqualShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createGreaterOrEqualDefinition(ToscaType.INTEGER.toString(), 10l, "10"),
ToscaSequence.class);
Assert.assertEquals(0, violations.size());
violations = validator.validate(createGreaterOrEqualDefinition(ToscaType.INTEGER.toString(), 10l, "20"), ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidIntegerGreaterOrEqualShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createGreaterOrEqualDefinition(ToscaType.INTEGER.toString(), 10l, "5"),
ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
@Test
public void validFloatGreaterOrEqualShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(
createGreaterOrEqualDefinition(ToscaType.FLOAT.toString(), 10.56d, "10.56"), ToscaSequence.class);
Assert.assertEquals(0, violations.size());
violations = validator.validate(createGreaterOrEqualDefinition(ToscaType.FLOAT.toString(), 10.56d, "20.56"), ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidFloatGreaterOrEqualShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(
createGreaterOrEqualDefinition(ToscaType.FLOAT.toString(), 10.56d, "5.56"), ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
// Greater Than
@Test
public void validIntegerGreaterThanShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createGreaterThanDefinition(ToscaType.INTEGER.toString(), 10l, "20"),
ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidIntegerGreaterThanShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createGreaterThanDefinition(ToscaType.INTEGER.toString(), 10l, "5"),
ToscaSequence.class);
Assert.assertEquals(1, violations.size());
violations = validator.validate(createGreaterThanDefinition(ToscaType.INTEGER.toString(), 10l, "10"), ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
@Test
public void validFloatGreaterThanShouldNotCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createGreaterThanDefinition(ToscaType.FLOAT.toString(), 10.56d, "20.56"),
ToscaSequence.class);
Assert.assertEquals(0, violations.size());
}
@Test
public void invalidFloatGreaterThanShouldCreateViolations() {
Set<ConstraintViolation<PropertyDefinition>> violations = validator.validate(createGreaterThanDefinition(ToscaType.FLOAT.toString(), 10.56d, "5.56"),
ToscaSequence.class);
Assert.assertEquals(1, violations.size());
violations = validator.validate(createGreaterThanDefinition(ToscaType.FLOAT.toString(), 10.56d, "10.56"), ToscaSequence.class);
Assert.assertEquals(1, violations.size());
}
}
| |
/*
* 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.sql.planner.planPrinter;
import com.facebook.presto.Session;
import com.facebook.presto.SystemSessionProperties;
import com.facebook.presto.cost.PlanNodeCostEstimate;
import com.facebook.presto.cost.PlanNodeStatsEstimate;
import com.facebook.presto.execution.StageInfo;
import com.facebook.presto.execution.StageStats;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.OperatorNotFoundException;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.TableHandle;
import com.facebook.presto.metadata.TableLayout;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorTableLayoutHandle;
import com.facebook.presto.spi.predicate.Domain;
import com.facebook.presto.spi.predicate.Marker;
import com.facebook.presto.spi.predicate.NullableValue;
import com.facebook.presto.spi.predicate.Range;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.FunctionInvoker;
import com.facebook.presto.sql.planner.OrderingScheme;
import com.facebook.presto.sql.planner.Partitioning;
import com.facebook.presto.sql.planner.PartitioningScheme;
import com.facebook.presto.sql.planner.PlanFragment;
import com.facebook.presto.sql.planner.SubPlan;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.iterative.GroupReference;
import com.facebook.presto.sql.planner.iterative.Lookup;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.AggregationNode.Aggregation;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.AssignUniqueId;
import com.facebook.presto.sql.planner.plan.Assignments;
import com.facebook.presto.sql.planner.plan.DeleteNode;
import com.facebook.presto.sql.planner.plan.DistinctLimitNode;
import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode;
import com.facebook.presto.sql.planner.plan.ExceptNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode.Scope;
import com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.GroupIdNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.IndexSourceNode;
import com.facebook.presto.sql.planner.plan.IntersectNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LateralJoinNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.MetadataDeleteNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.PlanFragmentId;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.facebook.presto.sql.planner.plan.PlanVisitor;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.RemoteSourceNode;
import com.facebook.presto.sql.planner.plan.RowNumberNode;
import com.facebook.presto.sql.planner.plan.SampleNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TableFinishNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.TopNRowNumberNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.UnnestNode;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.ComparisonExpression;
import com.facebook.presto.sql.tree.ComparisonExpressionType;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FrameBound;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.SymbolReference;
import com.facebook.presto.sql.tree.Window;
import com.facebook.presto.sql.tree.WindowFrame;
import com.facebook.presto.util.GraphvizPrinter;
import com.google.common.base.CaseFormat;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import io.airlift.slice.Slice;
import io.airlift.units.DataSize;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.facebook.presto.execution.StageInfo.getAllStages;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.sql.planner.DomainUtils.simplifyDomain;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION;
import static com.facebook.presto.sql.planner.planPrinter.PlanNodeStatsSummarizer.aggregatePlanNodeStats;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getOnlyElement;
import static io.airlift.units.DataSize.succinctBytes;
import static java.lang.Double.isFinite;
import static java.lang.Double.isNaN;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
public class PlanPrinter
{
private final StringBuilder output = new StringBuilder();
private final Metadata metadata;
private final Optional<Map<PlanNodeId, PlanNodeStats>> stats;
private final boolean verbose;
private PlanPrinter(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session sesion)
{
this(plan, types, metadata, lookup, sesion, 0, false);
}
private PlanPrinter(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session session, int indent, boolean verbose)
{
requireNonNull(plan, "plan is null");
requireNonNull(types, "types is null");
requireNonNull(metadata, "metadata is null");
requireNonNull(lookup, "lookup is null");
this.metadata = metadata;
this.stats = Optional.empty();
this.verbose = verbose;
Visitor visitor = new Visitor(types, lookup, session);
plan.accept(visitor, indent);
}
private PlanPrinter(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session session, Map<PlanNodeId, PlanNodeStats> stats, int indent, boolean verbose)
{
requireNonNull(plan, "plan is null");
requireNonNull(types, "types is null");
requireNonNull(metadata, "metadata is null");
requireNonNull(lookup, "lookup is null");
this.metadata = metadata;
this.stats = Optional.of(stats);
this.verbose = verbose;
Visitor visitor = new Visitor(types, lookup, session);
plan.accept(visitor, indent);
}
@Override
public String toString()
{
return output.toString();
}
public static String textLogicalPlan(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session session)
{
return new PlanPrinter(plan, types, metadata, lookup, session).toString();
}
public static String textLogicalPlan(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session session, int indent)
{
return textLogicalPlan(plan, types, metadata, lookup, session, indent, false);
}
public static String textLogicalPlan(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session session, int indent, boolean verbose)
{
return new PlanPrinter(plan, types, metadata, lookup, session, indent, verbose).toString();
}
public static String textLogicalPlan(PlanNode plan, Map<Symbol, Type> types, Metadata metadata, Lookup lookup, Session session, Map<PlanNodeId, PlanNodeStats> stats, int indent, boolean verbose)
{
return new PlanPrinter(plan, types, metadata, lookup, session, stats, indent, verbose).toString();
}
public static String textDistributedPlan(StageInfo outputStageInfo, Metadata metadata, Lookup lookup, Session session)
{
return textDistributedPlan(outputStageInfo, metadata, lookup, session, false);
}
public static String textDistributedPlan(StageInfo outputStageInfo, Metadata metadata, Lookup lookup, Session session, boolean verbose)
{
StringBuilder builder = new StringBuilder();
List<StageInfo> allStages = outputStageInfo.getSubStages().stream()
.flatMap(stage -> getAllStages(Optional.of(stage)).stream())
.collect(toImmutableList());
for (StageInfo stageInfo : allStages) {
Map<PlanNodeId, PlanNodeStats> aggregatedStats = aggregatePlanNodeStats(stageInfo);
builder.append(formatFragment(metadata, lookup, session, stageInfo.getPlan(), Optional.of(stageInfo), Optional.of(aggregatedStats), verbose));
}
return builder.toString();
}
public static String textDistributedPlan(SubPlan plan, Metadata metadata, Lookup lookup, Session session)
{
return textDistributedPlan(plan, metadata, lookup, session, false);
}
public static String textDistributedPlan(SubPlan plan, Metadata metadata, Lookup lookup, Session session, boolean verbose)
{
StringBuilder builder = new StringBuilder();
for (PlanFragment fragment : plan.getAllFragments()) {
builder.append(formatFragment(metadata, lookup, session, fragment, Optional.empty(), Optional.empty(), verbose));
}
return builder.toString();
}
private static String formatFragment(Metadata metadata, Lookup lookup, Session session, PlanFragment fragment, Optional<StageInfo> stageInfo, Optional<Map<PlanNodeId, PlanNodeStats>> planNodeStats, boolean verbose)
{
StringBuilder builder = new StringBuilder();
builder.append(format("Fragment %s [%s]\n",
fragment.getId(),
fragment.getPartitioning()));
if (stageInfo.isPresent()) {
StageStats stageStats = stageInfo.get().getStageStats();
double avgPositionsPerTask = stageInfo.get().getTasks().stream().mapToLong(task -> task.getStats().getProcessedInputPositions()).average().orElse(Double.NaN);
double squaredDifferences = stageInfo.get().getTasks().stream().mapToDouble(task -> Math.pow(task.getStats().getProcessedInputPositions() - avgPositionsPerTask, 2)).sum();
double sdAmongTasks = Math.sqrt(squaredDifferences / stageInfo.get().getTasks().size());
builder.append(indentString(1))
.append(format("CPU: %s, Input: %s (%s); per task: avg.: %s std.dev.: %s, Output: %s (%s)",
stageStats.getTotalCpuTime(),
formatPositions(stageStats.getProcessedInputPositions()),
stageStats.getProcessedInputDataSize(),
formatDouble(avgPositionsPerTask),
formatDouble(sdAmongTasks),
formatPositions(stageStats.getOutputPositions()),
stageStats.getOutputDataSize()));
if (isNonZero(stageStats.getSpilledDataSize())) {
builder.append(", Spilled " + stageStats.getSpilledDataSize());
}
builder.append("\n");
}
PartitioningScheme partitioningScheme = fragment.getPartitioningScheme();
builder.append(indentString(1))
.append(format("Output layout: [%s]\n",
Joiner.on(", ").join(partitioningScheme.getOutputLayout())));
boolean replicateNullsAndAny = partitioningScheme.isReplicateNullsAndAny();
List<String> arguments = partitioningScheme.getPartitioning().getArguments().stream()
.map(argument -> {
if (argument.isConstant()) {
NullableValue constant = argument.getConstant();
String printableValue = castToVarchar(constant.getType(), constant.getValue(), metadata.getFunctionRegistry(), session);
return constant.getType().getDisplayName() + "(" + printableValue + ")";
}
return argument.getColumn().toString();
})
.collect(toImmutableList());
builder.append(indentString(1));
if (replicateNullsAndAny) {
builder.append(format("Output partitioning: %s (replicate nulls and any) [%s]%s\n",
partitioningScheme.getPartitioning().getHandle(),
Joiner.on(", ").join(arguments),
formatHash(partitioningScheme.getHashColumn())));
}
else {
builder.append(format("Output partitioning: %s [%s]%s\n",
partitioningScheme.getPartitioning().getHandle(),
Joiner.on(", ").join(arguments),
formatHash(partitioningScheme.getHashColumn())));
}
if (stageInfo.isPresent()) {
builder.append(textLogicalPlan(fragment.getRoot(), fragment.getSymbols(), metadata, lookup, session, planNodeStats.get(), 1, verbose))
.append("\n");
}
else {
builder.append(textLogicalPlan(fragment.getRoot(), fragment.getSymbols(), metadata, lookup, session, 1, verbose))
.append("\n");
}
return builder.toString();
}
private static boolean isNonZero(DataSize dataSize)
{
return dataSize != null && dataSize.getValue() != 0;
}
public static String graphvizLogicalPlan(PlanNode plan, Map<Symbol, Type> types)
{
PlanFragment fragment = new PlanFragment(
new PlanFragmentId("graphviz_plan"),
plan,
types,
SINGLE_DISTRIBUTION,
ImmutableList.of(plan.getId()),
new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), plan.getOutputSymbols()));
return GraphvizPrinter.printLogical(ImmutableList.of(fragment));
}
public static String graphvizDistributedPlan(SubPlan plan)
{
return GraphvizPrinter.printDistributed(plan);
}
private void print(int indent, String format, Object... args)
{
String value;
if (args.length == 0) {
value = format;
}
else {
value = format(format, args);
}
output.append(indentString(indent)).append(value).append('\n');
}
private void print(int indent, String format, List<Object> args)
{
print(indent, format, args.toArray(new Object[args.size()]));
}
private void printStats(int intent, PlanNodeId planNodeId)
{
printStats(intent, planNodeId, false, false);
}
private void printStats(int indent, PlanNodeId planNodeId, boolean printInput, boolean printFiltered)
{
if (!stats.isPresent()) {
return;
}
long totalMillis = stats.get().values().stream()
.mapToLong(node -> node.getPlanNodeWallTime().toMillis())
.sum();
PlanNodeStats nodeStats = stats.get().get(planNodeId);
if (nodeStats == null) {
output.append(indentString(indent));
output.append("Cost: ?");
if (printInput) {
output.append(", Input: ? rows (?B)");
}
output.append(", Output: ? rows (?B)");
if (printFiltered) {
output.append(", Filtered: ?%");
}
output.append('\n');
return;
}
double fraction = 100.0d * nodeStats.getPlanNodeWallTime().toMillis() / totalMillis;
output.append(indentString(indent));
output.append("CPU fraction: " + formatDouble(fraction) + "%");
if (printInput) {
output.append(format(", Input: %s (%s)",
formatPositions(nodeStats.getPlanNodeInputPositions()),
nodeStats.getPlanNodeInputDataSize().toString()));
}
output.append(format(", Output: %s (%s)",
formatPositions(nodeStats.getPlanNodeOutputPositions()),
nodeStats.getPlanNodeOutputDataSize().toString()));
if (printFiltered) {
double filtered = 100.0d * (nodeStats.getPlanNodeInputPositions() - nodeStats.getPlanNodeOutputPositions()) / nodeStats.getPlanNodeInputPositions();
output.append(", Filtered: " + formatDouble(filtered) + "%");
}
if (isNonZero(nodeStats.getPlanNodeSpilledDataSize())) {
output.append(", Spilled: " + nodeStats.getPlanNodeSpilledDataSize());
}
output.append('\n');
printDistributions(indent, nodeStats);
if (nodeStats.getWindowOperatorStats().isPresent()) {
// TODO: Once PlanNodeStats becomes broken into smaller classes, we should rely on toString() method of WindowOperatorStats here
printWindowOperatorStats(indent, nodeStats.getWindowOperatorStats().get());
}
}
private void printDistributions(int indent, PlanNodeStats nodeStats)
{
Map<String, Double> inputAverages = nodeStats.getOperatorInputPositionsAverages();
Map<String, Double> inputStdDevs = nodeStats.getOperatorInputPositionsStdDevs();
Map<String, Double> hashCollisionsAverages = nodeStats.getOperatorHashCollisionsAverages();
Map<String, Double> hashCollisionsStdDevs = nodeStats.getOperatorHashCollisionsStdDevs();
Map<String, Double> expectedHashCollisionsAverages = nodeStats.getOperatorExpectedCollisionsAverages();
Map<String, String> translatedOperatorTypes = translateOperatorTypes(nodeStats.getOperatorTypes());
for (String operator : translatedOperatorTypes.keySet()) {
String translatedOperatorType = translatedOperatorTypes.get(operator);
double inputAverage = inputAverages.get(operator);
output.append(indentString(indent));
output.append(translatedOperatorType);
output.append(format(Locale.US, "Input avg.: %s rows, Input std.dev.: %s%%",
formatDouble(inputAverage), formatDouble(100.0d * inputStdDevs.get(operator) / inputAverage)));
output.append('\n');
double hashCollisionsAverage = hashCollisionsAverages.getOrDefault(operator, 0.0d);
double expectedHashCollisionsAverage = expectedHashCollisionsAverages.getOrDefault(operator, 0.0d);
if (hashCollisionsAverage != 0.0d) {
double hashCollisionsStdDevRatio = hashCollisionsStdDevs.get(operator) / hashCollisionsAverage;
if (translatedOperatorType.isEmpty()) {
output.append(indentString(indent));
}
else {
output.append(indentString(indent + 2));
}
if (expectedHashCollisionsAverage != 0.0d) {
double hashCollisionsRatio = hashCollisionsAverage / expectedHashCollisionsAverage;
output.append(format(Locale.US, "Collisions avg.: %s (%s%% est.), Collisions std.dev.: %s%%",
formatDouble(hashCollisionsAverage), formatDouble(hashCollisionsRatio * 100.0d), formatDouble(hashCollisionsStdDevRatio * 100.0d)));
}
else {
output.append(format(Locale.US, "Collisions avg.: %s, Collisions std.dev.: %s%%",
formatDouble(hashCollisionsAverage), formatDouble(hashCollisionsStdDevRatio * 100.0d)));
}
output.append('\n');
}
}
}
private static Map<String, String> translateOperatorTypes(Set<String> operators)
{
if (operators.size() == 1) {
// don't display operator (plan node) name again
return ImmutableMap.of(getOnlyElement(operators), "");
}
if (operators.contains("LookupJoinOperator") && operators.contains("HashBuilderOperator")) {
// join plan node
return ImmutableMap.of(
"LookupJoinOperator", "Left (probe) ",
"HashBuilderOperator", "Right (build) ");
}
return ImmutableMap.of();
}
private void printWindowOperatorStats(int indent, WindowOperatorStats stats)
{
if (!verbose) {
// these stats are too detailed for non-verbose mode
return;
}
output.append(indentString(indent));
output.append(format("Active Drivers: [ %d / %d ]", stats.getActiveDrivers(), stats.getTotalDrivers()));
output.append('\n');
output.append(indentString(indent));
output.append(format("Index size: std.dev.: %s bytes , %s rows", formatDouble(stats.getIndexSizeStdDev()), formatDouble(stats.getIndexPositionsStdDev())));
output.append('\n');
output.append(indentString(indent));
output.append(format("Index count per driver: std.dev.: %s", formatDouble(stats.getIndexCountPerDriverStdDev())));
output.append('\n');
output.append(indentString(indent));
output.append(format("Rows per driver: std.dev.: %s", formatDouble(stats.getRowsPerDriverStdDev())));
output.append('\n');
output.append(indentString(indent));
output.append(format("Size of partition: std.dev.: %s", formatDouble(stats.getPartitionRowsStdDev())));
output.append('\n');
}
private static String formatDouble(double value)
{
if (isFinite(value)) {
return format(Locale.US, "%.2f", value);
}
return "?";
}
private static String formatAsLong(double value)
{
if (isFinite(value)) {
return format(Locale.US, "%d", Math.round(value));
}
return "?";
}
private static String formatPositions(long positions)
{
if (positions == 1) {
return "1 row";
}
return positions + " rows";
}
private static String indentString(int indent)
{
return Strings.repeat(" ", indent);
}
private class Visitor
extends PlanVisitor<Void, Integer>
{
private final Map<Symbol, Type> types;
private final Lookup lookup;
private final Session session;
@SuppressWarnings("AssignmentToCollectionOrArrayFieldFromParameter")
public Visitor(Map<Symbol, Type> types, Lookup lookup, Session session)
{
this.types = types;
this.lookup = lookup;
this.session = session;
}
@Override
public Void visitExplainAnalyze(ExplainAnalyzeNode node, Integer indent)
{
print(indent, "- ExplainAnalyze => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitJoin(JoinNode node, Integer indent)
{
List<Expression> joinExpressions = new ArrayList<>();
for (JoinNode.EquiJoinClause clause : node.getCriteria()) {
joinExpressions.add(clause.toExpression());
}
node.getFilter().ifPresent(expression -> joinExpressions.add(expression));
// Check if the node is actually a cross join node
if (node.getType() == JoinNode.Type.INNER && joinExpressions.isEmpty()) {
print(indent, "- CrossJoin => [%s]", formatOutputs(node.getOutputSymbols()));
}
else {
print(indent, "- %s[%s]%s => [%s]",
node.getType().getJoinLabel(),
Joiner.on(" AND ").join(joinExpressions),
formatHash(node.getLeftHashSymbol(), node.getRightHashSymbol()),
formatOutputs(node.getOutputSymbols()));
}
node.getSortExpression().ifPresent(expression -> print(indent + 2, "SortExpression[%s]", expression));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
node.getLeft().accept(this, indent + 1);
node.getRight().accept(this, indent + 1);
return null;
}
@Override
public Void visitSemiJoin(SemiJoinNode node, Integer indent)
{
print(indent, "- SemiJoin[%s = %s]%s => [%s]",
node.getSourceJoinSymbol(),
node.getFilteringSourceJoinSymbol(),
formatHash(node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
node.getSource().accept(this, indent + 1);
node.getFilteringSource().accept(this, indent + 1);
return null;
}
@Override
public Void visitIndexSource(IndexSourceNode node, Integer indent)
{
print(indent, "- IndexSource[%s, lookup = %s] => [%s]", node.getIndexHandle(), node.getLookupSymbols(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (Map.Entry<Symbol, ColumnHandle> entry : node.getAssignments().entrySet()) {
if (node.getOutputSymbols().contains(entry.getKey())) {
print(indent + 2, "%s := %s", entry.getKey(), entry.getValue());
}
}
return null;
}
@Override
public Void visitIndexJoin(IndexJoinNode node, Integer indent)
{
List<Expression> joinExpressions = new ArrayList<>();
for (IndexJoinNode.EquiJoinClause clause : node.getCriteria()) {
joinExpressions.add(new ComparisonExpression(ComparisonExpressionType.EQUAL,
clause.getProbe().toSymbolReference(),
clause.getIndex().toSymbolReference()));
}
print(indent, "- %sIndexJoin[%s]%s => [%s]",
node.getType().getJoinLabel(),
Joiner.on(" AND ").join(joinExpressions),
formatHash(node.getProbeHashSymbol(), node.getIndexHashSymbol()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
node.getProbeSource().accept(this, indent + 1);
node.getIndexSource().accept(this, indent + 1);
return null;
}
@Override
public Void visitLimit(LimitNode node, Integer indent)
{
print(indent, "- Limit%s[%s] => [%s]", node.isPartial() ? "Partial" : "", node.getCount(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitDistinctLimit(DistinctLimitNode node, Integer indent)
{
print(indent, "- DistinctLimit%s[%s]%s => [%s]",
node.isPartial() ? "Partial" : "",
node.getLimit(),
formatHash(node.getHashSymbol()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitAggregation(AggregationNode node, Integer indent)
{
String type = "";
if (node.getStep() != AggregationNode.Step.SINGLE) {
type = format("(%s)", node.getStep().toString());
}
String key = "";
if (!node.getGroupingKeys().isEmpty()) {
key = node.getGroupingKeys().toString();
}
print(indent, "- Aggregate%s%s%s => [%s]", type, key, formatHash(node.getHashSymbol()), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (Map.Entry<Symbol, Aggregation> entry : node.getAggregations().entrySet()) {
if (entry.getValue().getMask().isPresent()) {
print(indent + 2, "%s := %s (mask = %s)", entry.getKey(), entry.getValue().getCall(), entry.getValue().getMask().get());
}
else {
print(indent + 2, "%s := %s", entry.getKey(), entry.getValue().getCall());
}
}
return processChildren(node, indent + 1);
}
@Override
public Void visitGroupId(GroupIdNode node, Integer indent)
{
// grouping sets are easier to understand in terms of inputs
List<List<Symbol>> inputGroupingSetSymbols = node.getGroupingSets().stream()
.map(set -> set.stream()
.map(symbol -> node.getGroupingSetMappings().get(symbol))
.collect(Collectors.toList()))
.collect(Collectors.toList());
print(indent, "- GroupId%s => [%s]", inputGroupingSetSymbols, formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (Map.Entry<Symbol, Symbol> mapping : node.getGroupingSetMappings().entrySet()) {
print(indent + 2, "%s := %s", mapping.getKey(), mapping.getValue());
}
for (Map.Entry<Symbol, Symbol> argument : node.getArgumentMappings().entrySet()) {
print(indent + 2, "%s := %s", argument.getKey(), argument.getValue());
}
return processChildren(node, indent + 1);
}
@Override
public Void visitMarkDistinct(MarkDistinctNode node, Integer indent)
{
print(indent, "- MarkDistinct[distinct=%s marker=%s]%s => [%s]",
formatOutputs(node.getDistinctSymbols()),
node.getMarkerSymbol(),
formatHash(node.getHashSymbol()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitWindow(WindowNode node, Integer indent)
{
List<String> partitionBy = Lists.transform(node.getPartitionBy(), Functions.toStringFunction());
List<String> orderBy = Lists.transform(node.getOrderBy(), input -> input + " " + node.getOrderings().get(input));
List<String> args = new ArrayList<>();
if (!partitionBy.isEmpty()) {
List<Symbol> prePartitioned = node.getPartitionBy().stream()
.filter(node.getPrePartitionedInputs()::contains)
.collect(toImmutableList());
List<Symbol> notPrePartitioned = node.getPartitionBy().stream()
.filter(column -> !node.getPrePartitionedInputs().contains(column))
.collect(toImmutableList());
StringBuilder builder = new StringBuilder();
if (!prePartitioned.isEmpty()) {
builder.append("<")
.append(Joiner.on(", ").join(prePartitioned))
.append(">");
if (!notPrePartitioned.isEmpty()) {
builder.append(", ");
}
}
if (!notPrePartitioned.isEmpty()) {
builder.append(Joiner.on(", ").join(notPrePartitioned));
}
args.add(format("partition by (%s)", builder));
}
if (!orderBy.isEmpty()) {
args.add(format("order by (%s)", Stream.concat(
node.getOrderBy().stream()
.limit(node.getPreSortedOrderPrefix())
.map(symbol -> "<" + symbol + " " + node.getOrderings().get(symbol) + ">"),
node.getOrderBy().stream()
.skip(node.getPreSortedOrderPrefix())
.map(symbol -> symbol + " " + node.getOrderings().get(symbol)))
.collect(Collectors.joining(", "))));
}
print(indent, "- Window[%s]%s => [%s]", Joiner.on(", ").join(args), formatHash(node.getHashSymbol()), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (Map.Entry<Symbol, WindowNode.Function> entry : node.getWindowFunctions().entrySet()) {
FunctionCall call = entry.getValue().getFunctionCall();
String frameInfo = call.getWindow()
.flatMap(Window::getFrame)
.map(PlanPrinter::formatFrame)
.orElse("");
print(indent + 2, "%s := %s(%s) %s", entry.getKey(), call.getName(), Joiner.on(", ").join(call.getArguments()), frameInfo);
}
return processChildren(node, indent + 1);
}
@Override
public Void visitTopNRowNumber(TopNRowNumberNode node, Integer indent)
{
List<String> partitionBy = Lists.transform(node.getPartitionBy(), Functions.toStringFunction());
List<String> orderBy = Lists.transform(node.getOrderBy(), input -> input + " " + node.getOrderings().get(input));
List<String> args = new ArrayList<>();
args.add(format("partition by (%s)", Joiner.on(", ").join(partitionBy)));
args.add(format("order by (%s)", Joiner.on(", ").join(orderBy)));
print(indent, "- TopNRowNumber[%s limit %s]%s => [%s]",
Joiner.on(", ").join(args),
node.getMaxRowCountPerPartition(),
formatHash(node.getHashSymbol()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
print(indent + 2, "%s := %s", node.getRowNumberSymbol(), "row_number()");
return processChildren(node, indent + 1);
}
@Override
public Void visitRowNumber(RowNumberNode node, Integer indent)
{
List<String> partitionBy = Lists.transform(node.getPartitionBy(), Functions.toStringFunction());
List<String> args = new ArrayList<>();
if (!partitionBy.isEmpty()) {
args.add(format("partition by (%s)", Joiner.on(", ").join(partitionBy)));
}
if (node.getMaxRowCountPerPartition().isPresent()) {
args.add(format("limit = %s", node.getMaxRowCountPerPartition().get()));
}
print(indent, "- RowNumber[%s]%s => [%s]",
Joiner.on(", ").join(args),
formatHash(node.getHashSymbol()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
print(indent + 2, "%s := %s", node.getRowNumberSymbol(), "row_number()");
return processChildren(node, indent + 1);
}
@Override
public Void visitTableScan(TableScanNode node, Integer indent)
{
TableHandle table = node.getTable();
print(indent, "- TableScan[%s, originalConstraint = %s] => [%s]", table, node.getOriginalConstraint(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
printTableScanInfo(node, indent);
return null;
}
@Override
public Void visitValues(ValuesNode node, Integer indent)
{
print(indent, "- Values => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (List<Expression> row : node.getRows()) {
print(indent + 2, "(" + Joiner.on(", ").join(row) + ")");
}
return null;
}
@Override
public Void visitFilter(FilterNode node, Integer indent)
{
return visitScanFilterAndProjectInfo(node.getId(), Optional.of(node), Optional.empty(), indent);
}
@Override
public Void visitProject(ProjectNode node, Integer indent)
{
if (node.getSource() instanceof FilterNode) {
return visitScanFilterAndProjectInfo(node.getId(), Optional.of((FilterNode) node.getSource()), Optional.of(node), indent);
}
return visitScanFilterAndProjectInfo(node.getId(), Optional.empty(), Optional.of(node), indent);
}
private Void visitScanFilterAndProjectInfo(
PlanNodeId planNodeId,
Optional<FilterNode> filterNode,
Optional<ProjectNode> projectNode,
int indent)
{
checkState(projectNode.isPresent() || filterNode.isPresent());
PlanNode sourceNode;
if (filterNode.isPresent()) {
sourceNode = filterNode.get().getSource();
}
else {
sourceNode = projectNode.get().getSource();
}
Optional<TableScanNode> scanNode;
if (sourceNode instanceof TableScanNode) {
scanNode = Optional.of((TableScanNode) sourceNode);
}
else {
scanNode = Optional.empty();
}
String format = "[";
String operatorName = "- ";
List<Object> arguments = new LinkedList<>();
if (scanNode.isPresent()) {
operatorName += "Scan";
format += "table = %s, originalConstraint = %s";
if (filterNode.isPresent()) {
format += ", ";
}
TableHandle table = scanNode.get().getTable();
arguments.add(table);
arguments.add(scanNode.get().getOriginalConstraint());
}
if (filterNode.isPresent()) {
operatorName += "Filter";
format += "filterPredicate = %s";
arguments.add(filterNode.get().getPredicate());
}
format += "] => [%s]";
if (projectNode.isPresent()) {
operatorName += "Project";
arguments.add(formatOutputs(projectNode.get().getOutputSymbols()));
}
else {
arguments.add(formatOutputs(filterNode.get().getOutputSymbols()));
}
format = operatorName + format;
print(indent, format, arguments);
printPlanNodesStatsAndCost(indent + 2,
Stream.of(scanNode, filterNode, projectNode)
.filter(Optional::isPresent)
.map(Optional::get)
.toArray(PlanNode[]::new));
printStats(indent + 2, planNodeId, true, true);
if (projectNode.isPresent()) {
printAssignments(projectNode.get().getAssignments(), indent + 2);
}
if (scanNode.isPresent()) {
printTableScanInfo(scanNode.get(), indent);
return null;
}
sourceNode.accept(this, indent + 1);
return null;
}
private void printTableScanInfo(TableScanNode node, int indent)
{
TableHandle table = node.getTable();
TupleDomain<ColumnHandle> predicate = node.getLayout()
.map(layoutHandle -> metadata.getLayout(session, layoutHandle))
.map(TableLayout::getPredicate)
.orElse(TupleDomain.all());
if (node.getLayout().isPresent()) {
// TODO: find a better way to do this
ConnectorTableLayoutHandle layout = node.getLayout().get().getConnectorHandle();
if (!table.getConnectorHandle().toString().equals(layout.toString())) {
print(indent + 2, "LAYOUT: %s", layout);
}
}
if (predicate.isNone()) {
print(indent + 2, ":: NONE");
}
else {
// first, print output columns and their constraints
for (Map.Entry<Symbol, ColumnHandle> assignment : node.getAssignments().entrySet()) {
ColumnHandle column = assignment.getValue();
print(indent + 2, "%s := %s", assignment.getKey(), column);
printConstraint(indent + 3, column, predicate);
}
// then, print constraints for columns that are not in the output
if (!predicate.isAll()) {
Set<ColumnHandle> outputs = ImmutableSet.copyOf(node.getAssignments().values());
predicate.getDomains().get()
.entrySet().stream()
.filter(entry -> !outputs.contains(entry.getKey()))
.forEach(entry -> {
ColumnHandle column = entry.getKey();
print(indent + 2, "%s", column);
printConstraint(indent + 3, column, predicate);
});
}
}
}
@Override
public Void visitUnnest(UnnestNode node, Integer indent)
{
print(indent, "- Unnest [replicate=%s, unnest=%s] => [%s]", formatOutputs(node.getReplicateSymbols()), formatOutputs(node.getUnnestSymbols().keySet()), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitOutput(OutputNode node, Integer indent)
{
print(indent, "- Output[%s] => [%s]", Joiner.on(", ").join(node.getColumnNames()), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (int i = 0; i < node.getColumnNames().size(); i++) {
String name = node.getColumnNames().get(i);
Symbol symbol = node.getOutputSymbols().get(i);
if (!name.equals(symbol.toString())) {
print(indent + 2, "%s := %s", name, symbol);
}
}
return processChildren(node, indent + 1);
}
@Override
public Void visitTopN(TopNNode node, Integer indent)
{
Iterable<String> keys = Iterables.transform(node.getOrderBy(), input -> input + " " + node.getOrderings().get(input));
print(indent, "- TopN[%s by (%s)] => [%s]", node.getCount(), Joiner.on(", ").join(keys), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitSort(SortNode node, Integer indent)
{
Iterable<String> keys = Iterables.transform(node.getOrderBy(), input -> input + " " + node.getOrderings().get(input));
boolean isPartial = false;
if (SystemSessionProperties.isDistributedSortEnabled(session)) {
isPartial = true;
}
print(indent, "- %sSort[%s] => [%s]",
isPartial ? "Partial" : "",
Joiner.on(", ").join(keys),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitRemoteSource(RemoteSourceNode node, Integer indent)
{
print(indent, "- Remote%s[%s] => [%s]",
node.getOrderingScheme().isPresent() ? "Merge" : "Source",
Joiner.on(',').join(node.getSourceFragmentIds()),
formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return null;
}
@Override
public Void visitUnion(UnionNode node, Integer indent)
{
print(indent, "- Union => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitIntersect(IntersectNode node, Integer indent)
{
print(indent, "- Intersect => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitExcept(ExceptNode node, Integer indent)
{
print(indent, "- Except => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitTableWriter(TableWriterNode node, Integer indent)
{
print(indent, "- TableWriter => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
for (int i = 0; i < node.getColumnNames().size(); i++) {
String name = node.getColumnNames().get(i);
Symbol symbol = node.getColumns().get(i);
print(indent + 2, "%s := %s", name, symbol);
}
return processChildren(node, indent + 1);
}
@Override
public Void visitTableFinish(TableFinishNode node, Integer indent)
{
print(indent, "- TableCommit[%s] => [%s]", node.getTarget(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitSample(SampleNode node, Integer indent)
{
print(indent, "- Sample[%s: %s] => [%s]", node.getSampleType(), node.getSampleRatio(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitExchange(ExchangeNode node, Integer indent)
{
if (node.getOrderingScheme().isPresent()) {
OrderingScheme orderingScheme = node.getOrderingScheme().get();
List<String> orderBy = orderingScheme.getOrderBy()
.stream()
.map(input -> input + " " + orderingScheme.getOrderings().get(input))
.collect(toImmutableList());
print(indent, "- %sMerge[%s] => [%s]",
UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, node.getScope().toString()),
Joiner.on(", ").join(orderBy),
formatOutputs(node.getOutputSymbols()));
}
else if (node.getScope() == Scope.LOCAL) {
print(indent, "- LocalExchange[%s%s]%s (%s) => %s",
node.getPartitioningScheme().getPartitioning().getHandle(),
node.getPartitioningScheme().isReplicateNullsAndAny() ? " - REPLICATE NULLS AND ANY" : "",
formatHash(node.getPartitioningScheme().getHashColumn()),
Joiner.on(", ").join(node.getPartitioningScheme().getPartitioning().getArguments()),
formatOutputs(node.getOutputSymbols()));
}
else {
print(indent, "- %sExchange[%s%s]%s => %s",
UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, node.getScope().toString()),
node.getType(),
node.getPartitioningScheme().isReplicateNullsAndAny() ? " - REPLICATE NULLS AND ANY" : "",
formatHash(node.getPartitioningScheme().getHashColumn()),
formatOutputs(node.getOutputSymbols()));
}
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitDelete(DeleteNode node, Integer indent)
{
print(indent, "- Delete[%s] => [%s]", node.getTarget(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitMetadataDelete(MetadataDeleteNode node, Integer indent)
{
print(indent, "- MetadataDelete[%s] => [%s]", node.getTarget(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitEnforceSingleRow(EnforceSingleRowNode node, Integer indent)
{
print(indent, "- Scalar => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitAssignUniqueId(AssignUniqueId node, Integer indent)
{
print(indent, "- AssignUniqueId => [%s]", formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
public Void visitGroupReference(GroupReference node, Integer indent)
{
print(indent, "- GroupReference[%s] => [%s]", node.getGroupId(), formatOutputs(node.getOutputSymbols()));
return processChildren(node, indent + 1);
}
@Override
public Void visitApply(ApplyNode node, Integer indent)
{
print(indent, "- Apply[%s] => [%s]", node.getCorrelation(), formatOutputs(node.getOutputSymbols()));
printPlanNodesStatsAndCost(indent + 2, node);
printStats(indent + 2, node.getId());
printAssignments(node.getSubqueryAssignments(), indent + 4);
return processChildren(node, indent + 1);
}
@Override
public Void visitLateralJoin(LateralJoinNode node, Integer indent)
{
print(indent, "- Lateral[%s] => [%s]", node.getCorrelation(), formatOutputs(node.getOutputSymbols()));
printStats(indent + 2, node.getId());
return processChildren(node, indent + 1);
}
@Override
protected Void visitPlan(PlanNode node, Integer indent)
{
throw new UnsupportedOperationException("not yet implemented: " + node.getClass().getName());
}
private Void processChildren(PlanNode node, int indent)
{
for (PlanNode child : node.getSources()) {
child.accept(this, indent);
}
return null;
}
private void printAssignments(Assignments assignments, int indent)
{
for (Map.Entry<Symbol, Expression> entry : assignments.getMap().entrySet()) {
if (entry.getValue() instanceof SymbolReference && ((SymbolReference) entry.getValue()).getName().equals(entry.getKey().getName())) {
// skip identity assignments
continue;
}
print(indent, "%s := %s", entry.getKey(), entry.getValue());
}
}
private String formatOutputs(Iterable<Symbol> symbols)
{
return Joiner.on(", ").join(Iterables.transform(symbols, input -> input + ":" + types.get(input).getDisplayName()));
}
private void printConstraint(int indent, ColumnHandle column, TupleDomain<ColumnHandle> constraint)
{
checkArgument(!constraint.isNone());
Map<ColumnHandle, Domain> domains = constraint.getDomains().get();
if (!constraint.isAll() && domains.containsKey(column)) {
print(indent, ":: %s", formatDomain(simplifyDomain(domains.get(column))));
}
}
private String formatDomain(Domain domain)
{
ImmutableList.Builder<String> parts = ImmutableList.builder();
if (domain.isNullAllowed()) {
parts.add("NULL");
}
Type type = domain.getType();
domain.getValues().getValuesProcessor().consume(
ranges -> {
for (Range range : ranges.getOrderedRanges()) {
StringBuilder builder = new StringBuilder();
if (range.isSingleValue()) {
String value = castToVarchar(type, range.getSingleValue(), PlanPrinter.this.metadata.getFunctionRegistry(), session);
builder.append('[').append(value).append(']');
}
else {
builder.append((range.getLow().getBound() == Marker.Bound.EXACTLY) ? '[' : '(');
if (range.getLow().isLowerUnbounded()) {
builder.append("<min>");
}
else {
builder.append(castToVarchar(type, range.getLow().getValue(), PlanPrinter.this.metadata.getFunctionRegistry(), session));
}
builder.append(", ");
if (range.getHigh().isUpperUnbounded()) {
builder.append("<max>");
}
else {
builder.append(castToVarchar(type, range.getHigh().getValue(), PlanPrinter.this.metadata.getFunctionRegistry(), session));
}
builder.append((range.getHigh().getBound() == Marker.Bound.EXACTLY) ? ']' : ')');
}
parts.add(builder.toString());
}
},
discreteValues -> discreteValues.getValues().stream()
.map(value -> castToVarchar(type, value, PlanPrinter.this.metadata.getFunctionRegistry(), session))
.sorted() // Sort so the values will be printed in predictable order
.forEach(parts::add),
allOrNone -> {
if (allOrNone.isAll()) {
parts.add("ALL VALUES");
}
});
return "[" + Joiner.on(", ").join(parts.build()) + "]";
}
private void printPlanNodesStatsAndCost(int indent, PlanNode... nodes)
{
if (Arrays.stream(nodes).anyMatch(this::isKnownPlanNodeStatsOrCost)) {
String formattedStatsAndCost = Joiner.on("/").join(Arrays.stream(nodes)
.map(this::formatPlanNodeStatsAndCost)
.collect(toImmutableList()));
print(indent, "Cost: %s", formattedStatsAndCost);
}
}
private boolean isKnownPlanNodeStatsOrCost(PlanNode node)
{
return !PlanNodeCostEstimate.UNKNOWN_COST.equals(lookup.getCumulativeCost(node, session, types))
|| !PlanNodeStatsEstimate.UNKNOWN_STATS.equals(lookup.getStats(node, session, types));
}
private String formatPlanNodeStatsAndCost(PlanNode node)
{
PlanNodeStatsEstimate stats = lookup.getStats(node, session, types);
PlanNodeCostEstimate cost = lookup.getCumulativeCost(node, session, types);
return String.format("{rows: %s (%s), cpu: %s, memory: %s, network: %s}",
formatAsLong(stats.getOutputRowCount()),
formatEstimateAsDataSize(stats.getOutputSizeInBytes()),
formatDouble(cost.getCpuCost()),
formatDouble(cost.getMemoryCost()),
formatDouble(cost.getNetworkCost()));
}
}
private static String formatEstimateAsDataSize(double value)
{
return isNaN(value) ? "?" : succinctBytes((long) value).toString();
}
private static String formatHash(Optional<Symbol>... hashes)
{
List<Symbol> symbols = Arrays.stream(hashes)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
if (symbols.isEmpty()) {
return "";
}
return "[" + Joiner.on(", ").join(symbols) + "]";
}
private static String formatFrame(WindowFrame frame)
{
StringBuilder builder = new StringBuilder(frame.getType().toString());
FrameBound start = frame.getStart();
if (start.getValue().isPresent()) {
builder.append(" ").append(start.getOriginalValue().get());
}
builder.append(" ").append(start.getType());
Optional<FrameBound> end = frame.getEnd();
if (end.isPresent()) {
if (end.get().getOriginalValue().isPresent()) {
builder.append(" ").append(end.get().getOriginalValue().get());
}
builder.append(" ").append(end.get().getType());
}
return builder.toString();
}
private static String castToVarchar(Type type, Object value, FunctionRegistry functionRegistry, Session session)
{
if (value == null) {
return "NULL";
}
Signature coercion = functionRegistry.getCoercion(type, VARCHAR);
try {
Slice coerced = (Slice) new FunctionInvoker(functionRegistry).invoke(coercion, session.toConnectorSession(), value);
return coerced.toStringUtf8();
}
catch (OperatorNotFoundException e) {
return "<UNREPRESENTABLE VALUE>";
}
catch (Throwable throwable) {
throw Throwables.propagate(throwable);
}
}
}
| |
package org.finos.waltz.jobs.tools.importers;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.finos.waltz.common.*;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.schema.tables.records.AssessmentRatingRecord;
import org.finos.waltz.service.DIConfiguration;
import org.jooq.DSLContext;
import org.jooq.lambda.tuple.Tuple5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.lang.String.format;
import static java.util.stream.Collectors.toSet;
import static org.finos.waltz.common.StreamUtilities.mkSiphon;
import static org.finos.waltz.data.JooqUtilities.readRef;
import static org.finos.waltz.jobs.XlsUtilities.strVal;
import static org.finos.waltz.jobs.XlsUtilities.streamRows;
import static org.finos.waltz.model.EntityReference.mkRef;
import static org.finos.waltz.schema.Tables.*;
import static org.jooq.lambda.tuple.Tuple.tuple;
@Component
public class AssessmentRatingBulkImport {
private static final Logger LOG = LoggerFactory.getLogger(AssessmentRatingBulkImport.class);
private static final String PROVENANCE = "waltz_bulk_assessment_rating_importer";
private final DSLContext dsl;
@Autowired
public AssessmentRatingBulkImport(DSLContext dsl) {
this.dsl = dsl;
}
public void load(String filename, AssessmentRatingBulkImportConfig config) throws IOException {
InputStream inputStream = IOUtilities.getFileResource(filename).getInputStream();
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(config.sheetPosition());
Set<AssessmentRatingEntry> existingRatings = dsl
.select(ASSESSMENT_RATING.ENTITY_ID,
ASSESSMENT_RATING.ENTITY_KIND,
ASSESSMENT_RATING.RATING_ID,
ASSESSMENT_RATING.DESCRIPTION)
.from(ASSESSMENT_RATING)
.where(ASSESSMENT_RATING.ASSESSMENT_DEFINITION_ID.eq(config.assessmentDefinitionId()))
.fetchSet(r -> ImmutableAssessmentRatingEntry.builder()
.entity(readRef(r, ASSESSMENT_RATING.ENTITY_KIND, ASSESSMENT_RATING.ENTITY_ID))
.ratingId(r.get(ASSESSMENT_RATING.RATING_ID))
.description(r.get(ASSESSMENT_RATING.DESCRIPTION))
.build());
EntityKind subjectKind = EntityKind.valueOf(dsl
.select(ASSESSMENT_DEFINITION.ENTITY_KIND)
.from(ASSESSMENT_DEFINITION)
.where(ASSESSMENT_DEFINITION.ID.eq(config.assessmentDefinitionId()))
.fetchOne(ASSESSMENT_DEFINITION.ENTITY_KIND));
Aliases<Long> ratingAliases = mkRatingAliases(config);
Map<String, Long> externalIdToEntityIdMap = loadExternalIdToEntityIdMap(subjectKind);
StreamUtilities.Siphon<Tuple5<String, String, String, Long, Optional<Long>>> noEntityFoundSiphon = mkSiphon(t -> t.v4 == null);
StreamUtilities.Siphon<Tuple5<String, String, String, Long, Optional<Long>>> noRatingFoundSiphon = mkSiphon(t -> !t.v5.isPresent());
Set<AssessmentRatingEntry> requiredRatings = streamRows(sheet)
.skip(config.numberOfHeaderRows())
.map(r -> tuple(
strVal(r, Columns.A),
strVal(r, Columns.B),
strVal(r, Columns.C)))
.map(t -> t.concat(tuple(externalIdToEntityIdMap.get(t.v1), ratingAliases.lookup(t.v2))))
.filter(noEntityFoundSiphon)
.filter(noRatingFoundSiphon)
.map(t -> ImmutableAssessmentRatingEntry.builder()
.entity(mkRef(subjectKind, t.v4))
.ratingId(t.v5.get())
.description(t.v3)
.build())
.collect(toSet());
noEntityFoundSiphon.getResults().forEach(t -> System.out.printf("Couldn't find an entity id for row: %s%n", t.limit3()));
noRatingFoundSiphon.getResults().forEach(t -> System.out.printf("Couldn't find a rating id for row: %s%n", t.limit3()));
DiffResult<AssessmentRatingEntry> diff = DiffResult.mkDiff(
existingRatings,
requiredRatings,
AssessmentRatingEntry::entity,
Object::equals);
dsl.transaction(ctx -> {
DSLContext tx = ctx.dsl();
int[] insertedRecords = diff
.otherOnly()
.stream()
.map(r -> mkAssessmentRatingRecord(config.assessmentDefinitionId(), r, config.updateUser()))
.collect(Collectors.collectingAndThen(toSet(), tx::batchInsert))
.execute();
LOG.debug(format("inserted new assessment ratings for %d records", IntStream.of(insertedRecords).sum()));
int[] updatedRecords = diff
.differingIntersection()
.stream()
.map(r -> dsl
.update(ASSESSMENT_RATING)
.set(ASSESSMENT_RATING.DESCRIPTION, r.description())
.set(ASSESSMENT_RATING.RATING_ID, r.ratingId())
.set(ASSESSMENT_RATING.LAST_UPDATED_AT, DateTimeUtilities.nowUtcTimestamp())
.set(ASSESSMENT_RATING.LAST_UPDATED_BY, config.updateUser())
.where(ASSESSMENT_RATING.ASSESSMENT_DEFINITION_ID.eq(config.assessmentDefinitionId())
.and(ASSESSMENT_RATING.ENTITY_KIND.eq(r.entity().kind().name())
.and(ASSESSMENT_RATING.ENTITY_ID.eq(r.entity().id())))))
.collect(Collectors.collectingAndThen(toSet(), tx::batch))
.execute();
LOG.debug(format("Updated ratings or descriptions for %d records", IntStream.of(updatedRecords).sum()));
if(config.mode().equals(SynchronisationMode.FULL)){
int[] removedRecords = diff
.waltzOnly()
.stream()
.map(r -> dsl
.deleteFrom(ASSESSMENT_RATING)
.where(ASSESSMENT_RATING.ASSESSMENT_DEFINITION_ID.eq(config.assessmentDefinitionId())
.and(ASSESSMENT_RATING.ENTITY_ID.eq(r.entity().id())
.and(ASSESSMENT_RATING.ENTITY_KIND.eq(r.entity().kind().name())))))
.collect(Collectors.collectingAndThen(toSet(), tx::batch))
.execute();
LOG.debug(format("Deleted assessment ratings for %d records", IntStream.of(removedRecords).sum()));
}
// throw new IllegalArgumentException("BBooooooOOOOOooMMMMMMMM!");
});
}
private Map<String, Long> loadExternalIdToEntityIdMap(EntityKind subjectKind) {
switch (subjectKind){
case APPLICATION:
return fetchAppAssetCodeToIdMap();
case CHANGE_INITIATIVE:
return fetchChangeInitiativeExtidToIdMap();
case PHYSICAL_SPECIFICATION:
return getPhysicalSpecExtIdToIdMap();
case CHANGE_UNIT:
return getChangeUnitExtIdToIdMap();
case LICENCE:
return fetchLicenceExtIdToIdMap();
default:
throw new IllegalStateException(format("Cannot look up external id to name map for EntityKind: %s", subjectKind));
}
}
private Map<String, Long> fetchLicenceExtIdToIdMap() {
return dsl
.select(LICENCE.EXTERNAL_ID, LICENCE.ID)
.from(LICENCE)
.fetchMap(
r -> r.get(LICENCE.EXTERNAL_ID).toLowerCase(),
r -> r.get(LICENCE.ID));
}
private Map<String, Long> getChangeUnitExtIdToIdMap() {
return dsl
.select(CHANGE_UNIT.EXTERNAL_ID, CHANGE_UNIT.ID)
.from(CHANGE_UNIT)
.fetchMap(
r -> r.get(CHANGE_UNIT.EXTERNAL_ID).toLowerCase(),
r -> r.get(CHANGE_UNIT.ID));
}
private Map<String, Long> getPhysicalSpecExtIdToIdMap() {
return dsl
.select(PHYSICAL_SPECIFICATION.EXTERNAL_ID, PHYSICAL_SPECIFICATION.ID)
.from(PHYSICAL_SPECIFICATION)
.fetchMap(
r -> r.get(PHYSICAL_SPECIFICATION.EXTERNAL_ID).toLowerCase(),
r -> r.get(PHYSICAL_SPECIFICATION.ID));
}
private Map<String, Long> fetchChangeInitiativeExtidToIdMap() {
return dsl
.select(CHANGE_INITIATIVE.EXTERNAL_ID, CHANGE_INITIATIVE.ID)
.from(CHANGE_INITIATIVE)
.fetchMap(r -> r.get(CHANGE_INITIATIVE.EXTERNAL_ID).toLowerCase(),
r -> r.get(CHANGE_INITIATIVE.ID));
}
private Map<String, Long> fetchAppAssetCodeToIdMap() {
return dsl
.select(APPLICATION.ASSET_CODE, APPLICATION.ID)
.from(APPLICATION)
.fetchMap(
r -> r.get(APPLICATION.ASSET_CODE).toLowerCase(),
r -> r.get(APPLICATION.ID));
}
private Aliases<Long> mkRatingAliases(AssessmentRatingBulkImportConfig config) {
Aliases<Long> ratingAliases = new Aliases<>();
dsl
.select(RATING_SCHEME_ITEM.CODE, RATING_SCHEME_ITEM.NAME, RATING_SCHEME_ITEM.ID)
.from(RATING_SCHEME_ITEM)
.innerJoin(ASSESSMENT_DEFINITION).on(RATING_SCHEME_ITEM.SCHEME_ID.eq(ASSESSMENT_DEFINITION.RATING_SCHEME_ID))
.where(ASSESSMENT_DEFINITION.ID.eq(config.assessmentDefinitionId()))
.forEach(r -> {
Long val = r.get(RATING_SCHEME_ITEM.ID);
ratingAliases.register(val, r.get(RATING_SCHEME_ITEM.NAME));
ratingAliases.register(val, r.get(RATING_SCHEME_ITEM.CODE));
});
return ratingAliases;
}
private AssessmentRatingRecord mkAssessmentRatingRecord(Long defnId, AssessmentRatingEntry r, String updateUser) {
AssessmentRatingRecord record = dsl.newRecord(ASSESSMENT_RATING);
record.setAssessmentDefinitionId(defnId);
record.setEntityId(r.entity().id());
record.setEntityKind(r.entity().kind().name());
record.setRatingId(r.ratingId());
record.setLastUpdatedAt(DateTimeUtilities.nowUtcTimestamp());
record.setLastUpdatedBy(updateUser);
record.setDescription(r.description());
record.setProvenance(PROVENANCE);
return record;
}
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
AssessmentRatingBulkImport importer = ctx.getBean(AssessmentRatingBulkImport.class);
String filename = "/assessment_rating_upload.xlsx";
AssessmentRatingBulkImportConfig config = ImmutableAssessmentRatingBulkImportConfig.builder()
.assessmentDefinitionId(4L)
.numberOfHeaderRows(0)
.sheetPosition(0)
.updateUser(PROVENANCE)
.mode(SynchronisationMode.FULL)
.build();
importer.load(filename, config);
}
}
| |
/**
* 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.jdbc;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.List;
import net.hydromatic.avatica.AvaticaPrepareResult;
import net.hydromatic.avatica.AvaticaResultSet;
import net.hydromatic.avatica.AvaticaStatement;
import net.hydromatic.avatica.Cursor;
import net.hydromatic.avatica.Meta;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.drill.common.exceptions.DrillRuntimeException;
public class MetaImpl implements Meta {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MetaImpl.class);
static final Driver DRIVER = new Driver();
final DrillConnectionImpl connection;
public MetaImpl(DrillConnectionImpl connection) {
this.connection = connection;
}
public String getSqlKeywords() {
return "";
}
public String getNumericFunctions() {
return "";
}
public String getStringFunctions() {
return "";
}
public String getSystemFunctions() {
return "";
}
public String getTimeDateFunctions() {
return "";
}
public static ResultSet getEmptyResultSet() {
return null;
}
private ResultSet s(String s) {
try {
logger.debug("Running {}", s);
AvaticaStatement statement = connection.createStatement();
statement.execute(s);
return statement.getResultSet();
} catch (Exception e) {
throw new DrillRuntimeException("Failure while attempting to get DatabaseMetadata.", e);
}
}
public ResultSet getTables(String catalog, final Pat schemaPattern, final Pat tableNamePattern,
final List<String> typeList) {
StringBuilder sb = new StringBuilder();
sb.append("select "
+ "TABLE_CATALOG as TABLE_CAT, "
+ "TABLE_SCHEMA as TABLE_SCHEM, "
+ "TABLE_NAME, "
+ "TABLE_TYPE, "
+ "'' as REMARKS, "
+ "'' as TYPE_CAT, "
+ "'' as TYPE_SCHEM, "
+ "'' as TYPE_NAME, "
+ "'' as SELF_REFERENCING_COL_NAME, "
+ "'' as REF_GENERATION "
+ "FROM INFORMATION_SCHEMA.`TABLES` WHERE 1=1 ");
if (catalog != null) {
sb.append(" AND TABLE_CATALOG = '" + StringEscapeUtils.escapeSql(catalog) + "' ");
}
if (schemaPattern.s != null) {
sb.append(" AND TABLE_SCHEMA like '" + StringEscapeUtils.escapeSql(schemaPattern.s) + "'");
}
if (tableNamePattern.s != null) {
sb.append(" AND TABLE_NAME like '" + StringEscapeUtils.escapeSql(tableNamePattern.s) + "'");
}
if (typeList != null && typeList.size() > 0) {
sb.append("AND (");
for (int t = 0; t < typeList.size(); t++) {
if (t != 0) {
sb.append(" OR ");
}
sb.append(" TABLE_TYPE LIKE '" + StringEscapeUtils.escapeSql(typeList.get(t)) + "' ");
}
sb.append(")");
}
sb.append(" ORDER BY TABLE_TYPE, TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME");
return s(sb.toString());
}
public ResultSet getColumns(String catalog, Pat schemaPattern, Pat tableNamePattern, Pat columnNamePattern) {
StringBuilder sb = new StringBuilder();
sb.append("select "
+ "TABLE_CATALOG as TABLE_CAT, "
+ "TABLE_SCHEMA as TABLE_SCHEM, "
+ "TABLE_NAME, "
+ "COLUMN_NAME, "
+ "DATA_TYPE, "
+ "CHARACTER_MAXIMUM_LENGTH as BUFFER_LENGTH, "
+ "NUMERIC_PRECISION as DECIMAL_PRECISION, "
+ "NUMERIC_PRECISION_RADIX as NUM_PREC_RADIX, "
+ DatabaseMetaData.columnNullableUnknown
+ " as NULLABLE, "
+ "'' as REMARKS, "
+ "'' as COLUMN_DEF, "
+ "0 as SQL_DATA_TYPE, "
+ "0 as SQL_DATETIME_SUB, "
+ "4 as CHAR_OCTET_LENGTH, "
+ "1 as ORDINAL_POSITION, "
+ "'YES' as IS_NULLABLE, "
+ "'' as SCOPE_CATALOG,"
+ "'' as SCOPE_SCHEMA, "
+ "'' as SCOPE_TABLE, "
+ "'' as SOURCE_DATA_TYPE, "
+ "'' as IS_AUTOINCREMENT, "
+ "'' as IS_GENERATEDCOLUMN "
+ "FROM INFORMATION_SCHEMA.COLUMNS "
+ "WHERE 1=1 ");
if (catalog != null) {
sb.append(" AND TABLE_CATALOG = '" + StringEscapeUtils.escapeSql(catalog) + "' ");
}
if (schemaPattern.s != null) {
sb.append(" AND TABLE_SCHEMA like '" + StringEscapeUtils.escapeSql(schemaPattern.s) + "'");
}
if (tableNamePattern.s != null) {
sb.append(" AND TABLE_NAME like '" + StringEscapeUtils.escapeSql(tableNamePattern.s) + "'");
}
if (columnNamePattern.s != null) {
sb.append(" AND COLUMN_NAME like '" + StringEscapeUtils.escapeSql(columnNamePattern.s) + "'");
}
sb.append(" ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME");
return s(sb.toString());
}
public ResultSet getSchemas(String catalog, Pat schemaPattern) {
StringBuilder sb = new StringBuilder();
sb.append("select "
+ "SCHEMA_NAME as TABLE_SCHEM, "
+ "CATALOG_NAME as TABLE_CAT "
+ " FROM INFORMATION_SCHEMA.SCHEMATA WHERE 1=1 ");
if (catalog != null) {
sb.append(" AND CATALOG_NAME = '" + StringEscapeUtils.escapeSql(catalog) + "' ");
}
if (schemaPattern.s != null) {
sb.append(" AND SCHEMA_NAME like '" + StringEscapeUtils.escapeSql(schemaPattern.s) + "'");
}
sb.append(" ORDER BY CATALOG_NAME, SCHEMA_NAME");
return s(sb.toString());
}
public ResultSet getCatalogs() {
StringBuilder sb = new StringBuilder();
sb.append("select "
+ "CATALOG_NAME as TABLE_CAT "
+ " FROM INFORMATION_SCHEMA.CATALOGS ");
sb.append(" ORDER BY CATALOG_NAME");
return s(sb.toString());
}
public ResultSet getTableTypes() {
return getEmptyResultSet();
}
public ResultSet getProcedures(String catalog, Pat schemaPattern, Pat procedureNamePattern) {
return getEmptyResultSet();
}
public ResultSet getProcedureColumns(String catalog, Pat schemaPattern, Pat procedureNamePattern,
Pat columnNamePattern) {
return getEmptyResultSet();
}
public ResultSet getColumnPrivileges(String catalog, String schema, String table, Pat columnNamePattern) {
return getEmptyResultSet();
}
public ResultSet getTablePrivileges(String catalog, Pat schemaPattern, Pat tableNamePattern) {
return getEmptyResultSet();
}
public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) {
return getEmptyResultSet();
}
public ResultSet getVersionColumns(String catalog, String schema, String table) {
return getEmptyResultSet();
}
public ResultSet getPrimaryKeys(String catalog, String schema, String table) {
return getEmptyResultSet();
}
public ResultSet getImportedKeys(String catalog, String schema, String table) {
return getEmptyResultSet();
}
public ResultSet getExportedKeys(String catalog, String schema, String table) {
return getEmptyResultSet();
}
public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
String foreignCatalog, String foreignSchema, String foreignTable) {
return getEmptyResultSet();
}
public ResultSet getTypeInfo() {
return getEmptyResultSet();
}
public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) {
return getEmptyResultSet();
}
public ResultSet getUDTs(String catalog, Pat schemaPattern, Pat typeNamePattern, int[] types) {
return getEmptyResultSet();
}
public ResultSet getSuperTypes(String catalog, Pat schemaPattern, Pat typeNamePattern) {
return getEmptyResultSet();
}
public ResultSet getSuperTables(String catalog, Pat schemaPattern, Pat tableNamePattern) {
return getEmptyResultSet();
}
public ResultSet getAttributes(String catalog, Pat schemaPattern, Pat typeNamePattern, Pat attributeNamePattern) {
return getEmptyResultSet();
}
public ResultSet getClientInfoProperties() {
return getEmptyResultSet();
}
public ResultSet getFunctions(String catalog, Pat schemaPattern, Pat functionNamePattern) {
return getEmptyResultSet();
}
public ResultSet getFunctionColumns(String catalog, Pat schemaPattern, Pat functionNamePattern, Pat columnNamePattern) {
return getEmptyResultSet();
}
public ResultSet getPseudoColumns(String catalog, Pat schemaPattern, Pat tableNamePattern, Pat columnNamePattern) {
return getEmptyResultSet();
}
public Cursor createCursor(AvaticaResultSet resultSet_) {
return ((DrillResultSet) resultSet_).cursor;
}
public AvaticaPrepareResult prepare(AvaticaStatement statement_, String sql) {
//DrillStatement statement = (DrillStatement) statement_;
return new DrillPrepareResult(sql);
}
interface Named {
String getName();
}
}
| |
/*
* Copyright 2014 NAVER Corp.
*
* 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.baidu.oped.apm.profiler.logging;
import com.baidu.oped.apm.bootstrap.logging.PLogger;
import org.slf4j.Marker;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;
/**
* @author emeroad
*/
public class Slf4jPLoggerAdapter implements PLogger {
public static final int BUFFER_SIZE = 512;
private static final Map<Class<?>, Class<?>> SIMPLE_TYPE = new IdentityHashMap<Class<?>, Class<?>>();
static {
SIMPLE_TYPE.put(String.class, String.class);
SIMPLE_TYPE.put(Boolean.class, Boolean.class);
SIMPLE_TYPE.put(boolean.class, boolean.class);
SIMPLE_TYPE.put(Byte.class, Byte.class);
SIMPLE_TYPE.put(byte.class, byte.class);
SIMPLE_TYPE.put(Short.class, Short.class);
SIMPLE_TYPE.put(short.class, short.class);
SIMPLE_TYPE.put(Integer.class, Integer.class);
SIMPLE_TYPE.put(int.class, int.class);
SIMPLE_TYPE.put(Long.class, Long.class);
SIMPLE_TYPE.put(long.class, long.class);
SIMPLE_TYPE.put(Float.class, Float.class);
SIMPLE_TYPE.put(float.class, float.class);
SIMPLE_TYPE.put(Double.class, Double.class);
SIMPLE_TYPE.put(double.class, double.class);
SIMPLE_TYPE.put(Character.class, Character.class);
SIMPLE_TYPE.put(char.class, char.class);
SIMPLE_TYPE.put(BigDecimal.class, BigDecimal.class);
SIMPLE_TYPE.put(StringBuffer.class, StringBuffer.class);
SIMPLE_TYPE.put(BigInteger.class, BigInteger.class);
SIMPLE_TYPE.put(Class.class, Class.class);
SIMPLE_TYPE.put(java.sql.Date.class, java.sql.Date.class);
SIMPLE_TYPE.put(java.util.Date.class, java.util.Date.class);
SIMPLE_TYPE.put(Time.class, Time.class);
SIMPLE_TYPE.put(Timestamp.class, Timestamp.class);
SIMPLE_TYPE.put(Calendar.class, Calendar.class);
SIMPLE_TYPE.put(GregorianCalendar.class, GregorianCalendar.class);
SIMPLE_TYPE.put(URL.class, URL.class);
SIMPLE_TYPE.put(Object.class, Object.class);
}
private final org.slf4j.Logger logger;
public Slf4jPLoggerAdapter(org.slf4j.Logger logger) {
if (logger == null) {
throw new NullPointerException("logger must not be null");
}
this.logger = logger;
}
public String getName() {
return logger.getName();
}
@Override
public void beforeInterceptor(Object target, String className, String methodName, String parameterDescription, Object[] args) {
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
sb.append("BEFORE ");
logMethod(sb, target, className, methodName, parameterDescription, args);
logger.debug(sb.toString());
}
@Override
public void beforeInterceptor(Object target, Object[] args) {
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
sb.append("BEFORE ");
logMethod(sb, target, args);
logger.debug(sb.toString());
}
@Override
public void afterInterceptor(Object target, String className, String methodName, String parameterDescription, Object[] args, Object result, Throwable throwable) {
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
sb.append("AFTER ");
logMethod(sb, target, className, methodName, parameterDescription, args);
logResult(sb, result, throwable);
if (throwable == null) {
logger.debug(sb.toString());
} else {
logger.debug(sb.toString(), throwable);
}
}
@Override
public void afterInterceptor(Object target, Object[] args, Object result, Throwable throwable) {
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
sb.append("AFTER ");
logMethod(sb, target, args);
logResult(sb, result, throwable);
if (throwable == null) {
logger.debug(sb.toString());
} else {
logger.debug(sb.toString(), throwable);
}
}
private static void logResult(StringBuilder sb, Object result, Throwable throwable) {
if (throwable == null) {
sb.append(" result:");
sb.append(normalizedParameter(result));
} else {
sb.append(" Caused:");
sb.append(throwable.getMessage());
}
}
@Override
public void afterInterceptor(Object target, String className, String methodName, String parameterDescription, Object[] args) {
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
sb.append("AFTER ");
logMethod(sb, target, className, methodName, parameterDescription, args);
logger.debug(sb.toString());
}
@Override
public void afterInterceptor(Object target, Object[] args) {
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
sb.append("AFTER ");
logMethod(sb, target, args);
logger.debug(sb.toString());
}
private static void logMethod(StringBuilder sb, Object target, String className, String methodName, String parameterDescription, Object[] args) {
sb.append(getTarget(target));
sb.append(' ');
sb.append(className);
sb.append(' ');
sb.append(methodName);
sb.append(parameterDescription);
sb.append(" args:");
appendParameterList(sb, args);
}
private static void logMethod(StringBuilder sb, Object target, Object[] args) {
sb.append(getTarget(target));
sb.append(' ');
sb.append(" args:");
appendParameterList(sb, args);
}
private static String getTarget(Object target) {
// Use class name instead of target.toString() because latter could cause side effects.
if (target == null) {
return "target=null";
} else {
return target.getClass().getName();
}
}
private static void appendParameterList(StringBuilder sb, Object[] args) {
if (args == null) {
sb.append("()");
return;
}
if (args.length == 0) {
sb.append("()");
return;
}
if (args.length > 0) {
sb.append('(');
sb.append(normalizedParameter(args[0]));
for (int i = 1; i < args.length; i++) {
sb.append(", ");
sb.append(normalizedParameter(args[i]));
}
sb.append(')');
}
}
private static String normalizedParameter(Object arg) {
// Do not call toString() because it could cause some side effects.
if (arg == null) {
return "null";
} else {
// Check if arg is simple type which is safe to invoke toString()
if (isSimpleType(arg)) {
return arg.toString();
} else {
return arg.getClass().getSimpleName();
}
}
}
private static boolean isSimpleType(Object arg) {
Class<?> find = SIMPLE_TYPE.get(arg.getClass());
if (find == null) {
return false;
}
return true;
}
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override
public void trace(String msg) {
logger.trace(msg);
}
@Override
public void trace(String format, Object arg) {
logger.trace(format, arg);
}
@Override
public void trace(String format, Object arg1, Object arg2) {
logger.trace(format, arg1, arg2);
}
@Override
public void trace(String format, Object[] argArray) {
logger.trace(format, argArray);
}
@Override
public void trace(String msg, Throwable t) {
logger.trace(msg, t);
}
public boolean isTraceEnabled(Marker marker) {
return logger.isTraceEnabled(marker);
}
public void trace(Marker marker, String msg) {
logger.trace(marker, msg);
}
public void trace(Marker marker, String format, Object arg) {
logger.trace(marker, format, arg);
}
public void trace(Marker marker, String format, Object arg1, Object arg2) {
logger.trace(marker, format, arg1, arg2);
}
public void trace(Marker marker, String format, Object[] argArray) {
logger.trace(marker, format, argArray);
}
public void trace(Marker marker, String msg, Throwable t) {
logger.trace(marker, msg, t);
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public void debug(String msg) {
logger.debug(msg);
}
@Override
public void debug(String format, Object arg) {
logger.debug(format, arg);
}
@Override
public void debug(String format, Object arg1, Object arg2) {
logger.debug(format, arg1, arg2);
}
@Override
public void debug(String format, Object[] argArray) {
logger.debug(format, argArray);
}
@Override
public void debug(String msg, Throwable t) {
logger.debug(msg, t);
}
public boolean isDebugEnabled(Marker marker) {
return logger.isDebugEnabled(marker);
}
public void debug(Marker marker, String msg) {
logger.debug(marker, msg);
}
public void debug(Marker marker, String format, Object arg) {
logger.debug(marker, format, arg);
}
public void debug(Marker marker, String format, Object arg1, Object arg2) {
logger.debug(marker, format, arg1, arg2);
}
public void debug(Marker marker, String format, Object[] argArray) {
logger.debug(marker, format, argArray);
}
public void debug(Marker marker, String msg, Throwable t) {
logger.debug(marker, msg, t);
}
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override
public void info(String msg) {
logger.info(msg);
}
@Override
public void info(String format, Object arg) {
logger.info(format, arg);
}
@Override
public void info(String format, Object arg1, Object arg2) {
logger.info(format, arg1, arg2);
}
@Override
public void info(String format, Object[] argArray) {
logger.info(format, argArray);
}
@Override
public void info(String msg, Throwable t) {
logger.info(msg, t);
}
public boolean isInfoEnabled(Marker marker) {
return logger.isInfoEnabled(marker);
}
public void info(Marker marker, String msg) {
logger.info(marker, msg);
}
public void info(Marker marker, String format, Object arg) {
logger.info(marker, format, arg);
}
public void info(Marker marker, String format, Object arg1, Object arg2) {
logger.info(marker, format, arg1, arg2);
}
public void info(Marker marker, String format, Object[] argArray) {
logger.info(marker, format, argArray);
}
public void info(Marker marker, String msg, Throwable t) {
logger.info(marker, msg, t);
}
@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override
public void warn(String msg) {
logger.warn(msg);
}
@Override
public void warn(String format, Object arg) {
logger.warn(format, arg);
}
@Override
public void warn(String format, Object[] argArray) {
logger.warn(format, argArray);
}
@Override
public void warn(String format, Object arg1, Object arg2) {
logger.warn(format, arg1, arg2);
}
@Override
public void warn(String msg, Throwable t) {
logger.warn(msg, t);
}
public boolean isWarnEnabled(Marker marker) {
return logger.isWarnEnabled(marker);
}
public void warn(Marker marker, String msg) {
logger.warn(marker, msg);
}
public void warn(Marker marker, String format, Object arg) {
logger.warn(marker, format, arg);
}
public void warn(Marker marker, String format, Object arg1, Object arg2) {
logger.warn(marker, format, arg1, arg2);
}
public void warn(Marker marker, String format, Object[] argArray) {
logger.warn(marker, format, argArray);
}
public void warn(Marker marker, String msg, Throwable t) {
logger.warn(marker, msg, t);
}
@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override
public void error(String msg) {
logger.error(msg);
}
@Override
public void error(String format, Object arg) {
logger.error(format, arg);
}
@Override
public void error(String format, Object arg1, Object arg2) {
logger.error(format, arg1, arg2);
}
@Override
public void error(String format, Object[] argArray) {
logger.error(format, argArray);
}
@Override
public void error(String msg, Throwable t) {
logger.error(msg, t);
}
public boolean isErrorEnabled(Marker marker) {
return logger.isErrorEnabled(marker);
}
public void error(Marker marker, String msg) {
logger.error(marker, msg);
}
public void error(Marker marker, String format, Object arg) {
logger.error(marker, format, arg);
}
public void error(Marker marker, String format, Object arg1, Object arg2) {
logger.error(marker, format, arg1, arg2);
}
public void error(Marker marker, String format, Object[] argArray) {
logger.error(marker, format, argArray);
}
public void error(Marker marker, String msg, Throwable t) {
logger.error(marker, msg, t);
}
}
| |
/*
Copyright 2016, 2017 Institut National de la Recherche Agronomique
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 fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.prolog;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import alice.tuprolog.Double;
import alice.tuprolog.Int;
import alice.tuprolog.NoSolutionException;
import alice.tuprolog.SolveInfo;
import alice.tuprolog.Struct;
import alice.tuprolog.Term;
import alice.tuprolog.lib.InvalidObjectIdException;
import alice.tuprolog.lib.JavaLibrary;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Element;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.AbstractEvaluator;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.EvaluationContext;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.EvaluationType;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.Evaluator;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.Expression;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.FunctionLibrary;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.LibraryResolver;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.ResolverException;
import fr.inra.maiage.bibliome.alvisnlp.core.documentation.Documentation;
import fr.inra.maiage.bibliome.alvisnlp.core.module.ModuleException;
import fr.inra.maiage.bibliome.alvisnlp.core.module.NameUsage;
import fr.inra.maiage.bibliome.util.Iterators;
import fr.inra.maiage.bibliome.util.StringCat;
public class SolveInfoLibrary extends FunctionLibrary {
private JavaLibrary javaLibrary;
private SolveInfo solveInfo;
SolveInfoLibrary() {
super();
}
public JavaLibrary getJavaLibrary() {
return javaLibrary;
}
public void setJavaLibrary(JavaLibrary javaLibrary) {
this.javaLibrary = javaLibrary;
}
public SolveInfo getSolveInfo() {
return solveInfo;
}
public void setSolveInfo(SolveInfo solveInfo) {
this.solveInfo = solveInfo;
}
@Override
public String getName() {
return "goal";
}
@Override
public Evaluator resolveExpression(LibraryResolver resolver, List<String> ftors, List<Expression> args) throws ResolverException {
checkExactFtors(ftors, 1);
checkExactArity(ftors, args, 0);
return new SolveInfoEvaluator(ftors.get(0));
}
private class SolveInfoEvaluator extends AbstractEvaluator {
private final String varName;
private SolveInfoEvaluator(String varName) {
super();
this.varName = varName;
}
private Term getTerm() {
try {
return solveInfo.getVarValue(varName);
}
catch (NoSolutionException e) {
return null;
}
}
@Override
public boolean evaluateBoolean(EvaluationContext ctx, Element elt) {
Term term = getTerm();
if (term == null)
return false;
if (term.isEmptyList())
return false;
if (term.isList())
return true;
if (term.isAtom())
return !term.toString().isEmpty();
if (term instanceof alice.tuprolog.Number)
return ((alice.tuprolog.Number) term).intValue() != 0;
throw new RuntimeException();
}
@Override
public int evaluateInt(EvaluationContext ctx, Element elt) {
return termToInt(getTerm());
}
private int termToInt(Term term) {
if (term == null)
return 0;
if (term.isList())
return ((Struct) term).listSize();
if (term.isAtom()) {
try {
return Integer.parseInt(term.toString());
}
catch (NumberFormatException e) {
return 0;
}
}
if (term instanceof alice.tuprolog.Number)
return ((alice.tuprolog.Number) term).intValue();
throw new RuntimeException();
}
@Override
public double evaluateDouble(EvaluationContext ctx, Element elt) {
return termToDouble(getTerm());
}
private double termToDouble(Term term) {
if (term == null)
return 0;
if (term.isList())
return ((Struct) term).listSize();
if (term.isAtom()) {
try {
return java.lang.Double.parseDouble(term.toString());
}
catch (NumberFormatException e) {
return 0;
}
}
if (term instanceof alice.tuprolog.Number)
return ((alice.tuprolog.Number) term).doubleValue();
throw new RuntimeException();
}
@Override
public String evaluateString(EvaluationContext ctx, Element elt) {
StringCat strcat = new StringCat();
evaluateString(ctx, elt, strcat);
return strcat.toString();
}
@Override
public void evaluateString(EvaluationContext ctx, Element elt, StringCat strcat) {
termToString(getTerm(), strcat);
}
private void termToString(Term term, StringCat strcat) {
if (term == null)
return;
if (term.isEmptyList())
return;
if (term.isList())
listToString((Struct) term, strcat);
strcat.append(term.toString());
}
@SuppressWarnings("unchecked")
private void listToString(Struct struct, StringCat strcat) {
for (Term t : Iterators.loop((Iterator<Term>) struct.listIterator()))
termToString(t, strcat);
}
@Override
public Iterator<Element> evaluateElements(EvaluationContext ctx, Element elt) {
return evaluateList(ctx, elt).iterator();
}
@SuppressWarnings("unchecked")
@Override
public List<Element> evaluateList(EvaluationContext ctx, Element elt) {
Term term = getTerm();
if (term == null)
return Collections.emptyList();
if (term.isEmptyList())
return Collections.emptyList();
if (term.isAtom()) {
Element e = termToElement(term);
if (e == null)
return Collections.emptyList();
return Collections.singletonList(e);
}
if (term.isList()) {
Struct struct = (Struct) term;
List<Element> result = new ArrayList<Element>(struct.listSize());
for (Term t : Iterators.loop((Iterator<Term>) struct.listIterator())) {
Element e = termToElement(t);
if (e != null)
result.add(e);
}
return result;
}
throw new RuntimeException();
}
private Element termToElement(Term term) {
if (term == null)
return null;
if (term.isEmptyList())
return null;
if (!term.isAtom())
return null;
Struct id = (Struct) term;
try {
return (Element) javaLibrary.getRegisteredObject(id);
}
catch (InvalidObjectIdException e) {
return null;
}
}
@Override
public boolean testEquality(EvaluationContext ctx, Evaluator that, Element elt, boolean mayDelegate) {
Term term = getTerm();
if (term == null)
return !that.evaluateBoolean(ctx, elt);
if (term.isEmptyList())
return !that.evaluateBoolean(ctx, elt);
if (term.isAtom()) {
Element e = termToElement(term);
if (e == null)
return term.toString().equals(that.evaluateString(ctx, elt));
if (mayDelegate)
return that.testEquality(ctx, this, elt, false);
Iterator<Element> it = that.evaluateElements(ctx, elt);
if (!it.hasNext())
return false;
if (e.equals(it.next()))
return !it.hasNext();
return false;
}
if (term.isList()) {
if (mayDelegate)
return that.testEquality(ctx, this, elt, false);
@SuppressWarnings("unchecked")
Iterator<? extends Term> thisIt = ((Struct) term).listIterator();
Iterator<Element> thatIt = that.evaluateElements(ctx, elt);
while (thisIt.hasNext()) {
if (!thatIt.hasNext())
return false;
Element t = termToElement(thisIt.next());
if (t == null)
return false;
Element e = thatIt.next();
if (!t.equals(e))
return false;
}
return !thatIt.hasNext();
}
throw new RuntimeException();
}
@Override
public Collection<EvaluationType> getTypes() {
Term term = getTerm();
if (term == null)
return Collections.singleton(EvaluationType.ELEMENTS);
if (term.isList())
return Collections.singleton(EvaluationType.ELEMENTS);
if (term.isAtom()) {
Element e = termToElement(term);
if (e == null)
Collections.singleton(EvaluationType.STRING);
return Collections.singleton(EvaluationType.ELEMENTS);
}
if (term instanceof Int)
return Collections.singleton(EvaluationType.INT);
if (term instanceof Double)
return Collections.singleton(EvaluationType.DOUBLE);
throw new RuntimeException();
}
@Override
public void collectUsedNames(NameUsage nameUsage, String defaultType) throws ModuleException {
}
}
@Override
public Documentation getDocumentation() {
return null;
}
}
| |
/*
* oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.saml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xdi.xml.SimpleNamespaceContext;
import org.xml.sax.SAXException;
/**
* Loads and validates SAML response
*
* @author Yuriy Movchan Date: 24/04/2014
*/
public class Response {
private static final SimpleNamespaceContext NAMESPACES;
public static final String SAML_RESPONSE_STATUS_SUCCESS = "urn:oasis:names:tc:SAML:2.0:status:Success";
public static final String SAML_RESPONSE_STATUS_RESPONDER = "urn:oasis:names:tc:SAML:2.0:status:Responder";
public static final String SAML_RESPONSE_STATUS_AUTHNFAILED = "urn:oasis:names:tc:SAML:2.0:status:AuthnFailed";
static {
HashMap<String, String> preferences = new HashMap<String, String>() {
{
put("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
put("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
}
};
NAMESPACES = new SimpleNamespaceContext(preferences);
}
private Document xmlDoc;
private SamlConfiguration samlSettings;
public Response(SamlConfiguration samlSettings) throws CertificateException {
this.samlSettings = samlSettings;
}
public void loadXml(String xml) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory fty = DocumentBuilderFactory.newInstance();
fty.setNamespaceAware(true);
// Fix XXE vulnerability
fty.setXIncludeAware(false);
fty.setExpandEntityReferences(false);
fty.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
fty.setFeature("http://xml.org/sax/features/external-general-entities", false);
fty.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder builder = fty.newDocumentBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
xmlDoc = builder.parse(bais);
}
public void loadXmlFromBase64(String response) throws ParserConfigurationException, SAXException, IOException {
Base64 base64 = new Base64();
byte[] decodedResponse = base64.decode(response);
String decodedS = new String(decodedResponse);
loadXml(decodedS);
}
public boolean isValid() throws Exception {
NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodes == null || nodes.getLength() == 0) {
throw new Exception("Can't find signature in document.");
}
if (setIdAttributeExists()) {
tagIdAttributes(xmlDoc);
}
X509Certificate cert = samlSettings.getCertificate();
DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0));
XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");
XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx);
return xmlSignature.validate(ctx);
}
public boolean isAuthnFailed() throws Exception {
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(NAMESPACES);
XPathExpression query = xPath.compile("/samlp:Response/samlp:Status/samlp:StatusCode");
NodeList nodes = (NodeList) query.evaluate(xmlDoc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getAttributes().getNamedItem("Value") == null) {
continue;
}
String statusCode = node.getAttributes().getNamedItem("Value").getNodeValue();
if (SAML_RESPONSE_STATUS_SUCCESS.equalsIgnoreCase(statusCode)) {
return false;
} else if (SAML_RESPONSE_STATUS_AUTHNFAILED.equalsIgnoreCase(statusCode)) {
return true;
} else if (SAML_RESPONSE_STATUS_RESPONDER.equalsIgnoreCase(statusCode)) {
// nothing?
continue;
}
}
return false;
}
private void tagIdAttributes(Document xmlDoc) {
NodeList nodeList = xmlDoc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getAttributes().getNamedItem("ID") != null) {
((Element) node).setIdAttribute("ID", true);
}
}
}
}
private boolean setIdAttributeExists() {
for (Method method : Element.class.getDeclaredMethods()) {
if (method.getName().equals("setIdAttribute")) {
return true;
}
}
return false;
}
public String getNameId() throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(NAMESPACES);
XPathExpression query = xPath.compile("/samlp:Response/saml:Assertion/saml:Subject/saml:NameID");
return query.evaluate(xmlDoc);
}
public Map<String, List<String>> getAttributes() throws XPathExpressionException {
Map<String, List<String>> result = new HashMap<String, List<String>>();
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(NAMESPACES);
XPathExpression query = xPath.compile("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute");
NodeList nodes = (NodeList) query.evaluate(xmlDoc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Node nameNode = node.getAttributes().getNamedItem("Name");
if (nameNode == null) {
continue;
}
String attributeName = nameNode.getNodeValue();
List<String> attributeValues = new ArrayList<String>();
NodeList nameChildNodes = node.getChildNodes();
for (int j = 0; j < nameChildNodes.getLength(); j++) {
Node nameChildNode = nameChildNodes.item(j);
if ("urn:oasis:names:tc:SAML:2.0:assertion".equalsIgnoreCase(nameChildNode.getNamespaceURI())
&& "AttributeValue".equals(nameChildNode.getLocalName())) {
NodeList valueChildNodes = nameChildNode.getChildNodes();
for (int k = 0; k < valueChildNodes.getLength(); k++) {
Node valueChildNode = valueChildNodes.item(k);
attributeValues.add(valueChildNode.getNodeValue());
}
}
}
result.put(attributeName, attributeValues);
}
return result;
}
public void printDocument(OutputStream out) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(xmlDoc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
}
| |
/*
* 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.cql3.validation.entities;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.utils.FBUtilities;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class SecondaryIndexTest extends CQLTester
{
private static final int TOO_BIG = 1024 * 65;
@Test
public void testCreateAndDropIndex() throws Throwable
{
testCreateAndDropIndex("test", false);
testCreateAndDropIndex("test2", true);
}
@Test
public void testCreateAndDropIndexWithQuotedIdentifier() throws Throwable
{
testCreateAndDropIndex("\"quoted_ident\"", false);
testCreateAndDropIndex("\"quoted_ident2\"", true);
}
@Test
public void testCreateAndDropIndexWithCamelCaseIdentifier() throws Throwable
{
testCreateAndDropIndex("CamelCase", false);
testCreateAndDropIndex("CamelCase2", true);
}
/**
* Test creating and dropping an index with the specified name.
*
* @param indexName the index name
* @param addKeyspaceOnDrop add the keyspace name in the drop statement
* @throws Throwable if an error occurs
*/
private void testCreateAndDropIndex(String indexName, boolean addKeyspaceOnDrop) throws Throwable
{
execute("USE system");
assertInvalidMessage("Index '" + removeQuotes(indexName.toLowerCase(Locale.US)) + "' could not be found", "DROP INDEX " + indexName + ";");
createTable("CREATE TABLE %s (a int primary key, b int);");
createIndex("CREATE INDEX " + indexName + " ON %s(b);");
createIndex("CREATE INDEX IF NOT EXISTS " + indexName + " ON %s(b);");
assertInvalidMessage("Index already exists", "CREATE INDEX " + indexName + " ON %s(b)");
execute("INSERT INTO %s (a, b) values (?, ?);", 0, 0);
execute("INSERT INTO %s (a, b) values (?, ?);", 1, 1);
execute("INSERT INTO %s (a, b) values (?, ?);", 2, 2);
execute("INSERT INTO %s (a, b) values (?, ?);", 3, 1);
assertRows(execute("SELECT * FROM %s where b = ?", 1), row(1, 1), row(3, 1));
assertInvalidMessage("Index '" + removeQuotes(indexName.toLowerCase(Locale.US)) + "' could not be found in any of the tables of keyspace 'system'",
"DROP INDEX " + indexName);
if (addKeyspaceOnDrop)
{
dropIndex("DROP INDEX " + KEYSPACE + "." + indexName);
}
else
{
execute("USE " + KEYSPACE);
execute("DROP INDEX " + indexName);
}
assertInvalidMessage("No supported secondary index found for the non primary key columns restrictions",
"SELECT * FROM %s where b = ?", 1);
dropIndex("DROP INDEX IF EXISTS " + indexName);
assertInvalidMessage("Index '" + removeQuotes(indexName.toLowerCase(Locale.US)) + "' could not be found", "DROP INDEX " + indexName);
}
/**
* Removes the quotes from the specified index name.
*
* @param indexName the index name from which the quotes must be removed.
* @return the unquoted index name.
*/
private static String removeQuotes(String indexName)
{
return StringUtils.remove(indexName, '\"');
}
/**
* Check that you can query for an indexed column even with a key EQ clause,
* migrated from cql_tests.py:TestCQL.static_cf_test()
*/
@Test
public void testSelectWithEQ() throws Throwable
{
createTable("CREATE TABLE %s (userid uuid PRIMARY KEY, firstname text, lastname text, age int)");
createIndex("CREATE INDEX byAge ON %s(age)");
UUID id1 = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
UUID id2 = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479");
execute("INSERT INTO %s (userid, firstname, lastname, age) VALUES (?, 'Frodo', 'Baggins', 32)", id1);
execute("UPDATE %s SET firstname = 'Samwise', lastname = 'Gamgee', age = 33 WHERE userid = ?", id2);
assertEmpty(execute("SELECT firstname FROM %s WHERE userid = ? AND age = 33", id1));
assertRows(execute("SELECT firstname FROM %s WHERE userid = ? AND age = 33", id2),
row("Samwise"));
}
/**
* Check CREATE INDEX without name and validate the index can be dropped,
* migrated from cql_tests.py:TestCQL.nameless_index_test()
*/
@Test
public void testNamelessIndex() throws Throwable
{
createTable(" CREATE TABLE %s (id text PRIMARY KEY, birth_year int)");
createIndex("CREATE INDEX on %s (birth_year)");
execute("INSERT INTO %s (id, birth_year) VALUES ('Tom', 42)");
execute("INSERT INTO %s (id, birth_year) VALUES ('Paul', 24)");
execute("INSERT INTO %s (id, birth_year) VALUES ('Bob', 42)");
assertRows(execute("SELECT id FROM %s WHERE birth_year = 42"),
row("Tom"),
row("Bob"));
execute("DROP INDEX %s_birth_year_idx");
assertInvalid("SELECT id FROM users WHERE birth_year = 42");
}
/**
* Test range queries with 2ndary indexes (#4257),
* migrated from cql_tests.py:TestCQL.range_query_2ndary_test()
*/
@Test
public void testRangeQuery() throws Throwable
{
createTable("CREATE TABLE %s (id int primary key, row int, setid int)");
createIndex("CREATE INDEX indextest_setid_idx ON %s (setid)");
execute("INSERT INTO %s (id, row, setid) VALUES (?, ?, ?)", 0, 0, 0);
execute("INSERT INTO %s (id, row, setid) VALUES (?, ?, ?)", 1, 1, 0);
execute("INSERT INTO %s (id, row, setid) VALUES (?, ?, ?)", 2, 2, 0);
execute("INSERT INTO %s (id, row, setid) VALUES (?, ?, ?)", 3, 3, 0);
assertInvalid("SELECT * FROM %s WHERE setid = 0 AND row < 1");
assertRows(execute("SELECT * FROM %s WHERE setid = 0 AND row < 1 ALLOW FILTERING"),
row(0, 0, 0));
}
/**
* Check for unknown compression parameters options (#4266),
* migrated from cql_tests.py:TestCQL.compression_option_validation_test()
*/
@Test
public void testUnknownCompressionOptions() throws Throwable
{
String tableName = createTableName();
assertInvalidThrow(SyntaxException.class, String.format(
"CREATE TABLE %s (key varchar PRIMARY KEY, password varchar, gender varchar) WITH compression_parameters:sstable_compressor = 'DeflateCompressor'", tableName));
assertInvalidThrow(ConfigurationException.class, String.format(
"CREATE TABLE %s (key varchar PRIMARY KEY, password varchar, gender varchar) WITH compression = { 'sstable_compressor': 'DeflateCompressor' }", tableName));
}
/**
* Check one can use arbitrary name for datacenter when creating keyspace (#4278),
* migrated from cql_tests.py:TestCQL.keyspace_creation_options_test()
*/
@Test
public void testDataCenterName() throws Throwable
{
execute("CREATE KEYSPACE Foo WITH replication = { 'class' : 'NetworkTopologyStrategy', 'us-east' : 1, 'us-west' : 1 };");
}
/**
* Migrated from cql_tests.py:TestCQL.indexes_composite_test()
*/
@Test
public void testIndexOnComposite() throws Throwable
{
String tableName = createTable("CREATE TABLE %s (blog_id int, timestamp int, author text, content text, PRIMARY KEY (blog_id, timestamp))");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 0, 0, "bob", "1st post");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 0, 1, "tom", "2nd post");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 0, 2, "bob", "3rd post");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 0, 3, "tom", "4th post");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 1, 0, "bob", "5th post");
createIndex("CREATE INDEX authoridx ON %s (author)");
assertTrue(waitForIndex(keyspace(), tableName, "authoridx"));
assertRows(execute("SELECT blog_id, timestamp FROM %s WHERE author = 'bob'"),
row(1, 0),
row(0, 0),
row(0, 2));
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 1, 1, "tom", "6th post");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 1, 2, "tom", "7th post");
execute("INSERT INTO %s (blog_id, timestamp, author, content) VALUES (?, ?, ?, ?)", 1, 3, "bob", "8th post");
assertRows(execute("SELECT blog_id, timestamp FROM %s WHERE author = 'bob'"),
row(1, 0),
row(1, 3),
row(0, 0),
row(0, 2));
execute("DELETE FROM %s WHERE blog_id = 0 AND timestamp = 2");
assertRows(execute("SELECT blog_id, timestamp FROM %s WHERE author = 'bob'"),
row(1, 0),
row(1, 3),
row(0, 0));
}
/**
* Test for the validation bug of #4709,
* migrated from cql_tests.py:TestCQL.refuse_in_with_indexes_test()
*/
@Test
public void testInvalidIndexSelect() throws Throwable
{
createTable("create table %s (pk varchar primary key, col1 varchar, col2 varchar)");
createIndex("create index on %s (col1)");
createIndex("create index on %s (col2)");
execute("insert into %s (pk, col1, col2) values ('pk1','foo1','bar1')");
execute("insert into %s (pk, col1, col2) values ('pk1a','foo1','bar1')");
execute("insert into %s (pk, col1, col2) values ('pk1b','foo1','bar1')");
execute("insert into %s (pk, col1, col2) values ('pk1c','foo1','bar1')");
execute("insert into %s (pk, col1, col2) values ('pk2','foo2','bar2')");
execute("insert into %s (pk, col1, col2) values ('pk3','foo3','bar3')");
assertInvalid("select * from %s where col2 in ('bar1', 'bar2')");
//Migrated from cql_tests.py:TestCQL.bug_6050_test()
createTable("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)");
createIndex("CREATE INDEX ON %s (a)");
assertInvalid("SELECT * FROM %s WHERE a = 3 AND b IN (1, 3)");
}
/**
* Migrated from cql_tests.py:TestCQL.edge_2i_on_complex_pk_test()
*/
@Test
public void testIndexesOnComplexPrimaryKey() throws Throwable
{
createTable("CREATE TABLE %s (pk0 int, pk1 int, ck0 int, ck1 int, ck2 int, value int, PRIMARY KEY ((pk0, pk1), ck0, ck1, ck2))");
execute("CREATE INDEX ON %s (pk0)");
execute("CREATE INDEX ON %s (ck0)");
execute("CREATE INDEX ON %s (ck1)");
execute("CREATE INDEX ON %s (ck2)");
execute("INSERT INTO %s (pk0, pk1, ck0, ck1, ck2, value) VALUES (0, 1, 2, 3, 4, 5)");
execute("INSERT INTO %s (pk0, pk1, ck0, ck1, ck2, value) VALUES (1, 2, 3, 4, 5, 0)");
execute("INSERT INTO %s (pk0, pk1, ck0, ck1, ck2, value) VALUES (2, 3, 4, 5, 0, 1)");
execute("INSERT INTO %s (pk0, pk1, ck0, ck1, ck2, value) VALUES (3, 4, 5, 0, 1, 2)");
execute("INSERT INTO %s (pk0, pk1, ck0, ck1, ck2, value) VALUES (4, 5, 0, 1, 2, 3)");
execute("INSERT INTO %s (pk0, pk1, ck0, ck1, ck2, value) VALUES (5, 0, 1, 2, 3, 4)");
assertRows(execute("SELECT value FROM %s WHERE pk0 = 2"),
row(1));
assertRows(execute("SELECT value FROM %s WHERE ck0 = 0"),
row(3));
assertRows(execute("SELECT value FROM %s WHERE pk0 = 3 AND pk1 = 4 AND ck1 = 0"),
row(2));
assertRows(execute("SELECT value FROM %s WHERE pk0 = 5 AND pk1 = 0 AND ck0 = 1 AND ck2 = 3 ALLOW FILTERING"),
row(4));
}
/**
* Test for CASSANDRA-5240,
* migrated from cql_tests.py:TestCQL.bug_5240_test()
*/
@Test
public void testIndexOnCompoundRowKey() throws Throwable
{
createTable("CREATE TABLE %s (interval text, seq int, id int, severity int, PRIMARY KEY ((interval, seq), id) ) WITH CLUSTERING ORDER BY (id DESC)");
execute("CREATE INDEX ON %s (severity)");
execute("insert into %s (interval, seq, id , severity) values('t',1, 1, 1)");
execute("insert into %s (interval, seq, id , severity) values('t',1, 2, 1)");
execute("insert into %s (interval, seq, id , severity) values('t',1, 3, 2)");
execute("insert into %s (interval, seq, id , severity) values('t',1, 4, 3)");
execute("insert into %s (interval, seq, id , severity) values('t',2, 1, 3)");
execute("insert into %s (interval, seq, id , severity) values('t',2, 2, 3)");
execute("insert into %s (interval, seq, id , severity) values('t',2, 3, 1)");
execute("insert into %s (interval, seq, id , severity) values('t',2, 4, 2)");
assertRows(execute("select * from %s where severity = 3 and interval = 't' and seq =1"),
row("t", 1, 4, 3));
}
/**
* Migrated from cql_tests.py:TestCQL.secondary_index_counters()
*/
@Test
public void testIndexOnCountersInvalid() throws Throwable
{
createTable("CREATE TABLE %s (k int PRIMARY KEY, c counter)");
assertInvalid("CREATE INDEX ON test(c)");
}
/**
* Migrated from cql_tests.py:TestCQL.collection_indexing_test()
*/
@Test
public void testIndexOnCollections() throws Throwable
{
createTable(" CREATE TABLE %s ( k int, v int, l list<int>, s set<text>, m map<text, int>, PRIMARY KEY (k, v))");
createIndex("CREATE INDEX ON %s (l)");
createIndex("CREATE INDEX ON %s (s)");
createIndex("CREATE INDEX ON %s (m)");
execute("INSERT INTO %s (k, v, l, s, m) VALUES (0, 0, [1, 2], {'a'}, {'a' : 1})");
execute("INSERT INTO %s (k, v, l, s, m) VALUES (0, 1, [3, 4], {'b', 'c'}, {'a' : 1, 'b' : 2})");
execute("INSERT INTO %s (k, v, l, s, m) VALUES (0, 2, [1], {'a', 'c'}, {'c' : 3})");
execute("INSERT INTO %s (k, v, l, s, m) VALUES (1, 0, [1, 2, 4], {}, {'b' : 1})");
execute("INSERT INTO %s (k, v, l, s, m) VALUES (1, 1, [4, 5], {'d'}, {'a' : 1, 'b' : 3})");
// lists
assertRows(execute("SELECT k, v FROM %s WHERE l CONTAINS 1"), row(1, 0), row(0, 0), row(0, 2));
assertRows(execute("SELECT k, v FROM %s WHERE k = 0 AND l CONTAINS 1"), row(0, 0), row(0, 2));
assertRows(execute("SELECT k, v FROM %s WHERE l CONTAINS 2"), row(1, 0), row(0, 0));
assertEmpty(execute("SELECT k, v FROM %s WHERE l CONTAINS 6"));
// sets
assertRows(execute("SELECT k, v FROM %s WHERE s CONTAINS 'a'"), row(0, 0), row(0, 2));
assertRows(execute("SELECT k, v FROM %s WHERE k = 0 AND s CONTAINS 'a'"), row(0, 0), row(0, 2));
assertRows(execute("SELECT k, v FROM %s WHERE s CONTAINS 'd'"), row(1, 1));
assertEmpty(execute("SELECT k, v FROM %s WHERE s CONTAINS 'e'"));
// maps
assertRows(execute("SELECT k, v FROM %s WHERE m CONTAINS 1"), row(1, 0), row(1, 1), row(0, 0), row(0, 1));
assertRows(execute("SELECT k, v FROM %s WHERE k = 0 AND m CONTAINS 1"), row(0, 0), row(0, 1));
assertRows(execute("SELECT k, v FROM %s WHERE m CONTAINS 2"), row(0, 1));
assertEmpty(execute("SELECT k, v FROM %s WHERE m CONTAINS 4"));
}
/**
* Migrated from cql_tests.py:TestCQL.map_keys_indexing()
*/
@Test
public void testIndexOnMapKeys() throws Throwable
{
createTable("CREATE TABLE %s (k int, v int, m map<text, int>, PRIMARY KEY (k, v))");
createIndex("CREATE INDEX ON %s(keys(m))");
execute("INSERT INTO %s (k, v, m) VALUES (0, 0, {'a' : 1})");
execute("INSERT INTO %s (k, v, m) VALUES (0, 1, {'a' : 1, 'b' : 2})");
execute("INSERT INTO %s (k, v, m) VALUES (0, 2, {'c' : 3})");
execute("INSERT INTO %s (k, v, m) VALUES (1, 0, {'b' : 1})");
execute("INSERT INTO %s (k, v, m) VALUES (1, 1, {'a' : 1, 'b' : 3})");
// maps
assertRows(execute("SELECT k, v FROM %s WHERE m CONTAINS KEY 'a'"), row(1, 1), row(0, 0), row(0, 1));
assertRows(execute("SELECT k, v FROM %s WHERE k = 0 AND m CONTAINS KEY 'a'"), row(0, 0), row(0, 1));
assertRows(execute("SELECT k, v FROM %s WHERE m CONTAINS KEY 'c'"), row(0, 2));
assertEmpty(execute("SELECT k, v FROM %s WHERE m CONTAINS KEY 'd'"));
// we're not allowed to create a value index if we already have a key one
assertInvalid("CREATE INDEX ON %s(m)");
}
/**
* Test for #6950 bug,
* migrated from cql_tests.py:TestCQL.key_index_with_reverse_clustering()
*/
@Test
public void testIndexOnKeyWithReverseClustering() throws Throwable
{
createTable(" CREATE TABLE %s (k1 int, k2 int, v int, PRIMARY KEY ((k1, k2), v) ) WITH CLUSTERING ORDER BY (v DESC)");
createIndex("CREATE INDEX ON %s (k2)");
execute("INSERT INTO %s (k1, k2, v) VALUES (0, 0, 1)");
execute("INSERT INTO %s (k1, k2, v) VALUES (0, 1, 2)");
execute("INSERT INTO %s (k1, k2, v) VALUES (0, 0, 3)");
execute("INSERT INTO %s (k1, k2, v) VALUES (1, 0, 4)");
execute("INSERT INTO %s (k1, k2, v) VALUES (1, 1, 5)");
execute("INSERT INTO %s (k1, k2, v) VALUES (2, 0, 7)");
execute("INSERT INTO %s (k1, k2, v) VALUES (2, 1, 8)");
execute("INSERT INTO %s (k1, k2, v) VALUES (3, 0, 1)");
assertRows(execute("SELECT * FROM %s WHERE k2 = 0 AND v >= 2 ALLOW FILTERING"),
row(2, 0, 7),
row(0, 0, 3),
row(1, 0, 4));
}
/**
* Test for CASSANDRA-6612,
* migrated from cql_tests.py:TestCQL.bug_6612_test()
*/
@Test
public void testSelectCountOnIndexedColumn() throws Throwable
{
createTable("CREATE TABLE %s (username text, session_id text, app_name text, account text, last_access timestamp, created_on timestamp, PRIMARY KEY (username, session_id, app_name, account))");
createIndex("create index ON %s (app_name)");
createIndex("create index ON %s (last_access)");
assertRows(execute("select count(*) from %s where app_name='foo' and account='bar' and last_access > 4 allow filtering"), row(0L));
execute("insert into %s (username, session_id, app_name, account, last_access, created_on) values ('toto', 'foo', 'foo', 'bar', 12, 13)");
assertRows(execute("select count(*) from %s where app_name='foo' and account='bar' and last_access > 4 allow filtering"), row(1L));
}
/**
* Test for CASSANDRA-5732, Can not query secondary index
* migrated from cql_tests.py:TestCQL.bug_5732_test(),
* which was executing with a row cache size of 100 MB
* and restarting the node, here we just cleanup the cache.
*/
@Test
public void testCanQuerySecondaryIndex() throws Throwable
{
String tableName = createTable("CREATE TABLE %s (k int PRIMARY KEY, v int,)");
execute("ALTER TABLE %s WITH CACHING='ALL'");
execute("INSERT INTO %s (k,v) VALUES (0,0)");
execute("INSERT INTO %s (k,v) VALUES (1,1)");
createIndex("CREATE INDEX testindex on %s (v)");
assertTrue(waitForIndex(keyspace(), tableName, "testindex"));
assertRows(execute("SELECT k FROM %s WHERE v = 0"), row(0));
cleanupCache();
assertRows(execute("SELECT k FROM %s WHERE v = 0"), row(0));
}
// CASSANDRA-8280/8081
// reject updates with indexed values where value > 64k
@Test
public void testIndexOnCompositeValueOver64k() throws Throwable
{
createTable("CREATE TABLE %s(a int, b int, c blob, PRIMARY KEY (a))");
createIndex("CREATE INDEX ON %s(c)");
failInsert("INSERT INTO %s (a, b, c) VALUES (0, 0, ?)", ByteBuffer.allocate(TOO_BIG));
}
@Test
public void testCompactTableWithValueOver64k() throws Throwable
{
createTable("CREATE TABLE %s(a int, b blob, PRIMARY KEY (a)) WITH COMPACT STORAGE");
createIndex("CREATE INDEX ON %s(b)");
failInsert("INSERT INTO %s (a, b) VALUES (0, ?)", ByteBuffer.allocate(TOO_BIG));
}
@Test
public void testIndexOnPartitionKeyInsertValueOver64k() throws Throwable
{
createTable("CREATE TABLE %s(a int, b int, c blob, PRIMARY KEY ((a, b)))");
createIndex("CREATE INDEX ON %s(a)");
succeedInsert("INSERT INTO %s (a, b, c) VALUES (0, 0, ?)", ByteBuffer.allocate(TOO_BIG));
}
@Test
public void testIndexOnClusteringColumnInsertValueOver64k() throws Throwable
{
createTable("CREATE TABLE %s(a int, b int, c blob, PRIMARY KEY (a, b))");
createIndex("CREATE INDEX ON %s(b)");
succeedInsert("INSERT INTO %s (a, b, c) VALUES (0, 0, ?)", ByteBuffer.allocate(TOO_BIG));
}
@Test
public void testIndexOnFullCollectionEntryInsertCollectionValueOver64k() throws Throwable
{
createTable("CREATE TABLE %s(a int, b frozen<map<int, blob>>, PRIMARY KEY (a))");
createIndex("CREATE INDEX ON %s(full(b))");
Map<Integer, ByteBuffer> map = new HashMap();
map.put(0, ByteBuffer.allocate(1024 * 65));
failInsert("INSERT INTO %s (a, b) VALUES (0, ?)", map);
}
public void failInsert(String insertCQL, Object...args) throws Throwable
{
try
{
execute(insertCQL, args);
fail("Expected statement to fail validation");
}
catch (Exception e)
{
// as expected
}
}
public void succeedInsert(String insertCQL, Object...args) throws Throwable
{
execute(insertCQL, args);
flush();
}
/**
* Migrated from cql_tests.py:TestCQL.clustering_indexing_test()
*/
@Test
public void testIndexesOnClustering() throws Throwable
{
createTable("CREATE TABLE %s ( id1 int, id2 int, author text, time bigint, v1 text, v2 text, PRIMARY KEY ((id1, id2), author, time))");
createIndex("CREATE INDEX ON %s (time)");
execute("CREATE INDEX ON %s (id2)");
execute("INSERT INTO %s (id1, id2, author, time, v1, v2) VALUES(0, 0, 'bob', 0, 'A', 'A')");
execute("INSERT INTO %s (id1, id2, author, time, v1, v2) VALUES(0, 0, 'bob', 1, 'B', 'B')");
execute("INSERT INTO %s (id1, id2, author, time, v1, v2) VALUES(0, 1, 'bob', 2, 'C', 'C')");
execute("INSERT INTO %s (id1, id2, author, time, v1, v2) VALUES(0, 0, 'tom', 0, 'D', 'D')");
execute("INSERT INTO %s (id1, id2, author, time, v1, v2) VALUES(0, 1, 'tom', 1, 'E', 'E')");
assertRows(execute("SELECT v1 FROM %s WHERE time = 1"),
row("B"), row("E"));
assertRows(execute("SELECT v1 FROM %s WHERE id2 = 1"),
row("C"), row("E"));
assertRows(execute("SELECT v1 FROM %s WHERE id1 = 0 AND id2 = 0 AND author = 'bob' AND time = 0"),
row("A"));
// Test for CASSANDRA-8206
execute("UPDATE %s SET v2 = null WHERE id1 = 0 AND id2 = 0 AND author = 'bob' AND time = 1");
assertRows(execute("SELECT v1 FROM %s WHERE id2 = 0"),
row("A"), row("B"), row("D"));
assertRows(execute("SELECT v1 FROM %s WHERE time = 1"),
row("B"), row("E"));
}
/**
* Migrated from cql_tests.py:TestCQL.invalid_clustering_indexing_test()
*/
@Test
public void testIndexesOnClusteringInvalid() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY ((a, b))) WITH COMPACT STORAGE");
assertInvalid("CREATE INDEX ON %s (a)");
assertInvalid("CREATE INDEX ON %s (b)");
createTable("CREATE TABLE %s (a int, b int, c int, PRIMARY KEY (a, b)) WITH COMPACT STORAGE");
assertInvalid("CREATE INDEX ON %s (a)");
assertInvalid("CREATE INDEX ON %s (b)");
assertInvalid("CREATE INDEX ON %s (c)");
createTable("CREATE TABLE %s (a int, b int, c int static , PRIMARY KEY (a, b))");
assertInvalid("CREATE INDEX ON %s (c)");
}
}
| |
package com.orientechnologies.orient.core.storage.index.sbtree.local.v2;
import com.orientechnologies.common.directmemory.OByteBufferPool;
import com.orientechnologies.common.directmemory.ODirectMemoryAllocator.Intention;
import com.orientechnologies.common.directmemory.OPointer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLinkSerializer;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.cache.OCacheEntryImpl;
import com.orientechnologies.orient.core.storage.cache.OCachePointer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.TreeSet;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Andrey Lomakin (a.lomakin-at-orientdb.com)
* @since 12.08.13
*/
public class SBTreeNonLeafBucketV2Test {
@Test
public void testInitialization() {
final OByteBufferPool bufferPool = OByteBufferPool.instance(null);
final OPointer pointer = bufferPool.acquireDirect(true, Intention.TEST);
OCachePointer cachePointer = new OCachePointer(pointer, bufferPool, 0, 0);
OCacheEntry cacheEntry = new OCacheEntryImpl(0, 0, cachePointer, false);
cacheEntry.acquireExclusiveLock();
cachePointer.incrementReferrer();
OSBTreeBucketV2<Long, OIdentifiable> treeBucket = new OSBTreeBucketV2<>(cacheEntry);
treeBucket.init(false);
Assert.assertEquals(treeBucket.size(), 0);
Assert.assertFalse(treeBucket.isLeaf());
treeBucket = new OSBTreeBucketV2<>(cacheEntry);
Assert.assertEquals(treeBucket.size(), 0);
Assert.assertFalse(treeBucket.isLeaf());
Assert.assertEquals(treeBucket.getLeftSibling(), -1);
Assert.assertEquals(treeBucket.getRightSibling(), -1);
cacheEntry.releaseExclusiveLock();
cachePointer.decrementReferrer();
}
@Test
public void testSearch() {
long seed = System.currentTimeMillis();
System.out.println("testSearch seed : " + seed);
TreeSet<Long> keys = new TreeSet<>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBucketV2.MAX_PAGE_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
final OByteBufferPool bufferPool = OByteBufferPool.instance(null);
final OPointer pointer = bufferPool.acquireDirect(true, Intention.TEST);
OCachePointer cachePointer = new OCachePointer(pointer, bufferPool, 0, 0);
OCacheEntry cacheEntry = new OCacheEntryImpl(0, 0, cachePointer, false);
cacheEntry.acquireExclusiveLock();
cachePointer.incrementReferrer();
OSBTreeBucketV2<Long, OIdentifiable> treeBucket = new OSBTreeBucketV2<>(cacheEntry);
treeBucket.init(false);
int index = 0;
Map<Long, Integer> keyIndexMap = new HashMap<>();
for (Long key : keys) {
if (!treeBucket.addNonLeafEntry(
index,
OLongSerializer.INSTANCE.serializeNativeAsWhole(key),
random.nextInt(Integer.MAX_VALUE),
random.nextInt(Integer.MAX_VALUE),
true)) {
break;
}
keyIndexMap.put(key, index);
index++;
}
Assert.assertEquals(treeBucket.size(), keyIndexMap.size());
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey(), OLongSerializer.INSTANCE);
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
long prevRight = -1;
for (int i = 0; i < treeBucket.size(); i++) {
OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
treeBucket.getEntry(i, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
if (prevRight > 0) {
Assert.assertEquals(entry.leftChild, prevRight);
}
prevRight = entry.rightChild;
}
long prevLeft = -1;
for (int i = treeBucket.size() - 1; i >= 0; i--) {
OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
treeBucket.getEntry(i, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
if (prevLeft > 0) Assert.assertEquals(entry.rightChild, prevLeft);
prevLeft = entry.leftChild;
}
cacheEntry.releaseExclusiveLock();
cachePointer.decrementReferrer();
}
@Test
public void testShrink() {
long seed = System.currentTimeMillis();
System.out.println("testShrink seed : " + seed);
TreeSet<Long> keys = new TreeSet<>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBucketV2.MAX_PAGE_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
final OByteBufferPool bufferPool = OByteBufferPool.instance(null);
final OPointer pointer = bufferPool.acquireDirect(true, Intention.TEST);
OCachePointer cachePointer = new OCachePointer(pointer, bufferPool, 0, 0);
OCacheEntry cacheEntry = new OCacheEntryImpl(0, 0, cachePointer, false);
cacheEntry.acquireExclusiveLock();
cachePointer.incrementReferrer();
OSBTreeBucketV2<Long, OIdentifiable> treeBucket = new OSBTreeBucketV2<>(cacheEntry);
treeBucket.init(false);
int index = 0;
for (Long key : keys) {
if (!treeBucket.addNonLeafEntry(
index, OLongSerializer.INSTANCE.serializeNativeAsWhole(key), index, index + 1, true)) {
break;
}
index++;
}
int originalSize = treeBucket.size();
treeBucket.shrink(treeBucket.size() / 2, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
Assert.assertEquals(treeBucket.size(), index / 2);
index = 0;
final Map<Long, Integer> keyIndexMap = new HashMap<>();
Iterator<Long> keysIterator = keys.iterator();
while (keysIterator.hasNext() && index < treeBucket.size()) {
Long key = keysIterator.next();
keyIndexMap.put(key, index);
index++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey(), OLongSerializer.INSTANCE);
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
treeBucket.getEntry(
keyIndexEntry.getValue(), OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
Assert.assertEquals(
entry,
new OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable>(
keyIndexEntry.getValue(),
keyIndexEntry.getValue() + 1,
keyIndexEntry.getKey(),
null));
}
int keysToAdd = originalSize - treeBucket.size();
int addedKeys = 0;
while (keysIterator.hasNext() && index < originalSize) {
Long key = keysIterator.next();
if (!treeBucket.addNonLeafEntry(
index, OLongSerializer.INSTANCE.serializeNativeAsWhole(key), index, index + 1, true)) {
break;
}
keyIndexMap.put(key, index);
index++;
addedKeys++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
treeBucket.getEntry(
keyIndexEntry.getValue(), OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
Assert.assertEquals(
entry,
new OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable>(
keyIndexEntry.getValue(),
keyIndexEntry.getValue() + 1,
keyIndexEntry.getKey(),
null));
}
Assert.assertEquals(treeBucket.size(), originalSize);
Assert.assertEquals(addedKeys, keysToAdd);
cacheEntry.releaseExclusiveLock();
cachePointer.decrementReferrer();
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.io;
import com.intellij.Patches;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.win32.FileInfo;
import com.intellij.openapi.util.io.win32.IdeaWin32;
import com.intellij.util.ArrayUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.containers.ContainerUtil;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import static com.intellij.util.BitUtil.isSet;
/**
* @version 11.1
*/
public class FileSystemUtil {
static final String FORCE_USE_NIO2_KEY = "idea.io.use.nio2";
static final String FORCE_USE_FALLBACK_KEY = "idea.io.use.fallback";
static final String COARSE_TIMESTAMP_KEY = "idea.io.coarse.ts";
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileSystemUtil");
private abstract static class Mediator {
@Nullable
protected abstract FileAttributes getAttributes(@NotNull String path) throws Exception;
@Nullable
protected abstract String resolveSymLink(@NotNull String path) throws Exception;
protected boolean clonePermissions(@NotNull String source, @NotNull String target, boolean onlyPermissionsToExecute) throws Exception { return false; }
@NotNull
private String getName() { return getClass().getSimpleName().replace("MediatorImpl", ""); }
}
@NotNull
private static Mediator ourMediator = getMediator();
private static Mediator getMediator() {
boolean forceNio2 = SystemProperties.getBooleanProperty(FORCE_USE_NIO2_KEY, false);
boolean forceFallback = SystemProperties.getBooleanProperty(FORCE_USE_FALLBACK_KEY, false);
Throwable error = null;
if (!forceNio2 && !forceFallback) {
if (SystemInfo.isWindows && IdeaWin32.isAvailable()) {
try {
return check(new IdeaWin32MediatorImpl());
}
catch (Throwable t) {
error = t;
}
}
else if (SystemInfo.isLinux || SystemInfo.isMac || SystemInfo.isSolaris || SystemInfo.isFreeBSD) {
try {
return check(new JnaUnixMediatorImpl());
}
catch (Throwable t) {
error = t;
}
}
}
if (!forceFallback && SystemInfo.isJavaVersionAtLeast("1.7") && !"1.7.0-ea".equals(SystemInfo.JAVA_VERSION)) {
try {
return check(new Nio2MediatorImpl());
}
catch (Throwable t) {
error = t;
}
}
if (!forceFallback) {
LOG.warn("Failed to load filesystem access layer: " + SystemInfo.OS_NAME + ", " + SystemInfo.JAVA_VERSION + ", " + "nio2=" + forceNio2, error);
}
return new FallbackMediatorImpl();
}
private static Mediator check(final Mediator mediator) throws Exception {
final String quickTestPath = SystemInfo.isWindows ? "C:\\" : "/";
mediator.getAttributes(quickTestPath);
return mediator;
}
private FileSystemUtil() { }
@Nullable
public static FileAttributes getAttributes(@NotNull String path) {
try {
return ourMediator.getAttributes(path);
}
catch (Exception e) {
LOG.warn(e);
}
return null;
}
@Nullable
public static FileAttributes getAttributes(@NotNull File file) {
return getAttributes(file.getPath());
}
public static long lastModified(@NotNull File file) {
FileAttributes attributes = getAttributes(file);
return attributes != null ? attributes.lastModified : 0;
}
/**
* Checks if a last element in the path is a symlink.
*/
public static boolean isSymLink(@NotNull String path) {
if (SystemInfo.areSymLinksSupported) {
final FileAttributes attributes = getAttributes(path);
return attributes != null && attributes.isSymLink();
}
return false;
}
/**
* Checks if a last element in the path is a symlink.
*/
public static boolean isSymLink(@NotNull File file) {
return isSymLink(file.getAbsolutePath());
}
@Nullable
public static String resolveSymLink(@NotNull String path) {
try {
final String realPath = ourMediator.resolveSymLink(path);
if (realPath != null && new File(realPath).exists()) {
return realPath;
}
}
catch (Exception e) {
LOG.warn(e);
}
return null;
}
@Nullable
public static String resolveSymLink(@NotNull File file) {
return resolveSymLink(file.getAbsolutePath());
}
/**
* Gives the second file permissions of the first one if possible; returns true if succeed.
* Will do nothing on Windows.
*/
public static boolean clonePermissions(@NotNull String source, @NotNull String target) {
try {
return ourMediator.clonePermissions(source, target, false);
}
catch (Exception e) {
LOG.warn(e);
return false;
}
}
/**
* Gives the second file permissions to execute of the first one if possible; returns true if succeed.
* Will do nothing on Windows.
*/
public static boolean clonePermissionsToExecute(@NotNull String source, @NotNull String target) {
try {
return ourMediator.clonePermissions(source, target, true);
}
catch (Exception e) {
LOG.warn(e);
return false;
}
}
private static class Nio2MediatorImpl extends Mediator {
private final Object myDefaultFileSystem;
private final Method myGetPath;
private final Method myIsSymbolicLink;
private final Object myLinkOptions;
private final Object myNoFollowLinkOptions;
private final Method myReadAttributes;
private final Method mySetAttribute;
private final Method myToMillis;
private final String mySchema;
private Nio2MediatorImpl() throws Exception {
//noinspection ConstantConditions
assert Patches.USE_REFLECTION_TO_ACCESS_JDK7;
myDefaultFileSystem = Class.forName("java.nio.file.FileSystems").getMethod("getDefault").invoke(null);
final Class<?> fsClass = Class.forName("java.nio.file.FileSystem");
myGetPath = fsClass.getMethod("getPath", String.class, String[].class);
myGetPath.setAccessible(true);
final Class<?> pathClass = Class.forName("java.nio.file.Path");
final Class<?> filesClass = Class.forName("java.nio.file.Files");
myIsSymbolicLink = filesClass.getMethod("isSymbolicLink", pathClass);
myIsSymbolicLink.setAccessible(true);
final Class<?> linkOptClass = Class.forName("java.nio.file.LinkOption");
myLinkOptions = Array.newInstance(linkOptClass, 0);
myNoFollowLinkOptions = Array.newInstance(linkOptClass, 1);
Array.set(myNoFollowLinkOptions, 0, linkOptClass.getField("NOFOLLOW_LINKS").get(null));
final Class<?> linkOptArrClass = myLinkOptions.getClass();
myReadAttributes = filesClass.getMethod("readAttributes", pathClass, String.class, linkOptArrClass);
myReadAttributes.setAccessible(true);
mySetAttribute = filesClass.getMethod("setAttribute", pathClass, String.class, Object.class, linkOptArrClass);
mySetAttribute.setAccessible(true);
final Class<?> fileTimeClass = Class.forName("java.nio.file.attribute.FileTime");
myToMillis = fileTimeClass.getMethod("toMillis");
myToMillis.setAccessible(true);
mySchema = SystemInfo.isWindows ? "dos:*" : "posix:*";
}
@Override
protected FileAttributes getAttributes(@NotNull String path) throws Exception {
try {
Object pathObj = myGetPath.invoke(myDefaultFileSystem, path, ArrayUtil.EMPTY_STRING_ARRAY);
Map attributes = (Map)myReadAttributes.invoke(null, pathObj, mySchema, myNoFollowLinkOptions);
boolean isSymbolicLink = (Boolean)attributes.get("isSymbolicLink");
if (isSymbolicLink) {
try {
attributes = (Map)myReadAttributes.invoke(null, pathObj, mySchema, myLinkOptions);
}
catch (InvocationTargetException e) {
final Throwable cause = e.getCause();
if (cause != null && "java.nio.file.NoSuchFileException".equals(cause.getClass().getName())) {
return FileAttributes.BROKEN_SYMLINK;
}
}
}
boolean isDirectory = (Boolean)attributes.get("isDirectory");
boolean isOther = (Boolean)attributes.get("isOther");
long size = (Long)attributes.get("size");
long lastModified = (Long)myToMillis.invoke(attributes.get("lastModifiedTime"));
if (SystemInfo.isWindows) {
boolean isHidden = new File(path).getParent() == null ? false : (Boolean)attributes.get("hidden");
boolean isWritable = isDirectory || !(Boolean)attributes.get("readonly");
return new FileAttributes(isDirectory, isOther, isSymbolicLink, isHidden, size, lastModified, isWritable);
}
else {
boolean isWritable = new File(path).canWrite();
return new FileAttributes(isDirectory, isOther, isSymbolicLink, false, size, lastModified, isWritable);
}
}
catch (InvocationTargetException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException || cause != null && "java.nio.file.InvalidPathException".equals(cause.getClass().getName())) {
LOG.debug(cause);
return null;
}
throw e;
}
}
@Override
protected String resolveSymLink(@NotNull final String path) throws Exception {
if (!new File(path).exists()) return null;
final Object pathObj = myGetPath.invoke(myDefaultFileSystem, path, ArrayUtil.EMPTY_STRING_ARRAY);
final Method toRealPath = pathObj.getClass().getMethod("toRealPath", myLinkOptions.getClass());
toRealPath.setAccessible(true);
return toRealPath.invoke(pathObj, myLinkOptions).toString();
}
@Override
protected boolean clonePermissions(@NotNull String source, @NotNull String target, boolean onlyPermissionsToExecute) throws Exception {
if (SystemInfo.isUnix) {
Object sourcePath = myGetPath.invoke(myDefaultFileSystem, source, ArrayUtil.EMPTY_STRING_ARRAY);
Object targetPath = myGetPath.invoke(myDefaultFileSystem, target, ArrayUtil.EMPTY_STRING_ARRAY);
Collection sourcePermissions = getPermissions(sourcePath);
Collection targetPermissions = getPermissions(targetPath);
if (sourcePermissions != null && targetPermissions != null) {
if (onlyPermissionsToExecute) {
Collection<Object> permissionsToSet = ContainerUtil.newHashSet();
for (Object permission : targetPermissions) {
if (!permission.toString().endsWith("_EXECUTE")) {
permissionsToSet.add(permission);
}
}
for (Object permission : sourcePermissions) {
if (permission.toString().endsWith("_EXECUTE")) {
permissionsToSet.add(permission);
}
}
mySetAttribute.invoke(null, targetPath, "posix:permissions", permissionsToSet, myLinkOptions);
}
else {
mySetAttribute.invoke(null, targetPath, "posix:permissions", sourcePermissions, myLinkOptions);
}
return true;
}
}
return false;
}
private Collection getPermissions(Object sourcePath) throws IllegalAccessException, InvocationTargetException {
Map attributes = (Map)myReadAttributes.invoke(null, sourcePath, "posix:permissions", myLinkOptions);
if (attributes == null) return null;
Object permissions = attributes.get("permissions");
return permissions instanceof Collection ? (Collection)permissions : null;
}
}
private static class IdeaWin32MediatorImpl extends Mediator {
private IdeaWin32 myInstance = IdeaWin32.getInstance();
@Override
protected FileAttributes getAttributes(@NotNull final String path) throws Exception {
final FileInfo fileInfo = myInstance.getInfo(path);
return fileInfo != null ? fileInfo.toFileAttributes() : null;
}
@Override
protected String resolveSymLink(@NotNull final String path) throws Exception {
return myInstance.resolveSymLink(path);
}
}
// thanks to SVNKit for the idea of platform-specific offsets
private static class JnaUnixMediatorImpl extends Mediator {
@SuppressWarnings({"OctalInteger", "SpellCheckingInspection"})
private static class LibC {
static final int S_MASK = 0177777;
static final int S_IFMT = 0170000;
static final int S_IFLNK = 0120000; // symbolic link
static final int S_IFREG = 0100000; // regular file
static final int S_IFDIR = 0040000; // directory
static final int PERM_MASK = 0777;
static final int EXECUTE_MASK = 0111;
static final int WRITE_MASK = 0222;
static final int W_OK = 2; // write permission flag for access(2)
static native int getuid();
static native int getgid();
static native int chmod(String path, int mode);
static native int access(String path, int mode);
}
@SuppressWarnings("SpellCheckingInspection")
private static class UnixLibC {
static native int lstat(String path, Pointer stat);
static native int stat(String path, Pointer stat);
}
@SuppressWarnings("SpellCheckingInspection")
private static class LinuxLibC {
static native int __lxstat64(int ver, String path, Pointer stat);
static native int __xstat64(int ver, String path, Pointer stat);
}
private static final int[] LINUX_32 = {16, 44, 72, 24, 28};
private static final int[] LINUX_64 = {24, 48, 88, 28, 32};
private static final int[] LNX_PPC32 = {16, 48, 80, 24, 28};
private static final int[] LNX_PPC64 = LINUX_64;
private static final int[] LNX_ARM32 = LNX_PPC32;
private static final int[] BSD_32 = { 8, 48, 32, 12, 16};
private static final int[] BSD_64 = { 8, 72, 40, 12, 16};
private static final int[] SUN_OS_32 = {20, 48, 64, 28, 32};
private static final int[] SUN_OS_64 = {16, 40, 64, 24, 28};
private static final int STAT_VER = 1;
private static final int OFF_MODE = 0;
private static final int OFF_SIZE = 1;
private static final int OFF_TIME = 2;
private static final int OFF_UID = 3;
private static final int OFF_GID = 4;
private final int[] myOffsets;
private final int myUid;
private final int myGid;
private final boolean myCoarseTs = SystemProperties.getBooleanProperty(COARSE_TIMESTAMP_KEY, false);
private JnaUnixMediatorImpl() throws Exception {
if (SystemInfo.isLinux) {
if ("arm".equals(SystemInfo.OS_ARCH)) {
if (SystemInfo.is32Bit) {
myOffsets = LNX_ARM32;
}
else {
throw new IllegalStateException("AArch64 architecture is not supported");
}
}
else if ("ppc".equals(SystemInfo.OS_ARCH)) {
myOffsets = SystemInfo.is32Bit ? LNX_PPC32 : LNX_PPC64;
}
else {
myOffsets = SystemInfo.is32Bit ? LINUX_32 : LINUX_64;
}
}
else if (SystemInfo.isMac | SystemInfo.isFreeBSD) {
myOffsets = SystemInfo.is32Bit ? BSD_32 : BSD_64;
}
else if (SystemInfo.isSolaris) {
myOffsets = SystemInfo.is32Bit ? SUN_OS_32 : SUN_OS_64;
}
else {
throw new IllegalStateException("Unsupported OS/arch: " + SystemInfo.OS_NAME + "/" + SystemInfo.OS_ARCH);
}
Native.register(LibC.class, "c");
Native.register(SystemInfo.isLinux ? LinuxLibC.class : UnixLibC.class, "c");
myUid = LibC.getuid();
myGid = LibC.getgid();
}
@Override
protected FileAttributes getAttributes(@NotNull String path) throws Exception {
Memory buffer = new Memory(256);
int res = SystemInfo.isLinux ? LinuxLibC.__lxstat64(STAT_VER, path, buffer) : UnixLibC.lstat(path, buffer);
if (res != 0) return null;
int mode = getModeFlags(buffer) & LibC.S_MASK;
boolean isSymlink = (mode & LibC.S_IFMT) == LibC.S_IFLNK;
if (isSymlink) {
if (!loadFileStatus(path, buffer)) {
return FileAttributes.BROKEN_SYMLINK;
}
mode = getModeFlags(buffer) & LibC.S_MASK;
}
boolean isDirectory = (mode & LibC.S_IFMT) == LibC.S_IFDIR;
boolean isSpecial = !isDirectory && (mode & LibC.S_IFMT) != LibC.S_IFREG;
long size = buffer.getLong(myOffsets[OFF_SIZE]);
long mTime1 = SystemInfo.is32Bit ? buffer.getInt(myOffsets[OFF_TIME]) : buffer.getLong(myOffsets[OFF_TIME]);
long mTime2 = myCoarseTs ? 0 : SystemInfo.is32Bit ? buffer.getInt(myOffsets[OFF_TIME] + 4) : buffer.getLong(myOffsets[OFF_TIME] + 8);
long mTime = mTime1 * 1000 + mTime2 / 1000000;
boolean writable = ownFile(buffer) ? (mode & LibC.WRITE_MASK) != 0 : LibC.access(path, LibC.W_OK) == 0;
return new FileAttributes(isDirectory, isSpecial, isSymlink, false, size, mTime, writable);
}
private static boolean loadFileStatus(String path, Memory buffer) {
return (SystemInfo.isLinux ? LinuxLibC.__xstat64(STAT_VER, path, buffer) : UnixLibC.stat(path, buffer)) == 0;
}
@Override
protected String resolveSymLink(@NotNull final String path) throws Exception {
try {
return new File(path).getCanonicalPath();
}
catch (IOException e) {
String message = e.getMessage();
if (message != null && message.toLowerCase(Locale.US).contains("too many levels of symbolic links")) {
LOG.debug(e);
return null;
}
throw new IOException("Cannot resolve '" + path + "'", e);
}
}
@Override
protected boolean clonePermissions(@NotNull String source, @NotNull String target, boolean onlyPermissionsToExecute) throws Exception {
Memory buffer = new Memory(256);
if (!loadFileStatus(source, buffer)) return false;
int permissions;
int sourcePermissions = getModeFlags(buffer) & LibC.PERM_MASK;
if (onlyPermissionsToExecute) {
if (!loadFileStatus(target, buffer)) return false;
int targetPermissions = getModeFlags(buffer) & LibC.PERM_MASK;
permissions = targetPermissions & ~LibC.EXECUTE_MASK | sourcePermissions & LibC.EXECUTE_MASK;
}
else {
permissions = sourcePermissions;
}
return LibC.chmod(target, permissions) == 0;
}
private int getModeFlags(Memory buffer) {
return SystemInfo.isLinux ? buffer.getInt(myOffsets[OFF_MODE]) : buffer.getShort(myOffsets[OFF_MODE]);
}
private boolean ownFile(Memory buffer) {
return buffer.getInt(myOffsets[OFF_UID]) == myUid && buffer.getInt(myOffsets[OFF_GID]) == myGid;
}
}
private static class FallbackMediatorImpl extends Mediator {
// from java.io.FileSystem
private static final int BA_REGULAR = 0x02;
private static final int BA_DIRECTORY = 0x04;
private static final int BA_HIDDEN = 0x08;
private final Object myFileSystem;
private final Method myGetBooleanAttributes;
private FallbackMediatorImpl() {
Object fileSystem;
Method getBooleanAttributes;
try {
Field fs = File.class.getDeclaredField("fs");
fs.setAccessible(true);
fileSystem = fs.get(null);
getBooleanAttributes = fileSystem.getClass().getMethod("getBooleanAttributes", File.class);
getBooleanAttributes.setAccessible(true);
}
catch (Throwable t) {
fileSystem = null;
getBooleanAttributes = null;
}
myFileSystem = fileSystem;
myGetBooleanAttributes = getBooleanAttributes;
}
@Override
protected FileAttributes getAttributes(@NotNull final String path) throws Exception {
final File file = new File(path);
if (myFileSystem != null) {
final int flags = (Integer)myGetBooleanAttributes.invoke(myFileSystem, file);
if (flags != 0) {
boolean isDirectory = isSet(flags, BA_DIRECTORY);
boolean isSpecial = !isSet(flags, BA_REGULAR) && !isSet(flags, BA_DIRECTORY);
boolean isHidden = isSet(flags, BA_HIDDEN) && !isWindowsRoot(path);
boolean isWritable = SystemInfo.isWindows && isDirectory || file.canWrite();
return new FileAttributes(isDirectory, isSpecial, false, isHidden, file.length(), file.lastModified(), isWritable);
}
}
else if (file.exists()) {
boolean isDirectory = file.isDirectory();
boolean isSpecial = !isDirectory && !file.isFile();
boolean isHidden = file.isHidden() && !isWindowsRoot(path);
boolean isWritable = SystemInfo.isWindows && isDirectory || file.canWrite();
return new FileAttributes(isDirectory, isSpecial, false, isHidden, file.length(), file.lastModified(), isWritable);
}
return null;
}
private static boolean isWindowsRoot(String p) {
return SystemInfo.isWindows && p.length() >= 2 && p.length() <= 3 && Character.isLetter(p.charAt(0)) && p.charAt(1) == ':';
}
@Override
protected String resolveSymLink(@NotNull final String path) throws Exception {
return new File(path).getCanonicalPath();
}
@Override
protected boolean clonePermissions(@NotNull String source, @NotNull String target, boolean onlyPermissionsToExecute) throws Exception {
if (SystemInfo.isUnix) {
File srcFile = new File(source);
File dstFile = new File(target);
if (!onlyPermissionsToExecute) {
if (!dstFile.setWritable(srcFile.canWrite(), true)) return false;
}
return dstFile.setExecutable(srcFile.canExecute(), true);
}
return false;
}
}
@TestOnly
static void resetMediator() {
ourMediator = getMediator();
}
@TestOnly
static String getMediatorName() {
return ourMediator.getName();
}
}
| |
/*
* 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.
*
* $Header:$
*/
package org.apache.beehive.controls.system.jdbc.parser;
import org.apache.beehive.controls.api.ControlException;
import org.apache.beehive.controls.api.context.ControlBeanContext;
import org.apache.beehive.controls.system.jdbc.TypeMappingsFactory;
import org.apache.beehive.controls.system.jdbc.JdbcControl;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Represents a method parameter substitution into the SQL annotation's statement member. Delimited by '{' and '}'.
* Method parameter names must exactly match the name used in the SQL statement in order for the substitution to occur.
* <p/>
* <pre>
* SQL(statement="SELECT * FROM {tableName}")
* public void getAll(String tableName) throws SQLException;
* </pre>
*/
public final class ReflectionFragment extends SqlFragment {
private static final String PREPARED_STATEMENT_SUB_MARK = "?";
private static final Pattern s_parameterNamePattern = Pattern.compile("\\.");
private final String _parameterName;
private final String[] _nameQualifiers;
private int _sqlDataType;
/**
* Create a new ReflectionFragment with the specifed method parameter name.
*
* @param parameterName The name of the parameter whose value should be substituted at this location.
*/
protected ReflectionFragment(String parameterName) {
_parameterName = parameterName;
_sqlDataType = TypeMappingsFactory.TYPE_UNKNOWN;
_nameQualifiers = s_parameterNamePattern.split(_parameterName);
}
/**
* Create a new ReflectionFragment with the specified method parameter name and SQL type.
*
* @param parameterName The name of the parameter whose value should be substituted at this location.
* @param sqlDataType A String specifing the SQL data type for this parameter.
*/
protected ReflectionFragment(String parameterName, String sqlDataType) {
this(parameterName);
if (sqlDataType != null) {
_sqlDataType = TypeMappingsFactory.getInstance().convertStringToSQLType(sqlDataType);
}
}
/**
* Return text generated by this fragment for a PreparedStatement
*
* @param context A ControlBeanContext instance.
* @param m The annotated method.
* @param args The method's parameters
* @return Always returns a PREPARED_STATEMENT_SUB_MARK
*/
protected String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) {
// this reflection fragment may resolve to a JdbcControl.ComplexSqlFragment
// if so it changes the behavior a bit.
Object val = getParameterValue(context, m, args);
if (val instanceof JdbcControl.ComplexSqlFragment) {
return ((JdbcControl.ComplexSqlFragment)val).getSQL();
} else {
return PREPARED_STATEMENT_SUB_MARK;
}
}
/**
* A reflection fragment may evaluate to an JdbcControl.ComplexSqlFragment type,
* which requires additional steps to evaluate after reflection.
*
* @param context Control bean context.
* @param m Method.
* @param args Method args.
* @return true or false.
*/
protected boolean hasComplexValue(ControlBeanContext context, Method m, Object[] args) {
Object val = getParameterValue(context, m, args);
return val instanceof JdbcControl.ComplexSqlFragment;
}
/**
* Always true for ReflectionFragment.
*
* @return true
*/
protected boolean hasParamValue() { return true; }
/**
* Get the parameter name (as specified in the SQL statement).
*
* @return The parameter name.
*/
protected String getParameterName() { return _parameterName; }
/**
* Get a copy of the array of parameter name qualifiers.
*
* @return An array of parameter name qualifiers.
*/
protected String[] getParameterNameQualifiers() {
String[] nameQualifiersCopy = new String[_nameQualifiers.length];
System.arraycopy(_nameQualifiers, 0, nameQualifiersCopy, 0, _nameQualifiers.length);
return nameQualifiersCopy;
}
/**
* Get the SQL data type of this param.
*
* @return The SQL data type for this param.
*/
protected int getParamSqlDataType() { return _sqlDataType; }
/**
* For JUnit testing.
*
* @return The String value of this fragment.
*/
public String toString() { return PREPARED_STATEMENT_SUB_MARK; }
/**
* Get the value of this parameter.
*
* @param context ControlBeanContext instance to evaluate the parameter's value against.
* @param method Method instance to evaluate against.
* @param args Method argument values
* @return All parameter object values contained within this fragment
*/
protected Object[] getParameterValues(ControlBeanContext context, Method method, Object[] args) {
Object value = getParameterValue(context, method, args);
if (value instanceof JdbcControl.ComplexSqlFragment) {
JdbcControl.SQLParameter[] params = ((JdbcControl.ComplexSqlFragment)value).getParameters();
Object[] values = new Object[params.length];
for (int i = 0; i < params.length; i++) {
values[i] = params[i].value;
}
return values;
}
return new Object[]{value};
}
//
// /////////////////////////////////////////////// PRIVATE METHODS /////////////////////////////////////////////
//
/**
* Get the value from the method param.
* @param method
* @param args
* @return Value of reflected method param.
*/
private Object getParameterValue(ControlBeanContext context, Method method, Object[] args) {
Object value;
try {
value = context.getParameterValue(method, _nameQualifiers[0], args);
} catch (IllegalArgumentException iae) {
throw new ControlException("Invalid argument name in SQL statement: " + _nameQualifiers[0], iae);
}
for (int i = 1; i < _nameQualifiers.length; i++) {
// handle maps, properties, and fields...
value = extractValue(value, _nameQualifiers[i - 1], _nameQualifiers[i]);
}
return value;
}
/**
* Get the value from the referenced method parameter using java reflection
*
* @param aValue
* @param aName
* @param bName
* @return The value
*/
private Object extractValue(Object aValue, String aName, String bName) {
Class aClass = aValue.getClass();
Object value;
//
// a.isB() or a.getB()
//
String bNameCapped = Character.toUpperCase(bName.charAt(0)) + bName.substring(1);
Method getMethod = null;
Class retType;
//
// try a.isB() first, if found verify that a.isB() returns a boolean value,
// and that there is not also a a.getB() method - if there is except
//
try {
getMethod = aClass.getMethod("is" + bNameCapped, (Class[]) null);
retType = getMethod.getReturnType();
if (!(retType.equals(Boolean.class) ||
retType.equals(Boolean.TYPE))) {
// only boolean returns can be isB()
getMethod = null;
} else {
/**
* make sure ("get" + bNameCapped) does not exist as well
* see CR216159
*/
boolean getMethodFound = true;
try {
aClass.getMethod("get" + bNameCapped, (Class[])null);
} catch (NoSuchMethodException e) {
getMethodFound = false;
}
if (getMethodFound) {
throw new ControlException("Colliding field accsessors in user defined class '"
+ aClass.getName() + "' for field '" + bName
+ "'. Please use is<FieldName> for boolean fields and get<FieldName> name for other datatypes.");
}
}
} catch (NoSuchMethodException e) {
// ignore
}
//
// try a.getB() if a.isB() was not found.
//
if (getMethod == null) {
try {
getMethod = aClass.getMethod("get" + bNameCapped, (Class[])null);
} catch (NoSuchMethodException e) {
// ignore
}
}
if (getMethod != null) {
// OK- a.getB()
try {
value = getMethod.invoke(aValue, (Object[]) null);
} catch (IllegalAccessException e) {
throw new ControlException("Unable to access public method: " + e.toString());
} catch (java.lang.reflect.InvocationTargetException e) {
throw new ControlException("Exception thrown when executing : " + getMethod.getName() + "() to use as parameter");
}
return value;
}
//
// try a.b
//
try {
value = aClass.getField(bName).get(aValue);
return value;
} catch (NoSuchFieldException e) {
// ignore
} catch (IllegalAccessException e) {
// ignore
}
//
// try a.get(b)
//
if (aValue instanceof Map) {
try {
value = TypeMappingsFactory.getInstance().lookupType(aValue, new Object[]{bName});
return value;
} catch (Exception mapex) {
throw new ControlException("Exception thrown when executing Map.get() to resolve parameter" + mapex.toString());
}
}
// no other options...
throw new ControlException("Illegal argument in SQL statement: " + _parameterName
+ "; unable to find suitable method of retrieving property " + bName
+ " out of object " + aName + ".");
}
}
| |
/*
* Copyright 2000-2012 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.
*/
/*
* Class EvaluatorBuilderImpl
* @author Jeka
*/
package com.intellij.debugger.engine.evaluation.expression;
import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.JVMName;
import com.intellij.debugger.engine.JVMNameUtil;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.debugger.ui.DebuggerEditorImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class EvaluatorBuilderImpl implements EvaluatorBuilder {
private static final EvaluatorBuilderImpl ourInstance = new EvaluatorBuilderImpl();
private EvaluatorBuilderImpl() {
}
public static EvaluatorBuilder getInstance() {
return ourInstance;
}
public static ExpressionEvaluator build(final TextWithImports text, final PsiElement contextElement, final SourcePosition position) throws EvaluateException {
if (contextElement == null) {
throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS;
}
final Project project = contextElement.getProject();
CodeFragmentFactory factory = DebuggerEditorImpl.findAppropriateFactory(text, contextElement);
PsiCodeFragment codeFragment = new CodeFragmentFactoryContextWrapper(factory).createCodeFragment(text, contextElement, project);
if(codeFragment == null) {
throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", text.getText()));
}
codeFragment.forceResolveScope(GlobalSearchScope.allScope(project));
DebuggerUtils.checkSyntax(codeFragment);
EvaluatorBuilder evaluatorBuilder = factory.getEvaluatorBuilder();
return evaluatorBuilder.build(codeFragment, position);
}
public ExpressionEvaluator build(final PsiElement codeFragment, final SourcePosition position) throws EvaluateException {
return new Builder(position).buildElement(codeFragment);
}
private static class Builder extends JavaElementVisitor {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl");
private Evaluator myResult = null;
private PsiClass myContextPsiClass;
private CodeFragmentEvaluator myCurrentFragmentEvaluator;
private final Set<JavaCodeFragment> myVisitedFragments = new HashSet<JavaCodeFragment>();
@Nullable
private final SourcePosition myPosition;
private Builder(@Nullable SourcePosition position) {
myPosition = position;
}
@Override
public void visitCodeFragment(JavaCodeFragment codeFragment) {
myVisitedFragments.add(codeFragment);
ArrayList<Evaluator> evaluators = new ArrayList<Evaluator>();
CodeFragmentEvaluator oldFragmentEvaluator = myCurrentFragmentEvaluator;
myCurrentFragmentEvaluator = new CodeFragmentEvaluator(oldFragmentEvaluator);
for (PsiElement child = codeFragment.getFirstChild(); child != null; child = child.getNextSibling()) {
child.accept(this);
if(myResult != null) {
evaluators.add(myResult);
}
myResult = null;
}
myCurrentFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[evaluators.size()]));
myResult = myCurrentFragmentEvaluator;
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
@Override
public void visitErrorElement(PsiErrorElement element) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", element.getText()));
}
@Override
public void visitAssignmentExpression(PsiAssignmentExpression expression) {
final PsiExpression rExpression = expression.getRExpression();
if(rExpression == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText())); return;
}
rExpression.accept(this);
Evaluator rEvaluator = myResult;
if(expression.getOperationTokenType() != JavaTokenType.EQ) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.operation.not.supported", expression.getOperationSign().getText()));
}
final PsiExpression lExpression = expression.getLExpression();
final PsiType lType = lExpression.getType();
if(lType == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", lExpression.getText()));
}
if(!TypeConversionUtil.areTypesAssignmentCompatible(lType, rExpression) && rExpression.getType() != null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.incompatible.types", expression.getOperationSign().getText()));
}
lExpression.accept(this);
Evaluator lEvaluator = myResult;
rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(lType, rExpression.getType(), rEvaluator);
myResult = new AssignmentEvaluator(lEvaluator, rEvaluator);
}
// returns rEvaluator possibly wrapped with boxing/unboxing and casting evaluators
private static Evaluator handleAssignmentBoxingAndPrimitiveTypeConversions(PsiType lType, PsiType rType, Evaluator rEvaluator) {
final PsiType unboxedLType = PsiPrimitiveType.getUnboxedType(lType);
if (unboxedLType != null) {
if (rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(rType)) {
if (!rType.equals(unboxedLType)) {
rEvaluator = new TypeCastEvaluator(rEvaluator, unboxedLType.getCanonicalText(), true);
}
rEvaluator = new BoxingEvaluator(rEvaluator);
}
}
else {
// either primitive type or not unboxable type
if (lType instanceof PsiPrimitiveType) {
if (rType instanceof PsiClassType) {
rEvaluator = new UnBoxingEvaluator(rEvaluator);
}
final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType);
final PsiType _rType = unboxedRType != null? unboxedRType : rType;
if (_rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(_rType)) {
if (!lType.equals(_rType)) {
rEvaluator = new TypeCastEvaluator(rEvaluator, lType.getCanonicalText(), true);
}
}
}
}
return rEvaluator;
}
@Override
public void visitStatement(PsiStatement statement) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.statement.not.supported", statement.getText()));
}
@Override
public void visitBlockStatement(PsiBlockStatement statement) {
PsiStatement[] statements = statement.getCodeBlock().getStatements();
Evaluator [] evaluators = new Evaluator[statements.length];
for (int i = 0; i < statements.length; i++) {
PsiStatement psiStatement = statements[i];
psiStatement.accept(this);
evaluators[i] = new DisableGC(myResult);
myResult = null;
}
myResult = new BlockStatementEvaluator(evaluators);
}
@Override
public void visitWhileStatement(PsiWhileStatement statement) {
PsiStatement body = statement.getBody();
if(body == null) return;
body.accept(this);
Evaluator bodyEvaluator = myResult;
PsiExpression condition = statement.getCondition();
if(condition == null) return;
condition.accept(this);
String label = null;
if(statement.getParent() instanceof PsiLabeledStatement) {
label = ((PsiLabeledStatement)statement.getParent()).getLabelIdentifier().getText();
}
myResult = new WhileStatementEvaluator(myResult, bodyEvaluator, label);
}
@Override
public void visitForStatement(PsiForStatement statement) {
PsiStatement initializer = statement.getInitialization();
Evaluator initializerEvaluator = null;
if(initializer != null){
initializer.accept(this);
initializerEvaluator = myResult;
}
PsiExpression condition = statement.getCondition();
Evaluator conditionEvaluator = null;
if(condition != null) {
condition.accept(this);
conditionEvaluator = myResult;
}
PsiStatement update = statement.getUpdate();
Evaluator updateEvaluator = null;
if(update != null){
update.accept(this);
updateEvaluator = myResult;
}
PsiStatement body = statement.getBody();
if(body == null) return;
body.accept(this);
Evaluator bodyEvaluator = myResult;
String label = null;
if(statement.getParent() instanceof PsiLabeledStatement) {
label = ((PsiLabeledStatement)statement.getParent()).getLabelIdentifier().getText();
}
myResult = new ForStatementEvaluator(initializerEvaluator, conditionEvaluator, updateEvaluator, bodyEvaluator, label);
}
@Override
public void visitIfStatement(PsiIfStatement statement) {
PsiStatement thenBranch = statement.getThenBranch();
if(thenBranch == null) return;
thenBranch.accept(this);
Evaluator thenEvaluator = myResult;
PsiStatement elseBranch = statement.getElseBranch();
Evaluator elseEvaluator = null;
if(elseBranch != null){
elseBranch.accept(this);
elseEvaluator = myResult;
}
PsiExpression condition = statement.getCondition();
if(condition == null) return;
condition.accept(this);
myResult = new IfStatementEvaluator(myResult, thenEvaluator, elseEvaluator);
}
@Override
public void visitBreakStatement(PsiBreakStatement statement) {
PsiIdentifier labelIdentifier = statement.getLabelIdentifier();
myResult = BreakContinueStatementEvaluator.createBreakEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null);
}
@Override
public void visitContinueStatement(PsiContinueStatement statement) {
PsiIdentifier labelIdentifier = statement.getLabelIdentifier();
myResult = BreakContinueStatementEvaluator.createContinueEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null);
}
@Override
public void visitExpressionStatement(PsiExpressionStatement statement) {
statement.getExpression().accept(this);
}
@Override
public void visitExpression(PsiExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitExpression " + expression);
}
}
@Override
public void visitPolyadicExpression(PsiPolyadicExpression wideExpression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitPolyadicExpression " + wideExpression);
}
PsiExpression[] operands = wideExpression.getOperands();
operands[0].accept(this);
Evaluator result = myResult;
PsiType lType = operands[0].getType();
for (int i = 1; i < operands.length; i++) {
PsiExpression expression = operands[i];
if (expression == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", wideExpression.getText()));
return;
}
expression.accept(this);
Evaluator rResult = myResult;
IElementType opType = wideExpression.getOperationTokenType();
PsiType rType = expression.getType();
if (rType == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true);
if (typeForBinOp == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", wideExpression.getText()));
}
myResult = createBinaryEvaluator(result, lType, rResult, rType, opType, typeForBinOp);
lType = typeForBinOp;
result = myResult;
}
}
// constructs binary evaluator handling unboxing and numeric promotion issues
private static BinaryExpressionEvaluator createBinaryEvaluator(Evaluator lResult,
PsiType lType,
Evaluator rResult,
@NotNull PsiType rType,
@NotNull IElementType operation,
@NotNull PsiType expressionExpectedType) {
// handle unboxing if neccesary
if (isUnboxingInBinaryExpressionApplicable(lType, rType, operation)) {
if (rType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(rType.getCanonicalText())) {
rResult = new UnBoxingEvaluator(rResult);
}
if (lType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(lType.getCanonicalText())) {
lResult = new UnBoxingEvaluator(lResult);
}
}
if (isBinaryNumericPromotionApplicable(lType, rType, operation)) {
PsiType _lType = lType;
final PsiPrimitiveType unboxedLType = PsiPrimitiveType.getUnboxedType(lType);
if (unboxedLType != null) {
_lType = unboxedLType;
}
PsiType _rType = rType;
final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType);
if (unboxedRType != null) {
_rType = unboxedRType;
}
// handle numeric promotion
if (PsiType.DOUBLE.equals(_lType)) {
if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.DOUBLE)) {
rResult = new TypeCastEvaluator(rResult, PsiType.DOUBLE.getCanonicalText(), true);
}
}
else if (PsiType.DOUBLE.equals(_rType)) {
if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.DOUBLE)) {
lResult = new TypeCastEvaluator(lResult, PsiType.DOUBLE.getCanonicalText(), true);
}
}
else if (PsiType.FLOAT.equals(_lType)) {
if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.FLOAT)) {
rResult = new TypeCastEvaluator(rResult, PsiType.FLOAT.getCanonicalText(), true);
}
}
else if (PsiType.FLOAT.equals(_rType)) {
if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.FLOAT)) {
lResult = new TypeCastEvaluator(lResult, PsiType.FLOAT.getCanonicalText(), true);
}
}
else if (PsiType.LONG.equals(_lType)) {
if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.LONG)) {
rResult = new TypeCastEvaluator(rResult, PsiType.LONG.getCanonicalText(), true);
}
}
else if (PsiType.LONG.equals(_rType)) {
if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.LONG)) {
lResult = new TypeCastEvaluator(lResult, PsiType.LONG.getCanonicalText(), true);
}
}
else {
if (!PsiType.INT.equals(_lType) && TypeConversionUtil.areTypesConvertible(_lType, PsiType.INT)) {
lResult = new TypeCastEvaluator(lResult, PsiType.INT.getCanonicalText(), true);
}
if (!PsiType.INT.equals(_rType) && TypeConversionUtil.areTypesConvertible(_rType, PsiType.INT)) {
rResult = new TypeCastEvaluator(rResult, PsiType.INT.getCanonicalText(), true);
}
}
}
return new BinaryExpressionEvaluator(lResult, rResult, operation, expressionExpectedType.getCanonicalText());
}
private static boolean isBinaryNumericPromotionApplicable(PsiType lType, PsiType rType, IElementType opType) {
if (lType == null || rType == null) {
return false;
}
if (!TypeConversionUtil.isNumericType(lType) || !TypeConversionUtil.isNumericType(rType)) {
return false;
}
if (opType == JavaTokenType.EQEQ || opType == JavaTokenType.NE) {
if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) {
return false;
}
if (lType instanceof PsiClassType && rType instanceof PsiClassType) {
return false;
}
if (lType instanceof PsiClassType) {
return PsiPrimitiveType.getUnboxedType(lType) != null; // should be unboxable
}
if (rType instanceof PsiClassType) {
return PsiPrimitiveType.getUnboxedType(rType) != null; // should be unboxable
}
return true;
}
return opType == JavaTokenType.ASTERISK ||
opType == JavaTokenType.DIV ||
opType == JavaTokenType.PERC ||
opType == JavaTokenType.PLUS ||
opType == JavaTokenType.MINUS ||
opType == JavaTokenType.LT ||
opType == JavaTokenType.LE ||
opType == JavaTokenType.GT ||
opType == JavaTokenType.GE ||
opType == JavaTokenType.AND ||
opType == JavaTokenType.XOR ||
opType == JavaTokenType.OR;
}
private static boolean isUnboxingInBinaryExpressionApplicable(PsiType lType, PsiType rType, IElementType opCode) {
if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) {
return false;
}
// handle '==' and '!=' separately
if (opCode == JavaTokenType.EQEQ || opCode == JavaTokenType.NE) {
return lType instanceof PsiPrimitiveType && rType instanceof PsiClassType ||
lType instanceof PsiClassType && rType instanceof PsiPrimitiveType;
}
// all other operations at least one should be of class type
return lType instanceof PsiClassType || rType instanceof PsiClassType;
}
/**
* @param type
* @return promotion type to cast to or null if no casting needed
*/
@Nullable
private static PsiType calcUnaryNumericPromotionType(PsiPrimitiveType type) {
if (PsiType.BYTE.equals(type) || PsiType.SHORT.equals(type) || PsiType.CHAR.equals(type) || PsiType.INT.equals(type)) {
return PsiType.INT;
}
return null;
}
@Override
public void visitDeclarationStatement(PsiDeclarationStatement statement) {
List<Evaluator> evaluators = new ArrayList<Evaluator>();
PsiElement[] declaredElements = statement.getDeclaredElements();
for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiLocalVariable) {
if (myCurrentFragmentEvaluator != null) {
final PsiLocalVariable localVariable = (PsiLocalVariable)declaredElement;
final PsiType lType = localVariable.getType();
PsiElementFactory elementFactory = JavaPsiFacade.getInstance(localVariable.getProject()).getElementFactory();
try {
PsiExpression initialValue = elementFactory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(lType), null);
Object value = JavaConstantExpressionEvaluator.computeConstantExpression(initialValue, true);
myCurrentFragmentEvaluator.setInitialValue(localVariable.getName(), value);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
catch (EvaluateException e) {
throw new EvaluateRuntimeException(e);
}
PsiExpression initializer = localVariable.getInitializer();
if (initializer != null) {
try {
if (!TypeConversionUtil.areTypesAssignmentCompatible(lType, initializer)) {
throwEvaluateException(
DebuggerBundle.message("evaluation.error.incompatible.variable.initializer.type", localVariable.getName()));
}
final PsiType rType = initializer.getType();
initializer.accept(this);
Evaluator rEvaluator = myResult;
PsiExpression localVarReference = elementFactory.createExpressionFromText(localVariable.getName(), initializer);
localVarReference.accept(this);
Evaluator lEvaluator = myResult;
rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(localVarReference.getType(), rType, rEvaluator);
Evaluator assignment = new AssignmentEvaluator(lEvaluator, rEvaluator);
evaluators.add(assignment);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
else {
throw new EvaluateRuntimeException(new EvaluateException(
DebuggerBundle.message("evaluation.error.local.variable.declarations.not.supported"), null));
}
}
else {
throw new EvaluateRuntimeException(new EvaluateException(
DebuggerBundle.message("evaluation.error.unsupported.declaration", declaredElement.getText()), null));
}
}
if(!evaluators.isEmpty()) {
CodeFragmentEvaluator codeFragmentEvaluator = new CodeFragmentEvaluator(myCurrentFragmentEvaluator);
codeFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[evaluators.size()]));
myResult = codeFragmentEvaluator;
} else {
myResult = null;
}
}
@Override
public void visitConditionalExpression(PsiConditionalExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitConditionalExpression " + expression);
}
final PsiExpression thenExpression = expression.getThenExpression();
final PsiExpression elseExpression = expression.getElseExpression();
if (thenExpression == null || elseExpression == null){
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText())); return;
}
PsiExpression condition = expression.getCondition();
condition.accept(this);
if (myResult == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", condition.getText())); return;
}
Evaluator conditionEvaluator = myResult;
thenExpression.accept(this);
if (myResult == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", thenExpression.getText())); return;
}
Evaluator thenEvaluator = myResult;
elseExpression.accept(this);
if (myResult == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", elseExpression.getText())); return;
}
Evaluator elseEvaluator = myResult;
myResult = new ConditionalExpressionEvaluator(conditionEvaluator, thenEvaluator, elseEvaluator);
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitReferenceExpression " + expression);
}
PsiExpression qualifier = expression.getQualifierExpression();
JavaResolveResult resolveResult = expression.advancedResolve(true);
PsiElement element = resolveResult.getElement();
if (element instanceof PsiLocalVariable || element instanceof PsiParameter) {
final Value labeledValue = element.getUserData(CodeFragmentFactoryContextWrapper.LABEL_VARIABLE_VALUE_KEY);
if (labeledValue != null) {
myResult = new IdentityEvaluator(labeledValue);
return;
}
//synthetic variable
final PsiFile containingFile = element.getContainingFile();
if(containingFile instanceof PsiCodeFragment && myCurrentFragmentEvaluator != null && myVisitedFragments.contains(containingFile)) {
// psiVariable may live in PsiCodeFragment not only in debugger editors, for example Fabrique has such variables.
// So treat it as synthetic var only when this code fragment is located in DebuggerEditor,
// that's why we need to check that containing code fragment is the one we visited
myResult = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, ((PsiVariable)element).getName());
return;
}
// local variable
final PsiVariable psiVar = (PsiVariable)element;
final String localName = psiVar.getName();
PsiClass variableClass = getContainingClass(psiVar);
if (getContextPsiClass() == null || getContextPsiClass().equals(variableClass)) {
final LocalVariableEvaluator localVarEvaluator = new LocalVariableEvaluator(localName, ContextUtil.isJspImplicit(element));
if (psiVar instanceof PsiParameter) {
final PsiParameter param = (PsiParameter)psiVar;
final PsiParameterList paramList = PsiTreeUtil.getParentOfType(param, PsiParameterList.class, true);
if (paramList != null) {
localVarEvaluator.setParameterIndex(paramList.getParameterIndex(param));
}
}
myResult = localVarEvaluator;
return;
}
// the expression references final var outside the context's class (in some of the outer classes)
int iterationCount = 0;
PsiClass aClass = getOuterClass(getContextPsiClass());
while (aClass != null && !aClass.equals(variableClass)) {
iterationCount++;
aClass = getOuterClass(aClass);
}
if (aClass != null) {
PsiExpression initializer = psiVar.getInitializer();
if(initializer != null) {
Object value = JavaPsiFacade.getInstance(psiVar.getProject()).getConstantEvaluationHelper().computeConstantExpression(initializer);
if(value != null) {
PsiType type = resolveResult.getSubstitutor().substitute(psiVar.getType());
myResult = new LiteralEvaluator(value, type.getCanonicalText());
return;
}
}
Evaluator objectEvaluator = new ThisEvaluator(iterationCount);
//noinspection HardCodedStringLiteral
final PsiClass classAt = myPosition != null? JVMNameUtil.getClassAt(myPosition) : null;
FieldEvaluator.TargetClassFilter filter = FieldEvaluator.createClassFilter(classAt != null? classAt : getContextPsiClass());
myResult = new FieldEvaluator(objectEvaluator, filter, "val$" + localName);
return;
}
throwEvaluateException(DebuggerBundle.message("evaluation.error.local.variable.missing.from.class.closure", localName));
}
else if (element instanceof PsiField) {
final PsiField psiField = (PsiField)element;
final PsiClass fieldClass = psiField.getContainingClass();
if(fieldClass == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.resolve.field.class", psiField.getName())); return;
}
Evaluator objectEvaluator;
if (psiField.hasModifierProperty(PsiModifier.STATIC)) {
objectEvaluator = new TypeEvaluator(JVMNameUtil.getContextClassJVMQualifiedName(SourcePosition.createFromElement(psiField)));
}
else if(qualifier != null) {
qualifier.accept(this);
objectEvaluator = myResult;
}
else if (fieldClass.equals(getContextPsiClass()) || getContextPsiClass().isInheritor(fieldClass, true)) {
objectEvaluator = new ThisEvaluator();
}
else { // myContextPsiClass != fieldClass && myContextPsiClass is not a subclass of fieldClass
int iterationCount = 0;
PsiClass aClass = getContextPsiClass();
while (aClass != null && !(aClass.equals(fieldClass) || aClass.isInheritor(fieldClass, true))) {
iterationCount++;
aClass = getOuterClass(aClass);
}
if (aClass == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.sources.for.field.class", psiField.getName()));
}
objectEvaluator = new ThisEvaluator(iterationCount);
}
myResult = new FieldEvaluator(objectEvaluator, FieldEvaluator.createClassFilter(fieldClass), psiField.getName());
}
else {
//let's guess what this could be
PsiElement nameElement = expression.getReferenceNameElement(); // get "b" part
String name;
if (nameElement instanceof PsiIdentifier) {
name = nameElement.getText();
}
else {
//noinspection HardCodedStringLiteral
final String elementDisplayString = nameElement != null ? nameElement.getText() : "(null)";
throwEvaluateException(DebuggerBundle.message("evaluation.error.identifier.expected", elementDisplayString));
return;
}
if(qualifier != null) {
final PsiElement qualifierTarget = qualifier instanceof PsiReferenceExpression
? ((PsiReferenceExpression)qualifier).resolve() : null;
if (qualifierTarget instanceof PsiClass) {
// this is a call to a 'static' field
PsiClass psiClass = (PsiClass)qualifierTarget;
final JVMName typeName = JVMNameUtil.getJVMQualifiedName(psiClass);
myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.createClassFilter(psiClass), name);
}
else {
PsiType type = qualifier.getType();
if(type == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.qualifier.type.unknown", qualifier.getText()));
}
qualifier.accept(this);
if (myResult == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.evaluate.qualifier", qualifier.getText()));
}
myResult = new FieldEvaluator(myResult, FieldEvaluator.createClassFilter(type), name);
}
}
else {
myResult = new LocalVariableEvaluator(name, false);
}
}
}
private static void throwEvaluateException(String message) throws EvaluateRuntimeException {
//noinspection ThrowableResultOfMethodCallIgnored
throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(message));
}
@Override
public void visitSuperExpression(PsiSuperExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitSuperExpression " + expression);
}
final int iterationCount = calcIterationCount(expression.getQualifier());
myResult = new SuperEvaluator(iterationCount);
}
@Override
public void visitThisExpression(PsiThisExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitThisExpression " + expression);
}
final int iterationCount = calcIterationCount(expression.getQualifier());
myResult = new ThisEvaluator(iterationCount);
}
private int calcIterationCount(final PsiJavaCodeReferenceElement qualifier) {
int iterationCount = 0;
if (qualifier != null) {
PsiElement targetClass = qualifier.resolve();
if (targetClass == null || getContextPsiClass() == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", qualifier.getText()));
}
try {
PsiClass aClass = getContextPsiClass();
while (aClass != null && !aClass.equals(targetClass)) {
iterationCount++;
aClass = getOuterClass(aClass);
}
}
catch (Exception e) {
//noinspection ThrowableResultOfMethodCallIgnored
throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(e));
}
}
return iterationCount;
}
@Override
public void visitInstanceOfExpression(PsiInstanceOfExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitInstanceOfExpression " + expression);
}
PsiTypeElement checkType = expression.getCheckType();
if(checkType == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText()));
return;
}
PsiType type = checkType.getType();
expression.getOperand().accept(this);
// ClassObjectEvaluator typeEvaluator = new ClassObjectEvaluator(type.getCanonicalText());
Evaluator operandEvaluator = myResult;
myResult = new InstanceofEvaluator(operandEvaluator, new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)));
}
@Override
public void visitParenthesizedExpression(PsiParenthesizedExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitParenthesizedExpression " + expression);
}
PsiExpression expr = expression.getExpression();
if (expr != null){
expr.accept(this);
}
}
@Override
public void visitPostfixExpression(PsiPostfixExpression expression) {
if(expression.getType() == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
final PsiExpression operandExpression = expression.getOperand();
operandExpression.accept(this);
final Evaluator operandEvaluator = myResult;
final IElementType operation = expression.getOperationTokenType();
final PsiType operandType = operandExpression.getType();
@Nullable final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType);
Evaluator incrementImpl = createBinaryEvaluator(
operandEvaluator, operandType,
new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT,
operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS,
unboxedOperandType!= null? unboxedOperandType : operandType
);
if (unboxedOperandType != null) {
incrementImpl = new BoxingEvaluator(incrementImpl);
}
myResult = new PostfixOperationEvaluator(operandEvaluator, incrementImpl);
}
@Override
public void visitPrefixExpression(final PsiPrefixExpression expression) {
final PsiType expressionType = expression.getType();
if(expressionType == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
final PsiExpression operandExpression = expression.getOperand();
if (operandExpression == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.operand", expression.getText()));
}
operandExpression.accept(this);
Evaluator operandEvaluator = myResult;
// handle unboxing issues
final PsiType operandType = operandExpression.getType();
@Nullable
final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType);
final IElementType operation = expression.getOperationTokenType();
if(operation == JavaTokenType.PLUSPLUS || operation == JavaTokenType.MINUSMINUS) {
try {
final BinaryExpressionEvaluator rightEval = createBinaryEvaluator(
operandEvaluator, operandType,
new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT,
operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS,
unboxedOperandType!= null? unboxedOperandType : operandType
);
myResult = new AssignmentEvaluator(operandEvaluator, unboxedOperandType != null? new BoxingEvaluator(rightEval) : rightEval);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
else {
if (JavaTokenType.PLUS.equals(operation) || JavaTokenType.MINUS.equals(operation)|| JavaTokenType.TILDE.equals(operation)) {
operandEvaluator = handleUnaryNumericPromotion(operandType, operandEvaluator);
}
else {
if (unboxedOperandType != null) {
operandEvaluator = new UnBoxingEvaluator(operandEvaluator);
}
}
myResult = new UnaryExpressionEvaluator(operation, expressionType.getCanonicalText(), operandEvaluator, expression.getOperationSign().getText());
}
}
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitMethodCallExpression " + expression);
}
final PsiExpressionList argumentList = expression.getArgumentList();
final PsiExpression[] argExpressions = argumentList.getExpressions();
final Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length];
// evaluate arguments
for (int idx = 0; idx < argExpressions.length; idx++) {
final PsiExpression psiExpression = argExpressions[idx];
psiExpression.accept(this);
if (myResult == null) {
// cannot build evaluator
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", psiExpression.getText()));
}
argumentEvaluators[idx] = new DisableGC(myResult);
}
PsiReferenceExpression methodExpr = expression.getMethodExpression();
final JavaResolveResult resolveResult = methodExpr.advancedResolve(false);
final PsiMethod psiMethod = (PsiMethod)resolveResult.getElement();
PsiExpression qualifier = methodExpr.getQualifierExpression();
Evaluator objectEvaluator;
JVMName contextClass = null;
if(psiMethod != null) {
PsiClass methodPsiClass = psiMethod.getContainingClass();
contextClass = JVMNameUtil.getJVMQualifiedName(methodPsiClass);
if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
objectEvaluator = new TypeEvaluator(contextClass);
}
else if (qualifier != null ) {
qualifier.accept(this);
objectEvaluator = myResult;
}
else {
int iterationCount = 0;
final PsiElement currentFileResolveScope = resolveResult.getCurrentFileResolveScope();
if (currentFileResolveScope instanceof PsiClass) {
PsiClass aClass = getContextPsiClass();
while(aClass != null && !aClass.equals(currentFileResolveScope)) {
aClass = getOuterClass(aClass);
iterationCount++;
}
}
objectEvaluator = new ThisEvaluator(iterationCount);
}
}
else {
//trying to guess
if (qualifier != null) {
PsiType type = qualifier.getType();
if (type != null) {
contextClass = JVMNameUtil.getJVMQualifiedName(type);
}
if (qualifier instanceof PsiReferenceExpression && ((PsiReferenceExpression)qualifier).resolve() instanceof PsiClass) {
// this is a call to a 'static' method
if (contextClass == null && type == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.qualifier.type.unknown", qualifier.getText()));
}
assert contextClass != null;
objectEvaluator = new TypeEvaluator(contextClass);
}
else {
qualifier.accept(this);
objectEvaluator = myResult;
}
}
else {
objectEvaluator = new ThisEvaluator();
contextClass = JVMNameUtil.getContextClassJVMQualifiedName(myPosition);
if(contextClass == null && myContextPsiClass != null) {
contextClass = JVMNameUtil.getJVMQualifiedName(myContextPsiClass);
}
//else {
// throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(
// DebuggerBundle.message("evaluation.error.method.not.found", methodExpr.getReferenceName()))
// );
//}
}
}
if (objectEvaluator == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText()));
}
if (psiMethod != null && !psiMethod.isConstructor()) {
if (psiMethod.getReturnType() == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.method.return.type", psiMethod.getText()));
}
}
if (psiMethod != null) {
processBoxingConversions(psiMethod.getParameterList().getParameters(), argExpressions, resolveResult.getSubstitutor(), argumentEvaluators);
}
myResult = new MethodEvaluator(objectEvaluator, contextClass, methodExpr.getReferenceName(), psiMethod != null ? JVMNameUtil.getJVMSignature(psiMethod) : null, argumentEvaluators);
}
@Override
public void visitLiteralExpression(PsiLiteralExpression expression) {
final HighlightInfo parsingError = HighlightUtil.checkLiteralExpressionParsingError(expression, PsiUtil.getLanguageLevel(expression),
expression.getContainingFile());
if (parsingError != null) {
throwEvaluateException(parsingError.getDescription());
return;
}
final PsiType type = expression.getType();
if (type == null) {
throwEvaluateException(expression + ": null type");
return;
}
myResult = new LiteralEvaluator(expression.getValue(), type.getCanonicalText());
}
@Override
public void visitArrayAccessExpression(PsiArrayAccessExpression expression) {
final PsiExpression indexExpression = expression.getIndexExpression();
if(indexExpression == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText())); return;
}
indexExpression.accept(this);
final Evaluator indexEvaluator = handleUnaryNumericPromotion(indexExpression.getType(), myResult);
expression.getArrayExpression().accept(this);
Evaluator arrayEvaluator = myResult;
myResult = new ArrayAccessEvaluator(arrayEvaluator, indexEvaluator);
}
/**
* Handles unboxing and numeric promotion issues for
* - array diumention expressions
* - array index expression
* - unary +, -, and ~ operations
* @param operandExpressionType
* @param operandEvaluator @return operandEvaluator possibly 'wrapped' with neccesary unboxing and type-casting evaluators to make returning value
* sutable for mentioned contexts
*/
private static Evaluator handleUnaryNumericPromotion(final PsiType operandExpressionType, Evaluator operandEvaluator) {
final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(operandExpressionType);
if (unboxedType != null && !PsiType.BOOLEAN.equals(unboxedType)) {
operandEvaluator = new UnBoxingEvaluator(operandEvaluator);
}
// handle numeric promotion
final PsiType _unboxedIndexType = unboxedType != null? unboxedType : operandExpressionType;
if (_unboxedIndexType instanceof PsiPrimitiveType) {
final PsiType promotionType = calcUnaryNumericPromotionType((PsiPrimitiveType)_unboxedIndexType);
if (promotionType != null) {
operandEvaluator = new TypeCastEvaluator(operandEvaluator, promotionType.getCanonicalText(), true);
}
}
return operandEvaluator;
}
@SuppressWarnings({"ConstantConditions"})
@Override
public void visitTypeCastExpression(PsiTypeCastExpression expression) {
final PsiExpression operandExpr = expression.getOperand();
operandExpr.accept(this);
Evaluator operandEvaluator = myResult;
final PsiType castType = expression.getCastType().getType();
final PsiType operandType = operandExpr.getType();
if (castType != null && operandType != null && !TypeConversionUtil.areTypesConvertible(operandType, castType)) {
throw new EvaluateRuntimeException(
new EvaluateException(JavaErrorMessages.message("inconvertible.type.cast", JavaHighlightUtil.formatType(operandType), JavaHighlightUtil
.formatType(castType)))
);
}
final boolean shouldPerformBoxingConversion = castType != null && operandType != null && TypeConversionUtil.boxingConversionApplicable(castType, operandType);
final boolean castingToPrimitive = castType instanceof PsiPrimitiveType;
if (shouldPerformBoxingConversion && castingToPrimitive) {
operandEvaluator = new UnBoxingEvaluator(operandEvaluator);
}
final boolean performCastToWrapperClass = shouldPerformBoxingConversion && !castingToPrimitive;
String castTypeName = castType.getCanonicalText();
if (performCastToWrapperClass) {
final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(castType);
if (unboxedType != null) {
castTypeName = unboxedType.getCanonicalText();
}
}
myResult = new TypeCastEvaluator(operandEvaluator, castTypeName, castingToPrimitive);
if (performCastToWrapperClass) {
myResult = new BoxingEvaluator(myResult);
}
}
@Override
public void visitClassObjectAccessExpression(PsiClassObjectAccessExpression expression) {
PsiType type = expression.getOperand().getType();
if (type instanceof PsiPrimitiveType) {
final JVMName typeName = JVMNameUtil.getJVMRawText(((PsiPrimitiveType)type).getBoxedTypeName());
myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.TargetClassFilter.ALL, "TYPE");
}
else {
myResult = new ClassObjectEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)));
}
}
@Override
public void visitNewExpression(final PsiNewExpression expression) {
PsiType expressionPsiType = expression.getType();
if (expressionPsiType instanceof PsiArrayType) {
Evaluator dimensionEvaluator = null;
PsiExpression[] dimensions = expression.getArrayDimensions();
if (dimensions.length == 1){
PsiExpression dimensionExpression = dimensions[0];
dimensionExpression.accept(this);
if (myResult != null) {
dimensionEvaluator = handleUnaryNumericPromotion(dimensionExpression.getType(), myResult);
}
else {
throwEvaluateException(
DebuggerBundle.message("evaluation.error.invalid.array.dimension.expression", dimensionExpression.getText()));
}
}
else if (dimensions.length > 1){
throwEvaluateException(DebuggerBundle.message("evaluation.error.multi.dimensional.arrays.creation.not.supported"));
}
Evaluator initializerEvaluator = null;
PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer();
if (arrayInitializer != null) {
if (dimensionEvaluator != null) { // initializer already exists
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText()));
}
arrayInitializer.accept(this);
if (myResult != null) {
initializerEvaluator = handleUnaryNumericPromotion(arrayInitializer.getType(), myResult);
}
else {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", arrayInitializer.getText()));
}
/*
PsiExpression[] initializers = arrayInitializer.getInitializers();
initializerEvaluators = new Evaluator[initializers.length];
for (int idx = 0; idx < initializers.length; idx++) {
PsiExpression initializer = initializers[idx];
initializer.accept(this);
if (myResult instanceof Evaluator) {
initializerEvaluators[idx] = myResult;
}
else {
throw new EvaluateException("Invalid expression for array initializer: " + initializer.getText(), true);
}
}
*/
}
if (dimensionEvaluator == null && initializerEvaluator == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText()));
}
myResult = new NewArrayInstanceEvaluator(
new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)),
dimensionEvaluator,
initializerEvaluator
);
}
else if (expressionPsiType instanceof PsiClassType){ // must be a class ref
PsiClass aClass = ((PsiClassType)expressionPsiType).resolve();
if(aClass instanceof PsiAnonymousClass) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.anonymous.class.evaluation.not.supported"));
}
PsiExpressionList argumentList = expression.getArgumentList();
if (argumentList == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText())); return;
}
final PsiExpression[] argExpressions = argumentList.getExpressions();
final JavaResolveResult constructorResolveResult = expression.resolveMethodGenerics();
final PsiMethod constructor = (PsiMethod)constructorResolveResult.getElement();
if (constructor == null && argExpressions.length > 0) {
throw new EvaluateRuntimeException(new EvaluateException(
DebuggerBundle.message("evaluation.error.cannot.resolve.constructor", expression.getText()), null));
}
Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length];
// evaluate arguments
for (int idx = 0; idx < argExpressions.length; idx++) {
PsiExpression argExpression = argExpressions[idx];
argExpression.accept(this);
if (myResult != null) {
argumentEvaluators[idx] = new DisableGC(myResult);
}
else {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", argExpression.getText()));
}
}
if (constructor != null) {
processBoxingConversions(constructor.getParameterList().getParameters(), argExpressions, constructorResolveResult.getSubstitutor(), argumentEvaluators);
}
//noinspection HardCodedStringLiteral
JVMName signature = constructor != null ? JVMNameUtil.getJVMSignature(constructor) : JVMNameUtil.getJVMRawText("()V");
myResult = new NewClassInstanceEvaluator(
new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)),
signature,
argumentEvaluators
);
}
else {
if (expressionPsiType != null) {
throwEvaluateException("Unsupported expression type: " + expressionPsiType.getPresentableText());
}
else {
throwEvaluateException("Unknown type for expression: " + expression.getText());
}
}
}
@Override
public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) {
PsiExpression[] initializers = expression.getInitializers();
Evaluator[] evaluators = new Evaluator[initializers.length];
final PsiType type = expression.getType();
boolean primitive = type instanceof PsiArrayType && ((PsiArrayType)type).getComponentType() instanceof PsiPrimitiveType;
for (int idx = 0; idx < initializers.length; idx++) {
PsiExpression initializer = initializers[idx];
initializer.accept(this);
if (myResult != null) {
final Evaluator coerced =
primitive ? handleUnaryNumericPromotion(initializer.getType(), myResult) : new BoxingEvaluator(myResult);
evaluators[idx] = new DisableGC(coerced);
}
else {
throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", initializer.getText()));
}
}
myResult = new ArrayInitializerEvaluator(evaluators);
}
@Nullable
private static PsiClass getOuterClass(PsiClass aClass) {
return aClass == null ? null : PsiTreeUtil.getContextOfType(aClass, PsiClass.class, true);
}
private PsiClass getContainingClass(PsiVariable variable) {
PsiElement element = PsiTreeUtil.getParentOfType(variable.getParent(), PsiClass.class, false);
return element == null ? getContextPsiClass() : (PsiClass)element;
}
public PsiClass getContextPsiClass() {
return myContextPsiClass;
}
protected ExpressionEvaluator buildElement(final PsiElement element) throws EvaluateException {
LOG.assertTrue(element.isValid());
myContextPsiClass = PsiTreeUtil.getContextOfType(element, PsiClass.class, false);
try {
element.accept(this);
}
catch (EvaluateRuntimeException e) {
throw e.getCause();
}
if (myResult == null) {
throw EvaluateExceptionUtil
.createEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", element.toString()));
}
return new ExpressionEvaluatorImpl(myResult);
}
}
private static void processBoxingConversions(final PsiParameter[] declaredParams,
final PsiExpression[] actualArgumentExpressions,
final PsiSubstitutor methodResolveSubstitutor,
final Evaluator[] argumentEvaluators) {
if (declaredParams.length > 0) {
final int paramCount = Math.max(declaredParams.length, actualArgumentExpressions.length);
PsiType varargType = null;
for (int idx = 0; idx < paramCount; idx++) {
if (idx >= actualArgumentExpressions.length) {
break; // actual arguments count is less than number of declared params
}
PsiType declaredParamType;
if (idx < declaredParams.length) {
declaredParamType = methodResolveSubstitutor.substitute(declaredParams[idx].getType());
if (declaredParamType instanceof PsiEllipsisType) {
declaredParamType = varargType = ((PsiEllipsisType)declaredParamType).getComponentType();
}
}
else if (varargType != null) {
declaredParamType = varargType;
}
else {
break;
}
final PsiType actualArgType = actualArgumentExpressions[idx].getType();
if (TypeConversionUtil.boxingConversionApplicable(declaredParamType, actualArgType)) {
final Evaluator argEval = argumentEvaluators[idx];
argumentEvaluators[idx] = declaredParamType instanceof PsiPrimitiveType ? new UnBoxingEvaluator(argEval) : new BoxingEvaluator(argEval);
}
}
}
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stallone.doubles.fastutils;
/* 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) */
/*
* Copyright (C) 2002-2011 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.
*/
import java.util.List;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collection;
import java.util.NoSuchElementException;
/** An abstract class providing basic methods for lists implementing a type-specific list interface.
*
* <P>As an additional bonus, this class implements on top of the list operations a type-specific stack.
*/
public abstract class AbstractDoubleList extends AbstractDoubleCollection implements DoubleList , DoubleStack {
protected AbstractDoubleList() {}
/** Ensures that the given index is nonnegative and not greater than the list size.
*
* @param index an index.
* @throws IndexOutOfBoundsException if the given index is negative or greater than the list size.
*/
protected void ensureIndex( final int index ) {
if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" );
if ( index > size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than list size (" + ( size() ) + ")" );
}
/** Ensures that the given index is nonnegative and smaller than the list size.
*
* @param index an index.
* @throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size.
*/
protected void ensureRestrictedIndex( final int index ) {
if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" );
if ( index >= size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than or equal to list size (" + ( size() ) + ")" );
}
public void add( final int index, final double k ) {
throw new UnsupportedOperationException();
}
public boolean add( final double k ) {
add( size(), k );
return true;
}
public double removeDouble( int i ) {
throw new UnsupportedOperationException();
}
public double setAndReturnOld( final int index, final double k ) {
throw new UnsupportedOperationException();
}
public boolean addAll( int index, final Collection<? extends Double> c ) {
ensureIndex( index );
int n = c.size();
if ( n == 0 ) return false;
Iterator<? extends Double> i = c.iterator();
while( n-- != 0 ) add( index++, i.next() );
return true;
}
/** Delegates to a more generic method. */
public boolean addAll( final Collection<? extends Double> c ) {
return addAll( size(), c );
}
/** Delegates to the new covariantly stronger generic method. */
@Deprecated
public DoubleListIterator doubleListIterator() {
return listIterator();
}
/** Delegates to the new covariantly stronger generic method. */
@Deprecated
public DoubleListIterator doubleListIterator( final int index ) {
return listIterator( index );
}
public DoubleListIterator iterator() {
return listIterator();
}
public DoubleListIterator listIterator() {
return listIterator( 0 );
}
public DoubleListIterator listIterator( final int index ) {
return new AbstractDoubleListIterator () {
int pos = index, last = -1;
public boolean hasNext() { return pos < AbstractDoubleList.this.size(); }
public boolean hasPrevious() { return pos > 0; }
public double nextDouble() { if ( ! hasNext() ) throw new NoSuchElementException(); return AbstractDoubleList.this.getDouble( last = pos++ ); }
public double previousDouble() { if ( ! hasPrevious() ) throw new NoSuchElementException(); return AbstractDoubleList.this.getDouble( last = --pos ); }
public int nextIndex() { return pos; }
public int previousIndex() { return pos - 1; }
public void add( double k ) {
if ( last == -1 ) throw new IllegalStateException();
AbstractDoubleList.this.add( pos++, k );
last = -1;
}
public void set( double k ) {
if ( last == -1 ) throw new IllegalStateException();
AbstractDoubleList.this.setAndReturnOld( last, k );
}
public void remove() {
if ( last == -1 ) throw new IllegalStateException();
AbstractDoubleList.this.removeDouble( last );
/* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */
if ( last < pos ) pos--;
last = -1;
}
};
}
public boolean contains( final double k ) {
return indexOf( k ) >= 0;
}
public int indexOf( final double k ) {
final DoubleListIterator i = listIterator();
double e;
while( i.hasNext() ) {
e = i.nextDouble();
if ( ( (k) == (e) ) ) return i.previousIndex();
}
return -1;
}
public int lastIndexOf( final double k ) {
DoubleListIterator i = listIterator( size() );
double e;
while( i.hasPrevious() ) {
e = i.previousDouble();
if ( ( (k) == (e) ) ) return i.nextIndex();
}
return -1;
}
public void size( final int size ) {
int i = size();
if ( size > i ) while( i++ < size ) add( (0) );
else while( i-- != size ) remove( i );
}
public DoubleList subList( final int from, final int to ) {
ensureIndex( from );
ensureIndex( to );
if ( from > to ) throw new IndexOutOfBoundsException( "Start index (" + from + ") is greater than end index (" + to + ")" );
return new DoubleSubList ( this, from, to );
}
/** Delegates to the new covariantly stronger generic method. */
@Deprecated
public DoubleList doubleSubList( final int from, final int to ) {
return subList( from, to );
}
/** Removes elements of this type-specific list one-by-one.
*
* <P>This is a trivial iterator-based implementation. It is expected that
* implementations will override this method with a more optimized version.
*
*
* @param from the start index (inclusive).
* @param to the end index (exclusive).
*/
public void removeElements( final int from, final int to ) {
ensureIndex( to );
DoubleListIterator i = listIterator( from );
int n = to - from;
if ( n < 0 ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" );
while( n-- != 0 ) {
i.nextDouble();
i.remove();
}
}
/** Adds elements to this type-specific list one-by-one.
*
* <P>This is a trivial iterator-based implementation. It is expected that
* implementations will override this method with a more optimized version.
*
* @param index the index at which to add elements.
* @param a the array containing the elements.
* @param offset the offset of the first element to add.
* @param length the number of elements to add.
*/
public void addElements( int index, final double a[], int offset, int length ) {
ensureIndex( index );
if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" );
if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" );
while( length-- != 0 ) add( index++, a[ offset++ ] );
}
public void addElements( final int index, final double a[] ) {
addElements( index, a, 0, a.length );
}
/** Copies element of this type-specific list into the given array one-by-one.
*
* <P>This is a trivial iterator-based implementation. It is expected that
* implementations will override this method with a more optimized version.
*
* @param from the start index (inclusive).
* @param a the destination array.
* @param offset the offset into the destination array where to store the first element copied.
* @param length the number of elements to be copied.
*/
public void getElements( final int from, final double a[], int offset, int length ) {
DoubleListIterator i = listIterator( from );
if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" );
if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" );
if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + ( from + length ) + ") is greater than list size (" + size() + ")" );
while( length-- != 0 ) a[ offset++ ] = i.nextDouble();
}
private boolean valEquals( final Object a, final Object b ) {
return a == null ? b == null : a.equals( b );
}
public boolean equals( final Object o ) {
if ( o == this ) return true;
if ( ! ( o instanceof List ) ) return false;
final List<?> l = (List<?>)o;
int s = size();
if ( s != l.size() ) return false;
final ListIterator<?> i1 = listIterator(), i2 = l.listIterator();
while( s-- != 0 ) if ( ! valEquals( i1.next(), i2.next() ) ) return false;
return true;
}
/** Compares this list to another object. If the
* argument is a {@link java.util.List}, this method performs a lexicographical comparison; otherwise,
* it throws a <code>ClassCastException</code>.
*
* @param l a list.
* @return if the argument is a {@link java.util.List}, a negative integer,
* zero, or a positive integer as this list is lexicographically less than, equal
* to, or greater than the argument.
* @throws ClassCastException if the argument is not a list.
*/
@SuppressWarnings("unchecked")
public int compareTo( final List<? extends Double> l ) {
if ( l == this ) return 0;
if ( l instanceof DoubleList ) {
final DoubleListIterator i1 = listIterator(), i2 = ((DoubleList )l).listIterator();
int r;
double e1, e2;
while( i1.hasNext() && i2.hasNext() ) {
e1 = i1.nextDouble();
e2 = i2.nextDouble();
if ( ( r = ( (e1) < (e2) ? -1 : ( (e1) == (e2) ? 0 : 1 ) ) ) != 0 ) return r;
}
return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 );
}
ListIterator<? extends Double> i1 = listIterator(), i2 = l.listIterator();
int r;
while( i1.hasNext() && i2.hasNext() ) {
if ( ( r = ((Comparable<? super Double>)i1.next()).compareTo( i2.next() ) ) != 0 ) return r;
}
return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 );
}
/** Returns the hash code for this list, which is identical to {@link java.util.List#hashCode()}.
*
* @return the hash code for this list.
*/
public int hashCode() {
DoubleIterator i = iterator();
int h = 1, s = size();
while ( s-- != 0 ) {
double k = i.nextDouble();
h = 31 * h + HashCommon.double2int(k);
}
return h;
}
public void push( double o ) {
add( o );
}
public double popDouble() {
if ( isEmpty() ) throw new NoSuchElementException();
return removeDouble( size() - 1 );
}
public double topDouble() {
if ( isEmpty() ) throw new NoSuchElementException();
return getDouble( size() - 1 );
}
public double peekDouble( int i ) {
return getDouble( size() - 1 - i );
}
public boolean rem( double k ) {
int index = indexOf( k );
if ( index == -1 ) return false;
removeDouble( index );
return true;
}
/** Delegates to <code>rem()</code>. */
public boolean remove( final Object o ) {
return rem( ((((Double)(o)).doubleValue())) );
}
/** Delegates to a more generic method. */
public boolean addAll( final int index, final DoubleCollection c ) {
return addAll( index, (Collection<? extends Double>)c );
}
/** Delegates to a more generic method. */
public boolean addAll( final int index, final DoubleList l ) {
return addAll( index, (DoubleCollection)l );
}
public boolean addAll( final DoubleCollection c ) {
return addAll( size(), c );
}
public boolean addAll( final DoubleList l ) {
return addAll( size(), l );
}
/** Delegates to the corresponding type-specific method. */
public void add( final int index, final Double ok ) {
add( index, ok.doubleValue() );
}
/** Delegates to the corresponding type-specific method. */
public Double set( final int index, final Double ok ) {
return (Double.valueOf(setAndReturnOld( index, ok.doubleValue() )));
}
/** Delegates to the corresponding type-specific method. */
public Double get( final int index ) {
return (Double.valueOf(getDouble( index )));
}
/** Delegates to the corresponding type-specific method. */
public int indexOf( final Object ok) {
return indexOf( ((((Double)(ok)).doubleValue())) );
}
/** Delegates to the corresponding type-specific method. */
public int lastIndexOf( final Object ok ) {
return lastIndexOf( ((((Double)(ok)).doubleValue())) );
}
/** Delegates to the corresponding type-specific method. */
public Double remove( final int index ) {
return (Double.valueOf(removeDouble( index )));
}
/** Delegates to the corresponding type-specific method. */
public void push( Double o ) {
push( o.doubleValue() );
}
/** Delegates to the corresponding type-specific method. */
public Double pop() {
return Double.valueOf( popDouble() );
}
/** Delegates to the corresponding type-specific method. */
public Double top() {
return Double.valueOf( topDouble() );
}
/** Delegates to the corresponding type-specific method. */
public Double peek( int i ) {
return Double.valueOf( peekDouble( i ) );
}
public String toString() {
final StringBuilder s = new StringBuilder();
final DoubleIterator i = iterator();
int n = size();
double k;
boolean first = true;
s.append("[");
while( n-- != 0 ) {
if (first) first = false;
else s.append(", ");
k = i.nextDouble();
s.append( String.valueOf( k ) );
}
s.append("]");
return s.toString();
}
public static class DoubleSubList extends AbstractDoubleList implements java.io.Serializable {
public static final long serialVersionUID = -7046029254386353129L;
/** The list this sublist restricts. */
protected final DoubleList l;
/** Initial (inclusive) index of this sublist. */
protected final int from;
/** Final (exclusive) index of this sublist. */
protected int to;
private static final boolean ASSERTS = false;
public DoubleSubList( final DoubleList l, final int from, final int to ) {
this.l = l;
this.from = from;
this.to = to;
}
private void assertRange() {
if ( ASSERTS ) {
assert from <= l.size();
assert to <= l.size();
assert to >= from;
}
}
public boolean add( final double k ) {
l.add( to, k );
to++;
if ( ASSERTS ) assertRange();
return true;
}
public void add( final int index, final double k ) {
ensureIndex( index );
l.add( from + index, k );
to++;
if ( ASSERTS ) assertRange();
}
public boolean addAll( final int index, final Collection<? extends Double> c ) {
ensureIndex( index );
to += c.size();
if ( ASSERTS ) {
boolean retVal = l.addAll( from + index, c );
assertRange();
return retVal;
}
return l.addAll( from + index, c );
}
public double getDouble( int index ) {
ensureRestrictedIndex( index );
return l.getDouble( from + index );
}
public double removeDouble( int index ) {
ensureRestrictedIndex( index );
to--;
return l.removeDouble( from + index );
}
public double setAndReturnOld( int index, double k ) {
ensureRestrictedIndex( index );
return l.setAndReturnOld( from + index, k );
}
public void clear() {
removeElements( 0, size() );
if ( ASSERTS ) assertRange();
}
public int size() {
return to - from;
}
public void getElements( final int from, final double[] a, final int offset, final int length ) {
ensureIndex( from );
if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + from + length + ") is greater than list size (" + size() + ")" );
l.getElements( this.from + from, a, offset, length );
}
public void removeElements( final int from, final int to ) {
ensureIndex( from );
ensureIndex( to );
l.removeElements( this.from + from, this.from + to );
this.to -= ( to - from );
if ( ASSERTS ) assertRange();
}
public void addElements( int index, final double a[], int offset, int length ) {
ensureIndex( index );
l.addElements( this.from + index, a, offset, length );
this.to += length;
if ( ASSERTS ) assertRange();
}
public DoubleListIterator listIterator( final int index ) {
ensureIndex( index );
return new AbstractDoubleListIterator () {
int pos = index, last = -1;
public boolean hasNext() { return pos < size(); }
public boolean hasPrevious() { return pos > 0; }
public double nextDouble() { if ( ! hasNext() ) throw new NoSuchElementException(); return l.getDouble( from + ( last = pos++ ) ); }
public double previousDouble() { if ( ! hasPrevious() ) throw new NoSuchElementException(); return l.getDouble( from + ( last = --pos ) ); }
public int nextIndex() { return pos; }
public int previousIndex() { return pos - 1; }
public void add( double k ) {
if ( last == -1 ) throw new IllegalStateException();
DoubleSubList.this.add( pos++, k );
last = -1;
if ( ASSERTS ) assertRange();
}
public void set( double k ) {
if ( last == -1 ) throw new IllegalStateException();
DoubleSubList.this.setAndReturnOld( last, k );
}
public void remove() {
if ( last == -1 ) throw new IllegalStateException();
DoubleSubList.this.removeDouble( last );
/* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */
if ( last < pos ) pos--;
last = -1;
if ( ASSERTS ) assertRange();
}
};
}
public DoubleList subList( final int from, final int to ) {
ensureIndex( from );
ensureIndex( to );
if ( from > to ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" );
return new DoubleSubList ( this, from, to );
}
public boolean rem( double k ) {
int index = indexOf( k );
if ( index == -1 ) return false;
to--;
l.removeDouble( from + index );
if ( ASSERTS ) assertRange();
return true;
}
public boolean remove( final Object o ) {
return rem( ((((Double)(o)).doubleValue())) );
}
public boolean addAll( final int index, final DoubleCollection c ) {
ensureIndex( index );
to += c.size();
if ( ASSERTS ) {
boolean retVal = l.addAll( from + index, c );
assertRange();
return retVal;
}
return l.addAll( from + index, c );
}
public boolean addAll( final int index, final DoubleList l ) {
ensureIndex( index );
to += l.size();
if ( ASSERTS ) {
boolean retVal = this.l.addAll( from + index, l );
assertRange();
return retVal;
}
return this.l.addAll( from + index, l );
}
}
}
| |
package com.cardshifter.gdx.screens;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.ui.List;
import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.SnapshotArray;
import com.cardshifter.api.config.DeckConfig;
import com.cardshifter.api.outgoing.CardInfoMessage;
import com.cardshifter.gdx.Callback;
import com.cardshifter.gdx.CardshifterGame;
import com.cardshifter.gdx.TargetStatus;
import com.cardshifter.gdx.TargetableCallback;
import com.cardshifter.gdx.ZoomCardCallback;
import com.cardshifter.gdx.ui.CardshifterClientContext;
import com.cardshifter.gdx.ui.EntityView;
import com.cardshifter.gdx.ui.cards.CardViewSmall;
import java.util.*;
/**
* Created by Simon on 2/10/2015.
*/
public class DeckBuilderScreen implements Screen, TargetableCallback, ZoomCardCallback {
private static final int ROWS_PER_PAGE = 3;
private static final int CARDS_PER_ROW = 4;
private static final int CARDS_PER_PAGE = CARDS_PER_ROW * ROWS_PER_PAGE;
private final Callback<DeckConfig> callback;
private final Table table;
private final CardshifterGame game;
private final java.util.List<CardInfoMessage> cards;
private final DeckConfig config;
private final int pageCount;
private final Table cardsTable;
private final CardshifterClientContext context;
private final Map<Integer, Label> countLabels = new HashMap<Integer, Label>();
private final VerticalGroup cardsInDeckList;
private final ScrollPane cardsInDeckScrollPane;
private final List<String> savedDecks;
private final Label nameLabel;
private final TextButton previousPageButton;
private final TextButton nextPageButton;
private int page;
private String deckName = "unnamed";
private FileHandle external;
private final Label totalLabel;
private final Screen lobbyScreen;
private final float screenWidth;
private final float screenHeight;
private boolean cardZoomedIn = false;
private float initialCardViewWidth = 0;
private float initialCardViewHeight = 0;
public DeckBuilderScreen(ClientScreen screen, CardshifterGame game, String modName, int gameId, final DeckConfig deckConfig, final Callback<DeckConfig> callback) {
this.config = deckConfig;
this.callback = callback;
this.lobbyScreen = screen;
this.game = game;
this.context = new CardshifterClientContext(game.skin, gameId, null, game.stage);
this.screenWidth = CardshifterGame.STAGE_WIDTH;
this.screenHeight = CardshifterGame.STAGE_HEIGHT;
Map<Integer, CardInfoMessage> data = deckConfig.getCardData();
cards = new ArrayList<CardInfoMessage>(data.values());
Collections.sort(cards, new Comparator<CardInfoMessage>() {
@Override
public int compare(CardInfoMessage o1, CardInfoMessage o2) {
return Integer.compare(o1.getId(), o2.getId());
}
});
pageCount = (int) Math.ceil(cards.size() / CARDS_PER_PAGE);
//normally once i start constructing libGDX UI elements, I will use a separate method
//not doing that here in order have the fields be final
//this.buildScreen();
TextButton backToMenu = new TextButton("Back to menu", game.skin);
backToMenu.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
DeckBuilderScreen.this.game.stage.clear();
DeckBuilderScreen.this.game.setScreen(DeckBuilderScreen.this.lobbyScreen);
}
});
backToMenu.setPosition(0, this.screenHeight - this.screenHeight/20);
this.game.stage.addActor(backToMenu);
this.table = new Table(game.skin);
this.table.setFillParent(true);
totalLabel = new Label("0/" + config.getMaxSize(), game.skin);
nameLabel = new Label(deckName, game.skin);
table.add(nameLabel);
table.add(totalLabel);
table.row();
cardsTable = new Table(game.skin);
cardsTable.defaults().space(4);
table.add(cardsTable);
cardsInDeckList = new VerticalGroup();
cardsInDeckList.align(Align.left);
this.cardsInDeckScrollPane = new ScrollPane(cardsInDeckList);
this.cardsInDeckScrollPane.setScrollingDisabled(true, false);
table.add(this.cardsInDeckScrollPane).width(this.screenWidth/5);
savedDecks = new List<String>(game.skin);
savedDecks.addListener(new ActorGestureListener(){
@Override
public boolean longPress(Actor actor, float x, float y) {
loadDeck(savedDecks.getSelected());
return true;
}
});
Table savedTable = scanSavedDecks(game, savedDecks, modName);
if (savedTable != null) {
savedTable.setHeight(this.screenHeight* 0.9f);
ScrollPane savedTableScroll = new ScrollPane(savedTable);
savedTableScroll.setScrollingDisabled(false, false);
table.add(savedTableScroll).top();
}
table.row();
HorizontalGroup prevNextButtons = new HorizontalGroup();
this.previousPageButton = addPageButton(prevNextButtons, "Previous", -1, game.skin);
this.nextPageButton = addPageButton(prevNextButtons, "Next", 1, game.skin);
table.add(prevNextButtons);
TextButton startGameButton = new TextButton("Start Game", game.skin);
startGameButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (config.total() >= config.getMinSize() && config.total() <= config.getMaxSize()) {
DeckBuilderScreen.this.game.stage.clear();
callback.callback(deckConfig);
}
}
});
table.add(startGameButton);
if (Gdx.app.getType() != ApplicationType.WebGL) {
TextButton save = new TextButton("Save", game.skin);
save.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
final TextField textField = new TextField(deckName, DeckBuilderScreen.this.game.skin);
Dialog dialog = new Dialog("Deck Name", DeckBuilderScreen.this.game.skin) {
@Override
protected void result(Object object) {
boolean result = (Boolean) object;
if (!result) {
return;
}
deckName = textField.getText();
saveDeck(deckName);
}
};
dialog.add(textField);
dialog.button("Save", true);
dialog.button("Cancel", false);
dialog.show(DeckBuilderScreen.this.game.stage);
}
});
TextButton load = new TextButton("Load", game.skin);
load.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
DeckBuilderScreen.this.loadDeck(DeckBuilderScreen.this.savedDecks.getSelected());
}
});
TextButton delete = new TextButton("Delete", game.skin);
delete.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Dialog dialog = new Dialog("Confirm Delete", DeckBuilderScreen.this.game.skin) {
@Override
protected void result(Object object) {
boolean result = (Boolean) object;
if (!result) {
return;
}
FileHandle handle = external.child(savedDecks.getSelected() + ".deck");
handle.delete();
updateSavedDeckList();
}
};
dialog.button("Delete", true);
dialog.button("Cancel", false);
dialog.show(DeckBuilderScreen.this.game.stage);
}
});
HorizontalGroup saveButtons = new HorizontalGroup();
saveButtons.addActor(save);
saveButtons.addActor(load);
saveButtons.addActor(delete);
table.add(saveButtons);
}
displayPage(1);
}
private Table scanSavedDecks(final CardshifterGame game, final List<String> savedDecks, String modName) {
if (Gdx.files.isExternalStorageAvailable()) {
Table saveTable = new Table();
external = Gdx.files.external("Cardshifter/decks/" + modName + "/");
external.mkdirs();
if (!external.exists()) {
Gdx.app.log("Files", external.path() + " does not exist.");
return null;
}
updateSavedDeckList();
saveTable.add(savedDecks).colspan(2).fill().row();
return saveTable;
}
return null;
}
private void updateSavedDeckList() {
java.util.List<String> list = new ArrayList<String>();
for (FileHandle handle : external.list()) {
if (!handle.isDirectory()) {
list.add(handle.nameWithoutExtension());
}
}
savedDecks.setItems(list.toArray(new String[list.size()]));
}
private void saveDeck(String deckName) {
FileHandle handle = external.child(deckName + ".deck");
StringBuilder str = new StringBuilder();
for (Map.Entry<Integer, Integer> entry : config.getChosen().entrySet()) {
int count = entry.getValue();
int id = entry.getKey();
for (int i = 0; i < count; i++) {
if (str.length() > 0) {
str.append(',');
}
str.append(id);
}
}
String deckString = str.toString();
savedDecks.getItems().add(deckName);
handle.writeString(deckString, false);
nameLabel.setText(deckName);
updateSavedDeckList();
}
private void loadDeck(String deckName) {
FileHandle handle = external.child(deckName + ".deck");
String deckString = handle.readString();
config.clearChosen();
this.cardsInDeckList.clear();
for (String id : deckString.split(",")) {
try {
int cardId = Integer.parseInt(id);
if (config.getCardData().get(cardId) != null) {
config.add(cardId);
}
}
catch (NumberFormatException ex) {
}
}
for (Map.Entry<Integer, Label> ee : countLabels.entrySet()) {
ee.getValue().setText(countText(ee.getKey()));
}
nameLabel.setText(deckName);
for (Map.Entry<Integer, Integer> ee : config.getChosen().entrySet()) {
DeckCardView cardView = labelFor(ee.getKey());
cardView.setCount(ee.getValue());
}
updateLabels();
}
private String countText(int id) {
Integer value = config.getChosen().get(id);
return countText(id, value == null ? 0 : value);
}
private String countText(int id, int count) {
int max = config.getMaxFor(id);
return count + "/" + max;
}
private TextButton addPageButton(Group table, String text, final int i, Skin skin) {
TextButton button = new TextButton(text, skin);
button.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
displayPage(page + i);
}
});
table.addActor(button);
return button;
}
private void displayPage(int page) {
this.page = page;
countLabels.clear();
int startIndex = (page - 1) * CARDS_PER_PAGE;
cardsTable.clearChildren();
for (int i = startIndex; i < startIndex + CARDS_PER_PAGE; i++) {
if (cards.size() <= i) {
break;
}
if (i % CARDS_PER_ROW == 0) {
cardsTable.row();
}
CardInfoMessage card = cards.get(i);
VerticalGroup choosableGroup = new VerticalGroup();
CardViewSmall cardView = new CardViewSmall(context, card, this, false);
cardView.setTargetable(TargetStatus.TARGETABLE, this);
choosableGroup.addActor(cardView.getActor());
Label label = new Label(countText(card.getId()), game.skin);
label.setHeight(this.screenHeight/30);
countLabels.put(card.getId(), label);
choosableGroup.addActor(label);
cardsTable.add(choosableGroup);
}
setButtonEnabled(previousPageButton, page > 1);
setButtonEnabled(nextPageButton, page <= pageCount);
}
private void setButtonEnabled(TextButton button, boolean enabled) {
if (enabled) {
button.setTouchable(Touchable.enabled);
button.setStyle(game.skin.get(TextButton.TextButtonStyle.class));
}
else {
button.setTouchable(Touchable.disabled);
button.setStyle(game.skin.get("disabled", TextButton.TextButtonStyle.class));
}
}
@Override
public void render(float delta) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
game.stage.addActor(table);
}
@Override
public void hide() {
table.remove();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
@Override
public boolean addEntity(final EntityView view) {
//prevent other cards from being added when one is zoomed in on
if (this.cardZoomedIn) {
return false;
}
final int id = view.getId();
int max = config.getMaxFor(id);
Integer chosen = config.getChosen().get(id);
if (chosen == null) {
chosen = 0;
}
int newChosen = (chosen + 1) % (max + 1);
if (config.total() >= config.getMaxSize() && chosen > 0) {
newChosen = 0;
}
config.setChosen(id, newChosen);
countLabels.get(id).setText(countText(id, newChosen));
DeckCardView cardView = labelFor(id);
cardView.setCount(newChosen);
updateLabels();
return true;
}
private DeckCardView labelFor(int id) {
SnapshotArray<Actor> children = cardsInDeckList.getChildren();
int index = 0;
String name = (String) config.getCardData().get(id).getProperties().get("name");
for (Actor actor : children) {
DeckCardView view = (DeckCardView) actor;
if (view.getId() == id) {
return view;
}
if (name.compareTo(view.getName()) < 0) {
break;
}
index++;
}
DeckCardView view = new DeckCardView(game.skin, id, name, this);
cardsInDeckList.addActorAt(index, view);
return view;
}
private void updateLabels() {
totalLabel.setText(config.total() + "/" + config.getMaxSize());
}
public void removeCardFromDeck(int id) {
for (Actor actor : cardsInDeckList.getChildren()) {
if (actor instanceof DeckCardView) {
if (actor instanceof DeckCardView) {
if (((DeckCardView)actor).getId() == id) {
int newCount = ((DeckCardView)actor).getCount() - 1;
if (newCount > 0) {
((DeckCardView) actor).setCount(newCount);
} else {
actor.remove();
}
config.setChosen(id, newCount);
}
}
}
}
this.updateLabels();
this.displayPage(this.page);
}
@Override
public void zoomCard(final CardViewSmall cardView) {
if (this.cardZoomedIn) {
return;
}
final CardViewSmall cardViewCopy = new CardViewSmall(this.context, cardView.cardInfo, this, true);
cardViewCopy.setTargetable(TargetStatus.TARGETABLE, this);
cardViewCopy.getActor().setPosition(this.screenWidth/2.7f, this.screenHeight/30);
this.game.stage.addActor(cardViewCopy.getActor());
this.initialCardViewWidth = cardView.getActor().getWidth();
this.initialCardViewHeight = cardView.getActor().getHeight();
SequenceAction sequence = new SequenceAction();
Runnable adjustForZoom = new Runnable() {
@Override
public void run() {
cardViewCopy.zoom();
}
};
sequence.addAction(Actions.sizeTo(this.screenWidth/4, this.screenHeight*0.9f, 0.2f));
sequence.addAction(Actions.run(adjustForZoom));
cardViewCopy.getActor().addAction(sequence);
this.cardZoomedIn = true;
}
@Override
public void endZoom(final CardViewSmall cardView) {
if (cardView.isZoomed){
SequenceAction sequence = new SequenceAction();
Runnable endZoom = new Runnable() {
@Override
public void run() {
cardView.endZoom();
cardView.getActor().remove();
DeckBuilderScreen.this.cardZoomedIn = false;
}
};
sequence.addAction(Actions.sizeTo(this.initialCardViewWidth, this.initialCardViewHeight, 0.2f));
sequence.addAction(Actions.run(endZoom));
cardView.getActor().addAction(sequence);
}
}
public boolean checkCardDrop(CardViewSmall cardView) {
Table table = (Table)cardView.getActor();
Vector2 stageLoc = table.localToStageCoordinates(new Vector2());
Rectangle tableRect = new Rectangle(stageLoc.x, stageLoc.y, table.getWidth(), table.getHeight());
Vector2 stageLocCardList = this.cardsInDeckList.localToStageCoordinates(new Vector2(this.cardsInDeckList.getX(), this.cardsInDeckList.getY()));
Vector2 modifiedSLCL = new Vector2(stageLocCardList.x, stageLocCardList.y - this.screenHeight/2);
Rectangle deckRect = new Rectangle(modifiedSLCL.x, modifiedSLCL.y, this.cardsInDeckList.getWidth(), this.screenHeight);
if (tableRect.overlaps(deckRect)) {
this.addEntity(cardView);
return true;
}
return false;
//these can be used to double check the location of the rectangles
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(modifiedSLCL.x, modifiedSLCL.y);
squareImage.setSize(deckRect.width, deckRect.height);
this.game.stage.addActor(squareImage);
*/
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(stageLoc.x, stageLoc.y);
squareImage.setSize(tableRect.width, tableRect.height);
this.game.stage.addActor(squareImage);
*/
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.connectors.kafka;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.typeutils.TypeInfoParser;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
import org.apache.flink.streaming.util.TestStreamEnvironment;
import org.apache.flink.streaming.util.serialization.KeyedDeserializationSchema;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper;
import org.apache.flink.util.InstantiationUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.util.Properties;
import static org.apache.flink.test.util.TestUtils.tryExecute;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* A class containing a special Kafka broker which has a log retention of only 250 ms.
* This way, we can make sure our consumer is properly handling cases where we run into out of offset
* errors
*/
@SuppressWarnings("serial")
public class KafkaShortRetentionTestBase implements Serializable {
protected static final Logger LOG = LoggerFactory.getLogger(KafkaShortRetentionTestBase.class);
protected static final int NUM_TMS = 1;
protected static final int TM_SLOTS = 8;
protected static final int PARALLELISM = NUM_TMS * TM_SLOTS;
private static KafkaTestEnvironment kafkaServer;
private static Properties standardProps;
private static LocalFlinkMiniCluster flink;
@ClassRule
public static TemporaryFolder tempFolder = new TemporaryFolder();
protected static Properties secureProps = new Properties();
@BeforeClass
public static void prepare() throws IOException, ClassNotFoundException {
LOG.info("-------------------------------------------------------------------------");
LOG.info(" Starting KafkaShortRetentionTestBase ");
LOG.info("-------------------------------------------------------------------------");
Configuration flinkConfig = new Configuration();
// dynamically load the implementation for the test
Class<?> clazz = Class.forName("org.apache.flink.streaming.connectors.kafka.KafkaTestEnvironmentImpl");
kafkaServer = (KafkaTestEnvironment) InstantiationUtil.instantiate(clazz);
LOG.info("Starting KafkaTestBase.prepare() for Kafka " + kafkaServer.getVersion());
if (kafkaServer.isSecureRunSupported()) {
secureProps = kafkaServer.getSecureProperties();
}
Properties specificProperties = new Properties();
specificProperties.setProperty("log.retention.hours", "0");
specificProperties.setProperty("log.retention.minutes", "0");
specificProperties.setProperty("log.retention.ms", "250");
specificProperties.setProperty("log.retention.check.interval.ms", "100");
kafkaServer.prepare(kafkaServer.createConfig().setKafkaServerProperties(specificProperties));
standardProps = kafkaServer.getStandardProperties();
// start also a re-usable Flink mini cluster
flinkConfig.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, NUM_TMS);
flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, TM_SLOTS);
flinkConfig.setLong(TaskManagerOptions.MANAGED_MEMORY_SIZE, 16L);
flinkConfig.setString(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY, "0 s");
flink = new LocalFlinkMiniCluster(flinkConfig, false);
flink.start();
TestStreamEnvironment.setAsContext(flink, PARALLELISM);
}
@AfterClass
public static void shutDownServices() throws Exception {
TestStreamEnvironment.unsetAsContext();
if (flink != null) {
flink.stop();
}
kafkaServer.shutdown();
secureProps.clear();
}
/**
* This test is concurrently reading and writing from a kafka topic.
* The job will run for a while
* In a special deserializationSchema, we make sure that the offsets from the topic
* are non-continuous (because the data is expiring faster than its consumed --> with auto.offset.reset = 'earliest', some offsets will not show up)
*
*/
private static boolean stopProducer = false;
public void runAutoOffsetResetTest() throws Exception {
final String topic = "auto-offset-reset-test";
final int parallelism = 1;
final int elementsPerPartition = 50000;
Properties tprops = new Properties();
tprops.setProperty("retention.ms", "250");
kafkaServer.createTestTopic(topic, parallelism, 1, tprops);
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(parallelism);
env.setRestartStrategy(RestartStrategies.noRestart()); // fail immediately
env.getConfig().disableSysoutLogging();
// ----------- add producer dataflow ----------
DataStream<String> stream = env.addSource(new RichParallelSourceFunction<String>() {
private boolean running = true;
@Override
public void run(SourceContext<String> ctx) throws InterruptedException {
int cnt = getRuntimeContext().getIndexOfThisSubtask() * elementsPerPartition;
int limit = cnt + elementsPerPartition;
while (running && !stopProducer && cnt < limit) {
ctx.collect("element-" + cnt);
cnt++;
Thread.sleep(10);
}
LOG.info("Stopping producer");
}
@Override
public void cancel() {
running = false;
}
});
Properties props = new Properties();
props.putAll(standardProps);
props.putAll(secureProps);
kafkaServer.produceIntoKafka(stream, topic, new KeyedSerializationSchemaWrapper<>(new SimpleStringSchema()), props, null);
// ----------- add consumer dataflow ----------
NonContinousOffsetsDeserializationSchema deserSchema = new NonContinousOffsetsDeserializationSchema();
FlinkKafkaConsumerBase<String> source = kafkaServer.getConsumer(topic, deserSchema, props);
DataStreamSource<String> consuming = env.addSource(source);
consuming.addSink(new DiscardingSink<String>());
tryExecute(env, "run auto offset reset test");
kafkaServer.deleteTestTopic(topic);
}
private class NonContinousOffsetsDeserializationSchema implements KeyedDeserializationSchema<String> {
private int numJumps;
long nextExpected = 0;
@Override
public String deserialize(byte[] messageKey, byte[] message, String topic, int partition, long offset) throws IOException {
if (offset != nextExpected) {
numJumps++;
nextExpected = offset;
LOG.info("Registered now jump at offset {}", offset);
}
nextExpected++;
try {
Thread.sleep(10); // slow down data consumption to trigger log eviction
} catch (InterruptedException e) {
throw new RuntimeException("Stopping it");
}
return "";
}
@Override
public boolean isEndOfStream(String nextElement) {
if (numJumps >= 5) {
// we saw 5 jumps and no failures --> consumer can handle auto.offset.reset
stopProducer = true;
return true;
}
return false;
}
@Override
public TypeInformation<String> getProducedType() {
return TypeInfoParser.parse("String");
}
}
/**
* Ensure that the consumer is properly failing if "auto.offset.reset" is set to "none".
* @throws Exception
*/
public void runFailOnAutoOffsetResetNone() throws Exception {
final String topic = "auto-offset-reset-none-test";
final int parallelism = 1;
kafkaServer.createTestTopic(topic, parallelism, 1);
final StreamExecutionEnvironment env =
StreamExecutionEnvironment.createRemoteEnvironment("localhost", flink.getLeaderRPCPort());
env.setParallelism(parallelism);
env.setRestartStrategy(RestartStrategies.noRestart()); // fail immediately
env.getConfig().disableSysoutLogging();
// ----------- add consumer ----------
Properties customProps = new Properties();
customProps.putAll(standardProps);
customProps.putAll(secureProps);
customProps.setProperty("auto.offset.reset", "none"); // test that "none" leads to an exception
FlinkKafkaConsumerBase<String> source = kafkaServer.getConsumer(topic, new SimpleStringSchema(), customProps);
DataStreamSource<String> consuming = env.addSource(source);
consuming.addSink(new DiscardingSink<String>());
try {
env.execute("Test auto offset reset none");
} catch (Throwable e) {
// check if correct exception has been thrown
if (!e.getCause().getCause().getMessage().contains("Unable to find previous offset") // kafka 0.8
&& !e.getCause().getCause().getMessage().contains("Undefined offset with no reset policy for partition") // kafka 0.9
) {
throw e;
}
}
kafkaServer.deleteTestTopic(topic);
}
public void runFailOnAutoOffsetResetNoneEager() throws Exception {
final String topic = "auto-offset-reset-none-test";
final int parallelism = 1;
kafkaServer.createTestTopic(topic, parallelism, 1);
// ----------- add consumer ----------
Properties customProps = new Properties();
customProps.putAll(standardProps);
customProps.putAll(secureProps);
customProps.setProperty("auto.offset.reset", "none"); // test that "none" leads to an exception
try {
kafkaServer.getConsumer(topic, new SimpleStringSchema(), customProps);
fail("should fail with an exception");
}
catch (IllegalArgumentException e) {
// expected
assertTrue(e.getMessage().contains("none"));
}
kafkaServer.deleteTestTopic(topic);
}
}
| |
package com.mesosphere.dcos.cassandra.scheduler.plan.backup;
import com.mesosphere.dcos.cassandra.common.offer.ClusterTaskOfferRequirementProvider;
import com.mesosphere.dcos.cassandra.common.persistence.PersistenceException;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraDaemonTask;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraState;
import com.mesosphere.dcos.cassandra.common.tasks.backup.BackupRestoreContext;
import com.mesosphere.dcos.cassandra.common.tasks.backup.BackupSchemaTask;
import com.mesosphere.dcos.cassandra.common.tasks.backup.BackupSnapshotTask;
import com.mesosphere.dcos.cassandra.common.tasks.backup.BackupUploadTask;
import com.mesosphere.dcos.cassandra.scheduler.resources.BackupRestoreRequest;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.TaskInfo;
import org.apache.mesos.Protos.TaskStatus;
import org.apache.mesos.config.SerializationUtils;
import org.apache.mesos.scheduler.plan.Phase;
import org.apache.mesos.scheduler.plan.Step;
import org.apache.mesos.state.StateStore;
import org.apache.mesos.state.StateStoreException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class BackupManagerTest {
private static final String SNAPSHOT_NODE_0 = "snapshot-node-0";
private static final String UPLOAD_NODE_0 = "upload-node-0";
private static final String BACKUPSCHEMA_NODE_0 = "backupschema-node-0";
private static final String NODE_0 = "node-0";
@Mock private ClusterTaskOfferRequirementProvider mockProvider;
@Mock private CassandraState mockCassandraState;
@Mock private StateStore mockState;
@Before
public void beforeEach() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testInitialNoState() {
when(mockState.fetchProperty(BackupManager.BACKUP_KEY)).thenThrow(
new StateStoreException("no state found"));
BackupManager manager = new BackupManager(mockCassandraState, mockProvider, mockState);
assertFalse(manager.isComplete());
assertFalse(manager.isInProgress());
assertTrue(manager.getPhases().isEmpty());
}
@Test
public void testInitialWithState() throws IOException {
final BackupRestoreContext context = BackupRestoreContext.create("", "", "", "", "", "", false, "","","");
when(mockState.fetchProperty(BackupManager.BACKUP_KEY)).thenReturn(
SerializationUtils.toJsonString(context).getBytes(StandardCharsets.UTF_8));
BackupManager manager = new BackupManager(mockCassandraState, mockProvider, mockState);
assertTrue(manager.isComplete());
assertFalse(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
}
@Test
public void testStartCompleteStop() {
when(mockState.fetchProperty(BackupManager.BACKUP_KEY)).thenThrow(
new StateStoreException("no state found"));
BackupManager manager = new BackupManager(mockCassandraState, mockProvider, mockState);
final CassandraDaemonTask daemonTask = Mockito.mock(CassandraDaemonTask.class);
Mockito.when(daemonTask.getState()).thenReturn(Protos.TaskState.TASK_RUNNING);
final HashMap<String, CassandraDaemonTask> map = new HashMap<>();
map.put(NODE_0, daemonTask);
when(mockCassandraState.getDaemons()).thenReturn(map);
when(mockCassandraState.get(SNAPSHOT_NODE_0)).thenReturn(Optional.of(daemonTask));
when(mockCassandraState.get(UPLOAD_NODE_0)).thenReturn(Optional.of(daemonTask));
when(mockCassandraState.get(BACKUPSCHEMA_NODE_0)).thenReturn(Optional.of(daemonTask));
manager.start(emptyRequest());
assertFalse(manager.isComplete());
assertTrue(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
Mockito.when(daemonTask.getState()).thenReturn(Protos.TaskState.TASK_FINISHED);
// notify steps to check for TASK_FINISHED:
for (Phase phase : manager.getPhases()) {
for (Step step : phase.getChildren()) {
step.update(TaskStatus.getDefaultInstance());
}
}
assertTrue(manager.isComplete());
assertFalse(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
manager.stop();
assertFalse(manager.isComplete());
assertFalse(manager.isInProgress());
assertTrue(manager.getPhases().isEmpty());
}
@Test
public void testStartCompleteStart() throws PersistenceException {
when(mockState.fetchProperty(BackupManager.BACKUP_KEY)).thenThrow(
new StateStoreException("no state found"));
BackupManager manager = new BackupManager(mockCassandraState, mockProvider, mockState);
final CassandraDaemonTask daemonTask = Mockito.mock(CassandraDaemonTask.class);
Mockito.when(daemonTask.getState()).thenReturn(Protos.TaskState.TASK_RUNNING);
final HashMap<String, CassandraDaemonTask> map = new HashMap<>();
map.put(NODE_0, daemonTask);
when(mockCassandraState.getDaemons()).thenReturn(map);
when(mockCassandraState.get(SNAPSHOT_NODE_0)).thenReturn(Optional.of(daemonTask));
when(mockCassandraState.get(UPLOAD_NODE_0)).thenReturn(Optional.of(daemonTask));
when(mockCassandraState.get(BACKUPSCHEMA_NODE_0)).thenReturn(Optional.of(daemonTask));
manager.start(emptyRequest());
assertFalse(manager.isComplete());
assertTrue(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
Mockito.when(daemonTask.getState()).thenReturn(Protos.TaskState.TASK_FINISHED);
// notify steps to check for TASK_FINISHED:
for (Phase phase : manager.getPhases()) {
for (Step step : phase.getChildren()) {
step.update(TaskStatus.getDefaultInstance());
}
}
assertTrue(manager.isComplete());
assertFalse(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
Mockito.when(daemonTask.getState()).thenReturn(Protos.TaskState.TASK_RUNNING);
Map<String, BackupUploadTask> previousUploadTasks = new HashMap<String, BackupUploadTask>();
previousUploadTasks.put("hey", BackupUploadTask.parse(TaskInfo.getDefaultInstance()));
Map<String, BackupSnapshotTask> previousBackupTasks = new HashMap<String, BackupSnapshotTask>();
previousBackupTasks.put("hi", BackupSnapshotTask.parse(TaskInfo.getDefaultInstance()));
Map<String, BackupSchemaTask> previousSchemaTasks = new HashMap<>();
previousSchemaTasks.put("hello", BackupSchemaTask.parse(TaskInfo.getDefaultInstance()));
when(mockCassandraState.getBackupUploadTasks()).thenReturn(previousUploadTasks);
when(mockCassandraState.getBackupSnapshotTasks()).thenReturn(previousBackupTasks);
when(mockCassandraState.getBackupSchemaTasks()).thenReturn(previousSchemaTasks);
manager.start(emptyRequest());
verify(mockCassandraState).remove(Collections.singleton("hi"));
verify(mockCassandraState).remove(Collections.singleton("hey"));
verify(mockCassandraState).remove(Collections.singleton("hello"));
assertFalse(manager.isComplete());
assertTrue(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
}
@Test
public void testStartStop() {
when(mockState.fetchProperty(BackupManager.BACKUP_KEY)).thenThrow(
new StateStoreException("no state found"));
BackupManager manager = new BackupManager(mockCassandraState, mockProvider, mockState);
final CassandraDaemonTask daemonTask = Mockito.mock(CassandraDaemonTask.class);
Mockito.when(daemonTask.getState()).thenReturn(Protos.TaskState.TASK_RUNNING);
final HashMap<String, CassandraDaemonTask> map = new HashMap<>();
map.put(NODE_0, daemonTask);
when(mockCassandraState.getDaemons()).thenReturn(map);
when(mockCassandraState.get(SNAPSHOT_NODE_0)).thenReturn(Optional.of(daemonTask));
when(mockCassandraState.get(UPLOAD_NODE_0)).thenReturn(Optional.of(daemonTask));
when(mockCassandraState.get(BACKUPSCHEMA_NODE_0)).thenReturn(Optional.of(daemonTask));
manager.start(emptyRequest());
assertFalse(manager.isComplete());
assertTrue(manager.isInProgress());
assertEquals(3, manager.getPhases().size());
manager.stop();
assertFalse(manager.isComplete());
assertFalse(manager.isInProgress());
assertTrue(manager.getPhases().isEmpty());
}
private BackupRestoreRequest emptyRequest() {
BackupRestoreRequest request = new BackupRestoreRequest();
request.setAzureAccount("");
request.setAzureKey("");
request.setExternalLocation("");
request.setName("");
request.setS3AccessKey("");
request.setS3SecretKey("");
request.setRestoreType("");
return request;
}
}
| |
package silent.kuasapmaterial;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.analytics.HitBuilders;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kuas.ap.R;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import silent.kuasapmaterial.base.SilentActivity;
import silent.kuasapmaterial.callback.BusBookCallback;
import silent.kuasapmaterial.callback.BusCallback;
import silent.kuasapmaterial.callback.GeneralCallback;
import silent.kuasapmaterial.libs.AlarmHelper;
import silent.kuasapmaterial.libs.Constant;
import silent.kuasapmaterial.libs.Helper;
import silent.kuasapmaterial.libs.ListScrollDistanceCalculator;
import silent.kuasapmaterial.libs.MaterialProgressBar;
import silent.kuasapmaterial.libs.Memory;
import silent.kuasapmaterial.libs.Utils;
import silent.kuasapmaterial.libs.compat.HtmlCompat;
import silent.kuasapmaterial.libs.segmentcontrol.SegmentControl;
import silent.kuasapmaterial.models.BusModel;
public class BusActivity extends SilentActivity
implements SegmentControl.OnSegmentControlClickListener, AdapterView.OnItemClickListener,
DatePickerDialog.OnDateSetListener, ListScrollDistanceCalculator.ScrollDistanceListener,
SwipeRefreshLayout.OnRefreshListener {
SegmentControl mSegmentControl;
ListView mListView;
TextView mTextView;
TextView mNoBusTextView;
LinearLayout mNoBusLinearLayout;
MaterialProgressBar mMaterialProgressBar;
FloatingActionButton mFab;
SwipeRefreshLayout mSwipeRefreshLayout;
String mDate;
List<BusModel> mJianGongList, mYanChaoList;
BusAdapter mAdapter;
ListScrollDistanceCalculator mListScrollDistanceCalculator;
boolean isRetry = false;
private int mInitListPos = 0, mInitListOffset = 0, mIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
setContentView(R.layout.activity_bus);
init(R.string.bus, R.layout.activity_bus, R.id.nav_bus);
initGA("Bus Screen");
restoreArgs(savedInstanceState);
findViews();
setUpViews();
}
@Override
public void finish() {
super.finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
private void restoreArgs(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mDate = savedInstanceState.getString("mDate");
mIndex = savedInstanceState.getInt("mIndex");
mInitListPos = savedInstanceState.getInt("mInitListPos");
mInitListOffset = savedInstanceState.getInt("mInitListOffset");
isRetry = savedInstanceState.getBoolean("isRetry");
if (savedInstanceState.containsKey("mJianGongList")) {
mJianGongList = new Gson().fromJson(savedInstanceState.getString("mJianGongList"),
new TypeToken<List<BusModel>>() {
}.getType());
}
if (savedInstanceState.containsKey("mYanChaoList")) {
mYanChaoList = new Gson().fromJson(savedInstanceState.getString("mYanChaoList"),
new TypeToken<List<BusModel>>() {
}.getType());
}
} else {
showDatePickerDialog();
}
if (mJianGongList == null) {
mJianGongList = new ArrayList<>();
}
if (mYanChaoList == null) {
mYanChaoList = new ArrayList<>();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("mDate", mDate);
outState.putInt("mIndex", mIndex);
outState.putBoolean("isRetry", isRetry);
if (mListView != null) {
outState.putInt("mInitListPos", mListView.getFirstVisiblePosition());
View vNewTop = mListView.getChildAt(0);
outState.putInt("mInitListOffset", (vNewTop == null) ? 0 : vNewTop.getTop());
}
if (mJianGongList != null) {
outState.putString("mJianGongList", new Gson().toJson(mJianGongList));
}
if (mYanChaoList != null) {
outState.putString("mYanChaoList", new Gson().toJson(mYanChaoList));
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Constant.REQUEST_BUS_RESERVATIONS:
if (resultCode == RESULT_OK && data != null) {
if (data.hasExtra("isRefresh") && data.getExtras().getBoolean("isRefresh")) {
getData();
}
}
break;
}
}
@Override
public void onResume() {
super.onResume();
DatePickerDialog dpd =
(DatePickerDialog) getFragmentManager().findFragmentByTag("DatePickerDialog");
if (dpd != null) {
dpd.setOnDateSetListener(this);
}
}
private void findViews() {
mSegmentControl = (SegmentControl) findViewById(R.id.segment_control);
mListView = (ListView) findViewById(R.id.listView);
mTextView = (TextView) findViewById(R.id.textView_pickDate);
mMaterialProgressBar = (MaterialProgressBar) findViewById(R.id.materialProgressBar);
mFab = (FloatingActionButton) findViewById(R.id.fab);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mNoBusLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_no_bus);
mNoBusTextView = (TextView) findViewById(R.id.textView_no_bus);
}
private void setUpViews() {
mSegmentControl.setmOnSegmentControlClickListener(this);
mListView.setOnItemClickListener(this);
mListView.setDividerHeight(5);
mAdapter = new BusAdapter(this);
mListView.setAdapter(mAdapter);
mListScrollDistanceCalculator = new ListScrollDistanceCalculator();
mListScrollDistanceCalculator.setScrollDistanceListener(this);
mListView.setOnScrollListener(mListScrollDistanceCalculator);
mFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTracker.send(new HitBuilders.EventBuilder().setCategory("bus reservations")
.setAction("click").build());
startActivityForResult(new Intent(BusActivity.this, BusReservationsActivity.class),
Constant.REQUEST_BUS_RESERVATIONS);
}
});
mSegmentControl.setIndex(mIndex);
setUpSegmentColor();
setUpPullRefresh();
mListView.setSelectionFromTop(mInitListPos, mInitListOffset);
mTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTracker.send(
new HitBuilders.EventBuilder().setCategory("pick date").setAction("click")
.build());
showDatePickerDialog();
}
});
mNoBusLinearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRetry) {
mTracker.send(
new HitBuilders.EventBuilder().setCategory("retry").setAction("click")
.build());
isRetry = false;
getData();
} else {
mTracker.send(new HitBuilders.EventBuilder().setCategory("pick date")
.setAction("click").build());
showDatePickerDialog();
}
}
});
if (mDate != null && mDate.length() > 0) {
mTextView.setText(getString(R.string.bus_pick_date, mDate));
} else {
mSwipeRefreshLayout.setEnabled(false);
}
setUpListView();
}
@Override
public void onRefresh() {
if (mDate == null || mDate.length() == 0) {
return;
}
mTracker.send(
new HitBuilders.EventBuilder().setCategory("refresh").setAction("swipe").build());
mSwipeRefreshLayout.setRefreshing(true);
isRetry = false;
getData();
}
private void setUpPullRefresh() {
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeColors(Utils.getSwipeRefreshColors(this));
}
private void showDatePickerDialog() {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog
.newInstance(this, now.get(Calendar.YEAR), now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH));
dpd.setThemeDark(false);
dpd.vibrate(false);
dpd.dismissOnPause(false);
dpd.show(getFragmentManager(), "DatePickerDialog");
}
private void getData() {
if (!mSwipeRefreshLayout.isRefreshing()) {
mMaterialProgressBar.setVisibility(View.VISIBLE);
}
mListView.setVisibility(View.GONE);
mNoBusLinearLayout.setVisibility(View.GONE);
mFab.setEnabled(false);
mSwipeRefreshLayout.setEnabled(false);
mFab.hide();
Helper.getBusTimeTable(this, mDate, new BusCallback() {
@Override
public void onSuccess(List<BusModel> jiangongList, List<BusModel> yanchaoList) {
super.onSuccess(jiangongList, yanchaoList);
mJianGongList = jiangongList;
mYanChaoList = yanchaoList;
setUpListView();
mAdapter.notifyDataSetChanged();
mFab.setEnabled(true);
mFab.show();
mSwipeRefreshLayout.setEnabled(true);
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFail(String errorMessage) {
super.onFail(errorMessage);
mJianGongList.clear();
mYanChaoList.clear();
isRetry = true;
setUpListView();
mAdapter.notifyDataSetChanged();
mFab.setEnabled(true);
mFab.show();
mSwipeRefreshLayout.setEnabled(true);
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onTokenExpired() {
super.onTokenExpired();
Utils.showTokenExpired(BusActivity.this);
mTracker.send(
new HitBuilders.EventBuilder().setCategory("token").setAction("expired")
.build());
}
});
}
@Override
public void onSegmentControlClick(int index) {
mTracker.send(new HitBuilders.EventBuilder().setCategory("segment").setAction("click")
.setLabel(Integer.toString(index)).build());
mIndex = index;
mAdapter.notifyDataSetChanged();
setUpSegmentColor();
setUpListView();
mListView.smoothScrollToPosition(0);
if (!mFab.isShown() && mFab.isEnabled()) {
mFab.show();
}
}
@Override
public void onSegmentControlReselect() {
mListView.smoothScrollToPosition(0);
if (!mFab.isShown() && mFab.isEnabled()) {
mFab.show();
}
}
private void setUpSegmentColor() {
if (mIndex == 0) {
mSegmentControl.setColors(
ColorStateList.valueOf(ContextCompat.getColor(this, R.color.blue_600)));
} else {
mSegmentControl.setColors(
ColorStateList.valueOf(ContextCompat.getColor(this, R.color.green_600)));
}
setUpFabColor();
}
private void setUpFabColor() {
if (mIndex == 0) {
mFab.setBackgroundTintList(
ColorStateList.valueOf(ContextCompat.getColor(this, R.color.green_600)));
} else {
mFab.setBackgroundTintList(
ColorStateList.valueOf(ContextCompat.getColor(this, R.color.blue_600)));
}
}
private void setUpListView() {
mMaterialProgressBar.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
int count = mIndex == 0 ? mJianGongList.size() : mYanChaoList.size();
if (count == 0) {
if (isRetry) {
mNoBusTextView.setText(R.string.click_to_retry);
} else if (mDate == null || mDate.length() == 0) {
mNoBusTextView.setText(getString(R.string.bus_not_pick, "\uD83D\uDE0B"));
} else {
mNoBusTextView.setText(getString(R.string.bus_no_bus, "\uD83D\uDE0B"));
}
mNoBusLinearLayout.setVisibility(View.VISIBLE);
} else {
mNoBusLinearLayout.setVisibility(View.GONE);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final List<BusModel> modelList = mIndex == 0 ? mJianGongList : mYanChaoList;
if (modelList.get(position).isReserve) {
mTracker.send(
new HitBuilders.EventBuilder().setCategory("cancel bus").setAction("create")
.build());
new AlertDialog.Builder(this).setTitle(R.string.bus_cancel_reserve_confirm_title)
.setMessage(getString(R.string.bus_cancel_reserve_confirm_content, getString(
mIndex == 0 ? R.string.bus_from_jiangong : R.string.bus_from_yanchao),
modelList.get(position).Time))
.setPositiveButton(R.string.bus_cancel_reserve,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTracker.send(
new HitBuilders.EventBuilder().setCategory("cancel bus")
.setAction("click").build());
cancelBookBus(modelList, position);
}
}).setNegativeButton(R.string.back, null).show();
} else {
mTracker.send(new HitBuilders.EventBuilder().setCategory("book bus").setAction("create")
.build());
new AlertDialog.Builder(this).setTitle(R.string.bus_reserve_confirm_title).setMessage(
getString(R.string.bus_reserve_confirm_content, getString(
mIndex == 0 ? R.string.bus_from_jiangong : R.string.bus_from_yanchao),
modelList.get(position).Time))
.setPositiveButton(R.string.bus_reserve, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTracker.send(new HitBuilders.EventBuilder().setCategory("book bus")
.setAction("click").build());
bookBus(modelList.get(position).busId);
}
}).setNegativeButton(R.string.cancel, null).show();
}
}
private void cancelBookBus(final List<BusModel> modelList, final int position) {
Log.d(Constant.TAG, modelList.get(position).cancelKey);
Helper.cancelBookingBus(BusActivity.this, modelList.get(position).cancelKey,
new GeneralCallback() {
@Override
public void onSuccess() {
super.onSuccess();
mTracker.send(new HitBuilders.EventBuilder().setCategory("cancel bus")
.setAction("status").setLabel("success " + mIndex).build());
if (Memory.getBoolean(BusActivity.this, Constant.PREF_BUS_NOTIFY, false)) {
// must cancel alarm
AlarmHelper.cancelBusAlarm(BusActivity.this,
modelList.get(position).endStation,
modelList.get(position).runDateTime,
Integer.parseInt(modelList.get(position).cancelKey));
}
getData();
Toast.makeText(BusActivity.this, R.string.bus_cancel_reserve_success,
Toast.LENGTH_LONG).show();
}
@Override
public void onFail(String errorMessage) {
super.onFail(errorMessage);
mTracker.send(new HitBuilders.EventBuilder().setCategory("cancel bus")
.setAction("status").setLabel("fail " + mIndex).build());
Toast.makeText(BusActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
@Override
public void onTokenExpired() {
super.onTokenExpired();
Utils.showTokenExpired(BusActivity.this);
mTracker.send(new HitBuilders.EventBuilder().setCategory("token")
.setAction("expired").build());
}
});
}
private void bookBus(final String busId) {
Helper.bookingBus(BusActivity.this, busId, new BusBookCallback() {
@Override
public void onSuccess() {
super.onSuccess();
mTracker.send(
new HitBuilders.EventBuilder().setCategory("book bus").setAction("status")
.setLabel("success " + mIndex).build());
if (Memory.getBoolean(BusActivity.this, Constant.PREF_BUS_NOTIFY, false)) {
mMaterialProgressBar.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
mNoBusLinearLayout.setVisibility(View.GONE);
mFab.setEnabled(false);
mSwipeRefreshLayout.setEnabled(false);
mFab.hide();
Utils.setUpBusNotify(BusActivity.this, new GeneralCallback() {
@Override
public void onSuccess() {
super.onSuccess();
mTracker.send(new HitBuilders.EventBuilder().setCategory("notify bus")
.setAction("status").setLabel("success").build());
getData();
}
@Override
public void onFail(String errorMessage) {
super.onFail(errorMessage);
mTracker.send(new HitBuilders.EventBuilder().setCategory("notify bus")
.setAction("status").setLabel("fail " + errorMessage).build());
getData();
}
@Override
public void onTokenExpired() {
super.onTokenExpired();
Utils.showTokenExpired(BusActivity.this);
}
});
} else {
getData();
}
Toast.makeText(BusActivity.this, R.string.bus_reserve_success, Toast.LENGTH_LONG)
.show();
}
@Override
public void onFail(String errorMessage) {
super.onFail(errorMessage);
mTracker.send(
new HitBuilders.EventBuilder().setCategory("book bus").setAction("status")
.setLabel("fail " + busId).build());
Toast.makeText(BusActivity.this, HtmlCompat.fromHtml(errorMessage),
Toast.LENGTH_LONG).show();
}
@Override
public void onReserveFail(String errorMessage) {
super.onReserveFail(errorMessage);
mTracker.send(new HitBuilders.EventBuilder().setCategory("book bus")
.setAction("system ban").setLabel(errorMessage).build());
if (isFinishing()) {
return;
}
new AlertDialog.Builder(BusActivity.this).setTitle(R.string.bus_reserve_fail_title)
.setMessage(HtmlCompat.fromHtml(errorMessage))
.setPositiveButton(R.string.ok, null).setCancelable(false).show();
}
@Override
public void onTokenExpired() {
super.onTokenExpired();
Utils.showTokenExpired(BusActivity.this);
mTracker.send(
new HitBuilders.EventBuilder().setCategory("token").setAction("expired")
.build());
}
});
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
mTracker.send(new HitBuilders.EventBuilder().setCategory("date set").setAction("click")
.setLabel(mDate).build());
mTextView.setText(getString(R.string.bus_pick_date, mDate));
getData();
}
@Override
public void onScrollDistanceChanged(int delta, int total) {
if (delta > 10 && mFab.isEnabled()) {
mFab.show();
} else if (delta < -10) {
mFab.hide();
}
}
public class BusAdapter extends BaseAdapter {
private LayoutInflater inflater;
public BusAdapter(Context context) {
this.inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mIndex == 0 ? mJianGongList.size() : mYanChaoList.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public BusModel getItem(int position) {
return mIndex == 0 ? mJianGongList.get(position) : mYanChaoList.get(position);
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_bus, parent, false);
holder.textView_location =
(TextView) convertView.findViewById(R.id.textView_location);
holder.textView_time = (TextView) convertView.findViewById(R.id.textView_time);
holder.textView_count = (TextView) convertView.findViewById(R.id.textView_count);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (mIndex == 0) {
if (mJianGongList.get(position).isReserve) {
holder.linearLayout.setBackgroundColor(
ContextCompat.getColor(BusActivity.this, R.color.red_600));
holder.textView_location.setText(getString(R.string.bus_jiangong_reserved));
} else {
holder.linearLayout.setBackgroundColor(
ContextCompat.getColor(BusActivity.this, R.color.blue_600));
holder.textView_location.setText(getString(R.string.bus_jiangong));
}
holder.textView_count.setText(
getString(R.string.bus_count, mJianGongList.get(position).reserveCount,
mJianGongList.get(position).limitCount));
holder.textView_time.setText(mJianGongList.get(position).Time);
} else {
if (mYanChaoList.get(position).isReserve) {
holder.linearLayout.setBackgroundColor(
ContextCompat.getColor(BusActivity.this, R.color.red_600));
holder.textView_location.setText(getString(R.string.bus_yanchao_reserved));
} else {
holder.linearLayout.setBackgroundColor(
ContextCompat.getColor(BusActivity.this, R.color.green_600));
holder.textView_location.setText(getString(R.string.bus_yanchao));
}
holder.textView_count.setText(
getString(R.string.bus_count, mYanChaoList.get(position).reserveCount,
mYanChaoList.get(position).limitCount));
holder.textView_time.setText(mYanChaoList.get(position).Time);
}
return convertView;
}
class ViewHolder {
TextView textView_location;
TextView textView_time;
TextView textView_count;
LinearLayout linearLayout;
}
}
}
| |
package modules.vgmdb;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.tonyhsu17.utilities.Logger;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import net.minidev.json.JSONArray;
public class VGMDBParser implements Logger {
/**
* Callback to indicate results have been posted
*/
public interface VGMDBParserCB {
public void done(VGMDBSearchDetails details);
public void done(VGMDBDetails details);
}
/**
* Callback to retrieve the json reponse
*/
private interface RequestResponse {
public void requestComplete(String json);
}
public static final String vgmdbParserURL = "http://vgmdb.info/";
private CloseableHttpClient httpClient;
private VGMDBSearchDetails searchDetails; // cache the last results
private VGMDBDetails albumDetails; // cache the last results
private int selectedIndex; // cache the last index
private List<VGMDBParserCB> callbacks;
public VGMDBParser() {
httpClient = HttpClients.createDefault();
callbacks = new ArrayList<VGMDBParserCB>();
selectedIndex = -1;
}
/**
* Allow multiple callbacks to registered
*
* @param cb {@link VGMDBParserCB}
*/
public void registerCallback(VGMDBParserCB cb) {
callbacks.add(cb);
}
/**
* Unregister callback
*
* @param cb {@link VGMDBParserCB}
* @return True if removed
*/
public boolean unregisterCallback(VGMDBParserCB cb) {
return callbacks.remove(cb);
}
/**
* Remove all callbacks
*/
public void removeAllCallbacks() {
callbacks.clear();
}
/**
* Creates a new thread to grab json from url and callback to return
*
* @param url url to grab json from
* @param isSearch true if is a search, false for album
* @param cb {@link RequestResponse}
*/
private void handleHttpGet(String url, boolean isSearch, RequestResponse cb) {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", "application/json");
new Thread(new Runnable() {
@Override
public void run() {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
Scanner sc = new Scanner(entity.getContent());
StringBuffer buffer = new StringBuffer();
while(sc.hasNextLine()) {
buffer.append(sc.nextLine());
}
sc.close();
String jsonStr = buffer.toString();
EntityUtils.consume(entity);
cb.requestComplete(jsonStr);
}
catch (IOException e) {
}
finally {
try {
response.close();
}
catch (IOException | NullPointerException e) {
}
}
}
}).start();
}
/**
* Search vgmdb by album name
*
* @param album search query
*/
public void searchByAlbum(String album) {
// if there is a search cache, use it
if(searchDetails != null && searchDetails.getQuery().toLowerCase().equals(album.toLowerCase())) {
for(VGMDBParserCB cb : callbacks) {
cb.done(searchDetails);
}
}
// else do a search
else {
String spacesReplaced = album.replace(" ", "%20");
handleHttpGet(vgmdbParserURL + "search/albums/" + spacesReplaced, true, (json) -> {
VGMDBSearchDetails details = parseSearchQuesry(json);
searchDetails = details;
albumDetails = null; // reset album cache since a search was made
selectedIndex = -1; // reset album cache since a search was made
debug("search result: " + details);
for(VGMDBParserCB cb : callbacks) {
cb.done(details);
}
});
}
}
/**
* Get album information based on index of search result
*
* @param index Index of search result to select
* @throws IOException if search not done first or index invalid
*/
public void retrieveAlbumByIndex(int index) throws IOException {
// if out of bounds and such
if(searchDetails == null || index < 0 || index > searchDetails.getIDs().size()) {
throw new IOException("Invalid index or no search has been made initially");
}
else if(selectedIndex == index) {
for(VGMDBParserCB cb : callbacks) {
cb.done(albumDetails);
}
}
else {
debug(searchDetails.getIDs().get(index));
handleHttpGet(vgmdbParserURL + searchDetails.getIDs().get(index), true, (json) -> {
VGMDBDetails details = parseAlbum(json);
albumDetails = details;
selectedIndex = index;
debug("album result: " + details);
for(VGMDBParserCB cb : callbacks) {
cb.done(details);
}
});
}
}
/**
* Parse search query json
*
* @param json
* @return {@link VGMDBSearchDetails}
*/
private VGMDBSearchDetails parseSearchQuesry(String json) {
debug(json);
VGMDBSearchDetails search = new VGMDBSearchDetails();
search.setQuery(JsonPath.read(json, VGMDBPaths.SEARCH_QUERY.path()));
search.setAlbumTitles(JsonPath.read(json, VGMDBPaths.SEARCH_ALBUM_TITLES.path()));
search.setIDs(JsonPath.read(json, VGMDBPaths.SEARCH_ALBUM_ID.path()));
return search;
}
/**
* Parse album json
*
* @param json album json
* @return {@link VGMDBDetails}
*/
private VGMDBDetails parseAlbum(String json) {
debug(json);
VGMDBDetails details = new VGMDBDetails();
try {
details.setSeries(((JSONArray)JsonPath.read(json, VGMDBPaths.SERIES.varience(Variences.JAPANESE).path())).get(0).toString());
}
catch (PathNotFoundException | IndexOutOfBoundsException e) {
try {
details.setSeries(((JSONArray)JsonPath.read(json, VGMDBPaths.SERIES.varience(Variences.ENGLISH).path())).get(0).toString());
}
catch (PathNotFoundException | IndexOutOfBoundsException e2) {
}
}
details.setAlbumArtThumbUrl(JsonPath.read(json, VGMDBPaths.ALBUM_ART_THUMB_URL.path()));
details.setAlbumArtFull(JsonPath.read(json, VGMDBPaths.ALBUM_ART_FULL_URL.path()));
details.setAlbumName(JsonPath.read(json, VGMDBPaths.ALBUM_NAME.path()));
try {
details.setArtists(JsonPath.read(json, VGMDBPaths.ARTIST.varience(Variences.ENGLISH).path()));
}
catch (PathNotFoundException e) {
details.setArtists(JsonPath.read(json, VGMDBPaths.ARTIST.varience(Variences.JAPANESE).path()));
}
details.setAlbumName(JsonPath.read(json, VGMDBPaths.ALBUM_NAME.path()));
try {
details.setReleaseDate(JsonPath.read(json, VGMDBPaths.RELEAST_DATE.path()));
}
catch (PathNotFoundException e) {
}
try {
details.setTracks(JsonPath.read(json, VGMDBPaths.TRACKS.varience(Variences.ENGLISH).path()));
// somehow if path not found it still returned an empty list, so throw an error to be caught
if(details.getTracks().isEmpty()) {
throw new PathNotFoundException();
}
}
catch (PathNotFoundException e) {
try {
details.setTracks(JsonPath.read(json, VGMDBPaths.TRACKS.varience(Variences.ROMANJI).path()));
if(details.getTracks().isEmpty()) {
throw new PathNotFoundException();
}
}
catch (PathNotFoundException e2) {
details.setTracks(JsonPath.read(json, VGMDBPaths.TRACKS.varience(Variences.JAPANESE).path()));
}
}
details.setCatalog(JsonPath.read(json, VGMDBPaths.CATALOG.path()));
details.setAdditionNotes(JsonPath.read(json, VGMDBPaths.ADDITIONAL_NOTES.path()));
List<String> sites = new ArrayList<String>();
sites.add(JsonPath.read(json, VGMDBPaths.SITE_URL.path()));
try {
List<String> siteNames = JsonPath.read(json, VGMDBPaths.OTHER_SITE_NAMES.path());
List<String> siteUrls = JsonPath.read(json, VGMDBPaths.OTHER_SITE_URLS.path());
for(int i = 0; i < siteNames.size(); i++) {
if(siteNames.get(i).contains("CD Japan") || siteNames.get(i).contains("Play-Asia")) {
sites.add(siteUrls.get(i));
}
}
}
catch (PathNotFoundException e) {
}
details.setOtherSites(sites);
return details;
}
}
| |
/*
* Copyright 2011 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.configuration;
import com.google.common.collect.ImmutableList;
import org.gradle.api.JavaVersion;
import org.gradle.api.internal.file.FileCollectionFactory;
import org.gradle.initialization.BuildLayoutParameters;
import org.gradle.internal.jvm.GroovyJpmsWorkarounds;
import org.gradle.internal.jvm.JavaInfo;
import org.gradle.internal.jvm.Jvm;
import org.gradle.util.GUtil;
import javax.annotation.Nullable;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DaemonParameters {
static final int DEFAULT_IDLE_TIMEOUT = 3 * 60 * 60 * 1000;
public static final int DEFAULT_PERIODIC_CHECK_INTERVAL_MILLIS = 10 * 1000;
public static final List<String> DEFAULT_JVM_ARGS = ImmutableList.of("-Xmx512m", "-Xms256m", "-XX:MaxPermSize=256m", "-XX:+HeapDumpOnOutOfMemoryError");
public static final List<String> DEFAULT_JVM_8_ARGS = ImmutableList.of("-Xmx512m", "-Xms256m", "-XX:MaxMetaspaceSize=256m", "-XX:+HeapDumpOnOutOfMemoryError");
public static final List<String> ALLOW_ENVIRONMENT_VARIABLE_OVERWRITE = ImmutableList.of("--add-opens", "java.base/java.util=ALL-UNNAMED");
private final File gradleUserHomeDir;
private File baseDir;
private int idleTimeout = DEFAULT_IDLE_TIMEOUT;
private int periodicCheckInterval = DEFAULT_PERIODIC_CHECK_INTERVAL_MILLIS;
private final DaemonJvmOptions jvmOptions;
private Map<String, String> envVariables;
private boolean enabled = true;
private boolean hasJvmArgs;
private boolean userDefinedImmutableJvmArgs;
private boolean foreground;
private boolean stop;
private boolean status;
private Priority priority = Priority.NORMAL;
private JavaInfo jvm = Jvm.current();
public DaemonParameters(BuildLayoutParameters layout, FileCollectionFactory fileCollectionFactory) {
this(layout, fileCollectionFactory, Collections.<String, String>emptyMap());
}
public DaemonParameters(BuildLayoutParameters layout, FileCollectionFactory fileCollectionFactory, Map<String, String> extraSystemProperties) {
jvmOptions = new DaemonJvmOptions(fileCollectionFactory);
if (!extraSystemProperties.isEmpty()) {
List<String> immutableBefore = jvmOptions.getAllImmutableJvmArgs();
jvmOptions.systemProperties(extraSystemProperties);
List<String> immutableAfter = jvmOptions.getAllImmutableJvmArgs();
userDefinedImmutableJvmArgs = !immutableBefore.equals(immutableAfter);
}
baseDir = new File(layout.getGradleUserHomeDir(), "daemon");
gradleUserHomeDir = layout.getGradleUserHomeDir();
envVariables = new HashMap<String, String>(System.getenv());
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public File getBaseDir() {
return baseDir;
}
public File getGradleUserHomeDir() {
return gradleUserHomeDir;
}
public int getIdleTimeout() {
return idleTimeout;
}
public void setIdleTimeout(int idleTimeout) {
this.idleTimeout = idleTimeout;
}
public int getPeriodicCheckInterval() {
return periodicCheckInterval;
}
public void setPeriodicCheckInterval(int periodicCheckInterval) {
this.periodicCheckInterval = periodicCheckInterval;
}
public List<String> getEffectiveJvmArgs() {
return jvmOptions.getAllImmutableJvmArgs();
}
public List<String> getEffectiveSingleUseJvmArgs() {
return jvmOptions.getAllSingleUseImmutableJvmArgs();
}
public JavaInfo getEffectiveJvm() {
return jvm;
}
@Nullable
public DaemonParameters setJvm(JavaInfo jvm) {
this.jvm = jvm == null ? Jvm.current() : jvm;
return this;
}
public void applyDefaultsFor(JavaVersion javaVersion) {
if (javaVersion.compareTo(JavaVersion.VERSION_1_9) >= 0) {
jvmOptions.jvmArgs(ALLOW_ENVIRONMENT_VARIABLE_OVERWRITE);
jvmOptions.jvmArgs(GroovyJpmsWorkarounds.SUPPRESS_COMMON_GROOVY_WARNINGS);
}
if (hasJvmArgs) {
return;
}
if (javaVersion.compareTo(JavaVersion.VERSION_1_8) >= 0) {
jvmOptions.jvmArgs(DEFAULT_JVM_8_ARGS);
} else {
jvmOptions.jvmArgs(DEFAULT_JVM_ARGS);
}
}
public Map<String, String> getSystemProperties() {
Map<String, String> systemProperties = new HashMap<String, String>();
GUtil.addToMap(systemProperties, jvmOptions.getMutableSystemProperties());
return systemProperties;
}
public Map<String, String> getEffectiveSystemProperties() {
Map<String, String> systemProperties = new HashMap<String, String>();
GUtil.addToMap(systemProperties, jvmOptions.getMutableSystemProperties());
GUtil.addToMap(systemProperties, jvmOptions.getImmutableDaemonProperties());
GUtil.addToMap(systemProperties, System.getProperties());
return systemProperties;
}
public void setJvmArgs(Iterable<String> jvmArgs) {
hasJvmArgs = true;
List<String> immutableBefore = jvmOptions.getAllImmutableJvmArgs();
jvmOptions.setAllJvmArgs(jvmArgs);
List<String> immutableAfter = jvmOptions.getAllImmutableJvmArgs();
userDefinedImmutableJvmArgs = userDefinedImmutableJvmArgs || !immutableBefore.equals(immutableAfter);
}
public boolean hasUserDefinedImmutableJvmArgs() {
return userDefinedImmutableJvmArgs;
}
public void setEnvironmentVariables(Map<String, String> envVariables) {
this.envVariables = envVariables == null ? new HashMap<String, String>(System.getenv()) : envVariables;
}
public void setDebug(boolean debug) {
userDefinedImmutableJvmArgs = userDefinedImmutableJvmArgs || debug;
jvmOptions.setDebug(debug);
}
public DaemonParameters setBaseDir(File baseDir) {
this.baseDir = baseDir;
return this;
}
public boolean getDebug() {
return jvmOptions.getDebug();
}
public boolean isForeground() {
return foreground;
}
public void setForeground(boolean foreground) {
this.foreground = foreground;
}
public boolean isStop() {
return stop;
}
public void setStop(boolean stop) {
this.stop = stop;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Map<String, String> getEnvironmentVariables() {
return envVariables;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public enum Priority {
LOW,
NORMAL,
}
}
| |
/*
* Copyright 2012-2017 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.elasticfilesystem.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateFileSystem" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateFileSystemRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
* </p>
*/
private String creationToken;
/**
* <p>
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance mode
* for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher levels of
* aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file
* operations. This can't be changed after the file system has been created.
* </p>
*/
private String performanceMode;
/**
* <p>
* String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
* </p>
*
* @param creationToken
* String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
*/
public void setCreationToken(String creationToken) {
this.creationToken = creationToken;
}
/**
* <p>
* String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
* </p>
*
* @return String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
*/
public String getCreationToken() {
return this.creationToken;
}
/**
* <p>
* String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
* </p>
*
* @param creationToken
* String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateFileSystemRequest withCreationToken(String creationToken) {
setCreationToken(creationToken);
return this;
}
/**
* <p>
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance mode
* for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher levels of
* aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file
* operations. This can't be changed after the file system has been created.
* </p>
*
* @param performanceMode
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance
* mode for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher
* levels of aggregate throughput and operations per second with a tradeoff of slightly higher latencies for
* most file operations. This can't be changed after the file system has been created.
* @see PerformanceMode
*/
public void setPerformanceMode(String performanceMode) {
this.performanceMode = performanceMode;
}
/**
* <p>
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance mode
* for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher levels of
* aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file
* operations. This can't be changed after the file system has been created.
* </p>
*
* @return The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance
* mode for most file systems. File systems using the <code>maxIO</code> performance mode can scale to
* higher levels of aggregate throughput and operations per second with a tradeoff of slightly higher
* latencies for most file operations. This can't be changed after the file system has been created.
* @see PerformanceMode
*/
public String getPerformanceMode() {
return this.performanceMode;
}
/**
* <p>
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance mode
* for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher levels of
* aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file
* operations. This can't be changed after the file system has been created.
* </p>
*
* @param performanceMode
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance
* mode for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher
* levels of aggregate throughput and operations per second with a tradeoff of slightly higher latencies for
* most file operations. This can't be changed after the file system has been created.
* @return Returns a reference to this object so that method calls can be chained together.
* @see PerformanceMode
*/
public CreateFileSystemRequest withPerformanceMode(String performanceMode) {
setPerformanceMode(performanceMode);
return this;
}
/**
* <p>
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance mode
* for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher levels of
* aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file
* operations. This can't be changed after the file system has been created.
* </p>
*
* @param performanceMode
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance
* mode for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher
* levels of aggregate throughput and operations per second with a tradeoff of slightly higher latencies for
* most file operations. This can't be changed after the file system has been created.
* @see PerformanceMode
*/
public void setPerformanceMode(PerformanceMode performanceMode) {
this.performanceMode = performanceMode.toString();
}
/**
* <p>
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance mode
* for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher levels of
* aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file
* operations. This can't be changed after the file system has been created.
* </p>
*
* @param performanceMode
* The <code>PerformanceMode</code> of the file system. We recommend <code>generalPurpose</code> performance
* mode for most file systems. File systems using the <code>maxIO</code> performance mode can scale to higher
* levels of aggregate throughput and operations per second with a tradeoff of slightly higher latencies for
* most file operations. This can't be changed after the file system has been created.
* @return Returns a reference to this object so that method calls can be chained together.
* @see PerformanceMode
*/
public CreateFileSystemRequest withPerformanceMode(PerformanceMode performanceMode) {
setPerformanceMode(performanceMode);
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 (getCreationToken() != null)
sb.append("CreationToken: ").append(getCreationToken()).append(",");
if (getPerformanceMode() != null)
sb.append("PerformanceMode: ").append(getPerformanceMode());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateFileSystemRequest == false)
return false;
CreateFileSystemRequest other = (CreateFileSystemRequest) obj;
if (other.getCreationToken() == null ^ this.getCreationToken() == null)
return false;
if (other.getCreationToken() != null && other.getCreationToken().equals(this.getCreationToken()) == false)
return false;
if (other.getPerformanceMode() == null ^ this.getPerformanceMode() == null)
return false;
if (other.getPerformanceMode() != null && other.getPerformanceMode().equals(this.getPerformanceMode()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCreationToken() == null) ? 0 : getCreationToken().hashCode());
hashCode = prime * hashCode + ((getPerformanceMode() == null) ? 0 : getPerformanceMode().hashCode());
return hashCode;
}
@Override
public CreateFileSystemRequest clone() {
return (CreateFileSystemRequest) super.clone();
}
}
| |
package org.apache.maven;
/*
* 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 java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.DefaultMavenExecutionResult;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Build;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Repository;
import org.apache.maven.model.RepositoryPolicy;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.codehaus.plexus.ContainerConfiguration;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.FileUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
import org.eclipse.aether.repository.LocalRepository;
public abstract class AbstractCoreMavenComponentTestCase
extends PlexusTestCase
{
@Requirement
protected RepositorySystem repositorySystem;
@Requirement
protected org.apache.maven.project.ProjectBuilder projectBuilder;
protected void setUp()
throws Exception
{
repositorySystem = lookup( RepositorySystem.class );
projectBuilder = lookup( org.apache.maven.project.ProjectBuilder.class );
}
@Override
protected void tearDown()
throws Exception
{
repositorySystem = null;
projectBuilder = null;
super.tearDown();
}
abstract protected String getProjectsDirectory();
protected File getProject( String name )
throws Exception
{
File source = new File( new File( getBasedir(), getProjectsDirectory() ), name );
File target = new File( new File( getBasedir(), "target" ), name );
FileUtils.copyDirectoryStructureIfModified( source, target );
return new File( target, "pom.xml" );
}
/**
* We need to customize the standard Plexus container with the plugin discovery listener which
* is what looks for the META-INF/maven/plugin.xml resources that enter the system when a Maven
* plugin is loaded.
*
* We also need to customize the Plexus container with a standard plugin discovery listener
* which is the MavenPluginCollector. When a Maven plugin is discovered the MavenPluginCollector
* collects the plugin descriptors which are found.
*/
protected void customizeContainerConfiguration( ContainerConfiguration containerConfiguration )
{
containerConfiguration.setAutoWiring( true ).setClassPathScanning( PlexusConstants.SCANNING_INDEX );
}
protected MavenExecutionRequest createMavenExecutionRequest( File pom )
throws Exception
{
MavenExecutionRequest request = new DefaultMavenExecutionRequest()
.setPom( pom )
.setProjectPresent( true )
.setShowErrors( true )
.setPluginGroups( Arrays.asList( "org.apache.maven.plugins" ) )
.setLocalRepository( getLocalRepository() )
.setRemoteRepositories( getRemoteRepositories() )
.setPluginArtifactRepositories( getPluginArtifactRepositories() )
.setGoals( Arrays.asList( "package" ) );
return request;
}
// layer the creation of a project builder configuration with a request, but this will need to be
// a Maven subclass because we don't want to couple maven to the project builder which we need to
// separate.
protected MavenSession createMavenSession( File pom )
throws Exception
{
return createMavenSession( pom, new Properties() );
}
protected MavenSession createMavenSession( File pom, Properties executionProperties )
throws Exception
{
return createMavenSession( pom, executionProperties, false );
}
protected MavenSession createMavenSession( File pom, Properties executionProperties, boolean includeModules )
throws Exception
{
MavenExecutionRequest request = createMavenExecutionRequest( pom );
ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest()
.setLocalRepository( request.getLocalRepository() )
.setRemoteRepositories( request.getRemoteRepositories() )
.setPluginArtifactRepositories( request.getPluginArtifactRepositories() )
.setSystemProperties( executionProperties );
List<MavenProject> projects = new ArrayList<>();
if ( pom != null )
{
MavenProject project = projectBuilder.build( pom, configuration ).getProject();
projects.add( project );
if ( includeModules )
{
for( String module : project.getModules() )
{
File modulePom = new File( pom.getParentFile(), module );
if( modulePom.isDirectory() )
{
modulePom = new File( modulePom, "pom.xml" );
}
projects.add( projectBuilder.build( modulePom, configuration ).getProject() );
}
}
}
else
{
MavenProject project = createStubMavenProject();
project.setRemoteArtifactRepositories( request.getRemoteRepositories() );
project.setPluginArtifactRepositories( request.getPluginArtifactRepositories() );
projects.add( project );
}
initRepoSession( configuration );
MavenSession session =
new MavenSession( getContainer(), configuration.getRepositorySession(), request,
new DefaultMavenExecutionResult() );
session.setProjects( projects );
session.setAllProjects( session.getProjects() );
return session;
}
protected void initRepoSession( ProjectBuildingRequest request )
throws Exception
{
File localRepoDir = new File( request.getLocalRepository().getBasedir() );
LocalRepository localRepo = new LocalRepository( localRepoDir );
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( session, localRepo ) );
request.setRepositorySession( session );
}
protected MavenProject createStubMavenProject()
{
Model model = new Model();
model.setGroupId( "org.apache.maven.test" );
model.setArtifactId( "maven-test" );
model.setVersion( "1.0" );
return new MavenProject( model );
}
protected List<ArtifactRepository> getRemoteRepositories()
throws InvalidRepositoryException
{
File repoDir = new File( getBasedir(), "src/test/remote-repo" ).getAbsoluteFile();
RepositoryPolicy policy = new RepositoryPolicy();
policy.setEnabled( true );
policy.setChecksumPolicy( "ignore" );
policy.setUpdatePolicy( "always" );
Repository repository = new Repository();
repository.setId( RepositorySystem.DEFAULT_REMOTE_REPO_ID );
repository.setUrl( "file://" + repoDir.toURI().getPath() );
repository.setReleases( policy );
repository.setSnapshots( policy );
return Arrays.asList( repositorySystem.buildArtifactRepository( repository ) );
}
protected List<ArtifactRepository> getPluginArtifactRepositories()
throws InvalidRepositoryException
{
return getRemoteRepositories();
}
protected ArtifactRepository getLocalRepository()
throws InvalidRepositoryException
{
File repoDir = new File( getBasedir(), "target/local-repo" ).getAbsoluteFile();
return repositorySystem.createLocalRepository( repoDir );
}
protected class ProjectBuilder
{
private MavenProject project;
public ProjectBuilder( MavenProject project )
{
this.project = project;
}
public ProjectBuilder( String groupId, String artifactId, String version )
{
Model model = new Model();
model.setModelVersion( "4.0.0" );
model.setGroupId( groupId );
model.setArtifactId( artifactId );
model.setVersion( version );
model.setBuild( new Build() );
project = new MavenProject( model );
}
public ProjectBuilder setGroupId( String groupId )
{
project.setGroupId( groupId );
return this;
}
public ProjectBuilder setArtifactId( String artifactId )
{
project.setArtifactId( artifactId );
return this;
}
public ProjectBuilder setVersion( String version )
{
project.setVersion( version );
return this;
}
// Dependencies
//
public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope )
{
return addDependency( groupId, artifactId, version, scope, (Exclusion)null );
}
public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope, Exclusion exclusion )
{
return addDependency( groupId, artifactId, version, scope, null, exclusion );
}
public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope, String systemPath )
{
return addDependency( groupId, artifactId, version, scope, systemPath, null );
}
public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope, String systemPath, Exclusion exclusion )
{
Dependency d = new Dependency();
d.setGroupId( groupId );
d.setArtifactId( artifactId );
d.setVersion( version );
d.setScope( scope );
if ( systemPath != null && scope.equals( Artifact.SCOPE_SYSTEM ) )
{
d.setSystemPath( systemPath );
}
if ( exclusion != null )
{
d.addExclusion( exclusion );
}
project.getDependencies().add( d );
return this;
}
// Plugins
//
public ProjectBuilder addPlugin( Plugin plugin )
{
project.getBuildPlugins().add( plugin );
return this;
}
public MavenProject get()
{
return project;
}
}
}
| |
package com.github.duke605.dce.util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.awt.image.BufferedImage;
public class DrawingUtils {
/**
* Draws a scaled image to the screen
*
* @param xCoord The x coordinate where the image will be on the screen
* @param yCoord The y coordinate where the image will be drawn on the screen
* @param xLoc The x position of the image in the image file
* @param yLoc The y position of the image in the image file
* @param xSize The width of the image in the image file
* @param ySize The height of the image in the image file
* @param scale The scaling of the image
* @param image The {@link ResourceLocation} of the image
* @param red
* @param green
* @param blue
*/
public static void drawScaledImage(float xCoord, float yCoord, int xLoc, int yLoc, int xSize, int ySize, float scale, ResourceLocation image, double red, double green, double blue, float imageWidth, float imageHeight) {
drawScaledImage(xCoord, yCoord, xLoc, yLoc, xSize, ySize, scale, image, red, green, blue, 1, imageWidth, imageHeight);
}
/**
* Draws a scaled image to the screen
*
* @param xCoord The x coordinate where the image will be on the screen
* @param yCoord The y coordinate where the image will be drawn on the screen
* @param xLoc The x position of the image in the image file
* @param yLoc The y position of the image in the image file
* @param xSize The width of the image in the image file
* @param ySize The height of the image in the image file
* @param scale The scaling of the image
* @param image The {@link ResourceLocation} of the image
* @param red
* @param green
* @param blue
* @param alpha
*/
public static void drawScaledImage(float xCoord, float yCoord, int xLoc, int yLoc, int xSize, int ySize
, float scale, ResourceLocation image, double red, double green, double blue, double alpha, float imageWidth
, float imageHeight) {
Gui gui = Minecraft.getMinecraft().currentScreen;
if (gui == null)
return;
GL11.glPushMatrix();
Minecraft.getMinecraft().getTextureManager().bindTexture(image);
GL11.glColor4d(red/0xff, green/0xff, blue/0xff, alpha);
GL11.glEnable(3042);
GL11.glTranslatef(xCoord, yCoord, 1.0F);
GL11.glScaled(scale, scale, 1.0F);
Gui.drawModalRectWithCustomSizedTexture(0, 0, xLoc, yLoc, xSize, ySize, imageWidth, imageHeight);
GL11.glColor4d(1, 1, 1, 1);
GL11.glPopMatrix();
}
/**
* Draws a rounded rectangle on the screen
*
* @param xCoord The x coordinate where the rectangle will be on the screen
* @param yCoord The y coordinate where the rectangle will be on the screen
* @param xSize The width of the rectangle
* @param ySize The height of the rectangle
* @param colour The colour of the rectangle
* @param text The string of text that will be drawn on the rectangle
*/
public static void drawRoundedRect(int xCoord, int yCoord, int xSize, int ySize, int colour, String text) {
int width = xCoord + xSize;
int height = yCoord + ySize;
// Top rounding
Gui.drawRect(xCoord + 1, yCoord, width - 1, height, colour);
// Middle rect
Gui.drawRect(xCoord, yCoord + 1, width, height - 1, colour);
DrawingUtils.drawCenteredUnicodeString(text, xCoord + (xSize / 2), yCoord, 0xFFFFFF);
}
/**
* Draws a centered unicode string on the screen
*
* @param text The text that will be drawn to the screen
* @param xCoord The x position of the text
* @param yCoord The y position of the text
* @param colour The colour of the text
*/
public static void drawCenteredUnicodeString(String text, int xCoord, int yCoord, int colour) {
FontRenderer font = Minecraft.getMinecraft().fontRendererObj;
boolean prevFlag;
// Remembering unicode flag
prevFlag = font.getUnicodeFlag();
font.setUnicodeFlag(true);
font.drawString(text, xCoord - (font.getStringWidth(text) / 2), yCoord, colour);
font.setUnicodeFlag(prevFlag);
}
/**
* Draws a scaled string
*
* @param text The text that will be drawn
* @param xCoord The x position of where the text will be drawn
* @param yCoord The y position of where the text will be drawn
* @param scale The scale of the text
* @param colour The colour of the text
* @param unicodeFlag If the text should be in unicode
*/
public static void drawScaledString(String text, int xCoord, int yCoord, float scale, int colour, boolean unicodeFlag) {
FontRenderer font = Minecraft.getMinecraft().fontRendererObj;
boolean prevFlag;
// Remembering unicode flag
prevFlag = font.getUnicodeFlag();
font.setUnicodeFlag(unicodeFlag);
GL11.glPushMatrix();
// Positioning text
GL11.glTranslated(xCoord, yCoord, 0.0);
// Scaling text
GL11.glScalef(scale, scale, 1.0F);
// Drawing text
font.drawString(text, 0, 0, colour);
GL11.glPopMatrix();
font.setUnicodeFlag(prevFlag);
}
/**
* Draws a small unicode string on the screen that wraps
*
* @param text The text that will be drawn on the screen
* @param xCoord The x position of the text
* @param yCoord The y position of the text
* @param colour The colour of the text
* @param width The width of the string before it wraps
*/
public static void drawSplitUnicodeString(String text, int xCoord, int yCoord, int colour, int width) {
FontRenderer font = Minecraft.getMinecraft().fontRendererObj;
boolean prevFlag;
// Remembering unicode flag
prevFlag = font.getUnicodeFlag();
font.setUnicodeFlag(true);
font.drawSplitString(text, xCoord, yCoord, width, colour);
font.setUnicodeFlag(prevFlag);
}
/**
* Draws a small unicode string on the screen
*
* @param text The text that will be drawn to the screen
* @param xCoord The x position of the text
* @param yCoord The y position of the text
* @param colour The colour of the text
*/
public static void drawUnicodeString(String text, int xCoord, int yCoord, int colour) {
FontRenderer font = Minecraft.getMinecraft().fontRendererObj;
boolean prevFlag;
// Remembering unicode flag
prevFlag = font.getUnicodeFlag();
font.setUnicodeFlag(true);
font.drawString(text, xCoord, yCoord, colour);
font.setUnicodeFlag(prevFlag);
}
/**
* Gets the length of a string of unicode characters
*
* @param unicodeString a String of unicode characters
* @return the length of the unicodeString
*/
public static int getUnicodeStringWidth(String unicodeString) {
FontRenderer font = Minecraft.getMinecraft().fontRendererObj;
boolean prevFlag;
int stringLength;
// Storing previous unicode flag
prevFlag = font.getUnicodeFlag();
font.setUnicodeFlag(true);
stringLength = font.getStringWidth(unicodeString);
font.setUnicodeFlag(prevFlag);
return stringLength;
}
/**
* Makes an image circular
*
* @param image The image to make circular
* @return a circular image of the one passed in
*/
public static BufferedImage circularize(BufferedImage image)
{
// Making image circular
BufferedImage out = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = out.createGraphics();
try {
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setColor(Color.BLACK); // The color here doesn't really matter
graphics.fillOval(0, 0, image.getWidth(), image.getHeight());
graphics.setComposite(AlphaComposite.SrcIn); // Only paint inside the oval from now on
graphics.drawImage(image, 0, 0, null);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally {
graphics.dispose();
}
return out;
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.discovery;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.servlet.GuiceFilter;
import io.druid.curator.discovery.ServerDiscoverySelector;
import io.druid.guice.GuiceInjectors;
import io.druid.guice.Jerseys;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.LazySingleton;
import io.druid.guice.LifecycleModule;
import io.druid.guice.annotations.Self;
import io.druid.initialization.Initialization;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.http.client.HttpClient;
import io.druid.java.util.http.client.Request;
import io.druid.server.DruidNode;
import io.druid.server.initialization.BaseJettyTest;
import io.druid.server.initialization.jetty.JettyServerInitializer;
import org.easymock.EasyMock;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
/**
*/
public class DruidLeaderClientTest extends BaseJettyTest
{
@Rule
public ExpectedException expectedException = ExpectedException.none();
private DiscoveryDruidNode discoveryDruidNode;
private HttpClient httpClient;
@Override
protected Injector setupInjector()
{
final DruidNode node = new DruidNode("test", "localhost", null, null, true, false);
discoveryDruidNode = new DiscoveryDruidNode(node, "test", ImmutableMap.of());
Injector injector = Initialization.makeInjectorWithModules(
GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of(
new Module()
{
@Override
public void configure(Binder binder)
{
JsonConfigProvider.bindInstance(
binder,
Key.get(DruidNode.class, Self.class),
node
);
binder.bind(Integer.class).annotatedWith(Names.named("port")).toInstance(node.getPlaintextPort());
binder.bind(JettyServerInitializer.class).to(TestJettyServerInitializer.class).in(LazySingleton.class);
Jerseys.addResource(binder, SimpleResource.class);
LifecycleModule.register(binder, Server.class);
}
}
)
);
httpClient = injector.getInstance(ClientHolder.class).getClient();
return injector;
}
@Test
public void testSimple() throws Exception
{
DruidNodeDiscovery druidNodeDiscovery = EasyMock.createMock(DruidNodeDiscovery.class);
EasyMock.expect(druidNodeDiscovery.getAllNodes()).andReturn(
ImmutableList.of(discoveryDruidNode)
);
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider = EasyMock.createMock(DruidNodeDiscoveryProvider.class);
EasyMock.expect(druidNodeDiscoveryProvider.getForNodeType("nodetype")).andReturn(druidNodeDiscovery);
EasyMock.replay(druidNodeDiscovery, druidNodeDiscoveryProvider);
DruidLeaderClient druidLeaderClient = new DruidLeaderClient(
httpClient,
druidNodeDiscoveryProvider,
"nodetype",
"/simple/leader",
EasyMock.createNiceMock(ServerDiscoverySelector.class)
);
druidLeaderClient.start();
Request request = druidLeaderClient.makeRequest(HttpMethod.POST, "/simple/direct");
request.setContent("hello".getBytes("UTF-8"));
Assert.assertEquals("hello", druidLeaderClient.go(request).getContent());
}
@Test
public void testNoLeaderFound() throws Exception
{
DruidNodeDiscovery druidNodeDiscovery = EasyMock.createMock(DruidNodeDiscovery.class);
EasyMock.expect(druidNodeDiscovery.getAllNodes()).andReturn(ImmutableList.of());
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider = EasyMock.createMock(DruidNodeDiscoveryProvider.class);
EasyMock.expect(druidNodeDiscoveryProvider.getForNodeType("nodetype")).andReturn(druidNodeDiscovery);
EasyMock.replay(druidNodeDiscovery, druidNodeDiscoveryProvider);
DruidLeaderClient druidLeaderClient = new DruidLeaderClient(
httpClient,
druidNodeDiscoveryProvider,
"nodetype",
"/simple/leader",
EasyMock.createNiceMock(ServerDiscoverySelector.class)
);
druidLeaderClient.start();
expectedException.expect(IOException.class);
expectedException.expectMessage("No known server");
druidLeaderClient.makeRequest(HttpMethod.POST, "/simple/direct");
}
@Test
public void testRedirection() throws Exception
{
DruidNodeDiscovery druidNodeDiscovery = EasyMock.createMock(DruidNodeDiscovery.class);
EasyMock.expect(druidNodeDiscovery.getAllNodes()).andReturn(
ImmutableList.of(discoveryDruidNode)
);
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider = EasyMock.createMock(DruidNodeDiscoveryProvider.class);
EasyMock.expect(druidNodeDiscoveryProvider.getForNodeType("nodetype")).andReturn(druidNodeDiscovery);
EasyMock.replay(druidNodeDiscovery, druidNodeDiscoveryProvider);
DruidLeaderClient druidLeaderClient = new DruidLeaderClient(
httpClient,
druidNodeDiscoveryProvider,
"nodetype",
"/simple/leader",
EasyMock.createNiceMock(ServerDiscoverySelector.class)
);
druidLeaderClient.start();
Request request = druidLeaderClient.makeRequest(HttpMethod.POST, "/simple/redirect");
request.setContent("hello".getBytes("UTF-8"));
Assert.assertEquals("hello", druidLeaderClient.go(request).getContent());
}
@Test
public void testServerFailureAndRedirect() throws Exception
{
ServerDiscoverySelector serverDiscoverySelector = EasyMock.createMock(ServerDiscoverySelector.class);
EasyMock.expect(serverDiscoverySelector.pick()).andReturn(null).anyTimes();
DruidNodeDiscovery druidNodeDiscovery = EasyMock.createMock(DruidNodeDiscovery.class);
EasyMock.expect(druidNodeDiscovery.getAllNodes()).andReturn(
ImmutableList.of(new DiscoveryDruidNode(
new DruidNode("test", "dummyhost", 64231, null, true, false),
"test",
ImmutableMap.of()
))
);
EasyMock.expect(druidNodeDiscovery.getAllNodes()).andReturn(
ImmutableList.of(discoveryDruidNode)
);
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider = EasyMock.createMock(DruidNodeDiscoveryProvider.class);
EasyMock.expect(druidNodeDiscoveryProvider.getForNodeType("nodetype")).andReturn(druidNodeDiscovery).anyTimes();
EasyMock.replay(serverDiscoverySelector, druidNodeDiscovery, druidNodeDiscoveryProvider);
DruidLeaderClient druidLeaderClient = new DruidLeaderClient(
httpClient,
druidNodeDiscoveryProvider,
"nodetype",
"/simple/leader",
serverDiscoverySelector
);
druidLeaderClient.start();
Request request = druidLeaderClient.makeRequest(HttpMethod.POST, "/simple/redirect");
request.setContent("hello".getBytes("UTF-8"));
Assert.assertEquals("hello", druidLeaderClient.go(request).getContent());
}
@Test
public void testFindCurrentLeader()
{
DruidNodeDiscovery druidNodeDiscovery = EasyMock.createMock(DruidNodeDiscovery.class);
EasyMock.expect(druidNodeDiscovery.getAllNodes()).andReturn(
ImmutableList.of(discoveryDruidNode)
);
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider = EasyMock.createMock(DruidNodeDiscoveryProvider.class);
EasyMock.expect(druidNodeDiscoveryProvider.getForNodeType("nodetype")).andReturn(druidNodeDiscovery);
EasyMock.replay(druidNodeDiscovery, druidNodeDiscoveryProvider);
DruidLeaderClient druidLeaderClient = new DruidLeaderClient(
httpClient,
druidNodeDiscoveryProvider,
"nodetype",
"/simple/leader",
EasyMock.createNiceMock(ServerDiscoverySelector.class)
);
druidLeaderClient.start();
Assert.assertEquals("http://localhost:1234/", druidLeaderClient.findCurrentLeader());
}
private static class TestJettyServerInitializer implements JettyServerInitializer
{
@Override
public void initialize(Server server, Injector injector)
{
final ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
root.addServlet(new ServletHolder(new DefaultServlet()), "/*");
root.addFilter(GuiceFilter.class, "/*", null);
final HandlerList handlerList = new HandlerList();
handlerList.setHandlers(new Handler[]{root});
server.setHandler(handlerList);
}
}
@Path("/simple")
public static class SimpleResource
{
private final int port;
@Inject
public SimpleResource(@Named("port") int port)
{
this.port = port;
}
@POST
@Path("/direct")
@Produces(MediaType.APPLICATION_JSON)
public Response direct(String input)
{
if ("hello".equals(input)) {
return Response.ok("hello").build();
} else {
return Response.serverError().build();
}
}
@POST
@Path("/redirect")
@Produces(MediaType.APPLICATION_JSON)
public Response redirecting() throws Exception
{
return Response.temporaryRedirect(new URI(StringUtils.format("http://localhost:%s/simple/direct", port))).build();
}
@GET
@Path("/leader")
@Produces(MediaType.APPLICATION_JSON)
public Response leader()
{
return Response.ok("http://localhost:1234/").build();
}
}
}
| |
/*
* Copyright 2021 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.biosamples;
import java.time.Instant;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.hateoas.Resource;
import org.springframework.stereotype.Component;
import uk.ac.ebi.biosamples.client.BioSamplesClient;
import uk.ac.ebi.biosamples.model.Attribute;
import uk.ac.ebi.biosamples.model.ExternalReference;
import uk.ac.ebi.biosamples.model.Sample;
import uk.ac.ebi.biosamples.utils.IntegrationTestFailException;
@Component
@Order(3)
// @Profile({"default","rest"})
public class RestFacetIntegration extends AbstractIntegration {
private Logger log = LoggerFactory.getLogger(this.getClass());
private final IntegrationProperties integrationProperties;
private final BioSamplesProperties bioSamplesProperties;
public RestFacetIntegration(
BioSamplesClient client,
IntegrationProperties integrationProperties,
BioSamplesProperties bioSamplesProperties) {
super(client);
this.integrationProperties = integrationProperties;
this.bioSamplesProperties = bioSamplesProperties;
}
@Override
protected void phaseOne() {
Sample sampleTest1 = getSampleTest1();
Sample enaSampleTest = getEnaSampleTest();
Sample aeSampleTest = getArrayExpressSampleTest();
// put a sample
Resource<Sample> resource = client.persistSampleResource(sampleTest1);
sampleTest1 =
Sample.Builder.fromSample(sampleTest1)
.withAccession(resource.getContent().getAccession())
.build();
if (!sampleTest1.equals(resource.getContent())) {
throw new IntegrationTestFailException(
"Expected response ("
+ resource.getContent()
+ ") to equal submission ("
+ sampleTest1
+ ")",
Phase.ONE);
}
resource = client.persistSampleResource(enaSampleTest);
enaSampleTest =
Sample.Builder.fromSample(enaSampleTest)
.withAccession(resource.getContent().getAccession())
.build();
if (!enaSampleTest.equals(resource.getContent())) {
throw new IntegrationTestFailException(
"Expected response ("
+ resource.getContent()
+ ") to equal submission ("
+ enaSampleTest
+ ")",
Phase.ONE);
}
resource = client.persistSampleResource(aeSampleTest);
aeSampleTest =
Sample.Builder.fromSample(aeSampleTest)
.withAccession(resource.getContent().getAccession())
.build();
if (!aeSampleTest.equals(resource.getContent())) {
throw new IntegrationTestFailException(
"Expected response ("
+ resource.getContent()
+ ") to equal submission ("
+ aeSampleTest
+ ")",
Phase.ONE);
}
}
@Override
protected void phaseTwo() {
/*
* disable untill we can properly implement a facet format
Map<String, Object> parameters = new HashMap<>();
parameters.put("text","TESTrestfacet1");
Traverson traverson = new Traverson(bioSamplesProperties.getBiosamplesClientUri(), MediaTypes.HAL_JSON);
Traverson.TraversalBuilder builder = traverson.follow("samples", "facet").withTemplateParameters(parameters);
Resources<Facet> facets = builder.toObject(new TypeReferences.ResourcesType<Facet>(){});
log.info("GETting from " + builder.asLink().expand(parameters).getHref());
if (facets.getContent().size() <= 0) {
throw new RuntimeException("No facets found!");
}
List<Facet> content = new ArrayList<>(facets.getContent());
FacetContent facetContent = content.get(0).getContent();
if (facetContent instanceof LabelCountListContent) {
if (((LabelCountListContent) facetContent).size() <= 0) {
throw new RuntimeException("No facet values found!");
}
}
*/
// TODO check that the particular facets we expect are present
}
@Override
protected void phaseThree() {
/*
* disable untill we can properly implement a facet format
Sample enaSample = getEnaSampleTest();
SortedSet<ExternalReference> sampleExternalRefs = enaSample.getExternalReferences();
Map<String, Object> parameters = new HashMap<>();
parameters.put("text",enaSample.getAccession());
Traverson traverson = new Traverson(bioSamplesProperties.getBiosamplesClientUri(), MediaTypes.HAL_JSON);
Traverson.TraversalBuilder builder = traverson.follow("samples", "facet").withTemplateParameters(parameters);
Resources<Facet> facets = builder.toObject(new TypeReferences.ResourcesType<Facet>(){});
log.info("GETting from " + builder.asLink().expand(parameters).getHref());
if (facets.getContent().isEmpty()) {
throw new RuntimeException("Facet endpoint does not contain the expected number of facet");
}
List<ExternalReferenceDataFacet> externalDataFacetList = facets.getContent().stream()
.filter(facet -> facet.getType().equals(FacetType.EXTERNAL_REFERENCE_DATA_FACET))
.map(facet -> (ExternalReferenceDataFacet) facet)
.collect(Collectors.toList());
for (ExternalReferenceDataFacet facet: externalDataFacetList) {
List<String> facetContentLabels = facet.getContent().stream().map(LabelCountEntry::getLabel).collect(Collectors.toList());
for (String extRefDataId: facetContentLabels) {
boolean found = sampleExternalRefs.stream().anyMatch(extRef -> extRef.getUrl().toLowerCase().endsWith(extRefDataId.toLowerCase()));
if (!found) {
throw new RuntimeException("Facet content does not contain expected external reference data id");
}
}
}
*/
}
@Override
protected void phaseFour() {}
@Override
protected void phaseFive() {}
private Sample getSampleTest1() {
String name = "RestFacetIntegration_testRestFacet";
Instant update = Instant.parse("2016-05-05T11:36:57.00Z");
Instant release = Instant.parse("2016-04-01T11:36:57.00Z");
SortedSet<Attribute> attributes = new TreeSet<>();
attributes.add(
Attribute.build(
"organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null));
// use non alphanumeric characters in type
attributes.add(Attribute.build("geographic location (country and/or sea)", "Land of Oz"));
return new Sample.Builder(name)
.withDomain(defaultIntegrationSubmissionDomain)
.withRelease(release)
.withUpdate(update)
.withAttributes(attributes)
.build();
}
private Sample getEnaSampleTest() {
String name = "RestFacetIntegration_testEnaRestFacet";
Instant update = Instant.parse("2015-03-22T08:30:23.00Z");
Instant release = Instant.parse("2015-03-22T08:30:23.00Z");
SortedSet<Attribute> attributes = new TreeSet<>();
attributes.add(
Attribute.build(
"organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null));
// use non alphanumeric characters in type
attributes.add(Attribute.build("geographic location (country and/or sea)", "Land of Oz"));
SortedSet<ExternalReference> externalReferences = new TreeSet<>();
externalReferences.add(
ExternalReference.build(
"https://www.ebi.ac.uk/ena/ERA123123",
new TreeSet<>(Arrays.asList("DUO:0000005", "DUO:0000001", "DUO:0000007"))));
externalReferences.add(
ExternalReference.build("http://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-09123"));
return new Sample.Builder(name)
.withDomain(defaultIntegrationSubmissionDomain)
.withRelease(release)
.withUpdate(update)
.withAttributes(attributes)
.withExternalReferences(externalReferences)
.build();
}
private Sample getArrayExpressSampleTest() {
String name = "RestFacetIntegration_testArrayExpressRestFacet";
Instant update = Instant.parse("2015-03-22T08:30:23.00Z");
Instant release = Instant.parse("2015-03-22T08:30:23.00Z");
SortedSet<Attribute> attributes = new TreeSet<>();
attributes.add(
Attribute.build(
"organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null));
// use non alphanumeric characters in type
attributes.add(Attribute.build("geographic location (country and/or sea)", "Land of Oz"));
SortedSet<ExternalReference> externalReferences = new TreeSet<>();
externalReferences.add(
ExternalReference.build("http://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-5277"));
return new Sample.Builder(name)
.withDomain(defaultIntegrationSubmissionDomain)
.withRelease(release)
.withUpdate(update)
.withAttributes(attributes)
.withExternalReferences(externalReferences)
.build();
}
}
| |
package org.jboss.resteasy.core;
import org.jboss.resteasy.core.interception.PreMatchContainerRequestContext;
import org.jboss.resteasy.plugins.server.servlet.Cleanable;
import org.jboss.resteasy.plugins.server.servlet.Cleanables;
import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
import org.jboss.resteasy.specimpl.BuiltResponse;
import org.jboss.resteasy.specimpl.RequestImpl;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpRequestPreprocessor;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.InternalDispatcher;
import org.jboss.resteasy.spi.InternalServerErrorException;
import org.jboss.resteasy.spi.Registry;
import org.jboss.resteasy.spi.ResteasyAsynchronousContext;
import org.jboss.resteasy.spi.ResteasyConfiguration;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.UnhandledException;
import org.jboss.resteasy.util.HttpHeaderNames;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@SuppressWarnings("unchecked")
public class SynchronousDispatcher implements Dispatcher
{
protected ResteasyProviderFactory providerFactory;
protected Registry registry;
protected List<HttpRequestPreprocessor> requestPreprocessors = new ArrayList<HttpRequestPreprocessor>();
protected Map<Class, Object> defaultContextObjects = new HashMap<Class, Object>();
protected Set<String> unwrappedExceptions = new HashSet<String>();
protected boolean bufferExceptionEntityRead = false;
protected boolean bufferExceptionEntity = true;
public SynchronousDispatcher(ResteasyProviderFactory providerFactory)
{
this.providerFactory = providerFactory;
this.registry = new ResourceMethodRegistry(providerFactory);
defaultContextObjects.put(Providers.class, providerFactory);
defaultContextObjects.put(Registry.class, registry);
defaultContextObjects.put(Dispatcher.class, this);
defaultContextObjects.put(InternalDispatcher.class, InternalDispatcher.getInstance());
}
public SynchronousDispatcher(ResteasyProviderFactory providerFactory, ResourceMethodRegistry registry)
{
this(providerFactory);
this.registry = registry;
defaultContextObjects.put(Registry.class, registry);
}
public ResteasyProviderFactory getProviderFactory()
{
return providerFactory;
}
public Registry getRegistry()
{
return registry;
}
public Map<Class, Object> getDefaultContextObjects()
{
return defaultContextObjects;
}
public Set<String> getUnwrappedExceptions()
{
return unwrappedExceptions;
}
public Response preprocess(HttpRequest request)
{
Response aborted = null;
try
{
for (HttpRequestPreprocessor preprocessor : this.requestPreprocessors)
{
preprocessor.preProcess(request);
}
ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch();
PreMatchContainerRequestContext requestContext = new PreMatchContainerRequestContext(request);
for (ContainerRequestFilter filter : requestFilters)
{
filter.filter(requestContext);
aborted = requestContext.getResponseAbortedWith();
if (aborted != null) break;
}
}
catch (Exception e)
{
//logger.error("Failed in preprocess, mapping exception", e);
aborted = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
}
return aborted;
}
/**
* Call pre-process ContainerRequestFilters
*
* @return true if request should continue
*/
protected boolean preprocess(HttpRequest request, HttpResponse response)
{
Response aborted = null;
try
{
for (HttpRequestPreprocessor preprocessor : this.requestPreprocessors)
{
preprocessor.preProcess(request);
}
ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch();
PreMatchContainerRequestContext requestContext = new PreMatchContainerRequestContext(request);
for (ContainerRequestFilter filter : requestFilters)
{
filter.filter(requestContext);
aborted = requestContext.getResponseAbortedWith();
if (aborted != null) break;
}
}
catch (Exception e)
{
//logger.error("Failed in preprocess, mapping exception", e);
writeException(request, response, e);
return false;
}
if (aborted != null)
{
writeResponse(request, response, aborted);
return false;
}
return true;
}
public void writeException(HttpRequest request, HttpResponse response, Throwable e)
{
if (!bufferExceptionEntityRead)
{
bufferExceptionEntityRead = true;
ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class);
if (context != null)
{
String s = context.getParameter("resteasy.buffer.exception.entity");
if (s != null)
{
bufferExceptionEntity = Boolean.parseBoolean(s);
}
}
}
if (response.isCommitted()) throw new UnhandledException(Messages.MESSAGES.responseIsCommitted(), e);
Response handledResponse = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
if (handledResponse == null) throw new UnhandledException(e);
if (!bufferExceptionEntity)
{
response.getOutputHeaders().add("resteasy.buffer.exception.entity", "false");
}
try
{
ServerResponseWriter.writeNomapResponse(((BuiltResponse) handledResponse), request, response, providerFactory);
}
catch (Exception e1)
{
throw new UnhandledException(e1);
}
}
public void invoke(HttpRequest request, HttpResponse response)
{
try
{
pushContextObjects(request, response);
if (!preprocess(request, response)) return;
ResourceInvoker invoker = null;
try
{
invoker = getInvoker(request);
}
catch (Exception exception)
{
//logger.error("getInvoker() failed mapping exception", exception);
writeException(request, response, exception);
return;
}
invoke(request, response, invoker);
}
finally
{
clearContextData();
}
}
/**
* Propagate NotFoundException. This is used for Filters
*
* @param request
* @param response
*/
public void invokePropagateNotFound(HttpRequest request, HttpResponse response) throws NotFoundException
{
try
{
pushContextObjects(request, response);
if (!preprocess(request, response)) return;
ResourceInvoker invoker = null;
try
{
invoker = getInvoker(request);
}
catch (Exception failure)
{
if (failure instanceof NotFoundException)
{
throw ((NotFoundException) failure);
}
else
{
//logger.error("getInvoker() failed mapping exception", failure);
writeException(request, response, failure);
return;
}
}
invoke(request, response, invoker);
}
finally
{
clearContextData();
}
}
public ResourceInvoker getInvoker(HttpRequest request)
throws Failure
{
LogMessages.LOGGER.pathInfo(request.getUri().getPath());
if (!request.isInitial())
{
throw new InternalServerErrorException(Messages.MESSAGES.isNotInitialRequest(request.getUri().getPath()));
}
ResourceInvoker invoker = registry.getResourceInvoker(request);
if (invoker == null)
{
throw new NotFoundException(Messages.MESSAGES.unableToFindJaxRsResource(request.getUri().getPath()));
}
return invoker;
}
public void pushContextObjects(final HttpRequest request, final HttpResponse response)
{
Map contextDataMap = ResteasyProviderFactory.getContextDataMap();
contextDataMap.put(HttpRequest.class, request);
contextDataMap.put(HttpResponse.class, response);
contextDataMap.put(HttpHeaders.class, request.getHttpHeaders());
contextDataMap.put(UriInfo.class, request.getUri());
contextDataMap.put(Request.class, new RequestImpl(request, response));
contextDataMap.put(ResteasyAsynchronousContext.class, request.getAsyncContext());
ResourceContext resourceContext = new ResourceContext()
{
@Override
public <T> T getResource(Class<T> resourceClass)
{
return providerFactory.injectedInstance(resourceClass, request, response);
}
@Override
public <T> T initResource(T resource)
{
providerFactory.injectProperties(resource, request, response);
return resource;
}
};
contextDataMap.put(ResourceContext.class, resourceContext);
contextDataMap.putAll(defaultContextObjects);
contextDataMap.put(Cleanables.class, new Cleanables());
}
public Response internalInvocation(HttpRequest request, HttpResponse response, Object entity)
{
// be extra careful in the clean up process. Only pop if there was an
// equivalent push.
ResteasyProviderFactory.addContextDataLevel();
boolean pushedBody = false;
try
{
MessageBodyParameterInjector.pushBody(entity);
pushedBody = true;
ResourceInvoker invoker = getInvoker(request);
if (invoker != null)
{
pushContextObjects(request, response);
return execute(request, response, invoker);
}
// this should never happen, since getInvoker should throw an exception
// if invoker is null
return null;
}
finally
{
ResteasyProviderFactory.removeContextDataLevel();
if (pushedBody)
{
MessageBodyParameterInjector.popBody();
}
}
}
public void clearContextData()
{
Cleanables cleanables = ResteasyProviderFactory.getContextData(Cleanables.class);
if (cleanables != null)
{
for (Iterator<Cleanable> it = cleanables.getCleanables().iterator(); it.hasNext(); )
{
try
{
it.next().clean();
}
catch(Exception e)
{
// Empty
}
}
}
ResteasyProviderFactory.clearContextData();
// just in case there were internalDispatches that need to be cleaned up
MessageBodyParameterInjector.clearBodies();
}
/**
* Return a response wither from an invoke or exception handling
*
* @param request
* @param response
* @param invoker
* @return
*/
public Response execute(HttpRequest request, HttpResponse response, ResourceInvoker invoker)
{
Response jaxrsResponse = null;
try
{
jaxrsResponse = invoker.invoke(request, response);
if (request.getAsyncContext().isSuspended())
{
/**
* Callback by the initial calling thread. This callback will probably do nothing in an asynchronous environment
* but will be used to simulate AsynchronousResponse in vanilla Servlet containers that do not support
* asychronous HTTP.
*
*/
request.getAsyncContext().getAsyncResponse().initialRequestThreadFinished();
jaxrsResponse = null; // we're handing response asynchronously
}
}
catch (Exception e)
{
//logger.error("invoke() failed mapping exception", e);
jaxrsResponse = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
if (jaxrsResponse == null) throw new UnhandledException(e);
}
return jaxrsResponse;
}
/**
* Invoke and write response
*
* @param request
* @param response
* @param invoker
*/
public void invoke(HttpRequest request, HttpResponse response, ResourceInvoker invoker)
{
Response jaxrsResponse = null;
try
{
jaxrsResponse = invoker.invoke(request, response);
if (request.getAsyncContext().isSuspended())
{
/**
* Callback by the initial calling thread. This callback will probably do nothing in an asynchronous environment
* but will be used to simulate AsynchronousResponse in vanilla Servlet containers that do not support
* asychronous HTTP.
*
*/
request.getAsyncContext().getAsyncResponse().initialRequestThreadFinished();
jaxrsResponse = null; // we're handing response asynchronously
}
}
catch (Exception e)
{
//logger.error("invoke() failed mapping exception", e);
writeException(request, response, e);
return;
}
if (jaxrsResponse != null) writeResponse(request, response, jaxrsResponse);
}
public void asynchronousDelivery(HttpRequest request, HttpResponse response, Response jaxrsResponse) throws IOException
{
if (jaxrsResponse == null) return;
try
{
pushContextObjects(request, response);
ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory);
}
finally
{
clearContextData();
}
}
public void asynchronousExceptionDelivery(HttpRequest request, HttpResponse response, Throwable exception)
{
try
{
pushContextObjects(request, response);
writeException(request, response, exception);
}
catch (Throwable ex)
{
LogMessages.LOGGER.unhandledAsynchronousException(ex);
// unhandled exceptions need to be processed as they can't be thrown back to the servlet container
if (!response.isCommitted()) {
try
{
response.reset();
response.sendError(500);
}
catch (IOException e)
{
}
}
}
finally
{
clearContextData();
}
}
protected void writeResponse(HttpRequest request, HttpResponse response, Response jaxrsResponse)
{
try
{
ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory);
}
catch (Exception e)
{
//logger.error("writeResponse() failed mapping exception", e);
writeException(request, response, e);
}
}
public void addHttpPreprocessor(HttpRequestPreprocessor httpPreprocessor)
{
requestPreprocessors.add(httpPreprocessor);
}
}
| |
package org.nginx.loader;
import java.io.*;
import java.util.HashMap;
import java.net.URL;
import org.nginx.Context;
import org.nginx.Logger;
import org.nginx.Constants;
public class ServletClassLoader extends ClassLoader implements Constants {
protected ClassLoader system = null;
protected Context context = null;
protected Logger logger = null;
protected final HashMap<String, ResourceEntry> resourceEntries = new HashMap<String, ResourceEntry>();
public ServletClassLoader(Context context) {
this.context = context;
this.logger = context.getLogger();
system = getSystemClassLoader();
if (DEBUG)
logger.debug("Init servlet class loader");
}
public boolean modified() {
for (ResourceEntry entry : resourceEntries.values()) {
File file = new File(entry.path);
long lastModified = file.lastModified();
if (lastModified != entry.lastModified) {
if (DEBUG)
logger.info("Resource '" + entry.path
+ "' was modified; Date is now: "
+ new java.util.Date(lastModified) + " Was: "
+ new java.util.Date(entry.lastModified));
return true;
}
}
return false;
}
public void destroy() {
resourceEntries.clear();
}
private byte[] getBytes(String fileName) throws IOException {
if (DEBUG)
logger.debug("Read file " + fileName);
File file = new File(fileName);
long len = file.length();
byte raw[] = new byte[(int) len];
FileInputStream fin = new FileInputStream(file);
int r = fin.read(raw);
if (r != len)
throw new IOException("Can't read file '" + fileName + "'");
fin.close();
return raw;
}
protected ResourceEntry findResourceInternal(String name) throws ClassNotFoundException {
if (name == null)
return null;
ResourceEntry entry = resourceEntries.get(name);
if (entry != null)
return entry;
String fileStub = name.replace( '.', File.separatorChar );
URL url = getSystemResource(fileStub + ".java");
if (url == null)
throw new ClassNotFoundException("Class '" + name + "' not found");
String javaFilename = url.getPath();
String classFilename = javaFilename.substring(0, javaFilename.length() - "java".length()) + "class";
File javaFile = new File( javaFilename );
File classFile = new File( classFilename );
if (!classFile.exists() || javaFile.lastModified() > classFile.lastModified()) {
try {
if (!compile(javaFilename) || !classFile.exists()) {
throw new ClassNotFoundException("Compile failed of " + javaFilename);
}
} catch( IOException ie ) {
throw new ClassNotFoundException(ie.toString());
}
}
entry = new ResourceEntry();
try {
entry.binaryContent = getBytes(classFilename);
entry.lastModified = javaFile.lastModified();
entry.name = name;
entry.path = javaFilename;
} catch(IOException ie) {
throw new ClassNotFoundException(ie.toString());
}
resourceEntries.put(name, entry);
return entry;
}
@Override
public Class findClass(String name) throws ClassNotFoundException {
if (DEBUG)
logger.debug("Find class " + name);
Class clazz = null;
if (DEBUG)
logger.debug("Try super.findClass()");
try {
clazz = super.findClass(name);
} catch (ClassNotFoundException cnfe) {
} catch (RuntimeException e) {
throw e;
}
if (DEBUG)
logger.debug("Try findClassInternal()");
if (clazz == null) {
try {
clazz = findClassInternal(name);
} catch(ClassNotFoundException cnfe) {
throw cnfe;
} catch (RuntimeException e) {
throw e;
}
}
return clazz;
}
public Class findClassInternal(String name) throws ClassNotFoundException {
if (DEBUG)
logger.debug("Find class " + name);
if (!validate(name))
throw new ClassNotFoundException(name);
ResourceEntry entry = null;
entry = findResourceInternal(name);
if (entry == null)
throw new ClassNotFoundException(name);
Class clazz = entry.loadedClass;
if (clazz != null)
return clazz;
if (DEBUG)
logger.debug("Define class " + name);
clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length);
entry.loadedClass = clazz;
entry.binaryContent = null;
return entry.loadedClass;
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
protected Class<?> findLoadedClass0(String name) {
ResourceEntry entry = resourceEntries.get(name);
if (entry != null) {
return entry.loadedClass;
}
return null;
}
private boolean compile(String javaFile) throws IOException {
if (DEBUG)
logger.debug("Compiling " + javaFile);
String[] cmd = new String[4];
cmd[0] = "/usr/bin/javac";
cmd[1] = "-classpath";
cmd[2] = System.getProperty("java.class.path");
cmd[3] = javaFile;
Process p = Runtime.getRuntime().exec(cmd);
try {
p.waitFor();
} catch(InterruptedException ie) {
logger.error("Error to compile " + javaFile + " due: " + ie);
}
int ret = p.exitValue();
return ret == 0;
}
public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class clazz = null;
if (DEBUG)
logger.debug("Load class " + name);
clazz = findLoadedClass0(name);
if (clazz != null) {
if (resolve)
resolveClass(clazz);
return (clazz);
}
clazz = findLoadedClass(name);
if (clazz != null) {
if (resolve)
resolveClass(clazz);
return (clazz);
}
try {
clazz = findClass(name);
if (clazz != null) {
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
if (DEBUG)
logger.debug("Class " + name + " not found: " + e);
}
try {
clazz = system.loadClass(name);
if (clazz != null) {
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
throw new ClassNotFoundException(name);
}
protected boolean validate(String name) {
// Need to be careful with order here
if (name == null) {
// Can't load a class without a name
return false;
}
if (name.startsWith("java.")) {
// Must never load java.* classes
return false;
}
if (name.startsWith("javax.servlet.jsp.jstl")) {
// OK for web apps to package JSTL
return true;
}
if (name.startsWith("javax.servlet.")) {
// Web apps should never package any other Servlet or JSP classes
return false;
}
if (name.startsWith("javax.el")) {
// Must never load javax.el.* classes
return false;
}
if (name.startsWith("nginx.")) {
// Must never load nginx.* classes
return false;
}
// Assume everything else is OK
return true;
}
}
| |
package flame.client.xteam;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.Semaphore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import flame.client.FLAMEClient;
import flame.client.FLAMEGUI;
import flame.ScreenLogger;
import Prism.core.Event;
public class SimpleGUI extends FLAMEGUI {
///////////////////////////////////////////////
//Member Variables
///////////////////////////////////////////////
/**
* The mode of the XTEAM engine of which this GUI presents the result
*/
protected String mode;
/**
* The 'C' Commit button
*/
protected Button buttonCommit;
/**
* The 'U' Update button
*/
protected Button buttonUpdate;
/**
* The 'E' Exit button
*/
protected Button buttonExit;
/**
* Flag boxes
*/
protected Label[] flagBoxes;
/**
* The simulation status bar
*/
protected Label labelSimStatusBar;
/**
* The update status bar
*/
protected Label labelUpdateStatusBar;
/**
* Timestamp of the last message
*/
protected String arrivalTime_overall = new String("00000000_0000_00");
/**
* Semaphore to control the maximum number of concurrent XTEAM simulation threads.
*/
protected Semaphore mLockGUI;
/**
* Locks the outgoing Events semaphore
*/
public void getLock() {
try {
mLockGUI.acquire(); // get the semaphore
} catch (InterruptedException ie) {
printMsg("Thread interrupted while waiting for the semaphore");
}
}
/**
* Releases the outgoing Event semaphore
*/
public void releaseLock() {
mLockGUI.release();
}
///////////////////////////////////////////////
//Constructors
///////////////////////////////////////////////
/**
* Default constructor. Mainly invokes the super constructor.
*
* @param flameClient FLAMEClient instance
* @param username Username of the architect
* @param mode The mode of the XTEAMEngine of which this GUI presents. Could be one of MRSV, LSV, LocalV, or HeadLocalV
* @param xteamGUISwitch Switch to disable realtime conflict information presentation
* @param screenLogger ScreenLogger of FLAMEClient
*/
public SimpleGUI( FLAMEClient flameClient,
String username,
String mode,
boolean xteamGUISwitch,
ScreenLogger screenLogger) {
super(flameClient, username, xteamGUISwitch, screenLogger);
this.mode = mode;
}
@Override
protected void initComponents() {
mLockGUI = new Semaphore (1, true);
// Initializes the output window
display = new Display();
shell = new Shell(display, SWT.TITLE | SWT.ON_TOP);
//shell.setLayout(new FillLayout());
shell.setText("FLAME");
// reads the screen DPI setting and adjust magnification
int mag = shell.getDisplay().getDPI().x > 96 ? 2 : 1;
int x_gap = 5; // landscape gap between things
int y_gap = 3; // vertical gap between things
int box_width = 55; // flag box width
int box_height = 20; // flag box height
int box_number = requirements.getAnalysisTypes().size(); // number of flag boxes
int max_box_number = box_number > 3 ? box_number : 3;
int status_bar_height = 18;
int button_height = 23;
int title_bar_height = 25;
int window_width = x_gap + (box_width + x_gap) * max_box_number + x_gap;
int window_height = title_bar_height +
status_bar_height +
y_gap +
box_height +
y_gap +
button_height +
y_gap +
status_bar_height;
printMsg("Windows width: " + window_width + " window_height: " + window_height);
shell.setSize(window_width * mag, window_height * mag);
Monitor primary = display.getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.width - rect.width - 100;
int y = bounds.height - rect.height - 100;
shell.setLocation(x, y);
// creates flag boxes
int index = 0;
flagBoxes = new Label[requirements.getAnalysisTypes().size()];
for(String analysisType : requirements.getAnalysisTypes()) {
Label label = new Label(shell, SWT.BORDER | SWT.CENTER);
label.setSize(box_width * mag, box_height * mag);
label.setText(analysisType);
if(!xteamGUISwitch) {
label.setEnabled(false);
}
label.setLocation((x_gap + (index * (box_width + x_gap))) * mag, (status_bar_height+y_gap) * mag);
flagBoxes[index++] = label;
}
// creates simulation status bar
labelSimStatusBar = new Label(shell, SWT.NONE);
if(!xteamGUISwitch) {
labelSimStatusBar.setText("Simulation disabled");
} else {
labelSimStatusBar.setText("Simulation status");
}
labelSimStatusBar.setSize(window_width * mag, status_bar_height * mag);
labelSimStatusBar.setLocation(0 * mag, 0 * mag);
labelSimStatusBar.setBackground(display.getSystemColor(SWT.COLOR_GRAY));
// creates update status bar
labelUpdateStatusBar = new Label(shell, SWT.NONE);
labelUpdateStatusBar.setText("Ready");
labelUpdateStatusBar.setSize(window_width * mag, status_bar_height * mag);
labelUpdateStatusBar.setLocation(0 * mag, (window_height-status_bar_height-title_bar_height) * mag);
labelUpdateStatusBar.setBackground(display.getSystemColor(SWT.COLOR_GRAY));
// commit button
buttonCommit = new Button(shell, SWT.PUSH);
buttonCommit.setLocation(x_gap * mag, (status_bar_height + y_gap + box_height + y_gap) * mag);
buttonCommit.setSize(box_width * mag, button_height * mag);
buttonCommit.setText("Commit");
buttonCommit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
printMsg("Commit button pressed");
client.commit();
}
});
//buttonCommit.setEnabled(false);
// Update button
buttonUpdate = new Button(shell, SWT.PUSH);
buttonUpdate.setLocation((x_gap + ((x_gap + box_width) * 1)) * mag, (status_bar_height + y_gap + box_height + y_gap) * mag);
buttonUpdate.setSize(box_width * mag, button_height * mag);
buttonUpdate.setText("Update");
buttonUpdate.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
printMsg("Update button pressed");
client.update();
}
});
//buttonUpdate.setEnabled(false);
// Exit button
buttonExit = new Button(shell, SWT.PUSH);
buttonExit.setLocation((x_gap + ((x_gap + box_width) * 2)) * mag, (status_bar_height + y_gap + box_height + y_gap) * mag);
buttonExit.setSize(box_width * mag, button_height * mag);
buttonExit.setText("Exit");
buttonExit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
printMsg("Exit button pressed");
client.getModelingTool().destroy();
shell.dispose();
}
});
printMsg("Component initialization complete.");
}
@Override
public void presentSnapshot(final Event e) {
// do nothing
}
@Override
public void updateLV(ArrayList<String> lv) {
// do nothing
}
@SuppressWarnings("unchecked")
@Override
public void presentXTEAMInfo(Event e) {
// If the proactive conflict detection option is turned off, stops it.
if(!xteamGUISwitch) {
return;
}
// Checks if the event is an XTEAM info
if(!e.name.equals("XTEAM")) {
return;
}
// gets the username of the XTEAM Event ... SenderUsername is the mode (MRSV, LSV, LocalV)!
String senderUsername;
if(e.hasParameter("SenderUsername")) {
senderUsername = (String) e.getParameter("SenderUsername");
} else {
printMsg("Error: XTEAM Event does not have the SenderUsername parameter");
return;
}
// Checks if the senderUsername is NOT equal to the mode
if(!senderUsername.equals(mode)) {
return;
}
// Gets the arrival time (Design Event arrival at the Engine) of the Event
String arrivalTime;
if(e.hasParameter("ArrivalTime")) {
arrivalTime = (String) e.getParameter("ArrivalTime");
} else {
printMsg("Error: XTEAM Event does not have the ArrivalTime parameter");
return;
}
// checks the time stamp to see if it is from the past
if(arrivalTime_overall.compareTo(arrivalTime) > 0) {
return;
}
/*
*
* If the flow has reached here, that means at least one flag operation
* (e.g. down, green up, red up) will be performed.
*
*/
// lock the semaphore
getLock();
// overwrites the most recent time stamp
arrivalTime_overall = arrivalTime;
ArrayList<String> syntactic_conflicts = new ArrayList<>();
Map<String, java.util.List<String>> warnings = null;
boolean analysisComplete = true;
// If the Event has a list of syntactic conflicts
if(e.hasParameter("SyntacticConflicts")) {
ArrayList<String> data = (ArrayList<String>) e.getParameter("SyntacticConflicts");
// If the size is 1, the only entry could be a "None"
for(String entry : data) {
if(!entry.equals("None")) {
syntactic_conflicts.add("[ERR]: " + entry);
analysisComplete = false;
}
}
}
// Gets the XTEAM analysis type (Energy, Latency, ...).
String analysisType = "All";
if(e.hasParameter("AnalysisType")) {
analysisType = (String) e.getParameter("AnalysisType");
}
// Checks if the analysis type is known
if(requirements.hasAnalysisType(analysisType)) {
// If the Event has a list of analysis warning messages
if(e.hasParameter("AnalysisWarnings")) {
warnings = (Map<String, java.util.List<String>>) e.getParameter("AnalysisWarnings");
for(String key : warnings.keySet()) {
// if the analysis type of this Event has any warnings
if(key.equals(analysisType) && warnings.get(key).size() > 0) {
analysisComplete = false;
}
}
}
// Checks if there was any errors or warnings. Turns the flagbox to gray.
if(analysisComplete == false) {
// turns the flagbox to gray
flagDown(analysisType);
} else {
// Checks if the values satisfy the requirement(s)
boolean requirementSatisfied = true;
try {
// Looks at all requirements for the analysis type (e.g. Energy, Latency, etc.)
for(String target : requirements.getTargetValueNames(analysisType)) {
// Received simulation result is in string format. Needs to be transformed to a double value.
double doubleValue = 0;
String strValue = "";
// Depending on what target value (total, maximum, etc.) the requirement wants to look at
String parameterName = "";
switch (target.toLowerCase()) {
case "total":
parameterName = "OverallTotal"; break;
case "maximum":
parameterName = "OverallMax"; break;
case "average":
parameterName = "OverallAverage"; break;
case "success":
parameterName = "OverallSuccess"; break;
default:
printMsg("Unknown overall target value name found: " + target);
continue; // to the next requirement!
}
if(e.hasParameter(parameterName)) {
strValue = (String) e.getParameter(parameterName);
try {
// transforms the String formatted value to double for computation
if(!target.toLowerCase().equals("success")) {
doubleValue = transformToDouble(strValue);
} else {
doubleValue = transformSuccessRateToDouble(strValue);
}
// checks if the related requirement is satisfied
requirementSatisfied = requirements.isSatisfied(analysisType, target, doubleValue);
if(requirementSatisfied == false) {
break;
}
} catch (Exception exc) {
printMsg("Received " + parameterName + " value is incomprehensible: " + strValue);
}
} else {
printMsg("Event lacks " + parameterName + " attribute");
}
}
// Flags up depending on whether the requirements are satisfied
if(requirementSatisfied) {
greenFlagUp(analysisType);
} else {
redFlagUp(analysisType);
}
} catch (Exception exc) {
printMsg("Requirements validation: " + exc.getMessage());
}
}
}
releaseLock();
}
/**
* XTEAMEngine sends values in the "TargetValueName: value" format.
* It is necessary to strip the irrelevant text around the value to use it
* for computation.
*
* @param strValue String value received from XTEAMEngine
* @return double value
*/
protected double transformToDouble(String strValue) throws Exception {
double value = (double) 0;
String[] tokens = strValue.split(":");
if(tokens.length != 2) {
throw new Exception ("Received string value is ill-formatted: " + strValue);
}
try {
value = Double.parseDouble(tokens[1].trim());
} catch (NumberFormatException nfe) {
throw new Exception ("Received string value contains ill-formatted number: " + strValue);
}
return value;
}
/**
* XTEAMEngine sends success rate values in the "success/total[rate]" format.
* It is necessary to strip the irrelevant text around the value to use it
* for computation.
*
* @param strValue String success value received from XTEAMEngine
* @return double success value
*/
protected double transformSuccessRateToDouble(String strValue) throws Exception {
double value = (double) 0;
String[] tokens = strValue.split("\\[");
if(tokens.length != 2) {
throw new Exception ("Received string value is ill-formatted: " + strValue);
}
try {
value = Double.parseDouble(tokens[1].trim().substring(0, tokens[1].length()-2));
} catch (NumberFormatException nfe) {
throw new Exception ("Received string value contains ill-formatted number: " + strValue);
}
return value;
}
/**
* Turns the background color of a flagbox to gray
*
* @param analysisType Anaysis type of the flagbox to change
*/
protected void flagDown(String analysisType) {
changeFlagColor(analysisType, SWT.COLOR_GRAY);
}
/**
* Turns the background color of a flagbox to green
*
* @param analysisType Anaysis type of the flagbox to change
*/
protected void greenFlagUp(String analysisType) {
changeFlagColor(analysisType, SWT.COLOR_GREEN);
}
/**
* Turns the background color of a flagbox to red
*
* @param analysisType Anaysis type of the flagbox to change
*/
protected void redFlagUp(String analysisType) {
changeFlagColor(analysisType, SWT.COLOR_RED);
}
/**
* Turns the background color of a flagbox
*
* @param analysisType Analysis type of the flagbox to change
* @param color Target color
*/
protected void changeFlagColor(final String analysisType, final int color) {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
for(int i=0; i < flagBoxes.length; i++) {
if(flagBoxes[i].getText().equals(analysisType)) {
flagBoxes[i].setBackground(display.getSystemColor(color));
}
}
}
}
});
}
@Override
public void setSimStatus(String senderUsername, int thread_count) {
if (senderUsername.equals(mode)) {
if(xteamGUISwitch) {
updateSimStatus(thread_count);
}
}
}
/**
* Sets the simulation status
*
* @param thread_count Number of threads running simulation now
*/
protected void updateSimStatus(final Integer thread_count) {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
//int color = thread_count == 0 ? SWT.COLOR_GRAY : SWT.COLOR_CYAN;
labelSimStatusBar.setText(thread_count + " simulations running");
//labelSimStatusBar.setBackground(display.getSystemColor(color));
}
}
});
}
@Override
public void setInProgressStatus(final String message) {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
labelUpdateStatusBar.setText(message);
labelUpdateStatusBar.setBackground(display.getSystemColor(SWT.COLOR_RED));
}
}
});
}
@Override
public void setIdleStatus(final String message) {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
labelUpdateStatusBar.setText(message);
labelUpdateStatusBar.setBackground(display.getSystemColor(SWT.COLOR_GRAY));
}
}
});
}
@Override
public void disableButtonsImpl() {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
buttonCommit.setEnabled(false);
buttonUpdate.setEnabled(false);
}
}
});
}
@Override
public void enableButtonsImpl() {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
buttonCommit.setEnabled(true);
buttonUpdate.setEnabled(true);
}
}
});
}
@Override
public void disableCommitButtonImpl() {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
buttonCommit.setEnabled(false);
}
}
});
}
@Override
public void enableCommitButtonImpl() {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
buttonCommit.setEnabled(true);
}
}
});
}
@Override
public void disableUpdateButtonImpl() {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
buttonUpdate.setEnabled(false);
}
}
});
}
@Override
public void enableUpdateButtonImpl() {
display.asyncExec(new Runnable () {
public void run() {
if(!shell.isDisposed()) {
buttonUpdate.setEnabled(true);
}
}
});
}
@Override
public void presentLocalInfo() {
// do nothing
}
}
| |
package dyvilx.tools.compiler.ast.expression.access;
import dyvil.lang.Name;
import dyvil.source.position.SourcePosition;
import dyvilx.tools.asm.Label;
import dyvilx.tools.compiler.ast.context.IContext;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.expression.optional.OptionalChainAware;
import dyvilx.tools.compiler.ast.generic.GenericData;
import dyvilx.tools.compiler.ast.generic.ITypeContext;
import dyvilx.tools.compiler.ast.header.IClassCompilableList;
import dyvilx.tools.compiler.ast.header.ICompilableList;
import dyvilx.tools.compiler.ast.method.Candidate;
import dyvilx.tools.compiler.ast.method.IMethod;
import dyvilx.tools.compiler.ast.method.MatchList;
import dyvilx.tools.compiler.ast.method.intrinsic.IntrinsicData;
import dyvilx.tools.compiler.ast.method.intrinsic.Intrinsics;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.type.IType;
import dyvilx.tools.compiler.ast.type.builtin.Types;
import dyvilx.tools.compiler.backend.method.MethodWriter;
import dyvilx.tools.compiler.backend.exception.BytecodeException;
import dyvilx.tools.compiler.transform.Deprecation;
import dyvilx.tools.compiler.util.Markers;
import dyvilx.tools.compiler.util.Util;
import dyvilx.tools.parsing.marker.Marker;
import dyvilx.tools.parsing.marker.MarkerList;
public abstract class AbstractCall implements ICall, IReceiverAccess, OptionalChainAware
{
protected SourcePosition position;
protected IValue receiver;
protected ArgumentList arguments;
protected GenericData genericData;
// Metadata
protected IMethod method;
protected IType type;
@Override
public SourcePosition getPosition()
{
return this.position;
}
@Override
public void setPosition(SourcePosition position)
{
this.position = position;
}
@Override
public IValue getReceiver()
{
return this.receiver;
}
@Override
public void setReceiver(IValue receiver)
{
this.receiver = receiver;
}
public abstract Name getName();
@Override
public ArgumentList getArguments()
{
return this.arguments;
}
@Override
public void setArguments(ArgumentList arguments)
{
this.arguments = arguments;
}
public GenericData getGenericData()
{
if (this.genericData != null)
{
return this.genericData;
}
if (this.method == null)
{
return this.genericData = new GenericData();
}
return this.genericData = this.method.getGenericData(null, this.receiver, this.arguments);
}
public void setGenericData(GenericData data)
{
this.genericData = data;
}
@Override
public boolean isResolved()
{
return this.method != null && this.method.getType().isResolved();
}
public IMethod getMethod()
{
return this.method;
}
@Override
public boolean hasSideEffects()
{
return true;
}
@Override
public IType getType()
{
if (this.method == null)
{
return Types.UNKNOWN;
}
if (this.type == null)
{
this.type = this.method.getType().getConcreteType(this.getGenericData());
}
return this.type;
}
@Override
public void setType(IType type)
{
this.type = type;
}
@Override
public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context)
{
return this.isType(type) ? this : null;
}
@Override
public boolean isType(IType type)
{
return Types.isVoid(type) || this.method != null && Types.isSuperType(type, this.getType());
}
protected abstract Name getReferenceName();
@Override
public IValue toReferenceValue(MarkerList markers, IContext context)
{
final MethodCall methodCall = new MethodCall(this.position, this.receiver, this.getReferenceName(),
this.arguments);
methodCall.setGenericData(this.genericData);
return methodCall.resolveCall(markers, context, false);
}
@Override
public void resolveTypes(MarkerList markers, IContext context)
{
if (this.receiver != null)
{
this.receiver.resolveTypes(markers, context);
}
this.arguments.resolveTypes(markers, context);
if (this.genericData != null)
{
this.genericData.resolveTypes(markers, context);
}
}
@Override
public void resolveReceiver(MarkerList markers, IContext context)
{
if (this.receiver != null)
{
this.receiver = this.receiver.resolve(markers, context);
}
}
@Override
public void resolveArguments(MarkerList markers, IContext context)
{
this.arguments.resolve(markers, context);
if (this.genericData != null)
{
this.genericData.resolve(markers, context);
}
}
// every override of this method should call checkArguments on the result; among others to ensure Optional Chain Awareness.
@Override
public IValue resolveCall(MarkerList markers, IContext context, boolean report)
{
final MatchList<IMethod> candidates = this.resolveCandidates(context);
if (candidates.hasCandidate())
{
return this.checkArguments(markers, context, candidates.getBestMember());
}
if (report)
{
this.reportResolve(markers, candidates);
return this;
}
return null;
}
protected MatchList<IMethod> resolveCandidates(IContext context)
{
return ICall.resolveMethods(context, this.receiver, this.getName(), this.arguments);
}
protected void reportResolve(MarkerList markers, MatchList<IMethod> matches)
{
final Marker marker;
if (matches != null && matches.isAmbigous())
{
marker = Markers.semanticError(this.position, "method.access.ambiguous", this.getName());
}
else // isAmbiguous returns false for empty lists
{
marker = Markers.semanticError(this.position, "method.access.resolve", this.getName());
}
this.addArgumentInfo(marker);
this.addCandidates(matches, marker);
markers.add(marker);
}
private void addArgumentInfo(Marker marker)
{
if (this.receiver != null)
{
marker.addInfo(Markers.getSemantic("receiver.type", this.receiver.getType()));
}
if (!this.arguments.isEmpty())
{
marker.addInfo(Markers.getSemantic("method.access.argument_types", this.arguments.typesToString()));
}
}
private void addCandidates(MatchList<IMethod> matches, Marker marker)
{
if (matches == null || matches.isEmpty())
{
return;
}
marker.addInfo(Markers.getSemantic("method.access.candidates"));
for (Candidate<IMethod> candidate : matches.getAmbiguousCandidates())
{
final IMethod member = candidate.getMember();
final StringBuilder builder = new StringBuilder().append('\t');
builder.append(member.getReceiverType()).append(member.isStatic() ? '.' : '#');
Util.methodSignatureToString(member, this.genericData, builder);
marker.addInfo(builder.toString());
}
}
// every resolveCall implementation calls this
protected final IValue checkArguments(MarkerList markers, IContext context, IMethod method)
{
this.method = method;
final IntrinsicData intrinsicData = method.getIntrinsicData();
final int code;
final IValue intrinsic;
if (intrinsicData != null // Intrinsic annotation
&& (code = intrinsicData.getCompilerCode()) != 0 // compilerCode argument
&& (intrinsic = Intrinsics.getOperator(code, this.receiver, this.arguments)) != null) // valid intrinsic
{
Deprecation.checkAnnotations(method, this.position, markers);
intrinsic.setPosition(this.position);
return intrinsic;
}
final GenericData genericData;
if (this.genericData != null)
{
genericData = this.genericData = method.getGenericData(this.genericData, this.receiver, this.arguments);
}
else
{
genericData = this.getGenericData();
}
this.receiver = method.checkArguments(markers, this.position, context, this.receiver, this.arguments,
genericData);
this.type = null;
this.type = this.getType();
return OptionalChainAware.transform(this);
}
@Override
public void checkTypes(MarkerList markers, IContext context)
{
if (this.receiver != null)
{
this.receiver.checkTypes(markers, context);
}
this.arguments.checkTypes(markers, context);
if (this.genericData != null)
{
this.genericData.checkTypes(markers, context);
}
}
@Override
public void check(MarkerList markers, IContext context)
{
if (this.receiver != null)
{
this.receiver.check(markers, context);
}
if (this.method != null)
{
this.method
.checkCall(markers, this.position, context, this.receiver, this.arguments, this.getGenericData());
if (!this.getType().isResolved())
{
markers.add(Markers.semanticError(this.position, "method.access.unresolved_type", this.getName()));
}
}
this.arguments.check(markers, context);
if (this.genericData != null)
{
this.genericData.check(markers, context);
}
}
@Override
public IValue foldConstants()
{
if (this.receiver != null)
{
this.receiver = this.receiver.foldConstants();
}
this.arguments.foldConstants();
if (this.genericData != null)
{
this.genericData.foldConstants();
}
return this;
}
@Override
public IValue cleanup(ICompilableList compilableList, IClassCompilableList classCompilableList)
{
if (this.receiver != null)
{
this.receiver = this.receiver.cleanup(compilableList, classCompilableList);
}
this.arguments.cleanup(compilableList, classCompilableList);
if (this.genericData != null)
{
this.genericData.cleanup(compilableList, classCompilableList);
}
return this;
}
// Inlined for performance
@Override
public int lineNumber()
{
if (this.position == null)
{
return 0;
}
return this.position.startLine();
}
@Override
public void writeExpression(MethodWriter writer, IType type) throws BytecodeException
{
if (type == null)
{
type = this.getType();
}
this.method.writeCall(writer, this.receiver, this.arguments, this.genericData, type, this.lineNumber());
}
@Override
public void writeJump(MethodWriter writer, Label dest) throws BytecodeException
{
this.method.writeJump(writer, dest, this.receiver, this.arguments, this.genericData, this.lineNumber());
}
@Override
public void writeInvJump(MethodWriter writer, Label dest) throws BytecodeException
{
this.method.writeInvJump(writer, dest, this.receiver, this.arguments, this.genericData, this.lineNumber());
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
this.toString("", builder);
return builder.toString();
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Rodrigo Quesada <rodrigoquesada.dev@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.rodrigodev.xgen4j.test.organization;
import com.rodrigodev.xgen4j.ExceptionsGenerator;
import com.rodrigodev.xgen4j.test.TestSpecification;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.Root9NameError;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.Root9NameException;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.Common9Name1Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.Common9Name1Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.Common9Name2Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.Common9Name2Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_1.Common9Name3_1Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_1.Common9Name3_1Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_2.Common9Name3_2Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_2.Common9Name3_2Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_3.Common9Name3_3Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_3.Common9Name3_3Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.Error9Name1Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.Error9Name1Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.Error9Name2Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.Error9Name2Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_1.Error9Name3_1Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_1.Error9Name3_1Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_2.Error9Name3_2Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_2.Error9Name3_2Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_3.Error9Name3_3Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_3.Error9Name3_3Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Exception;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Error;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Exception;
import org.junit.Test;
import java.util.function.Function;
import static com.rodrigodev.xgen4j.model.error.configuration.ErrorConfiguration.*;
import static org.assertj.core.api.Assertions.*;
/**
* Created by Rodrigo Quesada on 21/06/15.
*/
public class PackageTests extends TestSpecification {
public PackageTests() {
generateErrorsForPackageGeneratedFromErrorNameTests();
generateErrorsForPackageGeneratedFromErrorNameTests_specialCases();
}
private void assert_basePackageHasInvalidFormat(String invalidPackage) {
assertThatThrownBy(() -> rootError("Root").basePackage(invalidPackage))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Base package '%s' has invalid format.", invalidPackage));
}
private void assert_basePackagePartsMustNotContainGivenCharacters(
String invalidCharacters, Function<Character, String> invalidPartSupplier
) {
for (char invalidCharacter : invalidCharacters.toCharArray()) {
String invalidPart = invalidPartSupplier.apply(invalidCharacter);
assert_basePackageHasInvalidFormat(
String.format("com.rodrigodev.xgen4j.test.organization.packages.%s", invalidPart));
assert_basePackageHasInvalidFormat(
String.format("com.rodrigodev.xgen4j.test.organization.packages.%s.something", invalidPart));
assert_basePackageHasInvalidFormat(
String.format("%s.com.rodrigodev.xgen4j.test.organization.packages", invalidPart));
}
}
private void assert_basePackagePartsCanBeginWithLetterOrUnderscore() {
ExceptionsGenerator xgen = generator();
// @formatter:off
xgen.generate(rootError("Root").basePackage("com.rodrigodev.xgen4j.test.organization.packages.BasePackagePartsCanBeginWithLetterOrUnderscore").build());
xgen.generate(rootError("Root").basePackage("com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanBeginWithLetterOrUnderscore").build());
xgen.generate(rootError("Root").basePackage("com.rodrigodev.xgen4j.test.organization.packages._basePackagePartsCanBeginWithLetterOrUnderscore").build());
// @formatter:on
//Next code should compile
com.rodrigodev.xgen4j.test.organization.packages.BasePackagePartsCanBeginWithLetterOrUnderscore.RootError.class.getName();
com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanBeginWithLetterOrUnderscore.RootError.class.getName();
com.rodrigodev.xgen4j.test.organization.packages._basePackagePartsCanBeginWithLetterOrUnderscore.RootError.class.getName();
}
@Test
public void basePackagePartsMustBeginWithLetterOrUnderscore() {
assert_basePackagePartsMustNotContainGivenCharacters("1-!@#$%^&*()+.", c -> c + "abcde");
assert_basePackagePartsCanBeginWithLetterOrUnderscore();
}
private void assert_basePackagePartsCanContainLettersNumbersOrUnderscores() {
ExceptionsGenerator xgen = generator();
// @formatter:off
xgen.generate(rootError("Root").basePackage("com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanContainLettersNumbersOrUnderscores").build());
xgen.generate(rootError("Root").basePackage("com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanContain1LettersNumbersOrUnderscores1").build());
xgen.generate(rootError("Root").basePackage("com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanContain_LettersNumbersOrUnderscores_").build());
// @formatter:on
//Next code should compile
com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanContainLettersNumbersOrUnderscores.RootError.class.getName();
com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanContain1LettersNumbersOrUnderscores1.RootError.class.getName();
com.rodrigodev.xgen4j.test.organization.packages.basePackagePartsCanContain_LettersNumbersOrUnderscores_.RootError.class.getName();
}
@Test
public void basePackagePartsMustOnlyContainLettersNumbersOrUnderscores() {
assert_basePackagePartsMustNotContainGivenCharacters("-!@#$%^&*()+.", c -> "name" + c);
assert_basePackagePartsMustNotContainGivenCharacters("-!@#$%^&*()+", c -> "name" + c + "suffix");
assert_basePackagePartsCanContainLettersNumbersOrUnderscores();
}
private void assert_packagesForErrorsAndExceptionsAreGeneratedFromCodeNamesWhenCodeNameIsProvided(
boolean withNumericId, String namespace
) {
try {
String basePackage = "com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAndExceptionsAreGeneratedFromCodeNamesWhenCodeNameIsProvided_" + namespace;
// @formatter:off
generator().generate(code(rootError("Root"), "code-9-name-root", 1, withNumericId).errors(
code(commonError("C1"), "code-9-name-c1", 2, withNumericId).errors(
code(error("C2"), "code-9-name-c2", 3, withNumericId).errors(
code(error("C3_1"), "code-9-name-c3-1", 4, withNumericId).description("ABCDE"),
code(error("C3_2"), "code-9-name-c3-2", 5, withNumericId).description("ABCDE"),
code(error("C3_3"), "code-9-name-c3-3", 6, withNumericId).description("ABCDE")
)
),
code(error("E1"), "code-9-name-e1", 7, withNumericId).errors(
code(error("E2"), "code-9-name-e2", 8, withNumericId).errors(
code(error("E3_1"), "code-9-name-e3-1", 9, withNumericId).description("ABCDE"),
code(error("E3_2"), "code-9-name-e3-2", 10, withNumericId).description("ABCDE"),
code(error("E3_3"), "code-9-name-e3-3", 11, withNumericId).description("ABCDE")
)
)
).basePackage(basePackage).build());
// @formatter:on
//Next code should not throw exception
assertThatErrorAndExceptionClassExist(basePackage, "Root");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_c1.C1");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_c1.code_9_name_c2.C2");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_c1.code_9_name_c2.code_9_name_c3_1.C3_1");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_c1.code_9_name_c2.code_9_name_c3_2.C3_2");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_c1.code_9_name_c2.code_9_name_c3_3.C3_3");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_e1.E1");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_e1.code_9_name_e2.E2");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_e1.code_9_name_e2.code_9_name_e3_1.E3_1");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_e1.code_9_name_e2.code_9_name_e3_2.E3_2");
assertThatErrorAndExceptionClassExist(basePackage, "code_9_name_e1.code_9_name_e2.code_9_name_e3_3.E3_3");
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void packagesForErrorsAndExceptionsAreGeneratedFromCodeNamesWhenCodeNameIsProvided() {
assert_packagesForErrorsAndExceptionsAreGeneratedFromCodeNamesWhenCodeNameIsProvided(
false,
"nameOnly"
);
assert_packagesForErrorsAndExceptionsAreGeneratedFromCodeNamesWhenCodeNameIsProvided(
true,
"withNumber"
);
}
private void generateErrorsForPackageGeneratedFromErrorNameTests() {
// @formatter:off
generator().generate(rootError("Root9Name").errors(
commonError("Common9Name1").errors(
error("Common9Name2").errors(
error("Common9Name3_1").description("ABCDE"),
error("Common9Name3_2").description("ABCDE"),
error("Common9Name3_3").description("ABCDE")
)
),
error("Error9Name1").errors(
error("Error9Name2").errors(
error("Error9Name3_1").description("ABCDE"),
error("Error9Name3_2").description("ABCDE"),
error("Error9Name3_3").description("ABCDE")
)
)
).basePackage("com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames").build());
// @formatter:on
}
@Test
public void noCodeNameIsProvided_packagesForErrorsAreGeneratedFromErrorNames() {
assertThat(Root9NameError.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames");
assertThat(Common9Name1Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1");
assertThat(Common9Name2Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2");
assertThat(Common9Name3_1Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_1");
assertThat(Common9Name3_2Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_2");
assertThat(Common9Name3_3Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_3");
assertThat(Error9Name1Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1");
assertThat(Error9Name2Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2");
assertThat(Error9Name3_1Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_1");
assertThat(Error9Name3_2Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_2");
assertThat(Error9Name3_3Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_3");
}
@Test
public void noCodeNameIsProvided_packagesForExceptionsAreGeneratedFromErrorNames() {
assertThat(Root9NameException.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames");
assertThat(Common9Name1Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1");
assertThat(Common9Name2Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2");
assertThat(Common9Name3_1Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_1");
assertThat(Common9Name3_2Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_2");
assertThat(Common9Name3_3Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.common9_name1.common9_name2.common9_name3_3");
assertThat(Error9Name1Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1");
assertThat(Error9Name2Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2");
assertThat(Error9Name3_1Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_1");
assertThat(Error9Name3_2Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_2");
assertThat(Error9Name3_3Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames.error9_name1.error9_name2.error9_name3_3");
}
private void generateErrorsForPackageGeneratedFromErrorNameTests_specialCases() {
// @formatter:off
generator().generate(rootError("RootName").errors(
error("ErrorName1").errors(
error("ErrorName2").errors(
error("Error_Name_9_Name3_1_"),
error("Error-Name-9-Name3_2-"),
error("Error__Name__9__Name3_3__"),
error("Error--Name--9--Name3_4--"),
error("Error_-_Name_-_9_-_Name3_5_-_"),
error("Error_name_9_name3_6"),
error("Error-name-9-name3_7")
)
)
).basePackage("com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases").build());
// @formatter:on
}
@Test
public void noCodeNameIsProvided_packagesForErrorsAreGeneratedFromErrorNames_specialCases() {
assertThat(Error_Name_9_Name3_1_Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_");
assertThat(Error_Name_9_Name3_2_Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_");
assertThat(Error__Name__9__Name3_3__Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__");
assertThat(Error__Name__9__Name3_4__Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__");
assertThat(Error___Name___9___Name3_5___Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___");
assertThat(Error_name_9_name3_6Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6");
assertThat(Error_name_9_name3_7Error.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7");
}
@Test
public void noCodeNameIsProvided_packagesForExceptionsAreGeneratedFromErrorNames_specialCases() {
assertThat(Error_Name_9_Name3_1_Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_");
assertThat(Error_Name_9_Name3_2_Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_");
assertThat(Error__Name__9__Name3_3__Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__");
assertThat(Error__Name__9__Name3_4__Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__");
assertThat(Error___Name___9___Name3_5___Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___");
assertThat(Error_name_9_name3_6Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6");
assertThat(Error_name_9_name3_7Exception.class.getPackage().getName()).isEqualTo(
"com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7");
}
}
| |
/*
* Copyright 2015 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.uberfire.commons.regex.util;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* PathMatcher implementation for Ant-style path patterns.
* <p/>
* This code has been borrowed from <a href="http://camel.apache.org">Apache Camel</a>.
* <p/>
*/
public class AntPathMatcher {
/**
* Default path separator: "/"
*/
public static final String DEFAULT_PATH_SEPARATOR = "/";
private String pathSeparator = DEFAULT_PATH_SEPARATOR;
/**
* Set the path separator to use for pattern parsing. Default is "/", as in
* Ant.
*/
public void setPathSeparator( final String pathSeparator ) {
this.pathSeparator = pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR;
}
public boolean isPattern( final String path ) {
return path.indexOf( '*' ) != -1 || path.indexOf( '?' ) != -1;
}
public boolean match( final String pattern,
final String path ) {
return doMatch( pattern, path, true );
}
public boolean matchStart( final String pattern,
final String path ) {
return doMatch( pattern, path, false );
}
/**
* Actually match the given <code>path</code> against the given
* <code>pattern</code>.
* @param pattern the pattern to match against
* @param path the path String to test
* @param fullMatch whether a full pattern match is required (else a pattern
* match as far as the given base path goes is sufficient)
* @return <code>true</code> if the supplied <code>path</code> matched,
* <code>false</code> if it didn't
*/
protected boolean doMatch( String pattern,
String path,
boolean fullMatch ) {
if ( path.startsWith( this.pathSeparator ) != pattern.startsWith( this.pathSeparator ) ) {
return false;
}
String[] pattDirs = tokenizeToStringArray( pattern, this.pathSeparator );
String[] pathDirs = tokenizeToStringArray( path, this.pathSeparator );
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while ( pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd ) {
String patDir = pattDirs[ pattIdxStart ];
if ( "**".equals( patDir ) ) {
break;
}
if ( !matchStrings( patDir, pathDirs[ pathIdxStart ] ) ) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if ( pathIdxStart > pathIdxEnd ) {
// Path is exhausted, only match if rest of pattern is * or **'s
if ( pattIdxStart > pattIdxEnd ) {
return pattern.endsWith( this.pathSeparator ) ? path.endsWith( this.pathSeparator ) : !path
.endsWith( this.pathSeparator );
}
if ( !fullMatch ) {
return true;
}
if ( pattIdxStart == pattIdxEnd && "*".equals( pattDirs[ pattIdxStart ] )
&& path.endsWith( this.pathSeparator ) ) {
return true;
}
for ( int i = pattIdxStart; i <= pattIdxEnd; i++ ) {
if ( !"**".equals( pattDirs[ i ] ) ) {
return false;
}
}
return true;
} else if ( pattIdxStart > pattIdxEnd ) {
// String not exhausted, but pattern is. Failure.
return false;
} else if ( !fullMatch && "**".equals( pattDirs[ pattIdxStart ] ) ) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while ( pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd ) {
String patDir = pattDirs[ pattIdxEnd ];
if ( "**".equals( patDir ) ) {
break;
}
if ( !matchStrings( patDir, pathDirs[ pathIdxEnd ] ) ) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if ( pathIdxStart > pathIdxEnd ) {
// String is exhausted
for ( int i = pattIdxStart; i <= pattIdxEnd; i++ ) {
if ( !"**".equals( pattDirs[ i ] ) ) {
return false;
}
}
return true;
}
while ( pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd ) {
int patIdxTmp = -1;
for ( int i = pattIdxStart + 1; i <= pattIdxEnd; i++ ) {
if ( "**".equals( pattDirs[ i ] ) ) {
patIdxTmp = i;
break;
}
}
if ( patIdxTmp == pattIdxStart + 1 ) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = patIdxTmp - pattIdxStart - 1;
int strLength = pathIdxEnd - pathIdxStart + 1;
int foundIdx = -1;
strLoop:
for ( int i = 0; i <= strLength - patLength; i++ ) {
for ( int j = 0; j < patLength; j++ ) {
String subPat = pattDirs[ pattIdxStart + j + 1 ];
String subStr = pathDirs[ pathIdxStart + i + j ];
if ( !matchStrings( subPat, subStr ) ) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if ( foundIdx == -1 ) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for ( int i = pattIdxStart; i <= pattIdxEnd; i++ ) {
if ( !"**".equals( pattDirs[ i ] ) ) {
return false;
}
}
return true;
}
/**
* Tests whether or not a string matches against a pattern. The pattern may
* contain two special characters:<br>
* '*' means zero or more characters<br>
* '?' means one and only one character
* @param pattern pattern to match against. Must not be <code>null</code>.
* @param str string which must be matched against the pattern. Must not be
* <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or
* <code>false</code> otherwise.
*/
private boolean matchStrings( String pattern,
String str ) {
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length - 1;
int strIdxStart = 0;
int strIdxEnd = strArr.length - 1;
char ch;
boolean containsStar = false;
for ( char c : patArr ) {
if ( c == '*' ) {
containsStar = true;
break;
}
}
if ( !containsStar ) {
// No '*'s, so we make a shortcut
if ( patIdxEnd != strIdxEnd ) {
return false; // Pattern and string do not have the same size
}
for ( int i = 0; i <= patIdxEnd; i++ ) {
ch = patArr[ i ];
if ( ch != '?' ) {
if ( ch != strArr[ i ] ) {
return false;
// Character mismatch
}
}
}
return true; // String matches against pattern
}
if ( patIdxEnd == 0 ) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ( ( ch = patArr[ patIdxStart ] ) != '*' && strIdxStart <= strIdxEnd ) {
if ( ch != '?' ) {
if ( ch != strArr[ strIdxStart ] ) {
return false;
// Character mismatch
}
}
patIdxStart++;
strIdxStart++;
}
if ( strIdxStart > strIdxEnd ) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for ( int i = patIdxStart; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] != '*' ) {
return false;
}
}
return true;
}
// Process characters after last star
while ( ( ch = patArr[ patIdxEnd ] ) != '*' && strIdxStart <= strIdxEnd ) {
if ( ch != '?' ) {
if ( ch != strArr[ strIdxEnd ] ) {
return false;
// Character mismatch
}
}
patIdxEnd--;
strIdxEnd--;
}
if ( strIdxStart > strIdxEnd ) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for ( int i = patIdxStart; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] != '*' ) {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) {
int patIdxTmp = -1;
for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] == '*' ) {
patIdxTmp = i;
break;
}
}
if ( patIdxTmp == patIdxStart + 1 ) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = patIdxTmp - patIdxStart - 1;
int strLength = strIdxEnd - strIdxStart + 1;
int foundIdx = -1;
strLoop:
for ( int i = 0; i <= strLength - patLength; i++ ) {
for ( int j = 0; j < patLength; j++ ) {
ch = patArr[ patIdxStart + j + 1 ];
if ( ch != '?' ) {
if ( ch != strArr[ strIdxStart + i + j ] ) {
continue strLoop;
}
}
}
foundIdx = strIdxStart + i;
break;
}
if ( foundIdx == -1 ) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for ( int i = patIdxStart; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] != '*' ) {
return false;
}
}
return true;
}
/**
* Given a pattern and a full path, determine the pattern-mapped part.
* <p/>
* For example:
* <ul>
* <li>'<code>/docs/cvs/commit.html</code>' and '
* <code>/docs/cvs/commit.html</code> -> ''</li>
* <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '
* <code>cvs/commit</code>'</li>
* <li>'<code>/docs/cvs/*.html</code>' and '
* <code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>
* <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '
* <code>cvs/commit</code>'</li>
* <li>'<code>/docs/**\/*.html</code>' and '
* <code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>
* <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '
* <code>docs/cvs/commit.html</code>'</li>
* <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '
* <code>/docs/cvs/commit.html</code>'</li>
* <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '
* <code>/docs/cvs/commit.html</code>'</li>
* </ul>
* <p/>
* Assumes that {@link #match} returns <code>true</code> for '
* <code>pattern</code>' and '<code>path</code>', but does
* <strong>not</strong> enforce this.
*/
public String extractPathWithinPattern( String pattern,
String path ) {
final String[] patternParts = tokenizeToStringArray( pattern, this.pathSeparator );
final String[] pathParts = tokenizeToStringArray( path, this.pathSeparator );
final StringBuilder buffer = new StringBuilder();
// Add any path parts that have a wildcarded pattern part.
int puts = 0;
for ( int i = 0; i < patternParts.length; i++ ) {
final String patternPart = patternParts[ i ];
if ( ( patternPart.indexOf( '*' ) > -1 || patternPart.indexOf( '?' ) > -1 ) && pathParts.length >= i + 1 ) {
if ( puts > 0 || ( i == 0 && !pattern.startsWith( this.pathSeparator ) ) ) {
buffer.append( this.pathSeparator );
}
buffer.append( pathParts[ i ] );
puts++;
}
}
// Append any trailing path parts.
for ( int i = patternParts.length; i < pathParts.length; i++ ) {
if ( puts > 0 || i > 0 ) {
buffer.append( this.pathSeparator );
}
buffer.append( pathParts[ i ] );
}
return buffer.toString();
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* Trims tokens and omits empty tokens.
* <p/>
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
* @param str the String to tokenize
* @param delimiters the delimiter characters, assembled as String (each of
* those characters is individually considered as delimiter).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
*/
public static String[] tokenizeToStringArray( String str,
String delimiters ) {
if ( str == null ) {
return new String[] {};
}
final StringTokenizer st = new StringTokenizer( str, delimiters );
final List<String> tokens = new ArrayList<String>();
while ( st.hasMoreTokens() ) {
final String token = st.nextToken().trim();
if ( token.length() > 0 ) {
tokens.add( token );
}
}
return tokens.toArray( new String[ tokens.size() ] );
}
}
| |
/*
* 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.indices.cluster;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteRequest;
import org.elasticsearch.action.admin.cluster.reroute.TransportClusterRerouteAction;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexResponse;
import org.elasticsearch.action.admin.indices.close.TransportCloseIndexAction;
import org.elasticsearch.action.admin.indices.close.TransportVerifyShardBeforeCloseAction;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.TransportCreateIndexAction;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.TransportDeleteIndexAction;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.admin.indices.open.TransportOpenIndexAction;
import org.elasticsearch.action.admin.indices.settings.put.TransportUpdateSettingsAction;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.DestructiveOperations;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.action.support.master.MasterNodeRequest;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.action.support.master.TransportMasterNodeActionUtils;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateTaskExecutor;
import org.elasticsearch.cluster.ClusterStateTaskExecutor.ClusterTasksResult;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.EmptyClusterInfoService;
import org.elasticsearch.cluster.action.shard.ShardStateAction;
import org.elasticsearch.cluster.action.shard.ShardStateAction.FailedShardEntry;
import org.elasticsearch.cluster.action.shard.ShardStateAction.StartedShardEntry;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.coordination.JoinTaskExecutor;
import org.elasticsearch.cluster.coordination.NodeRemovalClusterStateTaskExecutor;
import org.elasticsearch.cluster.metadata.AliasValidator;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.MetadataCreateIndexService;
import org.elasticsearch.cluster.metadata.MetadataDeleteIndexService;
import org.elasticsearch.cluster.metadata.MetadataIndexStateService;
import org.elasticsearch.cluster.metadata.MetadataIndexStateServiceUtils;
import org.elasticsearch.cluster.metadata.MetadataIndexUpgradeService;
import org.elasticsearch.cluster.metadata.MetadataUpdateSettingsService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.FailedShard;
import org.elasticsearch.cluster.routing.allocation.RandomAllocationDeciderTests;
import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.ReplicaAfterPrimaryActiveAllocationDecider;
import org.elasticsearch.cluster.routing.allocation.decider.SameShardAllocationDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.shard.IndexEventListener;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.test.gateway.TestGatewayAllocator;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.carrotsearch.randomizedtesting.RandomizedTest.getRandom;
import static org.elasticsearch.env.Environment.PATH_HOME_SETTING;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ClusterStateChanges {
private static final Settings SETTINGS = Settings.builder()
.put(PATH_HOME_SETTING.getKey(), "dummy")
.build();
private static final Logger logger = LogManager.getLogger(ClusterStateChanges.class);
private final AllocationService allocationService;
private final ClusterService clusterService;
private final ShardStateAction.ShardFailedClusterStateTaskExecutor shardFailedClusterStateTaskExecutor;
private final ShardStateAction.ShardStartedClusterStateTaskExecutor shardStartedClusterStateTaskExecutor;
// transport actions
private final TransportCloseIndexAction transportCloseIndexAction;
private final TransportOpenIndexAction transportOpenIndexAction;
private final TransportDeleteIndexAction transportDeleteIndexAction;
private final TransportUpdateSettingsAction transportUpdateSettingsAction;
private final TransportClusterRerouteAction transportClusterRerouteAction;
private final TransportCreateIndexAction transportCreateIndexAction;
private final NodeRemovalClusterStateTaskExecutor nodeRemovalExecutor;
private final JoinTaskExecutor joinTaskExecutor;
public ClusterStateChanges(NamedXContentRegistry xContentRegistry, ThreadPool threadPool) {
ClusterSettings clusterSettings = new ClusterSettings(SETTINGS, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
allocationService = new AllocationService(new AllocationDeciders(
new HashSet<>(Arrays.asList(new SameShardAllocationDecider(SETTINGS, clusterSettings),
new ReplicaAfterPrimaryActiveAllocationDecider(),
new RandomAllocationDeciderTests.RandomAllocationDecider(getRandom())))),
new TestGatewayAllocator(), new BalancedShardsAllocator(SETTINGS),
EmptyClusterInfoService.INSTANCE);
shardFailedClusterStateTaskExecutor
= new ShardStateAction.ShardFailedClusterStateTaskExecutor(allocationService, null, logger);
shardStartedClusterStateTaskExecutor
= new ShardStateAction.ShardStartedClusterStateTaskExecutor(allocationService, null, logger);
ActionFilters actionFilters = new ActionFilters(Collections.emptySet());
IndexNameExpressionResolver indexNameExpressionResolver = new IndexNameExpressionResolver();
DestructiveOperations destructiveOperations = new DestructiveOperations(SETTINGS, clusterSettings);
Environment environment = TestEnvironment.newEnvironment(SETTINGS);
Transport transport = mock(Transport.class); // it's not used
// mocks
clusterService = mock(ClusterService.class);
when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
IndicesService indicesService = mock(IndicesService.class);
// MetadataCreateIndexService uses withTempIndexService to check mappings -> fake it here
try {
when(indicesService.withTempIndexService(any(IndexMetadata.class), any(CheckedFunction.class)))
.then(invocationOnMock -> {
IndexService indexService = mock(IndexService.class);
IndexMetadata indexMetadata = (IndexMetadata) invocationOnMock.getArguments()[0];
when(indexService.index()).thenReturn(indexMetadata.getIndex());
MapperService mapperService = mock(MapperService.class);
when(indexService.mapperService()).thenReturn(mapperService);
when(mapperService.documentMapper()).thenReturn(null);
when(indexService.getIndexEventListener()).thenReturn(new IndexEventListener() {});
when(indexService.getIndexSortSupplier()).thenReturn(() -> null);
//noinspection unchecked
return ((CheckedFunction) invocationOnMock.getArguments()[1]).apply(indexService);
});
} catch (Exception e) {
/*
* Catch Exception because Eclipse uses the lower bound for
* CheckedFunction's exception type so it thinks the "when" call
* can throw Exception. javac seems to be ok inferring something
* else.
*/
throw new IllegalStateException(e);
}
// services
TransportService transportService = new TransportService(SETTINGS, transport, threadPool,
TransportService.NOOP_TRANSPORT_INTERCEPTOR,
boundAddress -> DiscoveryNode.createLocal(SETTINGS, boundAddress.publishAddress(), UUIDs.randomBase64UUID()), clusterSettings,
Collections.emptySet());
MetadataIndexUpgradeService metadataIndexUpgradeService = new MetadataIndexUpgradeService(SETTINGS, xContentRegistry, null, null) {
// metadata upgrader should do nothing
@Override
public IndexMetadata upgradeIndexMetadata(IndexMetadata indexMetadata, Version minimumIndexCompatibilityVersion) {
return indexMetadata;
}
};
NodeClient client = new NodeClient(Settings.EMPTY, threadPool);
Map<ActionType, TransportAction> actions = new HashMap<>();
actions.put(TransportVerifyShardBeforeCloseAction.TYPE, new TransportVerifyShardBeforeCloseAction(SETTINGS,
transportService, clusterService, indicesService, threadPool, null, actionFilters));
client.initialize(actions, transportService.getTaskManager(), null, null);
MetadataIndexStateService indexStateService = new MetadataIndexStateService(clusterService, allocationService,
metadataIndexUpgradeService, indicesService, threadPool, client);
MetadataDeleteIndexService deleteIndexService = new MetadataDeleteIndexService(SETTINGS, clusterService, allocationService);
MetadataUpdateSettingsService metadataUpdateSettingsService = new MetadataUpdateSettingsService(clusterService,
allocationService, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, indicesService, threadPool);
MetadataCreateIndexService createIndexService = new MetadataCreateIndexService(SETTINGS, clusterService, indicesService,
allocationService, new AliasValidator(), environment,
IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, threadPool, xContentRegistry, Collections.emptyList(), true);
transportCloseIndexAction = new TransportCloseIndexAction(SETTINGS, transportService, clusterService, threadPool,
indexStateService, clusterSettings, actionFilters, indexNameExpressionResolver, destructiveOperations);
transportOpenIndexAction = new TransportOpenIndexAction(transportService,
clusterService, threadPool, indexStateService, actionFilters, indexNameExpressionResolver, destructiveOperations);
transportDeleteIndexAction = new TransportDeleteIndexAction(transportService,
clusterService, threadPool, deleteIndexService, actionFilters, indexNameExpressionResolver, destructiveOperations);
transportUpdateSettingsAction = new TransportUpdateSettingsAction(
transportService, clusterService, threadPool, metadataUpdateSettingsService, actionFilters, indexNameExpressionResolver);
transportClusterRerouteAction = new TransportClusterRerouteAction(
transportService, clusterService, threadPool, allocationService, actionFilters, indexNameExpressionResolver);
transportCreateIndexAction = new TransportCreateIndexAction(
transportService, clusterService, threadPool, createIndexService, actionFilters, indexNameExpressionResolver);
nodeRemovalExecutor = new NodeRemovalClusterStateTaskExecutor(allocationService, logger);
joinTaskExecutor = new JoinTaskExecutor(allocationService, logger, (s, p, r) -> {});
}
public ClusterState createIndex(ClusterState state, CreateIndexRequest request) {
return execute(transportCreateIndexAction, request, state);
}
public ClusterState closeIndices(ClusterState state, CloseIndexRequest request) {
final Index[] concreteIndices = Arrays.stream(request.indices())
.map(index -> state.metadata().index(index).getIndex()).toArray(Index[]::new);
final Map<Index, ClusterBlock> blockedIndices = new HashMap<>();
ClusterState newState = MetadataIndexStateServiceUtils.addIndexClosedBlocks(concreteIndices, blockedIndices, state);
newState = MetadataIndexStateServiceUtils.closeRoutingTable(newState, blockedIndices,
blockedIndices.keySet().stream().collect(Collectors.toMap(Function.identity(), CloseIndexResponse.IndexResult::new)));
return allocationService.reroute(newState, "indices closed");
}
public ClusterState openIndices(ClusterState state, OpenIndexRequest request) {
return execute(transportOpenIndexAction, request, state);
}
public ClusterState deleteIndices(ClusterState state, DeleteIndexRequest request) {
return execute(transportDeleteIndexAction, request, state);
}
public ClusterState updateSettings(ClusterState state, UpdateSettingsRequest request) {
return execute(transportUpdateSettingsAction, request, state);
}
public ClusterState reroute(ClusterState state, ClusterRerouteRequest request) {
return execute(transportClusterRerouteAction, request, state);
}
public ClusterState addNodes(ClusterState clusterState, List<DiscoveryNode> nodes) {
return runTasks(joinTaskExecutor, clusterState, nodes.stream().map(node -> new JoinTaskExecutor.Task(node, "dummy reason"))
.collect(Collectors.toList()));
}
public ClusterState joinNodesAndBecomeMaster(ClusterState clusterState, List<DiscoveryNode> nodes) {
List<JoinTaskExecutor.Task> joinNodes = new ArrayList<>();
joinNodes.add(JoinTaskExecutor.newBecomeMasterTask());
joinNodes.add(JoinTaskExecutor.newFinishElectionTask());
joinNodes.addAll(nodes.stream().map(node -> new JoinTaskExecutor.Task(node, "dummy reason"))
.collect(Collectors.toList()));
return runTasks(joinTaskExecutor, clusterState, joinNodes);
}
public ClusterState removeNodes(ClusterState clusterState, List<DiscoveryNode> nodes) {
return runTasks(nodeRemovalExecutor, clusterState, nodes.stream()
.map(n -> new NodeRemovalClusterStateTaskExecutor.Task(n, "dummy reason")).collect(Collectors.toList()));
}
public ClusterState applyFailedShards(ClusterState clusterState, List<FailedShard> failedShards) {
List<FailedShardEntry> entries = failedShards.stream().map(failedShard ->
new FailedShardEntry(failedShard.getRoutingEntry().shardId(), failedShard.getRoutingEntry().allocationId().getId(),
0L, failedShard.getMessage(), failedShard.getFailure(), failedShard.markAsStale()))
.collect(Collectors.toList());
return runTasks(shardFailedClusterStateTaskExecutor, clusterState, entries);
}
public ClusterState applyStartedShards(ClusterState clusterState, List<ShardRouting> startedShards) {
final Map<ShardRouting, Long> entries = startedShards.stream()
.collect(Collectors.toMap(Function.identity(), startedShard -> {
final IndexMetadata indexMetadata = clusterState.metadata().index(startedShard.shardId().getIndex());
return indexMetadata != null ? indexMetadata.primaryTerm(startedShard.shardId().id()) : 0L;
}));
return applyStartedShards(clusterState, entries);
}
public ClusterState applyStartedShards(ClusterState clusterState, Map<ShardRouting, Long> startedShards) {
return runTasks(shardStartedClusterStateTaskExecutor, clusterState, startedShards.entrySet().stream()
.map(e -> new StartedShardEntry(e.getKey().shardId(), e.getKey().allocationId().getId(), e.getValue(), "shard started"))
.collect(Collectors.toList()));
}
private <T> ClusterState runTasks(ClusterStateTaskExecutor<T> executor, ClusterState clusterState, List<T> entries) {
try {
ClusterTasksResult<T> result = executor.execute(clusterState, entries);
for (ClusterStateTaskExecutor.TaskResult taskResult : result.executionResults.values()) {
if (taskResult.isSuccess() == false) {
throw taskResult.getFailure();
}
}
return result.resultingState;
} catch (Exception e) {
throw ExceptionsHelper.convertToRuntime(e);
}
}
private <Request extends MasterNodeRequest<Request>, Response extends ActionResponse> ClusterState execute(
TransportMasterNodeAction<Request, Response> masterNodeAction, Request request, ClusterState clusterState) {
return executeClusterStateUpdateTask(clusterState, () -> {
try {
TransportMasterNodeActionUtils.runMasterOperation(masterNodeAction, request, clusterState, new PlainActionFuture<>());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
private ClusterState executeClusterStateUpdateTask(ClusterState state, Runnable runnable) {
ClusterState[] result = new ClusterState[1];
doAnswer(invocationOnMock -> {
ClusterStateUpdateTask task = (ClusterStateUpdateTask)invocationOnMock.getArguments()[1];
result[0] = task.execute(state);
return null;
}).when(clusterService).submitStateUpdateTask(anyString(), any(ClusterStateUpdateTask.class));
runnable.run();
assertThat(result[0], notNullValue());
return result[0];
}
}
| |
/**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.api.registry;
import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.Pod;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Map;
import static io.fabric8.kubernetes.api.KubernetesHelper.getName;
/**
* Represents an API endpoint within a container
*/
@XmlRootElement(name = "api")
public class ApiDTO {
private String podId;
private String serviceId;
private Map<String, String> labels;
private String containerName;
private String objectName;
private String path;
private String url;
private int port;
private String state;
private String jolokiaUrl;
private String swaggerPath;
private String swaggerUrl;
private String wadlPath;
private String wadlUrl;
private String wsdlPath;
private String wsdlUrl;
public ApiDTO() {
}
public ApiDTO(String podId, String serviceId, Map<String, String> labels, String containerName, String objectName, String path, String url, int port, String state, String jolokiaUrl, String swaggerPath, String swaggerUrl, String wadlPath, String wadlUrl, String wsdlPath, String wsdlUrl) {
this.podId = podId;
this.serviceId = serviceId;
this.labels = labels;
this.containerName = containerName;
this.objectName = objectName;
this.url = url;
this.path = path;
this.port = port;
this.state = state;
this.jolokiaUrl = jolokiaUrl;
this.swaggerPath = swaggerPath;
this.swaggerUrl = swaggerUrl;
this.wadlPath = wadlPath;
this.wadlUrl = wadlUrl;
this.wsdlPath = wsdlPath;
this.wsdlUrl = wsdlUrl;
}
public ApiDTO(Pod pod, Container container, String serviceId, String objectName, String path, String url, int port, String state, String jolokiaUrl, String swaggerPath, String swaggerUrl, String wadlPath, String wadlUrl, String wsdlPath, String wsdlUrl) {
this(getName(pod), serviceId, KubernetesHelper.getLabels(pod.getMetadata()), container.getName(), objectName, path, url, port, state, jolokiaUrl, swaggerPath, swaggerUrl, wadlPath, wadlUrl, wsdlPath, wsdlUrl);
}
@Override
public String toString() {
return "ApiDTO{" +
"podId='" + podId + '\'' +
", serviceId='" + serviceId + '\'' +
", labels=" + labels +
", containerName='" + containerName + '\'' +
", objectName='" + objectName + '\'' +
", url='" + url + '\'' +
", state='" + state + '\'' +
", jolokiaUrl='" + jolokiaUrl + '\'' +
", swaggerUrl='" + swaggerUrl + '\'' +
", wadlUrl='" + wadlUrl + '\'' +
", wsdlUrl='" + wsdlUrl + '\'' +
'}';
}
public String getPodId() {
return podId;
}
public void setPodId(String podId) {
this.podId = podId;
}
public Map<String, String> getLabels() {
return labels;
}
public String getContainerName() {
return containerName;
}
public void setContainerName(String containerName) {
this.containerName = containerName;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getJolokiaUrl() {
return jolokiaUrl;
}
public void setJolokiaUrl(String jolokiaUrl) {
this.jolokiaUrl = jolokiaUrl;
}
public void setLabels(Map<String, String> labels) {
this.labels = labels;
}
public String getSwaggerUrl() {
return swaggerUrl;
}
public void setSwaggerUrl(String swaggerUrl) {
this.swaggerUrl = swaggerUrl;
}
public String getWsdlUrl() {
return wsdlUrl;
}
public void setWsdlUrl(String wsdlUrl) {
this.wsdlUrl = wsdlUrl;
}
public String getWadlUrl() {
return wadlUrl;
}
public void setWadlUrl(String wadlUrl) {
this.wadlUrl = wadlUrl;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getSwaggerPath() {
return swaggerPath;
}
public void setSwaggerPath(String swaggerPath) {
this.swaggerPath = swaggerPath;
}
public String getWadlPath() {
return wadlPath;
}
public void setWadlPath(String wadlPath) {
this.wadlPath = wadlPath;
}
public String getWsdlPath() {
return wsdlPath;
}
public void setWsdlPath(String wsdlPath) {
this.wsdlPath = wsdlPath;
}
}
| |
/*
* 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.karaf.shell.impl.console;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.felix.gogo.jline.Builtin;
import org.apache.felix.gogo.jline.Posix;
import org.apache.felix.gogo.runtime.CommandProcessorImpl;
import org.apache.felix.gogo.runtime.CommandSessionImpl;
import org.apache.felix.gogo.runtime.Reflective;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Function;
import org.apache.felix.service.threadio.ThreadIO;
import org.apache.karaf.shell.api.console.Command;
import org.apache.karaf.shell.api.console.Completer;
import org.apache.karaf.shell.api.console.Parser;
import org.apache.karaf.shell.api.console.Registry;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.api.console.SessionFactory;
import org.apache.karaf.shell.api.console.Terminal;
import org.apache.karaf.shell.impl.console.commands.ExitCommand;
import org.apache.karaf.shell.impl.console.commands.Procedural;
import org.apache.karaf.shell.impl.console.commands.SubShellCommand;
import org.apache.karaf.shell.impl.console.commands.help.HelpCommand;
public class SessionFactoryImpl extends RegistryImpl implements SessionFactory, Registry {
final CommandProcessorImpl commandProcessor;
final ThreadIO threadIO;
final Map<String, SubShellCommand> subshells = new HashMap<>();
boolean closed;
public SessionFactoryImpl(ThreadIO threadIO) {
super(null);
this.threadIO = threadIO;
commandProcessor = new CommandProcessorImpl(threadIO) {
@Override
public Object invoke(CommandSessionImpl session, Object target, String name, List<Object> args) throws Exception {
return SessionFactoryImpl.this.invoke(session, target, name, args);
}
@Override
public Path redirect(CommandSessionImpl session, Path path, int mode) {
return SessionFactoryImpl.this.redirect(session, path, mode);
}
};
register(new ExitCommand());
new HelpCommand(this);
register(new ShellCommand("addCommand", "Add a command", commandProcessor, "addCommand"));
register(new ShellCommand("removeCommand", "Remove a command", commandProcessor, "removeCommand"));
register(new ShellCommand("eval", "Evaluate", commandProcessor, "eval"));
Builtin builtin = new Builtin();
for (String name : new String[]{"format", "getopt", "new", "set", "tac", "type", "jobs", "fg", "bg", "keymap", "setopt", "unsetopt", "complete", "history", "widget", "__files", "__directories", "__usage_completion"}) {
register(new ShellCommand(name, null, builtin, name));
}
Procedural procedural = new Procedural();
for (String name : new String[]{"each", "if", "not", "throw", "try", "until", "while", "break", "continue"}) {
register(new ShellCommand(name, null, procedural, name));
}
Posix posix = new Posix(commandProcessor);
for (String name : new String[]{"cat", "echo", "grep", "sort", "sleep", "cd", "pwd", "ls", "less", "nano", "head", "tail", "clear", "wc", "date", "tmux", "ttop"}) {
register(new ShellCommand(name, null, posix, name));
}
}
protected Object invoke(CommandSessionImpl session, Object target, String name, List<Object> args) throws Exception {
return Reflective.invoke(session, target, name, args);
}
protected Path redirect(CommandSessionImpl session, Path path, int mode) {
return session.currentDir().resolve(path);
}
public CommandProcessorImpl getCommandProcessor() {
return commandProcessor;
}
@Override
public Registry getRegistry() {
return this;
}
@Override
public void register(Object service) {
synchronized (services) {
if (service instanceof Command) {
Command command = (Command) service;
String scope = command.getScope();
String name = command.getName();
if (!Session.SCOPE_GLOBAL.equals(scope)) {
if (!subshells.containsKey(scope)) {
SubShellCommand subShell = new SubShellCommand(scope);
subshells.put(scope, subShell);
register(subShell);
}
subshells.get(scope).increment();
}
commandProcessor.addCommand(scope, wrap(command), name);
}
super.register(service);
}
}
protected Function wrap(Command command) {
return new CommandWrapper(command);
}
@Override
public void unregister(Object service) {
synchronized (services) {
super.unregister(service);
if (service instanceof Command) {
Command command = (Command) service;
String scope = command.getScope();
String name = command.getName();
commandProcessor.removeCommand(scope, name);
if (!Session.SCOPE_GLOBAL.equals(scope)) {
if (subshells.get(scope).decrement() == 0) {
SubShellCommand subShell = subshells.remove(scope);
unregister(subShell);
}
}
}
}
}
@Override
public Session create(InputStream in, PrintStream out, PrintStream err, Terminal term, String encoding, Runnable closeCallback) {
synchronized (commandProcessor) {
if (closed) {
throw new IllegalStateException("SessionFactory has been closed");
}
final Session session = new ConsoleSessionImpl(this, commandProcessor, threadIO, in, out, err, term, encoding, closeCallback);
if (this.session == null) {
this.session = session;
}
return session;
}
}
@Override
public Session create(InputStream in, PrintStream out, PrintStream err) {
return create(in, out, err, null);
}
@Override
public Session create(InputStream in, PrintStream out, PrintStream err, Session parent) {
synchronized (commandProcessor) {
if (closed) {
throw new IllegalStateException("SessionFactory has been closed");
}
final Session session = new HeadlessSessionImpl(this, commandProcessor, in, out, err, parent);
return session;
}
}
public void stop() {
synchronized (commandProcessor) {
closed = true;
commandProcessor.stop();
}
}
private static class ShellCommand implements Command {
private final String name;
private final String desc;
private final Executable consumer;
interface Executable {
Object execute(CommandSession session, List<Object> args) throws Exception;
}
interface ExecutableStr {
void execute(CommandSession session, String[] args) throws Exception;
}
public ShellCommand(String name, String desc, Executable consumer) {
this.name = name;
this.desc = desc;
this.consumer = consumer;
}
public ShellCommand(String name, String desc, ExecutableStr consumer) {
this(name, desc, wrap(consumer));
}
public ShellCommand(String name, String desc, Object target, String method) {
this(name, desc, wrap(target, method));
}
private static Executable wrap(Object target, String name) {
return (session, args) -> Reflective.invoke(session, target, name, args);
}
private static Executable wrap(ExecutableStr command) {
return (session, args) -> {
command.execute(session, asStringArray(args));
return null;
};
}
private static String[] asStringArray(List<Object> args) {
String[] argv = new String[args.size()];
for (int i = 0; i < argv.length; i++) {
argv[i] = Objects.toString(args.get(i));
}
return argv;
}
@Override
public String getScope() {
return "shell";
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return desc;
}
@Override
public Completer getCompleter(boolean scoped) {
return null;
}
@Override
public Parser getParser() {
return null;
}
@Override
public Object execute(Session session, List<Object> arguments) throws Exception {
CommandSession cmdSession = (CommandSession) session.get(".commandSession");
return consumer.execute(cmdSession, arguments);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.metrics.datadog;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.Gauge;
import org.apache.flink.metrics.Histogram;
import org.apache.flink.metrics.Meter;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.reporter.MetricReporter;
import org.apache.flink.metrics.reporter.Scheduled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Metric Reporter for Datadog.
*
* <p>Variables in metrics scope will be sent to Datadog as tags.
*/
public class DatadogHttpReporter implements MetricReporter, Scheduled {
private static final Logger LOGGER = LoggerFactory.getLogger(DatadogHttpReporter.class);
private static final String HOST_VARIABLE = "<host>";
// Both Flink's Gauge and Meter values are taken as gauge in Datadog
private final Map<Gauge, DGauge> gauges = new ConcurrentHashMap<>();
private final Map<Counter, DCounter> counters = new ConcurrentHashMap<>();
private final Map<Meter, DMeter> meters = new ConcurrentHashMap<>();
private DatadogHttpClient client;
private List<String> configTags;
public static final String API_KEY = "apikey";
public static final String TAGS = "tags";
@Override
public void notifyOfAddedMetric(Metric metric, String metricName, MetricGroup group) {
final String name = group.getMetricIdentifier(metricName);
List<String> tags = new ArrayList<>(configTags);
tags.addAll(getTagsFromMetricGroup(group));
String host = getHostFromMetricGroup(group);
if (metric instanceof Counter) {
Counter c = (Counter) metric;
counters.put(c, new DCounter(c, name, host, tags));
} else if (metric instanceof Gauge) {
Gauge g = (Gauge) metric;
gauges.put(g, new DGauge(g, name, host, tags));
} else if (metric instanceof Meter) {
Meter m = (Meter) metric;
// Only consider rate
meters.put(m, new DMeter(m, name, host, tags));
} else if (metric instanceof Histogram) {
LOGGER.warn("Cannot add {} because Datadog HTTP API doesn't support Histogram", metricName);
} else {
LOGGER.warn("Cannot add unknown metric type {}. This indicates that the reporter " +
"does not support this metric type.", metric.getClass().getName());
}
}
@Override
public void notifyOfRemovedMetric(Metric metric, String metricName, MetricGroup group) {
if (metric instanceof Counter) {
counters.remove(metric);
} else if (metric instanceof Gauge) {
gauges.remove(metric);
} else if (metric instanceof Meter) {
meters.remove(metric);
} else if (metric instanceof Histogram) {
// No Histogram is registered
} else {
LOGGER.warn("Cannot remove unknown metric type {}. This indicates that the reporter " +
"does not support this metric type.", metric.getClass().getName());
}
}
@Override
public void open(MetricConfig config) {
client = new DatadogHttpClient(config.getString(API_KEY, null));
LOGGER.info("Configured DatadogHttpReporter");
configTags = getTagsFromConfig(config.getString(TAGS, ""));
}
@Override
public void close() {
client.close();
LOGGER.info("Shut down DatadogHttpReporter");
}
@Override
public void report() {
DatadogHttpRequest request = new DatadogHttpRequest();
for (Map.Entry<Gauge, DGauge> entry : gauges.entrySet()) {
DGauge g = entry.getValue();
try {
// Will throw exception if the Gauge is not of Number type
// Flink uses Gauge to store many types other than Number
g.getMetricValue();
request.addGauge(g);
} catch (Exception e) {
// Remove that Gauge if it's not of Number type
gauges.remove(entry.getKey());
}
}
for (DCounter c : counters.values()) {
request.addCounter(c);
}
for (DMeter m : meters.values()) {
request.addMeter(m);
}
try {
client.send(request);
} catch (SocketTimeoutException e) {
LOGGER.warn("Failed reporting metrics to Datadog because of socket timeout.", e.getMessage());
} catch (Exception e) {
LOGGER.warn("Failed reporting metrics to Datadog.", e);
}
}
/**
* Get config tags from config 'metrics.reporter.dghttp.tags'.
*/
private List<String> getTagsFromConfig(String str) {
return Arrays.asList(str.split(","));
}
/**
* Get tags from MetricGroup#getAllVariables(), excluding 'host'.
*/
private List<String> getTagsFromMetricGroup(MetricGroup metricGroup) {
List<String> tags = new ArrayList<>();
for (Map.Entry<String, String> entry: metricGroup.getAllVariables().entrySet()) {
if (!entry.getKey().equals(HOST_VARIABLE)) {
tags.add(getVariableName(entry.getKey()) + ":" + entry.getValue());
}
}
return tags;
}
private String getHostFromMetricGroup(MetricGroup metricGroup) {
return metricGroup.getAllVariables().get(HOST_VARIABLE);
}
/**
* Removes leading and trailing angle brackets.
*/
private String getVariableName(String str) {
return str.substring(1, str.length() - 1);
}
/**
* Compact metrics in batch, serialize them, and send to Datadog via HTTP.
*/
static class DatadogHttpRequest {
private final DSeries series;
public DatadogHttpRequest() {
series = new DSeries();
}
public void addGauge(DGauge gauge) {
series.addMetric(gauge);
}
public void addCounter(DCounter counter) {
series.addMetric(counter);
}
public void addMeter(DMeter meter) {
series.addMetric(meter);
}
public DSeries getSeries() {
return series;
}
}
}
| |
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.monitor.impl;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.partition.LocalReplicationStats;
import com.hazelcast.query.LocalIndexStats;
import com.hazelcast.replicatedmap.LocalReplicatedMapStats;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_CREATION_TIME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_MAX_GET_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_MAX_PUT_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_MAX_REMOVE_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_GET_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_HITS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_LAST_ACCESS_TIME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_LAST_UPDATE_TIME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_NUMBER_OF_EVENTS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_NUMBER_OF_OTHER_OPERATIONS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_PUT_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_REMOVE_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_TOTAL_GET_LATENCIES;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_TOTAL_PUT_LATENCIES;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_TOTAL_REMOVE_LATENCIES;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_OWNED_ENTRY_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_OWNED_ENTRY_MEMORY_COST;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_TOTAL;
import static com.hazelcast.internal.metrics.ProbeUnit.BYTES;
import static com.hazelcast.internal.metrics.ProbeUnit.MS;
import static com.hazelcast.internal.util.ConcurrencyUtil.setMax;
import static com.hazelcast.internal.util.TimeUtil.convertNanosToMillis;
import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater;
/**
* This class collects statistics about the replication map usage for management center and is
* able to transform those between wire format and instance view.
*/
@SuppressWarnings("checkstyle:methodcount")
public class LocalReplicatedMapStatsImpl implements LocalReplicatedMapStats {
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> LAST_ACCESS_TIME =
newUpdater(LocalReplicatedMapStatsImpl.class, "lastAccessTime");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> LAST_UPDATE_TIME =
newUpdater(LocalReplicatedMapStatsImpl.class, "lastUpdateTime");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> HITS =
newUpdater(LocalReplicatedMapStatsImpl.class, "hits");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> NUMBER_OF_OTHER_OPERATIONS =
newUpdater(LocalReplicatedMapStatsImpl.class, "numberOfOtherOperations");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> NUMBER_OF_EVENTS =
newUpdater(LocalReplicatedMapStatsImpl.class, "numberOfEvents");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> GET_COUNT =
newUpdater(LocalReplicatedMapStatsImpl.class, "getCount");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> PUT_COUNT =
newUpdater(LocalReplicatedMapStatsImpl.class, "putCount");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> REMOVE_COUNT =
newUpdater(LocalReplicatedMapStatsImpl.class, "removeCount");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> TOTAL_GET_LATENCIES =
newUpdater(LocalReplicatedMapStatsImpl.class, "totalGetLatenciesNanos");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> TOTAL_PUT_LATENCIES =
newUpdater(LocalReplicatedMapStatsImpl.class, "totalPutLatenciesNanos");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> TOTAL_REMOVE_LATENCIES =
newUpdater(LocalReplicatedMapStatsImpl.class, "totalRemoveLatenciesNanos");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> MAX_GET_LATENCY =
newUpdater(LocalReplicatedMapStatsImpl.class, "maxGetLatencyNanos");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> MAX_PUT_LATENCY =
newUpdater(LocalReplicatedMapStatsImpl.class, "maxPutLatencyNanos");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> MAX_REMOVE_LATENCY =
newUpdater(LocalReplicatedMapStatsImpl.class, "maxRemoveLatencyNanos");
private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> OWNED_ENTRY_MEMORY_COST =
newUpdater(LocalReplicatedMapStatsImpl.class, "ownedEntryMemoryCost");
// these fields are only accessed through the updaters
@Probe(name = REPLICATED_MAP_METRIC_LAST_ACCESS_TIME, unit = MS)
private volatile long lastAccessTime;
@Probe(name = REPLICATED_MAP_METRIC_LAST_UPDATE_TIME, unit = MS)
private volatile long lastUpdateTime;
@Probe(name = REPLICATED_MAP_METRIC_HITS)
private volatile long hits;
@Probe(name = REPLICATED_MAP_METRIC_NUMBER_OF_OTHER_OPERATIONS)
private volatile long numberOfOtherOperations;
@Probe(name = REPLICATED_MAP_METRIC_NUMBER_OF_EVENTS)
private volatile long numberOfEvents;
@Probe(name = REPLICATED_MAP_METRIC_GET_COUNT)
private volatile long getCount;
@Probe(name = REPLICATED_MAP_METRIC_PUT_COUNT)
private volatile long putCount;
@Probe(name = REPLICATED_MAP_METRIC_REMOVE_COUNT)
private volatile long removeCount;
private volatile long totalGetLatenciesNanos;
private volatile long totalPutLatenciesNanos;
private volatile long totalRemoveLatenciesNanos;
private volatile long maxGetLatencyNanos;
private volatile long maxPutLatencyNanos;
private volatile long maxRemoveLatencyNanos;
@Probe(name = REPLICATED_MAP_CREATION_TIME, unit = MS)
private final long creationTime;
@Probe(name = REPLICATED_MAP_OWNED_ENTRY_COUNT)
private volatile long ownedEntryCount;
@Probe(name = REPLICATED_MAP_OWNED_ENTRY_MEMORY_COST, unit = BYTES)
private volatile long ownedEntryMemoryCost;
public LocalReplicatedMapStatsImpl() {
creationTime = Clock.currentTimeMillis();
}
@Override
public long getOwnedEntryCount() {
return ownedEntryCount;
}
public void setOwnedEntryCount(long ownedEntryCount) {
this.ownedEntryCount = ownedEntryCount;
}
@Override
public long getBackupEntryCount() {
return 0;
}
// TODO: unused
public void setBackupEntryCount(long backupEntryCount) {
}
@Override
public int getBackupCount() {
return 0;
}
// TODO: unused
public void setBackupCount(int backupCount) {
}
@Override
public long getOwnedEntryMemoryCost() {
return ownedEntryMemoryCost;
}
public void setOwnedEntryMemoryCost(long ownedEntryMemoryCost) {
OWNED_ENTRY_MEMORY_COST.set(this, ownedEntryMemoryCost);
}
@Override
public long getBackupEntryMemoryCost() {
return 0;
}
// TODO: unused
public void setBackupEntryMemoryCost(long backupEntryMemoryCost) {
}
@Override
public long getCreationTime() {
return creationTime;
}
@Override
public long getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(long lastAccessTime) {
setMax(this, LAST_ACCESS_TIME, lastAccessTime);
}
@Override
public long getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(long lastUpdateTime) {
setMax(this, LAST_UPDATE_TIME, lastUpdateTime);
}
@Override
public long getHits() {
return hits;
}
public void setHits(long hits) {
HITS.set(this, hits);
}
@Override
public long getLockedEntryCount() {
return 0;
}
// TODO: unused
public void setLockedEntryCount(long lockedEntryCount) {
}
@Override
public long getDirtyEntryCount() {
return 0;
}
// TODO: unused
public void setDirtyEntryCount(long dirtyEntryCount) {
}
@Probe(name = REPLICATED_MAP_TOTAL)
@Override
public long total() {
return putCount + getCount + removeCount + numberOfOtherOperations;
}
@Override
public long getPutOperationCount() {
return putCount;
}
public void incrementPutsNanos(long latencyNanos) {
PUT_COUNT.incrementAndGet(this);
TOTAL_PUT_LATENCIES.addAndGet(this, latencyNanos);
setMax(this, MAX_PUT_LATENCY, latencyNanos);
}
@Override
public long getGetOperationCount() {
return getCount;
}
public void incrementGetsNanos(long latencyNanos) {
GET_COUNT.incrementAndGet(this);
TOTAL_GET_LATENCIES.addAndGet(this, latencyNanos);
setMax(this, MAX_GET_LATENCY, latencyNanos);
}
@Override
public long getRemoveOperationCount() {
return removeCount;
}
public void incrementRemovesNanos(long latencyNanos) {
REMOVE_COUNT.incrementAndGet(this);
TOTAL_REMOVE_LATENCIES.addAndGet(this, latencyNanos);
setMax(this, MAX_REMOVE_LATENCY, latencyNanos);
}
@Probe(name = REPLICATED_MAP_METRIC_TOTAL_PUT_LATENCIES, unit = MS)
@Override
public long getTotalPutLatency() {
return convertNanosToMillis(totalPutLatenciesNanos);
}
@Probe(name = REPLICATED_MAP_METRIC_TOTAL_GET_LATENCIES, unit = MS)
@Override
public long getTotalGetLatency() {
return convertNanosToMillis(totalGetLatenciesNanos);
}
@Probe(name = REPLICATED_MAP_METRIC_TOTAL_REMOVE_LATENCIES, unit = MS)
@Override
public long getTotalRemoveLatency() {
return convertNanosToMillis(totalRemoveLatenciesNanos);
}
@Probe(name = REPLICATED_MAP_MAX_PUT_LATENCY, unit = MS)
@Override
public long getMaxPutLatency() {
return convertNanosToMillis(maxPutLatencyNanos);
}
@Probe(name = REPLICATED_MAP_MAX_GET_LATENCY, unit = MS)
@Override
public long getMaxGetLatency() {
return convertNanosToMillis(maxGetLatencyNanos);
}
@Probe(name = REPLICATED_MAP_MAX_REMOVE_LATENCY, unit = MS)
@Override
public long getMaxRemoveLatency() {
return convertNanosToMillis(maxRemoveLatencyNanos);
}
@Override
public long getOtherOperationCount() {
return numberOfOtherOperations;
}
public void incrementOtherOperations() {
NUMBER_OF_OTHER_OPERATIONS.incrementAndGet(this);
}
@Override
public long getEventOperationCount() {
return numberOfEvents;
}
public void incrementReceivedEvents() {
NUMBER_OF_EVENTS.incrementAndGet(this);
}
@Override
public long getHeapCost() {
return 0;
}
// TODO: unused
public void setHeapCost(long heapCost) {
}
@Override
public long getMerkleTreesCost() {
return 0;
}
// TODO: unused
public void setMerkleTreesCost(long merkleTreesCost) {
}
@Override
public NearCacheStatsImpl getNearCacheStats() {
throw new UnsupportedOperationException("Replicated map has no Near Cache!");
}
@Override
public long getQueryCount() {
throw new UnsupportedOperationException("Queries on replicated maps are not supported.");
}
@Override
public long getIndexedQueryCount() {
throw new UnsupportedOperationException("Queries on replicated maps are not supported.");
}
@Override
public Map<String, LocalIndexStats> getIndexStats() {
throw new UnsupportedOperationException("Queries on replicated maps are not supported.");
}
@Override
public long getSetOperationCount() {
throw new UnsupportedOperationException("Set operation on replicated maps is not supported.");
}
@Override
public long getTotalSetLatency() {
throw new UnsupportedOperationException("Set operation on replicated maps is not supported.");
}
@Override
public long getMaxSetLatency() {
throw new UnsupportedOperationException("Set operation on replicated maps is not supported.");
}
@Override
public LocalReplicationStats getReplicationStats() {
throw new UnsupportedOperationException("Replication stats are not available for replicated maps.");
}
@Override
public String toString() {
return "LocalReplicatedMapStatsImpl{"
+ "lastAccessTime=" + lastAccessTime
+ ", lastUpdateTime=" + lastUpdateTime
+ ", hits=" + hits
+ ", numberOfOtherOperations=" + numberOfOtherOperations
+ ", numberOfEvents=" + numberOfEvents
+ ", getCount=" + getCount
+ ", putCount=" + putCount
+ ", removeCount=" + removeCount
+ ", totalGetLatencies=" + convertNanosToMillis(totalGetLatenciesNanos)
+ ", totalPutLatencies=" + convertNanosToMillis(totalPutLatenciesNanos)
+ ", totalRemoveLatencies=" + convertNanosToMillis(totalRemoveLatenciesNanos)
+ ", ownedEntryCount=" + ownedEntryCount
+ ", ownedEntryMemoryCost=" + ownedEntryMemoryCost
+ ", creationTime=" + creationTime
+ '}';
}
}
| |
package edu.messiah.cis284;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This class creates a LocationSummary object that stores important locational data such as
* average temperature, max. temperature, min. temperature, max. heat index, and min.
* wind chill for given dates.
*
* @author nerdkid93
*/
public class LocationSummary {
//This field contains the location of the LocationSummary object. Initialized in the constructor
private String siteID;
//This field is an array of WeatherObservation objects used to find the location's weather data.
WeatherObservation[] data;
/**
* This constructor forms a LocationSummary object when given a location, start date, and an end
* date, all as Strings. (Dates are in the YYYY-MM-DD form.)
*
* @param siteID
* @param startDate
* @param endDate
*/
public LocationSummary(String siteID, String startDate, String endDate) {
this.siteID = siteID;
data = getPscData(startDate, endDate);
}
/**
* This constructor forms a LocationSummary object when given a location as a Strinng and a year
* given as an int.
*
* @param siteID
* @param year
*/
public LocationSummary(String siteID, int year) {
this.siteID = siteID;
String startDate = year + "-01-01";
String endDate = year + "-12-31";
data = getPscData(startDate, endDate);
}
/**
* This constructor forms a LocationSummary object when given a location and an array of dates,
* all as Strings. (Dates are given in the YYYY-MM-DD form.)
*
* @param siteID
* @param dates
*/
public LocationSummary(String siteID, String[] dates) {
this.siteID = siteID;
WeatherObservation[] tempObj;
WeatherObservation[] finalList;
ArrayList<WeatherObservation> tempList = new ArrayList<WeatherObservation>();
for (String d : dates) {
tempObj = getPscData(d, d);
if(tempObj != null) {
tempList.add(tempObj[0]);
}
else {
System.out.println(siteID + " - " + d + " -> null");
}
}
finalList = tempList.toArray(new WeatherObservation[tempList.size()]);
data = finalList;
}
/**
* This method creates an array of WeatherObservations to populate the data field for the LocationSummary
* object. When given a start date and an end date, it checks the PennState weather database for PA
* and creates a WeatherObservation object for each date, given that every date returns a valid point
* of data to create the WeatherObservation object.
*
* @param startDate
* @param endDate
* @return weatherArray
*/
private WeatherObservation[] getPscData(String startDate, String endDate) {
try {
URL url = new URL(
"http://climate.met.psu.edu/data/ida/submit.php");
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
String formData = "siteid=" + siteID + "&"
+ "db=faa_hourly" + "&"
+ "datastart=" + startDate + "&"
+ "dataend=" + endDate + "&"
+ "choices[]=datetime" + "&"
+ "choices[]=temp_max" + "&"
+ "choices[]=temp_min" + "&"
+ "choices[]=rh_avg" + "&"
+ "choices[]=wspd_avg" + "&"
+ "filetype=file" + "&"
+ "isMeta=1";
writer.write(formData);
writer.flush();
Scanner scanner = new Scanner(connection.getInputStream());
ArrayList<WeatherObservation> lines =
new ArrayList<WeatherObservation>();
while (scanner.hasNextLine()) {
WeatherObservation observation =
new WeatherObservation(scanner.nextLine());
if (observation.isValid())
lines.add(observation);
}
scanner.close();
if (lines.size() == 0) {
return null;
}
else {
return lines.toArray(new WeatherObservation[lines.size()]);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
// Won't ever get here, but this line stops compiler from
// complaining about the method not returning anything.
return null;
}
}
/**
* Cycles through each WeatherObservation object in the data field and returns the object that has the highest
* temperature.
*
* @return maxTemp
*/
public WeatherObservation getMaxTempObservation() {
double compareTemp = 0;
int compareIndex = 0;
int index = 0;
for (WeatherObservation d : data){
if (d.getMaxTemp() > compareTemp){
compareTemp = d.getMaxTemp();
compareIndex = index;
}
index++;
}
return data[compareIndex];
}
/**
* Cycles through each WeatherObservation object in the data field and returns the object that has the lowest
* temperature.
*
* @return minTemp The WeatherObservation object that meets the condition of having the lowest temperature.
*/
public WeatherObservation getMinTempObservation() {
double compareTemp = 0;
int compareIndex = 0;
int index = 0;
for (WeatherObservation d : data){
if (index == 0){
compareTemp = d.getMinTemp();
}
else if (d.getMinTemp() < compareTemp){
compareTemp = d.getMinTemp();
compareIndex = index;
}
index++;
}
return data[compareIndex];
}
/**
* Cycles through each WeatherObservation object in the data field and returns the object that has the highest
* heat index.
*
* @return maxHeatIndex The WeatherObservation object that meets the condition of having the highest heat index.
*/
public WeatherObservation getMaxHeatIndexObservation() {
double compareHeatIndex = 0;
int compareIndex = 0;
int index = 0;
for (WeatherObservation d : data){
if (d.getHeatIndex() > compareHeatIndex){
compareHeatIndex = d.getHeatIndex();
compareIndex = index;
}
index++;
}
return data[compareIndex];
}
/**
* Cycles through each WeatherObservation object in the data field and returns the object that has the lowest
* wind chill.
*
* @return minWindChill The WeatherObservation object that meets the condition of having the lowest wind chill.
*/
public WeatherObservation getMinWindChillObservation() {
double compareWindChill = 0;
int compareIndex = 0;
int index = 0;
for (WeatherObservation d : data){
if (index == 0){
compareWindChill = d.getWindChill();
}
else if (d.getWindChill() < compareWindChill){
compareWindChill = d.getWindChill();
compareIndex = index;
}
index++;
}
return data[compareIndex];
}
/**
* Cycles through each WeatherObservation object in the data field and adds up each data point's max. and min.
* temperatures. After adding them up, it divides by the number of temperatures in the total
* (2*data.length).
*
* @return avg
*/
public double getAverageTemperature() {
double total = 0;
int sum = 0;
double avg;
for (WeatherObservation d : data) {
total += d.getMaxTemp() + d.getMinTemp();
sum += 2;
}
avg = total / sum;
return avg;
}
/**
* Returns the location of the LocationSummary object.
*
* @return location
*/
public String getLocation() {return siteID;}
}
| |
/*
* Copyright 2019 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.modelcompiler.builder.generator.visitor.accumulate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.expr.BinaryExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.LambdaExpr;
import com.github.javaparser.ast.expr.LiteralExpr;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.MethodReferenceExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import org.drools.compiler.lang.descr.AccumulateDescr;
import org.drools.compiler.lang.descr.AndDescr;
import org.drools.compiler.lang.descr.BaseDescr;
import org.drools.compiler.lang.descr.PatternDescr;
import org.drools.compiler.rule.builder.util.AccumulateUtil;
import org.drools.core.base.accumulators.CollectAccumulator;
import org.drools.core.base.accumulators.CollectListAccumulateFunction;
import org.drools.core.base.accumulators.CollectSetAccumulateFunction;
import org.drools.core.rule.Pattern;
import org.drools.modelcompiler.builder.PackageModel;
import org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult;
import org.drools.modelcompiler.builder.generator.DeclarationSpec;
import org.drools.modelcompiler.builder.generator.DrlxParseUtil;
import org.drools.modelcompiler.builder.generator.RuleContext;
import org.drools.modelcompiler.builder.generator.TypedExpression;
import org.drools.modelcompiler.builder.generator.drlxparse.ConstraintParser;
import org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseFail;
import org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseResult;
import org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseSuccess;
import org.drools.modelcompiler.builder.generator.drlxparse.ParseResultVisitor;
import org.drools.modelcompiler.builder.generator.drlxparse.SingleDrlxParseSuccess;
import org.drools.modelcompiler.builder.generator.expression.AbstractExpressionBuilder;
import org.drools.modelcompiler.builder.generator.expression.PatternExpressionBuilder;
import org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyper;
import org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyperContext;
import org.drools.modelcompiler.builder.generator.visitor.ModelGeneratorVisitor;
import org.drools.modelcompiler.util.LambdaUtil;
import org.drools.mvel.parser.ast.expr.DrlNameExpr;
import org.kie.api.runtime.rule.AccumulateFunction;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import static org.drools.modelcompiler.builder.generator.DrlxParseUtil.getLiteralExpressionType;
import static org.drools.modelcompiler.builder.generator.DrlxParseUtil.validateDuplicateBindings;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.ACCUMULATE_CALL;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.ACC_FUNCTION_CALL;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.AND_CALL;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.BIND_CALL;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.BIND_AS_CALL;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.VALUE_OF_CALL;
import static org.drools.modelcompiler.builder.generator.DslMethodNames.REACT_ON_CALL;
import static org.drools.modelcompiler.util.lambdareplace.ReplaceTypeInLambda.replaceTypeInExprLambda;
import static org.drools.mvel.parser.printer.PrintUtil.printConstraint;
public class AccumulateVisitor {
private final RuleContext context;
private final PackageModel packageModel;
private final ModelGeneratorVisitor modelGeneratorVisitor;
private final AbstractExpressionBuilder expressionBuilder;
public AccumulateVisitor(ModelGeneratorVisitor modelGeneratorVisitor, RuleContext context, PackageModel packageModel) {
this.context = context;
this.modelGeneratorVisitor = modelGeneratorVisitor;
this.packageModel = packageModel;
this.expressionBuilder = new PatternExpressionBuilder(context);
}
public void visit(AccumulateDescr descr, PatternDescr basePattern) {
final MethodCallExpr accumulateDSL = new MethodCallExpr(null, ACCUMULATE_CALL);
context.addExpression(accumulateDSL);
final MethodCallExpr accumulateExprs = new MethodCallExpr(null, AND_CALL);
accumulateDSL.addArgument(accumulateExprs);
this.context.pushScope(descr);
pushAccumulateContext( accumulateExprs );
try {
Set<String> externalDeclrs = new HashSet<>( context.getAvailableBindings() );
BaseDescr input = descr.getInputPattern() == null ? descr.getInput() : descr.getInputPattern();
input.accept( modelGeneratorVisitor );
if ( accumulateExprs.getArguments().isEmpty() ) {
accumulateDSL.remove( accumulateExprs );
} else if ( accumulateExprs.getArguments().size() == 1 ) {
accumulateDSL.setArgument( 0, accumulateExprs.getArguments().get( 0 ) );
}
if ( !descr.getFunctions().isEmpty() ) {
if ( validateBindings(descr) ) {
return;
}
classicAccumulate( descr, basePattern, input, accumulateDSL );
} else if ( descr.getFunctions().isEmpty() && descr.getInitCode() != null ) {
new AccumulateInlineVisitor( context, packageModel ).inlineAccumulate( descr, basePattern, accumulateDSL, externalDeclrs, input );
} else {
throw new UnsupportedOperationException( "Unknown type of Accumulate." );
}
} finally {
context.popExprPointer();
this.context.popScope();
}
}
private void classicAccumulate(AccumulateDescr descr, PatternDescr basePattern, BaseDescr input, MethodCallExpr accumulateDSL) {
for (AccumulateDescr.AccumulateFunctionCallDescr function : descr.getFunctions()) {
try {
Optional<NewBinding> optNewBinding = visit(function, basePattern, input, accumulateDSL);
processNewBinding(optNewBinding, accumulateDSL);
} catch (AccumulateNonExistingFunction e) {
addNonExistingFunctionError(context, e.function);
return;
} catch (AccumulateParsingFailedException e) {
context.addCompilationError(new InvalidExpressionErrorResult(e.getMessage(), Optional.of(context.getRuleDescr())));
return;
}
}
}
private boolean validateBindings(AccumulateDescr descr) {
final List<String> allBindings = descr
.getFunctions()
.stream()
.map(AccumulateDescr.AccumulateFunctionCallDescr::getBind)
.filter(Objects::nonNull)
.collect(toList());
final Optional<InvalidExpressionErrorResult> invalidExpressionErrorResult = validateDuplicateBindings(context.getRuleName(), allBindings);
invalidExpressionErrorResult.ifPresent(context::addCompilationError);
return invalidExpressionErrorResult.isPresent();
}
private Optional<NewBinding> visit(AccumulateDescr.AccumulateFunctionCallDescr function, PatternDescr basePattern, BaseDescr input, MethodCallExpr accumulateDSL) {
context.pushExprPointer(accumulateDSL::addArgument);
try {
final MethodCallExpr functionDSL = new MethodCallExpr( null, ACC_FUNCTION_CALL );
final String optBindingId = ofNullable( function.getBind() ).orElse( basePattern.getIdentifier() );
final String bindingId = context.getOutOfScopeVar( ofNullable( optBindingId ).orElse( context.getOrCreateAccumulatorBindingId( function.getFunction() ) ) );
Optional<NewBinding> optNewBinding = Optional.empty();
if ( function.getParams().length == 0 ) {
final AccumulateFunction optAccumulateFunction = getAccumulateFunction( function, Object.class );
zeroParameterFunction( basePattern, functionDSL, bindingId, optAccumulateFunction );
} else {
optNewBinding = parseFirstParameter( basePattern, input, function, functionDSL, bindingId );
}
if ( bindingId != null ) {
final MethodCallExpr asDSL = new MethodCallExpr( functionDSL, BIND_AS_CALL );
asDSL.addArgument( context.getVarExpr( bindingId, DrlxParseUtil.toVar(bindingId) ) );
accumulateDSL.addArgument( asDSL );
}
return optNewBinding;
} finally {
context.popExprPointer();
}
}
private Optional<NewBinding> parseFirstParameter(PatternDescr basePattern, BaseDescr input, AccumulateDescr.AccumulateFunctionCallDescr function, MethodCallExpr functionDSL, String bindingId) {
final String accumulateFunctionParameterStr = function.getParams()[0];
final Expression accumulateFunctionParameter = DrlxParseUtil.parseExpression(accumulateFunctionParameterStr).getExpr();
if (accumulateFunctionParameter instanceof BinaryExpr) {
return binaryExprParameter(basePattern, function, functionDSL, bindingId, accumulateFunctionParameterStr);
}
if (parameterNeedsConvertionToMethodCallExpr(accumulateFunctionParameter)) {
return methodCallExprParameter(basePattern, input, function, functionDSL, bindingId, accumulateFunctionParameter);
}
if (accumulateFunctionParameter instanceof DrlNameExpr) {
nameExprParameter(basePattern, function, functionDSL, bindingId, accumulateFunctionParameter);
} else if (accumulateFunctionParameter instanceof LiteralExpr) {
literalExprParameter(basePattern, function, functionDSL, bindingId, accumulateFunctionParameter);
} else {
context.addCompilationError(new InvalidExpressionErrorResult("Invalid expression " + accumulateFunctionParameterStr, Optional.of(context.getRuleDescr())));
throw new AccumulateParsingFailedException();
}
return Optional.empty();
}
private void literalExprParameter(PatternDescr basePattern, AccumulateDescr.AccumulateFunctionCallDescr function, MethodCallExpr functionDSL, String bindingId, Expression accumulateFunctionParameter) {
final Class<?> declarationClass = getLiteralExpressionType((LiteralExpr) accumulateFunctionParameter);
AccumulateFunction accumulateFunction = getAccumulateFunction(function, declarationClass);
validateAccFunctionTypeAgainstPatternType(context, basePattern, accumulateFunction);
functionDSL.addArgument(createAccSupplierExpr(accumulateFunction));
functionDSL.addArgument(new MethodCallExpr(null, VALUE_OF_CALL, NodeList.nodeList(accumulateFunctionParameter)));
addBindingAsDeclaration(context, bindingId, accumulateFunction);
}
private void nameExprParameter(PatternDescr basePattern, AccumulateDescr.AccumulateFunctionCallDescr function, MethodCallExpr functionDSL, String bindingId, Expression accumulateFunctionParameter) {
String nameExpr = ((DrlNameExpr) accumulateFunctionParameter).getName().asString();
Optional<DeclarationSpec> declaration = context.getDeclarationById(nameExpr);
if ( !declaration.isPresent() ) {
String name = nameExpr;
declaration = context.getAllDeclarations().stream().filter( d -> d.getVariableName().map( n -> n.equals( name ) ).orElse( false ) ).findFirst();
if ( declaration.isPresent() ) {
nameExpr = declaration.get().getBindingId();
} else {
throw new RuntimeException("Unknown parameter in accumulate: " + accumulateFunctionParameter);
}
}
AccumulateFunction accumulateFunction = getAccumulateFunction(function, declaration.get().getDeclarationClass());
validateAccFunctionTypeAgainstPatternType(context, basePattern, accumulateFunction);
functionDSL.addArgument(createAccSupplierExpr(accumulateFunction));
functionDSL.addArgument(context.getVarExpr(nameExpr));
addBindingAsDeclaration(context, bindingId, accumulateFunction);
}
private Optional<NewBinding> methodCallExprParameter(PatternDescr basePattern, BaseDescr input, AccumulateDescr.AccumulateFunctionCallDescr function, MethodCallExpr functionDSL, String bindingId, Expression accumulateFunctionParameter) {
final Expression parameterConverted = convertParameter(accumulateFunctionParameter);
final DrlxParseUtil.RemoveRootNodeResult methodCallWithoutRootNode = DrlxParseUtil.removeRootNode(parameterConverted);
String rootNodeName = getRootNodeName(methodCallWithoutRootNode);
Optional<DeclarationSpec> decl = context.getDeclarationById(rootNodeName);
Class<?> clazz = decl.map(DeclarationSpec::getDeclarationClass)
.orElseGet( () -> {
try {
return context.getTypeResolver().resolveType(rootNodeName);
} catch (ClassNotFoundException e) {
throw new RuntimeException( e );
}
} );
final ExpressionTyperContext expressionTyperContext = new ExpressionTyperContext();
final ExpressionTyper expressionTyper = new ExpressionTyper(context, clazz, bindingId, false, expressionTyperContext);
TypedExpression typedExpression =
expressionTyper
.toTypedExpression(methodCallWithoutRootNode.getWithoutRootNode())
.typedExpressionOrException();
final Class<?> methodCallExprType = typedExpression.getRawClass();
final AccumulateFunction accumulateFunction = getAccumulateFunction(function, methodCallExprType);
validateAccFunctionTypeAgainstPatternType(context, basePattern, accumulateFunction);
functionDSL.addArgument(createAccSupplierExpr(accumulateFunction));
// Every expression in an accumulate function gets transformed in a bind expression with a generated id
// Then the accumulate function will have that binding expression as a source
final Class accumulateFunctionResultType = accumulateFunction.getResultType();
final String bindExpressionVariable = context.getExprId(accumulateFunctionResultType, typedExpression.toString());
String paramExprBindingId = rootNodeName;
Class<?> patternType = clazz;
PatternDescr inputPattern = decl.isPresent() ? null : findInputPattern(input);
if (inputPattern != null) {
String inputId = inputPattern.getIdentifier();
Optional<DeclarationSpec> accumulateClassDeclOpt = context.getDeclarationById(inputId);
if (accumulateClassDeclOpt.isPresent()) {
// when static method is used in accumulate function, "_this" is a pattern input
// Note that DrlxParseUtil.generateLambdaWithoutParameters() takes the patternType as a class of "_this"
paramExprBindingId = inputId;
patternType = accumulateClassDeclOpt.get().getDeclarationClass();
}
}
SingleDrlxParseSuccess drlxParseResult = (SingleDrlxParseSuccess) new ConstraintParser(context, context.getPackageModel())
.drlxParse(patternType, paramExprBindingId, printConstraint(parameterConverted));
if (inputPattern != null) {
drlxParseResult.setAccumulateBinding( inputPattern.getIdentifier() );
}
return drlxParseResult.acceptWithReturnValue(new ReplaceBindingVisitor(functionDSL, bindingId, methodCallExprType, accumulateFunctionResultType, bindExpressionVariable, drlxParseResult));
}
private PatternDescr findInputPattern(BaseDescr input) {
if ( input instanceof PatternDescr ) {
return (PatternDescr) input;
}
if ( input instanceof AndDescr ) {
List<BaseDescr> childDescrs = (( AndDescr ) input).getDescrs();
for (int i = childDescrs.size()-1; i >= 0; i--) {
if ( childDescrs.get(i) instanceof PatternDescr ) {
return (( PatternDescr ) childDescrs.get( i ));
}
}
}
return null;
}
private class ReplaceBindingVisitor implements ParseResultVisitor<Optional<NewBinding>> {
private final MethodCallExpr functionDSL;
private final String bindingId;
private final Class<?> methodCallExprType;
private final Class accumulateFunctionResultType;
private final String bindExpressionVariable;
private final SingleDrlxParseSuccess drlxParseResult;
ReplaceBindingVisitor(MethodCallExpr functionDSL, String bindingId, Class<?> methodCallExprType, Class accumulateFunctionResultType, String bindExpressionVariable, SingleDrlxParseSuccess drlxParseResult) {
this.functionDSL = functionDSL;
this.bindingId = bindingId;
this.methodCallExprType = methodCallExprType;
this.accumulateFunctionResultType = accumulateFunctionResultType;
this.bindExpressionVariable = bindExpressionVariable;
this.drlxParseResult = drlxParseResult;
}
@Override
public Optional<NewBinding> onSuccess(DrlxParseSuccess result) {
SingleDrlxParseSuccess singleResult = drlxParseResult;
singleResult.setExprBinding(bindExpressionVariable);
final MethodCallExpr binding = expressionBuilder.buildBinding(singleResult);
context.addDeclarationReplacing(new DeclarationSpec(bindExpressionVariable, methodCallExprType));
functionDSL.addArgument(context.getVarExpr(bindExpressionVariable));
context.addDeclarationReplacing(new DeclarationSpec(bindingId, accumulateFunctionResultType));
context.getExpressions().forEach(expression -> replaceTypeInExprLambda(bindingId, accumulateFunctionResultType, expression));
List<String> ids = new ArrayList<>();
if (singleResult.getPatternBinding() != null) {
ids.add( singleResult.getPatternBinding() );
}
return Optional.of(new NewBinding(ids, binding));
}
@Override
public Optional<NewBinding> onFail(DrlxParseFail failure) {
return Optional.empty();
}
}
private Expression convertParameter(Expression accumulateFunctionParameter) {
final Expression parameterConverted;
if (accumulateFunctionParameter.isArrayAccessExpr()) {
parameterConverted = new ExpressionTyper(context, Object.class, null, false)
.toTypedExpression(accumulateFunctionParameter)
.getTypedExpression().orElseThrow(() -> new RuntimeException("Cannot convert expression to method call" + accumulateFunctionParameter))
.getExpression();
} else if (accumulateFunctionParameter.isFieldAccessExpr()) {
parameterConverted = new ExpressionTyper(context, Object.class, null, false)
.toTypedExpression(accumulateFunctionParameter)
.getTypedExpression().orElseThrow(() -> new RuntimeException("Cannot convert expression to method call" + accumulateFunctionParameter))
.getExpression();
} else {
parameterConverted = accumulateFunctionParameter;
}
return parameterConverted;
}
private boolean parameterNeedsConvertionToMethodCallExpr(Expression accumulateFunctionParameter) {
return accumulateFunctionParameter.isMethodCallExpr() || accumulateFunctionParameter.isArrayAccessExpr() || accumulateFunctionParameter.isFieldAccessExpr();
}
private Optional<NewBinding> binaryExprParameter(PatternDescr basePattern, AccumulateDescr.AccumulateFunctionCallDescr function, MethodCallExpr functionDSL, String bindingId, String accumulateFunctionParameterStr) {
final DrlxParseResult parseResult = new ConstraintParser(context, packageModel).drlxParse(Object.class, bindingId, accumulateFunctionParameterStr);
Optional<NewBinding> optNewBinding = parseResult.acceptWithReturnValue(new ParseResultVisitor<Optional<NewBinding>>() {
@Override
public Optional<NewBinding> onSuccess(DrlxParseSuccess drlxParseResult) {
SingleDrlxParseSuccess singleResult = (SingleDrlxParseSuccess) drlxParseResult;
Class<?> exprRawClass = singleResult.getExprRawClass();
AccumulateFunction accumulateFunction = getAccumulateFunction(function, exprRawClass);
validateAccFunctionTypeAgainstPatternType(context, basePattern, accumulateFunction);
final String bindExpressionVariable = context.getExprId(accumulateFunction.getResultType(), singleResult.getLeft().toString());
singleResult.setExprBinding(bindExpressionVariable);
context.addDeclarationReplacing(new DeclarationSpec(singleResult.getPatternBinding(), exprRawClass));
context.getExpressions().forEach(expression -> replaceTypeInExprLambda(bindingId, exprRawClass, expression));
functionDSL.addArgument(createAccSupplierExpr(accumulateFunction));
final MethodCallExpr newBindingFromBinary = AccumulateVisitor.this.buildBinding(bindExpressionVariable, singleResult.getUsedDeclarations(), singleResult.getExpr());
context.addDeclarationReplacing(new DeclarationSpec(bindExpressionVariable, exprRawClass));
functionDSL.addArgument(context.getVarExpr(bindExpressionVariable));
return Optional.of(new NewBinding(Collections.emptyList(), newBindingFromBinary));
}
@Override
public Optional<NewBinding> onFail(DrlxParseFail failure) {
return Optional.empty();
}
});
return optNewBinding;
}
private void zeroParameterFunction(PatternDescr basePattern, MethodCallExpr functionDSL, String bindingId, AccumulateFunction accumulateFunction) {
validateAccFunctionTypeAgainstPatternType(context, basePattern, accumulateFunction);
functionDSL.addArgument(createAccSupplierExpr(accumulateFunction));
Class accumulateFunctionResultType = accumulateFunction.getResultType();
context.addDeclarationReplacing(new DeclarationSpec(bindingId, accumulateFunctionResultType));
context.getExpressions().forEach(expression -> replaceTypeInExprLambda(bindingId, accumulateFunctionResultType, expression));
}
private static MethodReferenceExpr createAccSupplierExpr(AccumulateFunction accumulateFunction) {
NameExpr nameExpr = new NameExpr(accumulateFunction.getClass().getCanonicalName());
return new MethodReferenceExpr(nameExpr, new NodeList<>(), "new");
}
private void validateAccFunctionTypeAgainstPatternType(RuleContext context, PatternDescr basePattern, AccumulateFunction accumulateFunction) {
final String expectedResultTypeString = basePattern.getObjectType();
final Class<?> expectedResultType = DrlxParseUtil.getClassFromType(context.getTypeResolver(), DrlxParseUtil.toClassOrInterfaceType(expectedResultTypeString));
final Class actualResultType = accumulateFunction.getResultType();
final boolean isJavaDialect = context.getRuleDialect().equals(RuleContext.RuleDialect.JAVA);
final boolean isQuery = context.isQuery();
final boolean isCollectFunction = isCollectFunction(accumulateFunction);
final boolean isInsideAccumulate = ((AccumulateDescr) basePattern.getSource()).getInput() instanceof AndDescr;
final boolean checkCollect = !isCollectFunction || isInsideAccumulate;
if (!isQuery && checkCollect && isJavaDialect && !Pattern.isCompatibleWithAccumulateReturnType(expectedResultType, actualResultType)) {
context.addCompilationError(new InvalidExpressionErrorResult(
String.format(
"Pattern of type: '[ClassObjectType class=%s]' " +
"on rule '%s' " +
"is not compatible with type %s returned by accumulate function."
, expectedResultType.getCanonicalName(), context.getRuleName(), actualResultType.getCanonicalName()), Optional.of(context.getRuleDescr())));
}
}
private boolean isCollectFunction(AccumulateFunction accumulateFunction) {
return accumulateFunction instanceof CollectListAccumulateFunction ||
accumulateFunction instanceof CollectSetAccumulateFunction ||
accumulateFunction instanceof CollectAccumulator;
}
private void addNonExistingFunctionError(RuleContext context, AccumulateDescr.AccumulateFunctionCallDescr function) {
context.addCompilationError(new InvalidExpressionErrorResult(String.format("Unknown accumulate function: '%s' on rule '%s'.", function.getFunction(), context.getRuleDescr().getName()), Optional.of(context.getRuleDescr())));
}
private void addBindingAsDeclaration(RuleContext context, String bindingId, AccumulateFunction accumulateFunction) {
if (bindingId != null) {
Class accumulateFunctionResultType = accumulateFunction.getResultType();
context.addDeclarationReplacing(new DeclarationSpec(bindingId, accumulateFunctionResultType));
context.getExpressions().forEach(expression -> replaceTypeInExprLambda(bindingId, accumulateFunctionResultType, expression));
}
}
private AccumulateFunction getAccumulateFunction(AccumulateDescr.AccumulateFunctionCallDescr function, Class<?> methodCallExprType) {
final String accumulateFunctionName = AccumulateUtil.getFunctionName(() -> methodCallExprType, function.getFunction());
final Optional<AccumulateFunction> bundledAccumulateFunction = ofNullable(packageModel.getConfiguration().getAccumulateFunction(accumulateFunctionName));
final Optional<AccumulateFunction> importedAccumulateFunction = ofNullable(packageModel.getAccumulateFunctions().get(accumulateFunctionName));
return bundledAccumulateFunction
.map(Optional::of)
.orElse(importedAccumulateFunction)
.orElseThrow(() -> new AccumulateNonExistingFunction(function));
}
private String getRootNodeName(DrlxParseUtil.RemoveRootNodeResult methodCallWithoutRootNode) {
final Expression rootNode = methodCallWithoutRootNode.getRootNode().orElseThrow(UnsupportedOperationException::new);
final String rootNodeName;
if (rootNode instanceof NameExpr) {
rootNodeName = ((NameExpr) rootNode).getName().asString();
} else {
throw new AccumulateParsingFailedException("Root node of expression should be a declaration");
}
return rootNodeName;
}
Expression buildConstraintExpression(Expression expr, Collection<String> usedDeclarations) {
LambdaExpr lambdaExpr = new LambdaExpr();
lambdaExpr.setEnclosingParameters(true);
usedDeclarations.stream().map(s -> new Parameter(context.getDelarationType(s), s)).forEach(lambdaExpr::addParameter);
lambdaExpr.setBody(new ExpressionStmt(expr));
return lambdaExpr;
}
static List<String> collectNamesInBlock(BlockStmt block, RuleContext context) {
return block.findAll(NameExpr.class, n -> {
Optional<DeclarationSpec> optD = context.getDeclarationById(n.getNameAsString());
return optD.filter(d -> !d.isGlobal()).isPresent(); // Global aren't supported
})
.stream()
.map(NameExpr::getNameAsString)
.distinct()
.collect(toList());
}
private void pushAccumulateContext( MethodCallExpr accumulateExprs ) {
context.pushExprPointer(accumulateExprs::addArgument);
}
private MethodCallExpr buildBinding(String bindingName, Collection<String> usedDeclaration, Expression expression) {
MethodCallExpr bindDSL = new MethodCallExpr(null, BIND_CALL);
bindDSL.addArgument(context.getVar(bindingName));
usedDeclaration.stream().map(context::getVarExpr).forEach(bindDSL::addArgument);
bindDSL.addArgument(buildConstraintExpression(expression, usedDeclaration));
return bindDSL;
}
private void processNewBinding(Optional<NewBinding> optNewBinding, MethodCallExpr accumulateDSL) {
optNewBinding.ifPresent(newBinding -> {
final List<Expression> allExpressions = context.getExpressions();
final MethodCallExpr newBindingExpression = newBinding.bindExpression;
if (newBinding.patternBinding.size() == 1) {
new PatternToReplace(context, newBinding.patternBinding).findFromPattern()
.ifPresent(pattern -> addBindAsLastChainCall(newBindingExpression, pattern));
String binding = newBinding.patternBinding.iterator().next();
composeTwoBindings(binding, newBindingExpression);
} else if (newBinding.patternBinding.size() == 2) {
String binding = newBinding.patternBinding.iterator().next();
composeTwoBindings(binding, newBindingExpression);
} else {
final MethodCallExpr lastPattern = DrlxParseUtil.findLastPattern(allExpressions)
.orElseThrow(() -> new RuntimeException("Need the last pattern to add the binding"));
final MethodCallExpr replacedBinding = replaceBindingWithPatternBinding(newBindingExpression, lastPattern);
addBindAsLastChainCall(replacedBinding, lastPattern);
}
});
}
private void composeTwoBindings(String binding, MethodCallExpr newBindingExpression) {
context.findBindingExpression(binding).ifPresent(oldBind -> {
// compose newComposedBinding using oldBind and newBindingExpression. But still keep oldBind.
LambdaExpr oldBindLambda = oldBind.findFirst(LambdaExpr.class).orElseThrow(RuntimeException::new);
LambdaExpr newBindLambda = newBindingExpression.findFirst(LambdaExpr.class).orElseThrow(RuntimeException::new);
LambdaExpr tmpOldBindLambda = oldBindLambda.clone();
Expression newComposedLambda = LambdaUtil.appendNewLambdaToOld(tmpOldBindLambda, newBindLambda);
MethodCallExpr newComposedBinding = new MethodCallExpr(BIND_CALL, newBindingExpression.getArgument(0), newComposedLambda);
newComposedBinding.setScope(oldBind.getScope().orElseThrow(RuntimeException::new));
Optional<MethodCallExpr> optReactOn = oldBind.getArguments().stream()
.filter(MethodCallExpr.class::isInstance)
.map(MethodCallExpr.class::cast)
.filter(exp -> exp.getName().asString().equals(REACT_ON_CALL))
.findFirst();
if (optReactOn.isPresent()) {
newComposedBinding.addArgument(optReactOn.get().clone());
}
oldBind.setScope(newComposedBinding); // insert newComposedBinding at the first in the chain
});
}
private void addBindAsLastChainCall(MethodCallExpr newBindingExpression, MethodCallExpr pattern) {
final Optional<Node> optParent = pattern.getParentNode();
newBindingExpression.setScope(pattern);
optParent.ifPresent(parent -> {
parent.replace(pattern, newBindingExpression);
pattern.setParentNode( newBindingExpression );
});
}
private MethodCallExpr replaceBindingWithPatternBinding(MethodCallExpr bindExpression, MethodCallExpr lastPattern) {
// This method links a binding expression, used to evaluate the accumulated value,
// to the last pattern in a multi-pattern accumulate like the following
//
// accumulate( $c : Child( age < 10 ) and $a : Adult( name == $c.parent ) and $s : String( this == $a.name ),
// $sum : sum($a.getAge() + $c.getAge() + $s.length()) )
//
// In the case the bindExpression, that will have to be linked to the $s pattern, is originally generated as
//
// bind(var_$sum, var_$a, var_$c, var_$s, (Adult $a, Child $c, String $s) -> $a.getAge() + $c.getAge() + $s.length())
final Expression bindingId = lastPattern.getArgument(0);
bindExpression.findFirst(NameExpr.class, e -> e.equals(bindingId)).ifPresent( name -> {
// since the bind has to be linked to $s, the corresponding variable should be removed from the arguments list so it becomes
// bind(var_$sum, var_$a, var_$c, (Adult $a, Child $c, String $s) -> $a.getAge() + $c.getAge() + $s.length())
bindExpression.remove(name);
// also the first formal parameter in the binding lambda has to be $s so it becomes
// bind(var_$sum, var_$a, var_$c, (String $s, Adult $a, Child $c) -> $a.getAge() + $c.getAge() + $s.length())
LambdaExpr lambda = (LambdaExpr)bindExpression.getArgument( bindExpression.getArguments().size()-1 );
if (lambda.getParameters().size() > 1) {
String formalArg = context.fromVar( name.getNameAsString() );
for (Parameter param : lambda.getParameters()) {
if (param.getNameAsString().equals( formalArg )) {
lambda.getParameters().remove( param );
lambda.getParameters().add( 0, param );
break;
}
}
}
} );
return bindExpression;
}
static class NewBinding {
List<String> patternBinding;
MethodCallExpr bindExpression;
NewBinding(List<String> patternBinding, MethodCallExpr bindExpression) {
this.patternBinding = patternBinding;
this.bindExpression = bindExpression;
}
}
private class AccumulateParsingFailedException extends RuntimeException {
AccumulateParsingFailedException() {
}
AccumulateParsingFailedException(String message) {
super(message);
}
}
private class AccumulateNonExistingFunction extends RuntimeException {
private final AccumulateDescr.AccumulateFunctionCallDescr function;
AccumulateNonExistingFunction(AccumulateDescr.AccumulateFunctionCallDescr function) {
this.function = function;
}
}
}
| |
package com.planet_ink.coffee_mud.WebMacros;
import com.planet_ink.coffee_web.interfaces.*;
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.Libraries.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.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2019-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 INIEntry extends StdWebMacro
{
@Override
public String name()
{
return "INIEntry";
}
@Override
public boolean isAdminMacro()
{
return false;
}
protected String getFinalValue(final Map<String,String> parms, String key)
{
key=key.toUpperCase().trim();
final String iniVal;
if(CMath.s_valueOf(CMProps.Str.class, key) != null)
iniVal=CMProps.getVar((CMProps.Str)CMath.s_valueOf(CMProps.Str.class, key));
else
if(CMath.s_valueOf(CMProps.Int.class, key) != null)
iniVal=""+CMProps.getIntVar((CMProps.Int)CMath.s_valueOf(CMProps.Int.class, key));
else
if(CMath.s_valueOf(CMProps.Bool.class, key) != null)
iniVal=""+CMProps.getBoolVar((CMProps.Bool)CMath.s_valueOf(CMProps.Bool.class, key));
else
iniVal="";
if(parms.containsKey("VALUE"))
return clearWebMacros(iniVal);
String retVal="";
if(parms.containsKey("ISNULL"))
{
if((iniVal == null) || (iniVal.trim().length()==0))
retVal="true";
else
return "false";
}
if(parms.containsKey("ISNOTNULL"))
{
if((iniVal != null) && (iniVal.trim().length()>0))
retVal="true";
else
return "false";
}
if(parms.containsKey("CONTAINS"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("CONTAINS");
if(iniVal.indexOf(val)>0)
retVal="true";
else
return "false";
}
else
return "false";
}
if(parms.containsKey("NOTCONTAINS"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("NOTCONTAINS");
if(iniVal.indexOf(val)>0)
return "false";
else
retVal="true";
}
else
retVal="true";
}
if(parms.containsKey("CONTAINSIGNORECASE"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("CONTAINSIGNORECASE");
if(iniVal.toLowerCase().indexOf(val.toLowerCase())>0)
retVal="true";
else
return "false";
}
else
return "false";
}
if(parms.containsKey("NOTCONTAINSIGNORECASE"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("NOTCONTAINSIGNORECASE");
if(iniVal.toLowerCase().indexOf(val.toLowerCase())>0)
return "false";
else
retVal="true";
}
else
retVal="true";
}
if(parms.containsKey("EQUALS"))
{
if(iniVal != null)
{
final String val=parms.get("EQUALS");
if(iniVal.equals(val))
retVal="true";
else
return "false";
}
else
return "false";
}
if(parms.containsKey("NOTEQUALS"))
{
if(iniVal != null)
{
final String val=parms.get("NOTEQUALS");
if(iniVal.equals(val))
return "false";
else
retVal="true";
}
else
retVal="true";
}
if(parms.containsKey("EQUALSIGNORECASE"))
{
if(iniVal != null)
{
final String val=parms.get("EQUALSIGNORECASE");
if(iniVal.equalsIgnoreCase(val))
retVal="true";
else
return "false";
}
else
return "false";
}
if(parms.containsKey("NOTEQUALSIGNORECASE"))
{
if(iniVal != null)
{
final String val=parms.get("NOTEQUALSIGNORECASE");
if(iniVal.equalsIgnoreCase(val))
return "false";
else
retVal="true";
}
else
retVal="true";
}
if(parms.containsKey("GREATERTHAN"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("GREATERTHAN");
if(CMath.s_double(iniVal)>CMath.s_double(val))
retVal="true";
else
return "false";
}
else
return "false";
}
if(parms.containsKey("NOTGREATERTHAN"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("NOTGREATERTHAN");
if(CMath.s_double(iniVal)>CMath.s_double(val))
return "false";
else
retVal="true";
}
else
retVal="true";
}
if(parms.containsKey("LESSTHAN"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("LESSTHAN");
if(CMath.s_double(iniVal)<CMath.s_double(val))
retVal="true";
else
return "false";
}
else
return "false";
}
if(parms.containsKey("NOTLESSTHAN"))
{
if((iniVal != null)&&(iniVal.length()>0))
{
final String val=parms.get("NOTLESSTHAN");
if(CMath.s_double(iniVal)<CMath.s_double(val))
return "false";
else
retVal="true";
}
else
retVal="true";
}
return retVal;
}
@Override
public String runMacro(final HTTPRequest httpReq, final String parm, final HTTPResponse httpResp)
{
final java.util.Map<String,String> parms=parseParms(parm);
if(parms==null)
return "";
if(!parms.containsKey("MASK"))
return "'MASK' not found!";
final String mask=parms.get("MASK").toUpperCase();
if(mask.trim().endsWith("*"))
{
final List<String> allKeys = new LinkedList<String>();
for(final Iterator<String> e=allKeys.iterator();e.hasNext();)
{
final String key=e.next().toUpperCase();
if(key.startsWith(mask.substring(0,mask.length()-1)))
return getFinalValue(parms, key);
}
}
return getFinalValue(parms, mask);
}
}
| |
/*
* Copyright 2013 David Curtis
*
* 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.logicmill.util.concurrent;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Assert;
import org.junit.Test;
import org.logicmill.util.LargeHashMap;
import org.logicmill.util.LongHashable;
import org.logicmill.util.concurrent.ConcurrentLargeHashMap;
@SuppressWarnings("javadoc")
public class ConcurrentLargeHashMapTest {
@SuppressWarnings("rawtypes")
/*
* Performs a relatively exhaustive integrity check on the internal structure of the map.
* See ConcurrentLargeHashMapAuditor for more details.
*/
private void checkMapIntegrity(ConcurrentLargeHashMap map) throws SegmentIntegrityException {
ConcurrentLargeHashMapAuditor auditor = new ConcurrentLargeHashMapAuditor(map);
LinkedList<SegmentIntegrityException> exceptions = auditor.verifyMapIntegrity(false, 0);
Assert.assertEquals("map integrity exceptions found", 0, exceptions.size());
}
private void printMapStats(ConcurrentLargeHashMap<?,?> map, String title) {
ConcurrentLargeHashMapProbe mapProbe = new ConcurrentLargeHashMapProbe(map);
System.out.println();
System.out.println(title);
System.out.printf("\tmap size %d%n", map.size());
System.out.printf("\tsegment size %d%n", mapProbe.getSegmentSize());
System.out.printf("\tsegment count %d%n", mapProbe.getSegmentCount());
System.out.printf("\tload factor %f%n", (float)map.size()/((float)( mapProbe.getSegmentCount()*mapProbe.getSegmentSize())) );
System.out.printf("\tforced splits %d%n", mapProbe.getForcedSplitCount());
System.out.printf("\tthreshold splits %d%n", mapProbe.getThresholdSplitCount());
}
public static class ByteKeyAdapter implements LargeHashMap.KeyAdapter<byte[]> {
@Override
public long getLongHashCode(Object key) {
if (key instanceof byte[]) {
return org.logicmill.util.hash.SpookyHash64.hash((byte[])key, 0L);
} else {
throw new IllegalArgumentException("key must be type byte[]");
}
}
@Override
public boolean keyMatches(byte[] mappedKey, Object key) {
if (key instanceof byte[]) {
byte[] byteKey = (byte[])key;
if (mappedKey.length != byteKey.length) return false;
for (int i = 0; i < byteKey.length; i++) {
if (mappedKey[i] != byteKey[i]) return false;
}
return true;
} else return false;
}
}
public static class StringKeyAdapter implements LargeHashMap.KeyAdapter<String> {
@Override
public long getLongHashCode(Object key) {
if (key instanceof CharSequence) {
return org.logicmill.util.hash.SpookyHash64.hash((CharSequence)key, 0L);
} else {
throw new IllegalArgumentException("key must be type byte[]");
}
}
@Override
public boolean keyMatches(String mappedKey, Object key) {
if (key instanceof String) {
return mappedKey.equals(key);
} else if (key instanceof CharSequence) {
return mappedKey.contentEquals((CharSequence)key);
} else {
return false;
}
}
}
private final static StringKeyAdapter stringAdapter = new StringKeyAdapter();
private final static ByteKeyAdapter byteAdapter = new ByteKeyAdapter();
@Test
public void testKeyAdapter() {
ConcurrentLargeHashMap<byte[],Integer> map =
new ConcurrentLargeHashMap<byte[],Integer>(8192, 8, 0.9f, byteAdapter);
RandomKeySet keySet = new RandomKeySet(16, 128, 1337L);
byte[] key = keySet.getKey();
byte[] keyCopy = Arrays.copyOf(key, key.length);
map.put(key, 1);
Integer value = map.get(keyCopy);
Assert.assertNotNull(value);
Assert.assertEquals(1L, value.intValue());
}
/*
* Runs concurrent put test with 8 threads. If the test system has a larger number of cores, consider increasing
* the thread count.
*/
@Test
public void testConcurrentPut8() throws SegmentIntegrityException, InterruptedException, ExecutionException {
ConcurrentLargeHashMap<byte[],Integer> map = new ConcurrentLargeHashMap<byte[],Integer>(8192, 8, 0.9f, byteAdapter);
testConcurrentPut(map, 8, 1000000);
printMapStats(map, "testConcurrentPut8");
}
/*
* Runs concurrent put test with load factor 1.0, forcing segment overflow to cause splits.
*/
@Test
public void testConcurrentPutLoad1() throws SegmentIntegrityException, InterruptedException, ExecutionException {
ConcurrentLargeHashMap<byte[],Integer> map = new ConcurrentLargeHashMap<byte[],Integer>(524288, 2, 1.0f, byteAdapter);
testConcurrentPut(map, 4, 800000);
printMapStats(map, "testConcurrentPutLoad1");
}
/*
* Runs concurrent put/remove test with 8 threads. If the test system has a larger number of cores, consider increasing
* the thread count.
*/
@Test
public void testConcurrentPutRemoveGet8() throws SegmentIntegrityException, InterruptedException, ExecutionException {
ConcurrentLargeHashMap<byte[],Integer> map =
new ConcurrentLargeHashMap<byte[],Integer>(4096, 8, 1.0f, byteAdapter);
testConcurrentPutRemoveGet(map, 8, 200000, 0.25f, 1000000L);
printMapStats(map, "testConcurrentPutRemoveGet8");
}
@Test
public void testConcurrentPutRemoveGetSmash() throws SegmentIntegrityException, InterruptedException, ExecutionException {
ConcurrentLargeHashMap<byte[],Integer> map = new ConcurrentLargeHashMap<byte[],Integer>(8192, 2, 1.0f, byteAdapter);
testConcurrentPutRemoveGet(map, 4, 14400, 0.5f, 10000000L);
printMapStats(map, "testConcurrentPutRemoveGetSmash");
}
/*
* Runs concurrent put/remove/iterator test with 8 threads. If the test system has a larger number of cores, you know
* what to do.
*/
@Test
public void testConcurrentPutRemoveIteratorContract8() throws InterruptedException, ExecutionException, SegmentIntegrityException {
ConcurrentLargeHashMap<byte[],Integer> map = new ConcurrentLargeHashMap<byte[],Integer>(4096, 8, 0.8f, byteAdapter);
testConcurrentPutRemoveIteratorContract(map, 8, 200000, 0.5f);
printMapStats(map, "testConcurrentPutRemoveIteratorContract8");
}
@Test
public void testConcurrentPutRemoveIteratorContract2Segs() throws InterruptedException, ExecutionException, SegmentIntegrityException {
ConcurrentLargeHashMap<byte[],Integer> map = new ConcurrentLargeHashMap<byte[],Integer>(65536, 2, 1.0f, byteAdapter);
testConcurrentPutRemoveIteratorContract(map, 4, 200000, 0.5f);
printMapStats(map, "testConcurrentPutRemoveIteratorContract2Segs");
}
@Test
public void testConcurrentPutRemoveIterator4() throws InterruptedException, ExecutionException, SegmentIntegrityException {
ConcurrentLargeHashMap<byte[],Integer> map = new ConcurrentLargeHashMap<byte[],Integer>(65536, 2, 1.0f, byteAdapter);
testConcurrentPutRemoveIterator(map, 4, 200000, 0.5f, 1000000L);
printMapStats(map, "testConcurrentPutRemoveIterator4");
}
/* *****************************************************
* Simple functional tests with no concurrency.
* *****************************************************
*/
@Test(expected=NullPointerException.class)
public void testGetNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.get(null);
}
@Test(expected=NullPointerException.class)
public void testContainsKeyNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.containsKey(null);
}
@Test(expected=NullPointerException.class)
public void testPutIfAbsentNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.putIfAbsent(null, 1);
}
@Test(expected=NullPointerException.class)
public void testPutIfAbsentNullValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.putIfAbsent("Hello", null);
}
@Test(expected=NullPointerException.class)
public void testPutNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.put(null, 1);
}
@Test(expected=NullPointerException.class)
public void testPutNullValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.put("Hello", null);
}
@Test(expected=NullPointerException.class)
public void testRemoveKNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.remove(null);
}
@Test(expected=NullPointerException.class)
public void testRemoveKVNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.remove(null, 1);
}
@Test(expected=NullPointerException.class)
public void testRemoveKVNullValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.remove("Hello", null);
}
@Test(expected=NullPointerException.class)
public void testReplaceKVNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.replace(null, 1);
}
@Test(expected=NullPointerException.class)
public void testReplaceKVNullValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.replace("Hello", null);
}
@Test(expected=NullPointerException.class)
public void testReplaceKVVNullKey() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.replace(null, 1, 2);
}
@Test(expected=NullPointerException.class)
public void testReplaceKVVNullOldValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.replace("Hello", null, 2);
}
@Test(expected=NullPointerException.class)
public void testReplaceKVVNullNullValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.replace("Hello", 1, null);
}
@Test
public void testDefaultKeyAdapterString() throws SegmentIntegrityException {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
map.put("hello", 1);
Assert.assertTrue(map.containsKey("hello"));
}
public class LongHashableString implements LongHashable {
private final String string;
public LongHashableString(String s) {
string = s;
}
@Override
public long getLongHashCode() {
return org.logicmill.util.hash.SpookyHash64.hash(string, 0L);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof LongHashableString) {
LongHashableString other = (LongHashableString) obj;
return this.string.equals(other.string);
} else {
return false;
}
}
}
@Test
public void testDefaultKeyAdapterLongHashable() throws SegmentIntegrityException {
final ConcurrentLargeHashMap<LongHashableString, Integer> map =
new ConcurrentLargeHashMap<LongHashableString, Integer>(1024, 2, 0.8f);
map.putIfAbsent(new LongHashableString("hello"), new Integer(0));
Integer n = map.get(new LongHashableString("hel"+"lo"));
Assert.assertNotNull(n);
Assert.assertEquals(0, n.intValue());
checkMapIntegrity(map);
}
@Test(expected=IllegalArgumentException.class)
public void testDefaultKeyAdapterTypeMismatch() {
final ConcurrentLargeHashMap<Long, Integer> map =
new ConcurrentLargeHashMap<Long, Integer>(1024, 2, 0.8f);
map.putIfAbsent(new Long(0L), new Integer(0));
}
/*
* Confirms that remove(key, value) only removes the entry if the key maps to the specified value.
*/
@Test
public void testRemoveValue() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
String key = "Hello";
map.put(key, 1);
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(true, map.containsKey(key));
Assert.assertTrue(map.remove(key, 1));
Assert.assertEquals(false, map.containsKey(key));
map.put(key, 2);
Assert.assertEquals(true, map.containsKey(key));
Assert.assertFalse(map.remove(key, 1));
Assert.assertEquals(true, map.containsKey(key));
Assert.assertEquals(2, map.get(key).intValue());
}
@Test
public void testRemoveValueAll() throws SegmentIntegrityException {
RandomKeySet keySet = new RandomKeySet(100000, 128, 1337L);
final ConcurrentLargeHashMap<byte[], Integer> map =
new ConcurrentLargeHashMap<byte[], Integer>(1024, 2, 0.8f, byteAdapter);
for (int i = 0; i < keySet.size(); i++) {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
}
for (int i = 0; i < keySet.size(); i++) {
Assert.assertFalse(map.remove(keySet.getKey(i), new Integer(-1)));
}
for (int i = 0; i < keySet.size(); i++) {
Assert.assertTrue(map.remove(keySet.getKey(i), new Integer(i)));
}
checkMapIntegrity(map);
}
/*
* Confirms that containsKey(key) and remove(key) function properly.
*/
@Test
public void testContainsKeyAndRemove() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
String key = "Hello";
map.put(key, 1);
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(true, map.containsKey(key));
Integer val = map.remove(key);
Assert.assertEquals(1, val.intValue());
Assert.assertEquals(false, map.containsKey(key));
}
/*
* Confirms that get(key) functions properly.
*/
@Test
public void testGet() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
String key = "Hello";
map.put(key, 1);
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(true, map.containsKey(key));
Integer val = map.get(key);
Assert.assertEquals(1, val.intValue());
}
/*
* Confirms that isEmpty() functions properly.
*/
@Test
public void testIsEmpty() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
Assert.assertTrue(map.isEmpty());
String key = "Hello";
map.put(key, 1);
Assert.assertFalse(map.isEmpty());
}
/*
* Confirms that replace(key, value) functions properly; specifically, that it only
* replaces if a mapping for key already exists in the map, and that the return
* value matches the previously existing mapped value, or null if no previous mapping
* existed.
*/
@Test
public void testReplace() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
String key = "Hello";
map.put(key, 1);
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(true, map.containsKey(key));
Integer val = map.get(key);
Assert.assertEquals(1, val.intValue());
Integer oldValue = map.replace(key, 2);
Assert.assertNotNull(oldValue);
Assert.assertEquals(1, oldValue.intValue());
Integer newValue = map.get(key);
Assert.assertEquals(2, newValue.intValue());
newValue = map.remove(key);
Assert.assertEquals(2, newValue.intValue());
newValue = map.replace(key, 3);
Assert.assertNull(newValue);
Assert.assertFalse(map.containsKey(key));
}
@Test
public void testReplaceAll() throws SegmentIntegrityException {
RandomKeySet keySet = new RandomKeySet(100000, 128, 1337L);
final ConcurrentLargeHashMap<byte[], Integer> map =
new ConcurrentLargeHashMap<byte[], Integer>(1024, 2, 0.8f, byteAdapter);
for (int i = 0; i < keySet.size(); i++) {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
}
for (int i = 0; i < keySet.size(); i++) {
Integer n = map.replace(keySet.getKey(i), new Integer(-1));
Assert.assertNotNull(n);
Assert.assertEquals(i, n.intValue());
}
checkMapIntegrity(map);
}
@Test
public void testPutWithReplace() throws SegmentIntegrityException {
RandomKeySet keySet = new RandomKeySet(100000, 128, 1337L);
final ConcurrentLargeHashMap<byte[], Integer> map =
new ConcurrentLargeHashMap<byte[], Integer>(1024, 2, 0.8f, byteAdapter);
for (int i = 0; i < keySet.size(); i++) {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
}
for (int i = 0; i < keySet.size(); i++) {
Integer n = map.put(keySet.getKey(i), new Integer(-1));
Assert.assertNotNull(n);
Assert.assertEquals(i, n.intValue());
}
checkMapIntegrity(map);
}
/*
* Confirms that replace(key, oldValue, newValue) functions properly; specifically, that replacement
* occurs only if a previous mapping for key exists in the map, and the previous mapped value
* is equal to oldValue. Also confirms that the correct newValue is mapped (when appropriate) and
* that the return boolean value is correct.
*/
@Test
public void testReplaceOldNew() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
String key = "Hello";
map.put(key, 1);
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(true, map.containsKey(key));
Integer val = map.get(key);
Assert.assertEquals(1, val.intValue());
Assert.assertTrue(map.replace(key, 1, 2));
Assert.assertEquals(2, map.get(key).intValue());
Assert.assertFalse(map.replace(key, 1, 3));
Assert.assertEquals(2, map.get(key).intValue());
Integer value = map.replace(key, 3);
Assert.assertNotNull(value);
Assert.assertEquals(2, value.intValue());
value = map.remove(key);
Assert.assertEquals(3, value.intValue());
Assert.assertFalse(map.replace(key, 3, 4));
Assert.assertFalse(map.containsKey(key));
}
/*
* Confirms that putIfAbsent(key, value) functions correctly; specifically, that the mapping
* occurs only if no previous mapping for key exists in the map. Also confirms that the
* return value is null if no mapping previously existed, or that the return value matches
* the value to which key previously mapped (in which case the put does not change the mapping).
*/
@Test
public void testPutIfAbsent() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(1024, 2, 0.8f, stringAdapter);
String key = "Hello";
Assert.assertNull(map.putIfAbsent(key, 1));
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(true, map.containsKey(key));
Integer value = map.get(key);
Assert.assertEquals(1, value.intValue());
value = map.putIfAbsent(key,2);
Assert.assertEquals(1, value.intValue());
value = map.get(key);
Assert.assertEquals(1, value.intValue());
}
/*
* Confirms that the iterator returned by getEntryIterator() functions properly; specifically, that
* all entries in the map are returned by the iterator, and that hasNext() returns true until the
* iterator is exhausted, and false afterward.
*/
@Test
public void testEntryIterator() {
RandomKeySet keySet = new RandomKeySet(100000, 128, 1337L);
final ConcurrentLargeHashMap<byte[], Integer> map =
new ConcurrentLargeHashMap<byte[], Integer>(4096, 8, 0.8f, byteAdapter);
HashSet<byte[]> keysIntoMap = new HashSet<byte[]>();
HashSet<Integer> valsIntoMap = new HashSet<Integer>();
int i = 0;
while (keySet.hasMoreKeys()) {
byte[] key = keySet.getKey();
keysIntoMap.add(key);
valsIntoMap.add(i);
map.put(key, i++);
}
HashSet<Integer> valsFromMap = new HashSet<Integer>();
HashSet<byte[]> keysFromMap = new HashSet<byte[]>();
Iterator<LargeHashMap.Entry<byte[], Integer>> entryIter = map.getEntryIterator();
while (entryIter.hasNext()) {
LargeHashMap.Entry<byte[],Integer> entry = entryIter.next();
valsFromMap.add(entry.getValue());
keysFromMap.add(entry.getKey());
}
Assert.assertEquals(valsIntoMap, valsFromMap);
Assert.assertEquals(keysIntoMap, keysFromMap);
}
/*
* Confirms that the EntryIterator.remove() method throws an UnsupportedOperationException
*/
@Test(expected=UnsupportedOperationException.class)
public void testEntryIteratorRemove() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(4096, 8, 0.8f, stringAdapter);
map.put("Hello", 1);
Iterator<LargeHashMap.Entry<String, Integer>> entryIter = map.getEntryIterator();
@SuppressWarnings("unused")
LargeHashMap.Entry<String, Integer> entry = entryIter.next();
entryIter.remove();
}
/*
* Confirms that calling EntryIterator.next() after exhaustion throws a NoSuchElementException
*/
@Test(expected=NoSuchElementException.class)
public void testEntryIteratorExhaustion() {
final ConcurrentLargeHashMap<String, Integer> map = new ConcurrentLargeHashMap<String, Integer>(4096, 8, 0.8f, stringAdapter);
map.put("Hello", 1);
Iterator<LargeHashMap.Entry<String, Integer>> entryIter = map.getEntryIterator();
@SuppressWarnings("unused")
LargeHashMap.Entry<String, Integer> entry = entryIter.next();
entry = entryIter.next();
}
/*
* Configurable stress test of concurrent put/remove/get operations.
*
* For convenience, key/value pairs always consist of (keys[i], i), so a value
* can always be reverse-mapped to the corresponding key through the keys array.
* This test populates the map with a fraction of the available keys, based on
* the removeDepth parameter. If removeDepth >= 0, the map is filled with
* keys.length - removeDepth keys; if removeDepth < 0, the map is filled with
* keys.length/2 keys. The unused keys are put in a linked queue (the recycle queue). When the concurrent
* test starts, threadCount-1 threads execute the recycleTask callable, which alternates
* between two actions: 1) get a key from the recycle queue and put it in the map, and 2)
* select a random entry in the map and remove it, placing it in the recycle queue. This
* guarantees a sustainable flow on entries in and out of the map, with a (roughly) fixed
* fraction of keys in the map. The recycleTask threads continue until a total of recycleLimit
* put/remove operations have completed. The remaining thread executes the
* getTask callable, which performs get() operations on random keys, confirming that
* the entrys (keys[i], i) are valid. After the completion of the concurrent threads,
* the map integrity is checked.
*
*
* @param threadCount number of threads employed in test
* @param removeDepth if >= 0, the number of keys held in the
* recycle queue; if -1, half of the available keys are held in the recycle queue
* @param recycleLimit maximum number of put/remove operations performed in the test
* @param segSize segment size for the test map
* @param segCount initial segment count for the test map
* @param loadFactor load factor threshold for the test map
* @throws SegmentIntegrityException
* @throws InterruptedException
* @throws ExecutionException
*/
private void testConcurrentPutRemoveGet(final ConcurrentLargeHashMap<byte[], Integer> map,
final int threadCount, final int keyCount, final float recycleFraction, final long recycleLimit)
throws SegmentIntegrityException, InterruptedException, ExecutionException {
final RandomKeySet keySet = new RandomKeySet(keyCount, 128, 1337L);
final ConcurrentLinkedQueue<Integer> recycleQueue = new ConcurrentLinkedQueue<Integer>();
int recycQueueSize = (int)(keyCount * recycleFraction);
for (int i = 0; i < keyCount; i++) {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
}
Random rng = new Random(1337L);
for (int i = 0; i < recycQueueSize; i++) {
int ri = rng.nextInt(keyCount);
byte[] key = keySet.getKey(ri);
Integer val = map.remove(key);
while (val == null) {
ri = rng.nextInt(keyCount);
key = keySet.getKey(ri);
val = map.remove(key);
}
recycleQueue.offer(val);
}
final AtomicLong recycleCount = new AtomicLong(0L);
Callable<Long> recycleTask = new Callable<Long>() {
@Override
public Long call() throws InterruptedException {
long totalRecycles = recycleCount.getAndIncrement();
long localRecycleCount = 0L;
long currentThreadID = Thread.currentThread().getId();
Random localRng = new Random(currentThreadID);
while (totalRecycles < recycleLimit) {
Integer recycleVal = recycleQueue.poll();
Assert.assertNotNull(recycleVal);
Integer inMap = map.putIfAbsent(keySet.getKey(recycleVal.intValue()), recycleVal);
Assert.assertNull("unexpected recycle value already in map", inMap);
int ri = localRng.nextInt(keyCount);
Integer removedVal = map.remove(keySet.getKey(ri));
while (removedVal == null) {
ri = localRng.nextInt(keyCount);
removedVal = map.remove(keySet.getKey(ri));
}
Assert.assertEquals("removed value mismatch", removedVal.intValue(), ri);
recycleQueue.offer(removedVal);
localRecycleCount++;
totalRecycles = recycleCount.getAndIncrement();
}
Integer val = recycleQueue.poll();
while (val != null) {
Integer inMap = map.putIfAbsent(keySet.getKey(val.intValue()), val);
Assert.assertNull("unexpected recycle value already in map", inMap);
val = recycleQueue.poll();
}
return localRecycleCount;
}
};
Callable<Long> getTask = new Callable<Long>() {
@Override
public Long call() throws InterruptedException {
long totalGets = 0L;
long currentThreadID = Thread.currentThread().getId();
Random localRng = new Random(currentThreadID);
while (recycleCount.get() < recycleLimit) {
int ri = localRng.nextInt(keyCount);
Integer val = map.get(keySet.getKey(ri));
if (val != null) {
Assert.assertEquals(ri, val.intValue());
}
totalGets++;
}
return totalGets;
}
};
List<Callable<Long>> recycleTasks = Collections.nCopies(threadCount-1, recycleTask);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
LinkedList<Future<Long>> results = new LinkedList<Future<Long>>();
for (Callable<Long> task : recycleTasks) {
results.add(executorService.submit(task));
}
Future<Long> getResult = executorService.submit(getTask);
long totalRecycles = 0L;
for (Future<Long> result : results) {
totalRecycles += result.get();
}
long totalGets = getResult.get();
System.out.printf("totalGets %d%n", totalGets);
Assert.assertEquals("total recycles/recycleLimit mismatch", totalRecycles, recycleLimit);
Assert.assertEquals("keyCount/map size mismatch", keyCount, map.size());
for (int i = 0; i < keyCount; i++) {
Integer val = map.get(keySet.getKey(i));
Assert.assertNotNull(String.format("entry %d missing from map", i), val);
Assert.assertEquals("wrong value for key in map", val.intValue(), i);
}
checkMapIntegrity(map);
}
@Test
public void testConcurrentGet4() throws SegmentIntegrityException, InterruptedException, ExecutionException {
ConcurrentLargeHashMap<byte[], Integer> map =
new ConcurrentLargeHashMap<byte[], Integer>(8192, 4, 0.8f, byteAdapter);
testConcurrentGet(map, 4, 200000, 5000000L);
}
private void testConcurrentGet(final ConcurrentLargeHashMap<byte[], Integer> map, int threadCount, final int keyCount, final long getLimit)
throws SegmentIntegrityException, InterruptedException, ExecutionException {
final RandomKeySet keySet = new RandomKeySet(keyCount, 128, 1337L);
Callable<Long> getTask = new Callable<Long>() {
@Override
public Long call() {
int startIndex = 0;
long currentThreadID = Thread.currentThread().getId();
if (currentThreadID < 0) {
currentThreadID &= (1L << 62) - 1L;
}
startIndex = (int)(currentThreadID % keySet.size());
long getCount = 0;
int next = startIndex;
while (getCount++ < getLimit) {
map.get(keySet.getKey(next));
if (++next >= keySet.size()) {
next = 0;
}
}
return getCount;
}
};
for (int i = 0; i < keySet.size(); i++) {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
}
List<Callable<Long>> getTasks = Collections.nCopies(threadCount, getTask);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
List<Future<Long>> futures = executorService.invokeAll(getTasks);
Assert.assertEquals("future count should equal threadCount", threadCount, futures.size());
// Check for exceptions
long totalGets = 0;
for (Future<Long> future : futures) {
// Throws an exception if an exception was thrown by the task.
totalGets += future.get();
}
System.out.printf("total gets: %d%n", totalGets);
}
/* Creates threadCount threads that concurrently put (keys[i],i) entries for all elements
* in keys. When keys are exhausted, the threads terminate, and the main thread performs
* a map integrity check.
*
* @param threadCount number of threads concurrently adding to the map
* @param segSize size of segments in the created map
* @param segCount number of segments initially created in the map
* @param loadFactor load factory threshold for the map
* @throws SegmentIntegrityException
* @throws InterruptedException
* @throws ExecutionException
*/
private void testConcurrentPut(final ConcurrentLargeHashMap<byte[], Integer> map, int threadCount, int keyCount)
throws SegmentIntegrityException, InterruptedException, ExecutionException {
final RandomKeySet keySet = new RandomKeySet(keyCount, 128, 1337L);
final AtomicInteger nextKey = new AtomicInteger(0);
Callable<Integer> putTask = new Callable<Integer>() {
@Override
public Integer call() {
int putCount = 0;
int next = nextKey.getAndIncrement();
while (next < keySet.size()) {
byte[] key = keySet.getKey(next);
Integer val = new Integer(next);
Integer inMap = map.putIfAbsent(key, val);
Assert.assertNull(inMap);
putCount++;
next = nextKey.getAndIncrement();
}
return putCount;
}
};
List<Callable<Integer>> putTasks = Collections.nCopies(threadCount, putTask);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
List<Future<Integer>> futures = executorService.invokeAll(putTasks);
Assert.assertEquals("future count should equal threadCount", threadCount, futures.size());
// Check for exceptions
int totalPuts = 0;
for (Future<Integer> future : futures) {
// Throws an exception if an exception was thrown by the task.
totalPuts += future.get();
}
Assert.assertEquals("keyCount/totalPuts mismatch", keySet.size(), totalPuts);
Assert.assertEquals("keyCount/map size mismatch", keySet.size(), map.size());
for (int i = 0; i < keySet.size(); i++) {
Integer val = map.get(keySet.getKey(i));
Assert.assertNotNull(String.format("entry %d missing from map", i), val);
Assert.assertEquals("wrong value for key in map", val.intValue(), i);
}
checkMapIntegrity(map);
}
/* Concurrently executes put, remove, and iteration.
*
* Creates threadCount - 1 threads that execute the
* @param threadCount
* @param absentKeyPoolSize
* @param segSize
* @param segCount
* @param loadFactor
* @throws InterruptedException
* @throws ExecutionException
* @throws SegmentIntegrityException
*/
private void testConcurrentPutRemoveIteratorContract(final ConcurrentLargeHashMap<byte[], Integer> map,
int threadCount, final int keyCount, float fractionInPool)
throws InterruptedException, ExecutionException, SegmentIntegrityException {
final ConcurrentLinkedQueue<byte[]> initallyInMap = new ConcurrentLinkedQueue<byte[]>();
final ConcurrentLinkedQueue<byte[]> initiallyNotInMap = new ConcurrentLinkedQueue<byte[]>();
final ConcurrentLinkedQueue<byte[]> removedFromMap = new ConcurrentLinkedQueue<byte[]>();
final ConcurrentLinkedQueue<byte[]> putInMap = new ConcurrentLinkedQueue<byte[]>();
final AtomicBoolean iteratorStarted = new AtomicBoolean(false);
final AtomicBoolean iteratorFinished = new AtomicBoolean(false);
final RandomKeySet keySet = new RandomKeySet(keyCount, 128, 1337L);
int notInMapCount = (int)(keyCount * fractionInPool);
for (int i = 0; i < keySet.size(); i++) {
if (i < notInMapCount) {
initiallyNotInMap.add(keySet.getKey(i));
} else {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
initallyInMap.add(keySet.getKey(i));
}
}
int initiallyPresent = initallyInMap.size();
int initiallyAbsent = initiallyNotInMap.size();
Callable<Integer> putRemoveTask = new Callable<Integer>() {
@Override
public Integer call() throws InterruptedException {
int removed = 0;
byte[] removeKey = initallyInMap.poll();
while (removeKey != null) {
if (iteratorStarted.get()) {
if (!iteratorFinished.get()) {
/*
* The iterator is in use
*/
Assert.assertNotNull(map.remove(removeKey)); // remove key from the map
removedFromMap.add(removeKey); // put it in removedFromMap
byte[] addKey = initiallyNotInMap.poll(); // get a key that's not in the map
if (addKey != null) {
Assert.assertNull(map.putIfAbsent(addKey,-1));
putInMap.add(addKey); // put it in the map
}
removed++;
} else {
/*
* if the iterator is exhausted, put the key back and terminate
*/
initallyInMap.add(removeKey);
break;
}
} else {
/*
* the iterator hasn't started yet, so put the key back
*/
initallyInMap.add(removeKey);
}
removeKey = initallyInMap.poll(); // get the next key to remove
}
return new Integer(removed);
}
};
Callable<LinkedList<byte[]>> iteratorTask = new Callable<LinkedList<byte[]>>() {
@Override
public LinkedList<byte[]> call() throws InterruptedException {
LinkedList<byte[]> observed = new LinkedList<byte[]>();
Iterator<LargeHashMap.Entry<byte[],Integer>> entryIter = map.getEntryIterator();
iteratorStarted.set(true);
while (entryIter.hasNext()) {
observed.add(entryIter.next().getKey());
}
iteratorFinished.set(true);
return observed;
}
};
List<Callable<Integer>> putRemoveTasks = Collections.nCopies(threadCount-1, putRemoveTask);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
LinkedList<Future<Integer>> results = new LinkedList<Future<Integer>>();
for (Callable<Integer> task : putRemoveTasks) {
results.add(executorService.submit(task));
}
Future<LinkedList<byte[]>> iteratorResult = executorService.submit(iteratorTask);
@SuppressWarnings("unused")
int totalRemoves = 0;
for (Future<Integer> result : results) {
totalRemoves += result.get().intValue();
}
LinkedList<byte[]> observed = iteratorResult.get();
HashSet<byte[]> observedSet = new HashSet<byte[]>(observed);
int finallyPresent = initallyInMap.size();
int finallyAbsent = initiallyNotInMap.size();
int added = putInMap.size();
int removed = removedFromMap.size();
int addedAndObserved = 0;
for (byte[] key : putInMap) {
if (observedSet.contains(key)) {
addedAndObserved++;
}
}
int removedAndObserved = 0;
for (byte[] key : removedFromMap) {
if (observedSet.contains(key)) {
removedAndObserved++;
}
}
Assert.assertTrue(observedSet.containsAll(initallyInMap));
for (byte[] key : initiallyNotInMap) {
Assert.assertFalse(observedSet.contains(key));
}
Assert.assertEquals(finallyPresent + putInMap.size(), map.size());
checkMapIntegrity(map);
System.out.printf("initiallyPresent %d, initiallyAbsent %d, finallyPresent %d, finallyAbsent %d, added %d, removed %d%n",
initiallyPresent, initiallyAbsent, finallyPresent, finallyAbsent, added, removed);
System.out.printf("addedAndObserved %d, removedAndObserved %d, observed %d, map size %d%n",
addedAndObserved, removedAndObserved, observed.size(), map.size() );
}
private void testConcurrentPutRemoveIterator(final ConcurrentLargeHashMap<byte[], Integer> map,
final int threadCount, final int keyCount, final float recycleFraction, final long recycleLimit)
throws SegmentIntegrityException, InterruptedException, ExecutionException {
final RandomKeySet keySet = new RandomKeySet(keyCount, 128, 1337L);
final ConcurrentLinkedQueue<Integer> recycleQueue = new ConcurrentLinkedQueue<Integer>();
int recycQueueSize = (int)(keyCount * recycleFraction);
for (int i = 0; i < keyCount; i++) {
map.putIfAbsent(keySet.getKey(i), new Integer(i));
}
Random rng = new Random(1337L);
for (int i = 0; i < recycQueueSize; i++) {
int ri = rng.nextInt(keyCount);
byte[] key = keySet.getKey(ri);
Integer val = map.remove(key);
while (val == null) {
ri = rng.nextInt(keyCount);
key = keySet.getKey(ri);
val = map.remove(key);
}
recycleQueue.offer(val);
}
final AtomicLong recycleCount = new AtomicLong(0L);
Callable<Long> recycleTask = new Callable<Long>() {
@Override
public Long call() throws InterruptedException {
long totalRecycles = recycleCount.getAndIncrement();
long localRecycleCount = 0L;
long currentThreadID = Thread.currentThread().getId();
Random localRng = new Random(currentThreadID);
while (totalRecycles < recycleLimit) {
Integer recycleVal = recycleQueue.poll();
Assert.assertNotNull(recycleVal);
Integer inMap = map.putIfAbsent(keySet.getKey(recycleVal.intValue()), recycleVal);
Assert.assertNull("unexpected recycle value already in map", inMap);
int ri = localRng.nextInt(keyCount);
Integer removedVal = map.remove(keySet.getKey(ri));
while (removedVal == null) {
ri = localRng.nextInt(keyCount);
removedVal = map.remove(keySet.getKey(ri));
}
Assert.assertEquals("removed value mismatch", removedVal.intValue(), ri);
recycleQueue.offer(removedVal);
localRecycleCount++;
totalRecycles = recycleCount.getAndIncrement();
}
Integer val = recycleQueue.poll();
while (val != null) {
Integer inMap = map.putIfAbsent(keySet.getKey(val.intValue()), val);
Assert.assertNull("unexpected recycle value already in map", inMap);
val = recycleQueue.poll();
}
return localRecycleCount;
}
};
Callable<Long> iteratorTask = new Callable<Long>() {
@Override
public Long call() throws InterruptedException {
long localIterations = 0L;
while (recycleCount.get() < recycleLimit) {
Iterator<LargeHashMap.Entry<byte[],Integer>> iter = map.getEntryIterator();
while (iter.hasNext()) {
@SuppressWarnings("unused")
LargeHashMap.Entry<byte[],Integer> entry = iter.next();
}
localIterations++;
}
return localIterations;
}
};
List<Callable<Long>> recycleTasks = Collections.nCopies(threadCount-1, recycleTask);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
LinkedList<Future<Long>> results = new LinkedList<Future<Long>>();
for (Callable<Long> task : recycleTasks) {
results.add(executorService.submit(task));
}
Future<Long> getResult = executorService.submit(iteratorTask);
long totalRecycles = 0L;
for (Future<Long> result : results) {
totalRecycles += result.get();
}
long totalIterations = getResult.get();
System.out.printf("totalIterations %d%n", totalIterations);
Assert.assertEquals("total recycles/recycleLimit mismatch", totalRecycles, recycleLimit);
Assert.assertEquals("keyCount/map size mismatch", keyCount, map.size());
for (int i = 0; i < keyCount; i++) {
Integer val = map.get(keySet.getKey(i));
Assert.assertNotNull(String.format("entry %d missing from map", i), val);
Assert.assertEquals("wrong value for key in map", val.intValue(), i);
}
checkMapIntegrity(map);
}
}
| |
/*
* Copyright 2015 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.
*
* 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.compiler.kie.builder.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import org.drools.compiler.builder.InternalKnowledgeBuilder;
import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.drools.compiler.builder.impl.KnowledgeBuilderImpl;
import org.drools.compiler.kproject.models.KieBaseModelImpl;
import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.compiler.kproject.models.KieSessionModelImpl;
import org.drools.core.util.StringUtils;
import org.kie.api.builder.Message;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.internal.builder.CompositeKnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.builder.KnowledgeBuilderResult;
import org.kie.internal.builder.ResultSeverity;
import org.kie.internal.builder.conf.GroupDRLsInKieBasesByFolderOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.filterFileInKBase;
public abstract class AbstractKieProject implements KieProject {
private static final Logger log = LoggerFactory.getLogger(KieProject.class);
protected final Map<String, KieBaseModel> kBaseModels = new HashMap<>();
private KieBaseModel defaultKieBase = null;
private KieSessionModel defaultKieSession = null;
private KieSessionModel defaultStatelessKieSession = null;
private Map<KieBaseModel, Set<String>> includesInKieBase = new HashMap<>();
private final Map<String, KieSessionModel> kSessionModels = new HashMap<>();
private static final Predicate<String> BUILD_ALL = s -> true;
public ResultsImpl verify() {
ResultsImpl messages = new ResultsImpl();
verify(messages);
return messages;
}
public ResultsImpl verify(String... kBaseNames) {
ResultsImpl messages = new ResultsImpl();
verify(kBaseNames, messages);
return messages;
}
public void verify(ResultsImpl messages) {
for ( KieBaseModel model : kBaseModels.values() ) {
buildKnowledgePackages((KieBaseModelImpl) model, messages);
}
}
public void verify(String[] kBaseNames, ResultsImpl messages) {
for ( String modelName : kBaseNames ) {
KieBaseModelImpl kieBaseModel = (KieBaseModelImpl) kBaseModels.get( modelName );
if ( kieBaseModel == null ) {
throw new RuntimeException( "Unknown KieBase. Cannot find a KieBase named: " + modelName );
}
buildKnowledgePackages( kieBaseModel, messages);
}
}
public KieBaseModel getDefaultKieBaseModel() {
return defaultKieBase;
}
public KieSessionModel getDefaultKieSession() {
return defaultKieSession;
}
public KieSessionModel getDefaultStatelessKieSession() {
return defaultStatelessKieSession;
}
public KieBaseModel getKieBaseModel(String kBaseName) {
return kBaseName == null ? getDefaultKieBaseModel() : kBaseModels.get( kBaseName );
}
public Collection<String> getKieBaseNames() {
return kBaseModels.keySet();
}
public KieSessionModel getKieSessionModel(String kSessionName) {
return kSessionName == null ? getDefaultKieSession() : kSessionModels.get( kSessionName );
}
void indexParts( InternalKieModule mainKieModule,
Collection<InternalKieModule> depKieModules,
Map<String, InternalKieModule> kJarFromKBaseName ) {
for ( InternalKieModule kJar : depKieModules ) {
indexKieModule( kJarFromKBaseName, kJar, false );
}
if (mainKieModule != null) {
indexKieModule( kJarFromKBaseName, mainKieModule, true );
}
}
private void indexKieModule( Map<String, InternalKieModule> kJarFromKBaseName, InternalKieModule kJar, boolean isMainModule ) {
boolean defaultKieBaseFromMain = false;
boolean defaultKieSessionFromMain = false;
boolean defaultStatelessKieSessionFromMain = false;
KieModuleModel kieProject = kJar.getKieModuleModel();
for ( KieBaseModel kieBaseModel : kieProject.getKieBaseModels().values() ) {
if (kieBaseModel.isDefault()) {
if (defaultKieBase == null || (isMainModule && !defaultKieBaseFromMain)) {
defaultKieBase = kieBaseModel;
defaultKieBaseFromMain = isMainModule;
} else {
defaultKieBase = null;
log.warn("Found more than one default KieBase: disabling all. KieBases will be accessible only by name");
}
}
kBaseModels.put( kieBaseModel.getName(), kieBaseModel );
((KieBaseModelImpl) kieBaseModel).setKModule( kieProject ); // should already be set, but just in case
kJarFromKBaseName.put( kieBaseModel.getName(), kJar );
for ( KieSessionModel kieSessionModel : kieBaseModel.getKieSessionModels().values() ) {
if (kieSessionModel.isDefault()) {
if (kieSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
if (defaultKieSession == null || (isMainModule && !defaultKieSessionFromMain)) {
defaultKieSession = kieSessionModel;
defaultKieSessionFromMain = isMainModule;
} else {
defaultKieSession = null;
log.warn("Found more than one default KieSession: disabling all. KieSessions will be accessible only by name");
}
} else {
if (defaultStatelessKieSession == null || (isMainModule && !defaultStatelessKieSessionFromMain)) {
defaultStatelessKieSession = kieSessionModel;
defaultStatelessKieSessionFromMain = isMainModule;
} else {
defaultStatelessKieSession = null;
log.warn("Found more than one default StatelessKieSession: disabling all. StatelessKieSessions will be accessible only by name");
}
}
}
((KieSessionModelImpl) kieSessionModel).setKBase( kieBaseModel ); // should already be set, but just in case
kSessionModels.put( kieSessionModel.getName(), kieSessionModel );
}
}
}
void cleanIndex() {
kBaseModels.clear();
kSessionModels.clear();
includesInKieBase.clear();
defaultKieBase = null;
defaultKieSession = null;
defaultStatelessKieSession = null;
}
public Set<String> getTransitiveIncludes(String kBaseName) {
return getTransitiveIncludes(getKieBaseModel(kBaseName));
}
public Set<String> getTransitiveIncludes(KieBaseModel kBaseModel) {
Set<String> includes = includesInKieBase.get(kBaseModel);
if (includes == null) {
includes = new HashSet<>();
getTransitiveIncludes(kBaseModel, includes);
includesInKieBase.put(kBaseModel, includes);
}
return includes;
}
private void getTransitiveIncludes(KieBaseModel kBaseModel, Set<String> includes) {
if (kBaseModel == null) {
return;
}
Set<String> incs = ((KieBaseModelImpl)kBaseModel).getIncludes();
if (incs != null && !incs.isEmpty()) {
for (String inc : incs) {
if (!includes.contains(inc)) {
includes.add(inc);
getTransitiveIncludes(getKieBaseModel(inc), includes);
}
}
}
}
public KnowledgeBuilder buildKnowledgePackages( KieBaseModelImpl kBaseModel, ResultsImpl messages ) {
return buildKnowledgePackages( kBaseModel, messages, BUILD_ALL );
}
public KnowledgeBuilder buildKnowledgePackages( KieBaseModelImpl kBaseModel, ResultsImpl messages, Predicate<String> buildFilter ) {
boolean useFolders = useFolders( kBaseModel );
Set<Asset> assets = new HashSet<>();
boolean allIncludesAreValid = true;
for (String include : getTransitiveIncludes(kBaseModel)) {
if ( StringUtils.isEmpty( include )) {
continue;
}
InternalKieModule includeModule = getKieModuleForKBase(include);
if (includeModule == null) {
String text = "Unable to build KieBase, could not find include: " + include;
log.error(text);
messages.addMessage( Message.Level.ERROR, KieModuleModelImpl.KMODULE_SRC_PATH, text ).setKieBaseName( kBaseModel.getName() );
allIncludesAreValid = false;
continue;
}
if (compileIncludedKieBases()) {
addFiles( buildFilter, assets, getKieBaseModel( include ), includeModule, useFolders );
}
}
if (!allIncludesAreValid) {
return null;
}
InternalKieModule kModule = getKieModuleForKBase(kBaseModel.getName());
addFiles( buildFilter, assets, kBaseModel, kModule, useFolders );
KnowledgeBuilder kbuilder;
if (assets.isEmpty()) {
if (buildFilter == BUILD_ALL) {
log.warn( "No files found for KieBase " + kBaseModel.getName() +
(kModule instanceof FileKieModule ? ", searching folder " + kModule.getFile() : ""));
}
kbuilder = InternalKnowledgeBuilder.EMPTY;
} else {
kbuilder = createKnowledgeBuilder( kBaseModel, kModule );
if ( kbuilder == null ) {
return null;
}
(( KnowledgeBuilderImpl ) kbuilder).setReleaseId( getGAV() );
CompositeKnowledgeBuilder ckbuilder = kbuilder.batch();
for (Asset asset : assets) {
asset.kmodule.addResourceToCompiler( ckbuilder, kBaseModel, asset.name );
}
ckbuilder.build();
if ( kbuilder.hasErrors() ) {
for (KnowledgeBuilderError error : kbuilder.getErrors()) {
messages.addMessage( error ).setKieBaseName( kBaseModel.getName() );
}
log.error( "Unable to build KieBaseModel:" + kBaseModel.getName() + "\n" + kbuilder.getErrors().toString() );
}
if ( kbuilder.hasResults( ResultSeverity.WARNING ) ) {
for (KnowledgeBuilderResult warn : kbuilder.getResults( ResultSeverity.WARNING )) {
messages.addMessage( warn ).setKieBaseName( kBaseModel.getName() );
}
log.warn( "Warning : " + kBaseModel.getName() + "\n" + kbuilder.getResults( ResultSeverity.WARNING ).toString() );
}
}
// cache KnowledgeBuilder and results
if (buildFilter == BUILD_ALL) {
kModule.cacheKnowledgeBuilderForKieBase( kBaseModel.getName(), kbuilder );
kModule.cacheResultsForKieBase( kBaseModel.getName(), messages );
}
return kbuilder;
}
private boolean useFolders( KieBaseModelImpl kBaseModel ) {
String modelProp = kBaseModel.getKModule().getConfigurationProperty( GroupDRLsInKieBasesByFolderOption.PROPERTY_NAME );
if (modelProp == null) {
modelProp = System.getProperty( GroupDRLsInKieBasesByFolderOption.PROPERTY_NAME );
}
return modelProp != null && modelProp.toString().equalsIgnoreCase( "true" );
}
protected boolean compileIncludedKieBases() {
return true;
}
protected KnowledgeBuilder createKnowledgeBuilder( KieBaseModelImpl kBaseModel, InternalKieModule kModule ) {
return KnowledgeBuilderFactory.newKnowledgeBuilder( getBuilderConfiguration( kBaseModel, kModule ) );
}
private void addFiles( Predicate<String> buildFilter, Set<Asset> assets, KieBaseModel kieBaseModel,
InternalKieModule kieModule, boolean useFolders) {
for (String fileName : kieModule.getFileNames()) {
if (buildFilter.test( fileName ) && !fileName.startsWith(".") && !fileName.endsWith(".properties") &&
filterFileInKBase(kieModule, kieBaseModel, fileName, () -> kieModule.getResource( fileName ), useFolders)) {
assets.add(new Asset( kieModule, fileName ));
}
}
}
protected KnowledgeBuilderConfigurationImpl getBuilderConfiguration( KieBaseModelImpl kBaseModel, InternalKieModule kModule ) {
KnowledgeBuilderConfigurationImpl pconf = new KnowledgeBuilderConfigurationImpl(getClassLoader());
pconf.setCompilationCache(kModule.getCompilationCache(kBaseModel.getName()));
AbstractKieModule.setModelPropsOnConf( kBaseModel, pconf );
return pconf;
}
private static class Asset {
private final InternalKieModule kmodule;
private final String name;
private Asset( InternalKieModule kmodule, String name ) {
this.kmodule = kmodule;
this.name = name;
}
@Override
public boolean equals( Object o ) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
Asset asset = (Asset) o;
return kmodule.equals( asset.kmodule ) && name.equals( asset.name );
}
@Override
public int hashCode() {
int result = kmodule.hashCode();
result = 31 * result + name.hashCode();
return result;
}
}
}
| |
/*
* Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
*
* 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 JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.threeten.bp.temporal;
import java.io.Serializable;
import org.threeten.bp.DateTimeException;
/**
* The range of valid values for a date-time field.
* <p>
* All {@link TemporalField} instances have a valid range of values.
* For example, the ISO day-of-month runs from 1 to somewhere between 28 and 31.
* This class captures that valid range.
* <p>
* It is important to be aware of the limitations of this class.
* Only the minimum and maximum values are provided.
* It is possible for there to be invalid values within the outer range.
* For example, a weird field may have valid values of 1, 2, 4, 6, 7, thus
* have a range of '1 - 7', despite that fact that values 3 and 5 are invalid.
* <p>
* Instances of this class are not tied to a specific field.
*
* <h3>Specification for implementors</h3>
* This class is immutable and thread-safe.
*/
public final class ValueRange implements Serializable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -7317881728594519368L;
/**
* The smallest minimum value.
*/
private final long minSmallest;
/**
* The largest minimum value.
*/
private final long minLargest;
/**
* The smallest maximum value.
*/
private final long maxSmallest;
/**
* The largest maximum value.
*/
private final long maxLargest;
/**
* Obtains a fixed value range.
* <p>
* This factory obtains a range where the minimum and maximum values are fixed.
* For example, the ISO month-of-year always runs from 1 to 12.
*
* @param min the minimum value
* @param max the maximum value
* @return the ValueRange for min, max, not null
* @throws IllegalArgumentException if the minimum is greater than the maximum
*/
public static ValueRange of(long min, long max) {
if (min > max) {
throw new IllegalArgumentException("Minimum value must be less than maximum value");
}
return new ValueRange(min, min, max, max);
}
/**
* Obtains a variable value range.
* <p>
* This factory obtains a range where the minimum value is fixed and the maximum value may vary.
* For example, the ISO day-of-month always starts at 1, but ends between 28 and 31.
*
* @param min the minimum value
* @param maxSmallest the smallest maximum value
* @param maxLargest the largest maximum value
* @return the ValueRange for min, smallest max, largest max, not null
* @throws IllegalArgumentException if
* the minimum is greater than the smallest maximum,
* or the smallest maximum is greater than the largest maximum
*/
public static ValueRange of(long min, long maxSmallest, long maxLargest) {
return of(min, min, maxSmallest, maxLargest);
}
/**
* Obtains a fully variable value range.
* <p>
* This factory obtains a range where both the minimum and maximum value may vary.
*
* @param minSmallest the smallest minimum value
* @param minLargest the largest minimum value
* @param maxSmallest the smallest maximum value
* @param maxLargest the largest maximum value
* @return the ValueRange for smallest min, largest min, smallest max, largest max, not null
* @throws IllegalArgumentException if
* the smallest minimum is greater than the smallest maximum,
* or the smallest maximum is greater than the largest maximum
* or the largest minimum is greater than the largest maximum
*/
public static ValueRange of(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
if (minSmallest > minLargest) {
throw new IllegalArgumentException("Smallest minimum value must be less than largest minimum value");
}
if (maxSmallest > maxLargest) {
throw new IllegalArgumentException("Smallest maximum value must be less than largest maximum value");
}
if (minLargest > maxLargest) {
throw new IllegalArgumentException("Minimum value must be less than maximum value");
}
return new ValueRange(minSmallest, minLargest, maxSmallest, maxLargest);
}
/**
* Restrictive constructor.
*
* @param minSmallest the smallest minimum value
* @param minLargest the largest minimum value
* @param maxSmallest the smallest minimum value
* @param maxLargest the largest minimum value
*/
private ValueRange(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
this.minSmallest = minSmallest;
this.minLargest = minLargest;
this.maxSmallest = maxSmallest;
this.maxLargest = maxLargest;
}
//-----------------------------------------------------------------------
/**
* Is the value range fixed and fully known.
* <p>
* For example, the ISO day-of-month runs from 1 to between 28 and 31.
* Since there is uncertainty about the maximum value, the range is not fixed.
* However, for the month of January, the range is always 1 to 31, thus it is fixed.
*
* @return true if the set of values is fixed
*/
public boolean isFixed() {
return minSmallest == minLargest && maxSmallest == maxLargest;
}
//-----------------------------------------------------------------------
/**
* Gets the minimum value that the field can take.
* <p>
* For example, the ISO day-of-month always starts at 1.
* The minimum is therefore 1.
*
* @return the minimum value for this field
*/
public long getMinimum() {
return minSmallest;
}
/**
* Gets the largest possible minimum value that the field can take.
* <p>
* For example, the ISO day-of-month always starts at 1.
* The largest minimum is therefore 1.
*
* @return the largest possible minimum value for this field
*/
public long getLargestMinimum() {
return minLargest;
}
/**
* Gets the smallest possible maximum value that the field can take.
* <p>
* For example, the ISO day-of-month runs to between 28 and 31 days.
* The smallest maximum is therefore 28.
*
* @return the smallest possible maximum value for this field
*/
public long getSmallestMaximum() {
return maxSmallest;
}
/**
* Gets the maximum value that the field can take.
* <p>
* For example, the ISO day-of-month runs to between 28 and 31 days.
* The maximum is therefore 31.
*
* @return the maximum value for this field
*/
public long getMaximum() {
return maxLargest;
}
//-----------------------------------------------------------------------
/**
* Checks if all values in the range fit in an {@code int}.
* <p>
* This checks that all valid values are within the bounds of an {@code int}.
* <p>
* For example, the ISO month-of-year has values from 1 to 12, which fits in an {@code int}.
* By comparison, ISO nano-of-day runs from 1 to 86,400,000,000,000 which does not fit in an {@code int}.
* <p>
* This implementation uses {@link #getMinimum()} and {@link #getMaximum()}.
*
* @return true if a valid value always fits in an {@code int}
*/
public boolean isIntValue() {
return getMinimum() >= Integer.MIN_VALUE && getMaximum() <= Integer.MAX_VALUE;
}
/**
* Checks if the value is within the valid range.
* <p>
* This checks that the value is within the stored range of values.
*
* @param value the value to check
* @return true if the value is valid
*/
public boolean isValidValue(long value) {
return (value >= getMinimum() && value <= getMaximum());
}
/**
* Checks if the value is within the valid range and that all values
* in the range fit in an {@code int}.
* <p>
* This method combines {@link #isIntValue()} and {@link #isValidValue(long)}.
*
* @param value the value to check
* @return true if the value is valid and fits in an {@code int}
*/
public boolean isValidIntValue(long value) {
return isIntValue() && isValidValue(value);
}
/**
* Checks that the specified value is valid.
* <p>
* This validates that the value is within the valid range of values.
* The field is only used to improve the error message.
*
* @param value the value to check
* @param field the field being checked, may be null
* @return the value that was passed in
* @see #isValidValue(long)
*/
public long checkValidValue(long value, TemporalField field) {
if (isValidValue(value) == false) {
if (field != null) {
throw new DateTimeException("Invalid value for " + field + " (valid values " + this + "): " + value);
} else {
throw new DateTimeException("Invalid value (valid values " + this + "): " + value);
}
}
return value;
}
/**
* Checks that the specified value is valid and fits in an {@code int}.
* <p>
* This validates that the value is within the valid range of values and that
* all valid values are within the bounds of an {@code int}.
* The field is only used to improve the error message.
*
* @param value the value to check
* @param field the field being checked, may be null
* @return the value that was passed in
* @see #isValidIntValue(long)
*/
public int checkValidIntValue(long value, TemporalField field) {
if (isValidIntValue(value) == false) {
throw new DateTimeException("Invalid int value for " + field + ": " + value);
}
return (int) value;
}
//-----------------------------------------------------------------------
/**
* Checks if this range is equal to another range.
* <p>
* The comparison is based on the four values, minimum, largest minimum,
* smallest maximum and maximum.
* Only objects of type {@code ValueRange} are compared, other types return false.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other range
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ValueRange) {
ValueRange other = (ValueRange) obj;
return minSmallest == other.minSmallest && minLargest == other.minLargest &&
maxSmallest == other.maxSmallest && maxLargest == other.maxLargest;
}
return false;
}
/**
* A hash code for this range.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
long hash = minSmallest + minLargest << 16 + minLargest >> 48 + maxSmallest << 32 +
maxSmallest >> 32 + maxLargest << 48 + maxLargest >> 16;
return (int) (hash ^ (hash >>> 32));
}
//-----------------------------------------------------------------------
/**
* Outputs this range as a {@code String}.
* <p>
* The format will be '{min}/{largestMin} - {smallestMax}/{max}',
* where the largestMin or smallestMax sections may be omitted, together
* with associated slash, if they are the same as the min or max.
*
* @return a string representation of this range, not null
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(minSmallest);
if (minSmallest != minLargest) {
buf.append('/').append(minLargest);
}
buf.append(" - ").append(maxSmallest);
if (maxSmallest != maxLargest) {
buf.append('/').append(maxLargest);
}
return buf.toString();
}
}
| |
/**
* Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.mit.ll.nics.processor.email;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.util.regex.Pattern;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import javax.imageio.*;
import javax.activation.*;
import javax.xml.bind.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import edu.mit.ll.nics.common.email.*;
import edu.mit.ll.nics.common.email.constants.*;
import edu.mit.ll.nics.common.email.exception.*;
/**
* Processes XML message to extract e-mail message and sends message using
* specified mail server
*/
public class EmailConsumerSpring implements Processor {
/**
* <p>Member: LOG</p>
* <p>Description:
* The logger.
* </p>
*/
private static final Logger LOG = Logger.getLogger(EmailConsumerSpring.class);
private Unmarshaller unmarsh = null;
private EmailType email = null;
// Properties
/** The mail server hostname/IP to use */
private String mailUrl = null;
/** The log4j.properties file used by the Spring application */
private String log4jPropertyFile;
private String smtpHost = null;
private String smtpPort = null;
private String mailUsername = null;
private String mailPassword = null;
/**
* Default constructor, required by Spring
*/
public EmailConsumerSpring() {
}
/**
* This method is called by Spring once all the properties
* have been read as specified in the spring .xml file
*
* @throws JAXBException
*/
public void init() throws JAXBException {
PropertyConfigurator.configure(log4jPropertyFile);
try { // create JAXB objects
JAXBContext jaxbContext = JAXBContext.newInstance(XmlEmail.class.getPackage().getName());
unmarsh = jaxbContext.createUnmarshaller(); // get an unmarshaller
} catch (JAXBException e) {
LOG.warn("Exception getting JAXB unmarshaller: " + e.getMessage());
throw e;
}
}
/**
* Unmarshall xml message into an EmailType JAXB element then send the e-mail
* @param e
*/
@Override
public void process(Exchange e) {
// get the XML message from the exchange
String body = e.getIn().getBody(String.class);
LOG.debug("Processing Message: " + body);
if (isSimpleEmailMessage(body))
{
handleSimpleEmailMessage(body);
} else
{
handleXmlEmailMessage(body);
}
}
private boolean isSimpleEmailMessage(final String body)
{
try
{
JSONObject json = new JSONObject(body);
LOG.debug("Message is JSON");
return true;
} catch (JSONException je)
{
LOG.debug("Message not JSON");
}
return false;
}
private boolean testJsonArray(String val)
{
try
{
if (val.startsWith("[")) {
JSONArray arr = new JSONArray(val);
}
return true;
} catch (JSONException je)
{
return false;
}
}
private String getRecipientsFromJson(String val)
{
StringBuffer ret = new StringBuffer();
try
{
if (val.startsWith("["))
{
JSONArray arr = new JSONArray(val);
LOG.debug("Emails in array: " + arr.length());
for (int i=0; i < arr.length(); i++)
{
String email = arr.getString(i);
LOG.debug("Extracting email from JSONArray: " + email);
if (ret.length() != 0)
ret.append(",");
ret.append(email);
}
}
} catch (JSONException je)
{
}
return ret.toString();
}
private String validateRecipients(String recipients){
if (testJsonArray(recipients))
recipients = getRecipientsFromJson(recipients);
Pattern pattern = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
LOG.debug("Validating receipients: " + recipients);
StringBuffer validated = new StringBuffer();
String [] addresses = recipients.split(",");
for(int i=0; i<addresses.length; i++){
String email = addresses[i].trim();
if(pattern.matcher(email).find()){
if(validated.length() != 0){
validated.append(",");
}
validated.append(email);
}else{
LOG.debug("Removing invalid address: " + addresses[i]);
}
}
return validated.toString();
}
private Session createSession(String from)
{
Properties props = new Properties();
props.put(EmailConstants.MAIL_FROM_PROP, from);
props.put(EmailConstants.MAIL_STARTTLS, true);
props.put(EmailConstants.MAIL_HOST_PROP, smtpHost);
props.put(EmailConstants.MAIL_PORT_PROP, smtpPort);
props.put(EmailConstants.MAIL_AUTH_KEY, true);
// props.put(EmailConstants.MAIL_USER_KEY, mailUsername);
// props.put(EmailConstants.MAIL_PASSWD_KEY, mailPassword);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailUsername,mailPassword);
}
});
return session;
}
private MimeMessage createMimeMessage(Session session)
{
return new MimeMessage(session);
}
private MimeMessage createMimeMessage(Session session, String to, String subject)
throws MessagingException
{
MimeMessage msg = createMimeMessage(session);
// msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
validateRecipients(to));
msg.setSubject(subject);
return msg;
}
private MimeMessage createMimeMessage(String from, String to, final String subject)
throws MessagingException
{
return createMimeMessage(createSession(from), to, subject);
}
private MimeMessage setTextMessageBody(MimeMessage msg, final String body)
throws MessagingException
{
if (body.contains("<html>"))
{
// msg.setText(body, "utf-8", "text/html");
msg.setContent(body, "text/html; charset=utf-8");
} else
{
msg.setText(body);
}
return msg;
}
private void sendMessage(Session session, MimeMessage msg) throws MessagingException
{
Transport transport = session.getTransport("smtps");
// transport.connect(smtpHost, Integer.valueOf(smtpPort), mailUsername, mailPassword);
transport.connect(smtpHost, mailUsername, mailPassword);
LOG.debug("Transport: "+transport.toString());
transport.sendMessage(msg, msg.getAllRecipients());
// Transport.send(msg); // cause of duplicates
}
private void handleSimpleEmailMessage(String message)
{
try
{
JsonEmail je = JsonEmail.fromJSONString(message);
final String to = je.getTo().trim();
final String from = je.getFrom().trim();
final String subject = je.getSubject().trim();
final String body = je.getBody();
Session session = createSession(from);
MimeMessage msg = createMimeMessage(session, to, subject);
msg = setTextMessageBody(msg, body);
sendMessage(session, msg);
LOG.debug("Message sent");
} catch (JsonEmailException jee)
{
LOG.error("Caught JsonEmailException");
jee.printStackTrace();
} catch (MessagingException me)
{
LOG.error("Caught MessageException: " + me.getMessage(), me);
// me.printStackTrace();
}
}
private void handleXmlEmailMessage(String body)
{
// put the body into a string reader class
java.io.StringReader sr = new java.io.StringReader(body);
JAXBElement<EmailType> email_t;
try {
//Unmarshall the XML into Email object
email_t = (JAXBElement<EmailType>) unmarsh.unmarshal(sr);
email = email_t.getValue();
//Build MimeMessage from email object
Session session = createSession(email.getHeader().getFrom());
try {
//Add e-mail header
MimeMessage msg = createMimeMessage(session, email.getHeader().getTo(), email.getHeader().getSubject());
// add CC recipients
if (email.getHeader().getCc() != null) {
msg.addRecipients(Message.RecipientType.CC,
validateRecipients(email.getHeader().getCc()));
}
//Create and add the e-mail body
//If no images are included just add body text
if (email.getContent().getImage().getLocation() == null
&& email.getContent().getBody().getFormat() != null) {
String body_text = email.getContent().getBody().getText();
if (email.getContent().getBody().getFormat().equals("HTML")) {
msg.setContent(body_text, "text/html");
} else {
msg.setText(body_text);
}
} else {
//If Images are included create a multipart email body
Multipart multipartbody;
//Buffer the image
BufferedImage img = (BufferedImage) email.getContent().getImage().getJPEGPicture();
//Create a message body part and add the image
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(img, "jpeg", bos);
MimeBodyPart imageBodyPart = new MimeBodyPart();
imageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bos.toByteArray(), "image/jpeg")));
//Create the multipart body and add the image bodypart
if (email.getContent().getImage().getLocation().equals("embed")) {
//Embed image
multipartbody = new MimeMultipart("related");
imageBodyPart.setHeader("Content-ID", "<embedded_image>");
} else {
//Attach image
multipartbody = new MimeMultipart();
imageBodyPart.setFileName("image.jpg");
}
//add the text bodypart
if (email.getContent().getBody().getFormat() != null) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
String body_text = email.getContent().getBody().getText();
if (email.getContent().getImage().getLocation().equals("embed")
&& email.getContent().getBody().getFormat().equals("HTML")) {
//Embedded image in html message
//Insert image at end of body tag
messageBodyPart.setContent(body_text.substring(0, body_text.lastIndexOf("</body>"))
+ ("<br/><br/><img src=\"cid:embedded_image\">")
+ (body_text.substring(body_text.lastIndexOf("</body>"))), "text/html");
} else if (email.getContent().getImage().getLocation().equals("embed")) {
//Embedded image in regular text body
//Convert into html message
messageBodyPart.setContent("<html><body>"
+ body_text + "<br/><br/><img src=\"cid:embedded_image\">"
+ "</body></html>", "text/html");
} else if (email.getContent().getBody().getFormat().equals("HTML")) {
//Attached image with html body
messageBodyPart.setContent(body_text, "text/html");
} else {
//Attached image with text body
messageBodyPart.setText(body_text);
}
multipartbody.addBodyPart(messageBodyPart);
multipartbody.addBodyPart(imageBodyPart);
}
msg.setContent(multipartbody);
}
//Send the message
Transport.send(msg);
LOG.info("Message sent to:" + email.getHeader().getTo());
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
} catch (Exception ex) {
LOG.error("EmailSender:process: caught following "
+ "exception processing XML: "
+ ex.getMessage(),ex);
}
}
// Getters and Setters
public String getMailUrl() {
return mailUrl;
}
public void setMailUrl(String mailUrl) {
this.mailUrl = mailUrl;
}
public String getLog4jPropertyFile() {
return log4jPropertyFile;
}
public void setLog4jPropertyFile(String log4jPropertyFile) {
this.log4jPropertyFile = log4jPropertyFile;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpPort() {
return smtpPort;
}
public void setSmtpPort(String smtpPort) {
this.smtpPort = smtpPort;
}
public String getMailUsername() {
return mailUsername;
}
public void setMailUsername(String mailUsername) {
this.mailUsername = mailUsername;
}
public String getMailPassword() {
return mailPassword;
}
public void setMailPassword(String mailPassword) {
this.mailPassword = mailPassword;
}
}
| |
/*
* Copyright 2014-2019 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.datapipeline.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Contains the output of PutPipelineDefinition.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PutPipelineDefinitionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ValidationError> validationErrors;
/**
* <p>
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ValidationWarning> validationWarnings;
/**
* <p>
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be activated
* until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the corrected pipeline.
* </p>
*/
private Boolean errored;
/**
* <p>
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*
* @return The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
*/
public java.util.List<ValidationError> getValidationErrors() {
if (validationErrors == null) {
validationErrors = new com.amazonaws.internal.SdkInternalList<ValidationError>();
}
return validationErrors;
}
/**
* <p>
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*
* @param validationErrors
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
*/
public void setValidationErrors(java.util.Collection<ValidationError> validationErrors) {
if (validationErrors == null) {
this.validationErrors = null;
return;
}
this.validationErrors = new com.amazonaws.internal.SdkInternalList<ValidationError>(validationErrors);
}
/**
* <p>
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setValidationErrors(java.util.Collection)} or {@link #withValidationErrors(java.util.Collection)} if you
* want to override the existing values.
* </p>
*
* @param validationErrors
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutPipelineDefinitionResult withValidationErrors(ValidationError... validationErrors) {
if (this.validationErrors == null) {
setValidationErrors(new com.amazonaws.internal.SdkInternalList<ValidationError>(validationErrors.length));
}
for (ValidationError ele : validationErrors) {
this.validationErrors.add(ele);
}
return this;
}
/**
* <p>
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*
* @param validationErrors
* The validation errors that are associated with the objects defined in <code>pipelineObjects</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutPipelineDefinitionResult withValidationErrors(java.util.Collection<ValidationError> validationErrors) {
setValidationErrors(validationErrors);
return this;
}
/**
* <p>
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*
* @return The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
*/
public java.util.List<ValidationWarning> getValidationWarnings() {
if (validationWarnings == null) {
validationWarnings = new com.amazonaws.internal.SdkInternalList<ValidationWarning>();
}
return validationWarnings;
}
/**
* <p>
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*
* @param validationWarnings
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
*/
public void setValidationWarnings(java.util.Collection<ValidationWarning> validationWarnings) {
if (validationWarnings == null) {
this.validationWarnings = null;
return;
}
this.validationWarnings = new com.amazonaws.internal.SdkInternalList<ValidationWarning>(validationWarnings);
}
/**
* <p>
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setValidationWarnings(java.util.Collection)} or {@link #withValidationWarnings(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param validationWarnings
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutPipelineDefinitionResult withValidationWarnings(ValidationWarning... validationWarnings) {
if (this.validationWarnings == null) {
setValidationWarnings(new com.amazonaws.internal.SdkInternalList<ValidationWarning>(validationWarnings.length));
}
for (ValidationWarning ele : validationWarnings) {
this.validationWarnings.add(ele);
}
return this;
}
/**
* <p>
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* </p>
*
* @param validationWarnings
* The validation warnings that are associated with the objects defined in <code>pipelineObjects</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutPipelineDefinitionResult withValidationWarnings(java.util.Collection<ValidationWarning> validationWarnings) {
setValidationWarnings(validationWarnings);
return this;
}
/**
* <p>
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be activated
* until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the corrected pipeline.
* </p>
*
* @param errored
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be
* activated until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the
* corrected pipeline.
*/
public void setErrored(Boolean errored) {
this.errored = errored;
}
/**
* <p>
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be activated
* until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the corrected pipeline.
* </p>
*
* @return Indicates whether there were validation errors, and the pipeline definition is stored but cannot be
* activated until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the
* corrected pipeline.
*/
public Boolean getErrored() {
return this.errored;
}
/**
* <p>
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be activated
* until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the corrected pipeline.
* </p>
*
* @param errored
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be
* activated until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the
* corrected pipeline.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutPipelineDefinitionResult withErrored(Boolean errored) {
setErrored(errored);
return this;
}
/**
* <p>
* Indicates whether there were validation errors, and the pipeline definition is stored but cannot be activated
* until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the corrected pipeline.
* </p>
*
* @return Indicates whether there were validation errors, and the pipeline definition is stored but cannot be
* activated until you correct the pipeline and call <code>PutPipelineDefinition</code> to commit the
* corrected pipeline.
*/
public Boolean isErrored() {
return this.errored;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getValidationErrors() != null)
sb.append("ValidationErrors: ").append(getValidationErrors()).append(",");
if (getValidationWarnings() != null)
sb.append("ValidationWarnings: ").append(getValidationWarnings()).append(",");
if (getErrored() != null)
sb.append("Errored: ").append(getErrored());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof PutPipelineDefinitionResult == false)
return false;
PutPipelineDefinitionResult other = (PutPipelineDefinitionResult) obj;
if (other.getValidationErrors() == null ^ this.getValidationErrors() == null)
return false;
if (other.getValidationErrors() != null && other.getValidationErrors().equals(this.getValidationErrors()) == false)
return false;
if (other.getValidationWarnings() == null ^ this.getValidationWarnings() == null)
return false;
if (other.getValidationWarnings() != null && other.getValidationWarnings().equals(this.getValidationWarnings()) == false)
return false;
if (other.getErrored() == null ^ this.getErrored() == null)
return false;
if (other.getErrored() != null && other.getErrored().equals(this.getErrored()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getValidationErrors() == null) ? 0 : getValidationErrors().hashCode());
hashCode = prime * hashCode + ((getValidationWarnings() == null) ? 0 : getValidationWarnings().hashCode());
hashCode = prime * hashCode + ((getErrored() == null) ? 0 : getErrored().hashCode());
return hashCode;
}
@Override
public PutPipelineDefinitionResult clone() {
try {
return (PutPipelineDefinitionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/* 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) */
/*
* 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.bytes;
import it.unimi.dsi.fastutil.Hash;
import it.unimi.dsi.fastutil.HashCommon;
import it.unimi.dsi.fastutil.booleans.BooleanArrays;
import static it.unimi.dsi.fastutil.HashCommon.arraySize;
import static it.unimi.dsi.fastutil.HashCommon.maxFill;
import java.util.Map;
import java.util.NoSuchElementException;
import it.unimi.dsi.fastutil.objects.ReferenceCollection;
import it.unimi.dsi.fastutil.objects.AbstractReferenceCollection;
import it.unimi.dsi.fastutil.objects.ObjectArrays;
import it.unimi.dsi.fastutil.objects.AbstractObjectSet;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
/** A type-specific hash map with a fast, small-footprint implementation whose {@linkplain it.unimi.dsi.fastutil.Hash.Strategy hashing strategy}
* is specified at creation time.
*
* <P>Instances of this class use a hash table to represent a map. The table is
* enlarged as needed by doubling its size when new entries are created, but it is <em>never</em> made
* smaller (even on a {@link #clear()}). A family of {@linkplain #trim() trimming
* methods} lets you control the size of the table; this is particularly useful
* if you reuse instances of this class.
*
* <p><strong>Warning:</strong> The implementation of this class has significantly
* changed in <code>fastutil</code> 6.1.0. Please read the
* comments about this issue in the section “Faster Hash Tables” of the <a href="../../../../../overview-summary.html">overview</a>.
*
* @see Hash
* @see HashCommon
*/
public class Byte2ReferenceOpenCustomHashMap <V> extends AbstractByte2ReferenceMap <V> implements java.io.Serializable, Cloneable, Hash {
private static final long serialVersionUID = 0L;
private static final boolean ASSERTS = false;
/** The array of keys. */
protected transient byte key[];
/** The array of values. */
protected transient V value[];
/** The array telling whether a position is used. */
protected transient boolean used[];
/** The acceptable load factor. */
protected final float f;
/** The current table size. */
protected transient int n;
/** Threshold after which we rehash. It must be the table size times {@link #f}. */
protected transient int maxFill;
/** The mask for wrapping a position counter. */
protected transient int mask;
/** Number of entries in the set. */
protected int size;
/** Cached set of entries. */
protected transient volatile FastEntrySet <V> entries;
/** Cached set of keys. */
protected transient volatile ByteSet keys;
/** Cached collection of values. */
protected transient volatile ReferenceCollection <V> values;
/** The hash strategy of this custom map. */
protected it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy;
/** Creates a new hash map.
*
* <p>The actual table size will be the least power of two greater than <code>expected</code>/<code>f</code>.
*
* @param expected the expected number of elements in the hash set.
* @param f the load factor.
* @param strategy the strategy.
*/
@SuppressWarnings("unchecked")
public Byte2ReferenceOpenCustomHashMap( final int expected, final float f, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this.strategy = strategy;
if ( f <= 0 || f > 1 ) throw new IllegalArgumentException( "Load factor must be greater than 0 and smaller than or equal to 1" );
if ( expected < 0 ) throw new IllegalArgumentException( "The expected number of elements must be nonnegative" );
this.f = f;
n = arraySize( expected, f );
mask = n - 1;
maxFill = maxFill( n, f );
key = new byte[ n ];
value = (V[]) new Object[ n ];
used = new boolean[ n ];
}
/** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor.
*
* @param expected the expected number of elements in the hash map.
* @param strategy the strategy.
*/
public Byte2ReferenceOpenCustomHashMap( final int expected, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( expected, DEFAULT_LOAD_FACTOR, strategy );
}
/** Creates a new hash map with initial expected {@link Hash#DEFAULT_INITIAL_SIZE} entries
* and {@link Hash#DEFAULT_LOAD_FACTOR} as load factor.
* @param strategy the strategy.
*/
public Byte2ReferenceOpenCustomHashMap( final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy );
}
/** Creates a new hash map copying a given one.
*
* @param m a {@link Map} to be copied into the new hash map.
* @param f the load factor.
* @param strategy the strategy.
*/
public Byte2ReferenceOpenCustomHashMap( final Map<? extends Byte, ? extends V> m, final float f, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( m.size(), f, strategy );
putAll( m );
}
/** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given one.
*
* @param m a {@link Map} to be copied into the new hash map.
* @param strategy the strategy.
*/
public Byte2ReferenceOpenCustomHashMap( final Map<? extends Byte, ? extends V> m, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( m, DEFAULT_LOAD_FACTOR, strategy );
}
/** Creates a new hash map copying a given type-specific one.
*
* @param m a type-specific map to be copied into the new hash map.
* @param f the load factor.
* @param strategy the strategy.
*/
public Byte2ReferenceOpenCustomHashMap( final Byte2ReferenceMap <V> m, final float f, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( m.size(), f, strategy );
putAll( m );
}
/** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given type-specific one.
*
* @param m a type-specific map to be copied into the new hash map.
* @param strategy the strategy.
*/
public Byte2ReferenceOpenCustomHashMap( final Byte2ReferenceMap <V> m, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( m, DEFAULT_LOAD_FACTOR, strategy );
}
/** Creates a new hash map using the elements of two parallel arrays.
*
* @param k the array of keys of the new hash map.
* @param v the array of corresponding values in the new hash map.
* @param f the load factor.
* @param strategy the strategy.
* @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths.
*/
public Byte2ReferenceOpenCustomHashMap( final byte[] k, final V v[], final float f, final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( k.length, f, strategy );
if ( k.length != v.length ) throw new IllegalArgumentException( "The key array and the value array have different lengths (" + k.length + " and " + v.length + ")" );
for( int i = 0; i < k.length; i++ ) this.put( k[ i ], v[ i ] );
}
/** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor using the elements of two parallel arrays.
*
* @param k the array of keys of the new hash map.
* @param v the array of corresponding values in the new hash map.
* @param strategy the strategy.
* @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths.
*/
public Byte2ReferenceOpenCustomHashMap( final byte[] k, final V v[], final it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy ) {
this( k, v, DEFAULT_LOAD_FACTOR, strategy );
}
/** Returns the hashing strategy.
*
* @return the hashing strategy of this custom hash map.
*/
public it.unimi.dsi.fastutil.bytes.ByteHash.Strategy strategy() {
return strategy;
}
/*
* The following methods implements some basic building blocks used by
* all accessors. They are (and should be maintained) identical to those used in OpenHashSet.drv.
*/
public V put(final byte k, final V v) {
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) {
final V oldValue = value[ pos ];
value[ pos ] = v;
return oldValue;
}
pos = ( pos + 1 ) & mask;
}
used[ pos ] = true;
key[ pos ] = k;
value[ pos ] = v;
if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) );
if ( ASSERTS ) checkTable();
return defRetValue;
}
public V put( final Byte ok, final V ov ) {
final V v = (ov);
final byte k = ((ok).byteValue());
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) {
final V oldValue = (value[ pos ]);
value[ pos ] = v;
return oldValue;
}
pos = ( pos + 1 ) & mask;
}
used[ pos ] = true;
key[ pos ] = k;
value[ pos ] = v;
if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) );
if ( ASSERTS ) checkTable();
return (this.defRetValue);
}
/** Shifts left entries with the specified hash code, starting at the specified position,
* and empties the resulting free entry.
*
* @param pos a starting position.
* @return the position cleared by the shifting process.
*/
protected final int shiftKeys( int pos ) {
// Shift entries with the same hash.
int last, slot;
for(;;) {
pos = ( ( last = pos ) + 1 ) & mask;
while( used[ pos ] ) {
slot = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(key[ pos ]) ) ) & mask;
if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break;
pos = ( pos + 1 ) & mask;
}
if ( ! used[ pos ] ) break;
key[ last ] = key[ pos ];
value[ last ] = value[ pos ];
}
used[ last ] = false;
value[ last ] = null;
return last;
}
@SuppressWarnings("unchecked")
public V remove( final byte k ) {
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) {
size--;
final V v = value[ pos ];
shiftKeys( pos );
return v;
}
pos = ( pos + 1 ) & mask;
}
return defRetValue;
}
@SuppressWarnings("unchecked")
public V remove( final Object ok ) {
final byte k = ((((Byte)(ok)).byteValue()));
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) {
size--;
final V v = value[ pos ];
shiftKeys( pos );
return (v);
}
pos = ( pos + 1 ) & mask;
}
return (this.defRetValue);
}
public V get( final Byte ok ) {
final byte k = ((ok).byteValue());
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), ( k) ) ) ) return (value[ pos ]);
pos = ( pos + 1 ) & mask;
}
return (this.defRetValue);
}
@SuppressWarnings("unchecked")
public V get( final byte k ) {
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) return value[ pos ];
pos = ( pos + 1 ) & mask;
}
return defRetValue;
}
@SuppressWarnings("unchecked")
public boolean containsKey( final byte k ) {
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) return true;
pos = ( pos + 1 ) & mask;
}
return false;
}
public boolean containsValue( final Object v ) {
final V value[] = this.value;
final boolean used[] = this.used;
for( int i = n; i-- != 0; ) if ( used[ i ] && ( (value[ i ]) == (v) ) ) return true;
return false;
}
/* Removes all elements from this map.
*
* <P>To increase object reuse, this method does not change the table size.
* If you want to reduce the table size, you must use {@link #trim()}.
*
*/
public void clear() {
if ( size == 0 ) return;
size = 0;
BooleanArrays.fill( used, false );
// We null all object entries so that the garbage collector can do its work.
ObjectArrays.fill( value, null );
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
/** A no-op for backward compatibility.
*
* @param growthFactor unused.
* @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full.
*/
@Deprecated
public void growthFactor( int growthFactor ) {}
/** Gets the growth factor (2).
*
* @return the growth factor of this set, which is fixed (2).
* @see #growthFactor(int)
* @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full.
*/
@Deprecated
public int growthFactor() {
return 16;
}
/** The entry class for a hash map does not record key and value, but
* rather the position in the hash table of the corresponding entry. This
* is necessary so that calls to {@link java.util.Map.Entry#setValue(Object)} are reflected in
* the map */
private final class MapEntry implements Byte2ReferenceMap.Entry <V>, Map.Entry<Byte, V> {
// The table index this entry refers to, or -1 if this entry has been deleted.
private int index;
MapEntry( final int index ) {
this.index = index;
}
public Byte getKey() {
return (Byte.valueOf(key[ index ]));
}
public byte getByteKey() {
return key[ index ];
}
public V getValue() {
return (value[ index ]);
}
public V setValue( final V v ) {
final V oldValue = value[ index ];
value[ index ] = v;
return oldValue;
}
@SuppressWarnings("unchecked")
public boolean equals( final Object o ) {
if (!(o instanceof Map.Entry)) return false;
Map.Entry<Byte, V> e = (Map.Entry<Byte, V>)o;
return ( strategy.equals( (key[ index ]), (((e.getKey()).byteValue())) ) ) && ( (value[ index ]) == ((e.getValue())) );
}
public int hashCode() {
return ( strategy.hashCode(key[ index ]) ) ^ ( (value[ index ]) == null ? 0 : System.identityHashCode(value[ index ]) );
}
public String toString() {
return key[ index ] + "=>" + value[ index ];
}
}
/** An iterator over a hash map. */
private class MapIterator {
/** The index of the next entry to be returned, if positive or zero. If negative, the next entry to be
returned, if any, is that of index -pos -2 from the {@link #wrapped} list. */
int pos = Byte2ReferenceOpenCustomHashMap.this.n;
/** The index of the last entry that has been returned. It is -1 if either
we did not return an entry yet, or the last returned entry has been removed. */
int last = -1;
/** A downward counter measuring how many entries must still be returned. */
int c = size;
/** A lazily allocated list containing the keys of elements that have wrapped around the table because of removals; such elements
would not be enumerated (other elements would be usually enumerated twice in their place). */
ByteArrayList wrapped;
{
final boolean used[] = Byte2ReferenceOpenCustomHashMap.this.used;
if ( c != 0 ) while( ! used[ --pos ] );
}
public boolean hasNext() {
return c != 0;
}
public int nextEntry() {
if ( ! hasNext() ) throw new NoSuchElementException();
c--;
// We are just enumerating elements from the wrapped list.
if ( pos < 0 ) {
final byte k = wrapped.getByte( - ( last = --pos ) - 2 );
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) return pos;
pos = ( pos + 1 ) & mask;
}
}
last = pos;
//System.err.println( "Count: " + c );
if ( c != 0 ) {
final boolean used[] = Byte2ReferenceOpenCustomHashMap.this.used;
while ( pos-- != 0 && !used[ pos ] );
// When here pos < 0 there are no more elements to be enumerated by scanning, but wrapped might be nonempty.
}
return last;
}
/** Shifts left entries with the specified hash code, starting at the specified position,
* and empties the resulting free entry. If any entry wraps around the table, instantiates
* lazily {@link #wrapped} and stores the entry key.
*
* @param pos a starting position.
* @return the position cleared by the shifting process.
*/
protected final int shiftKeys( int pos ) {
// Shift entries with the same hash.
int last, slot;
for(;;) {
pos = ( ( last = pos ) + 1 ) & mask;
while( used[ pos ] ) {
slot = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(key[ pos ]) ) ) & mask;
if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break;
pos = ( pos + 1 ) & mask;
}
if ( ! used[ pos ] ) break;
if ( pos < last ) {
// Wrapped entry.
if ( wrapped == null ) wrapped = new ByteArrayList ();
wrapped.add( key[ pos ] );
}
key[ last ] = key[ pos ];
value[ last ] = value[ pos ];
}
used[ last ] = false;
value[ last ] = null;
return last;
}
@SuppressWarnings("unchecked")
public void remove() {
if ( last == -1 ) throw new IllegalStateException();
if ( pos < -1 ) {
// We're removing wrapped entries.
Byte2ReferenceOpenCustomHashMap.this.remove( wrapped.getByte( - pos - 2 ) );
last = -1;
return;
}
size--;
if ( shiftKeys( last ) == pos && c > 0 ) {
c++;
nextEntry();
}
last = -1; // You can no longer remove this entry.
if ( ASSERTS ) checkTable();
}
public int skip( final int n ) {
int i = n;
while( i-- != 0 && hasNext() ) nextEntry();
return n - i - 1;
}
}
private class EntryIterator extends MapIterator implements ObjectIterator<Byte2ReferenceMap.Entry <V> > {
private MapEntry entry;
public Byte2ReferenceMap.Entry <V> next() {
return entry = new MapEntry( nextEntry() );
}
@Override
public void remove() {
super.remove();
entry.index = -1; // You cannot use a deleted entry.
}
}
private class FastEntryIterator extends MapIterator implements ObjectIterator<Byte2ReferenceMap.Entry <V> > {
final BasicEntry <V> entry = new BasicEntry <V> ( ((byte)0), (null) );
public BasicEntry <V> next() {
final int e = nextEntry();
entry.key = key[ e ];
entry.value = value[ e ];
return entry;
}
}
private final class MapEntrySet extends AbstractObjectSet<Byte2ReferenceMap.Entry <V> > implements FastEntrySet <V> {
public ObjectIterator<Byte2ReferenceMap.Entry <V> > iterator() {
return new EntryIterator();
}
public ObjectIterator<Byte2ReferenceMap.Entry <V> > fastIterator() {
return new FastEntryIterator();
}
@SuppressWarnings("unchecked")
public boolean contains( final Object o ) {
if ( !( o instanceof Map.Entry ) ) return false;
final Map.Entry<Byte, V> e = (Map.Entry<Byte, V>)o;
final byte k = ((e.getKey()).byteValue());
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) return ( (value[ pos ]) == ((e.getValue())) );
pos = ( pos + 1 ) & mask;
}
return false;
}
@SuppressWarnings("unchecked")
public boolean remove( final Object o ) {
if ( !( o instanceof Map.Entry ) ) return false;
final Map.Entry<Byte, V> e = (Map.Entry<Byte, V>)o;
final byte k = ((e.getKey()).byteValue());
// The starting point.
int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
// There's always an unused entry.
while( used[ pos ] ) {
if ( ( strategy.equals( (key[ pos ]), (k) ) ) ) {
Byte2ReferenceOpenCustomHashMap.this.remove( e.getKey() );
return true;
}
pos = ( pos + 1 ) & mask;
}
return false;
}
public int size() {
return size;
}
public void clear() {
Byte2ReferenceOpenCustomHashMap.this.clear();
}
}
public FastEntrySet <V> byte2ReferenceEntrySet() {
if ( entries == null ) entries = new MapEntrySet();
return entries;
}
/** An iterator on keys.
*
* <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods
* (and possibly their type-specific counterparts) so that they return keys
* instead of entries.
*/
private final class KeyIterator extends MapIterator implements ByteIterator {
public KeyIterator() { super(); }
public byte nextByte() { return key[ nextEntry() ]; }
public Byte next() { return (Byte.valueOf(key[ nextEntry() ])); }
}
private final class KeySet extends AbstractByteSet {
public ByteIterator iterator() {
return new KeyIterator();
}
public int size() {
return size;
}
public boolean contains( byte k ) {
return containsKey( k );
}
public boolean remove( byte k ) {
final int oldSize = size;
Byte2ReferenceOpenCustomHashMap.this.remove( k );
return size != oldSize;
}
public void clear() {
Byte2ReferenceOpenCustomHashMap.this.clear();
}
}
public ByteSet keySet() {
if ( keys == null ) keys = new KeySet();
return keys;
}
/** An iterator on values.
*
* <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods
* (and possibly their type-specific counterparts) so that they return values
* instead of entries.
*/
private final class ValueIterator extends MapIterator implements ObjectIterator <V> {
public ValueIterator() { super(); }
public V next() { return value[ nextEntry() ]; }
}
public ReferenceCollection <V> values() {
if ( values == null ) values = new AbstractReferenceCollection <V>() {
public ObjectIterator <V> iterator() {
return new ValueIterator();
}
public int size() {
return size;
}
public boolean contains( Object v ) {
return containsValue( v );
}
public void clear() {
Byte2ReferenceOpenCustomHashMap.this.clear();
}
};
return values;
}
/** A no-op for backward compatibility. The kind of tables implemented by
* this class never need rehashing.
*
* <P>If you need to reduce the table size to fit exactly
* this set, use {@link #trim()}.
*
* @return true.
* @see #trim()
* @deprecated A no-op.
*/
@Deprecated
public boolean rehash() {
return true;
}
/** Rehashes the map, making the table as small as possible.
*
* <P>This method rehashes the table to the smallest size satisfying the
* load factor. It can be used when the set will not be changed anymore, so
* to optimize access speed and size.
*
* <P>If the table size is already the minimum possible, this method
* does nothing.
*
* @return true if there was enough memory to trim the map.
* @see #trim(int)
*/
public boolean trim() {
final int l = arraySize( size, f );
if ( l >= n ) return true;
try {
rehash( l );
}
catch(OutOfMemoryError cantDoIt) { return false; }
return true;
}
/** Rehashes this map if the table is too large.
*
* <P>Let <var>N</var> be the smallest table size that can hold
* <code>max(n,{@link #size()})</code> entries, still satisfying the load factor. If the current
* table size is smaller than or equal to <var>N</var>, this method does
* nothing. Otherwise, it rehashes this map in a table of size
* <var>N</var>.
*
* <P>This method is useful when reusing maps. {@linkplain #clear() Clearing a
* map} leaves the table size untouched. If you are reusing a map
* many times, you can call this method with a typical
* size to avoid keeping around a very large table just
* because of a few large transient maps.
*
* @param n the threshold for the trimming.
* @return true if there was enough memory to trim the map.
* @see #trim()
*/
public boolean trim( final int n ) {
final int l = HashCommon.nextPowerOfTwo( (int)Math.ceil( n / f ) );
if ( this.n <= l ) return true;
try {
rehash( l );
}
catch( OutOfMemoryError cantDoIt ) { return false; }
return true;
}
/** Resizes the map.
*
* <P>This method implements the basic rehashing strategy, and may be
* overriden by subclasses implementing different rehashing strategies (e.g.,
* disk-based rehashing). However, you should not override this method
* unless you understand the internal workings of this class.
*
* @param newN the new size
*/
@SuppressWarnings("unchecked")
protected void rehash( final int newN ) {
int i = 0, pos;
final boolean used[] = this.used;
byte k;
final byte key[] = this.key;
final V value[] = this.value;
final int newMask = newN - 1;
final byte newKey[] = new byte[ newN ];
final V newValue[] = (V[]) new Object[newN];
final boolean newUsed[] = new boolean[ newN ];
for( int j = size; j-- != 0; ) {
while( ! used[ i ] ) i++;
k = key[ i ];
pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & newMask;
while ( newUsed[ pos ] ) pos = ( pos + 1 ) & newMask;
newUsed[ pos ] = true;
newKey[ pos ] = k;
newValue[ pos ] = value[ i ];
i++;
}
n = newN;
mask = newMask;
maxFill = maxFill( n, f );
this.key = newKey;
this.value = newValue;
this.used = newUsed;
}
/** Returns a deep copy of this map.
*
* <P>This method performs a deep copy of this hash map; the data stored in the
* map, however, is not cloned. Note that this makes a difference only for object keys.
*
* @return a deep copy of this map.
*/
@SuppressWarnings("unchecked")
public Byte2ReferenceOpenCustomHashMap <V> clone() {
Byte2ReferenceOpenCustomHashMap <V> c;
try {
c = (Byte2ReferenceOpenCustomHashMap <V>)super.clone();
}
catch(CloneNotSupportedException cantHappen) {
throw new InternalError();
}
c.keys = null;
c.values = null;
c.entries = null;
c.key = key.clone();
c.value = value.clone();
c.used = used.clone();
c.strategy = strategy;
return c;
}
/** Returns a hash code for this map.
*
* This method overrides the generic method provided by the superclass.
* Since <code>equals()</code> is not overriden, it is important
* that the value returned by this method is the same value as
* the one returned by the overriden method.
*
* @return a hash code for this map.
*/
public int hashCode() {
int h = 0;
for( int j = size, i = 0, t = 0; j-- != 0; ) {
while( ! used[ i ] ) i++;
t = ( strategy.hashCode(key[ i ]) );
if ( this != value[ i ] )
t ^= ( (value[ i ]) == null ? 0 : System.identityHashCode(value[ i ]) );
h += t;
i++;
}
return h;
}
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
final byte key[] = this.key;
final V value[] = this.value;
final MapIterator i = new MapIterator();
s.defaultWriteObject();
for( int j = size, e; j-- != 0; ) {
e = i.nextEntry();
s.writeByte( key[ e ] );
s.writeObject( value[ e ] );
}
}
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
n = arraySize( size, f );
maxFill = maxFill( n, f );
mask = n - 1;
final byte key[] = this.key = new byte[ n ];
final V value[] = this.value = (V[]) new Object[ n ];
final boolean used[] = this.used = new boolean[ n ];
byte k;
V v;
for( int i = size, pos = 0; i-- != 0; ) {
k = s.readByte();
v = (V) s.readObject();
pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(k) ) ) & mask;
while ( used[ pos ] ) pos = ( pos + 1 ) & mask;
used[ pos ] = true;
key[ pos ] = k;
value[ pos ] = v;
}
if ( ASSERTS ) checkTable();
}
private void checkTable() {}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.