answer
stringlengths
17
10.2M
package org.openntf.domino.utils; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openntf.domino.ACL; import org.openntf.domino.Database; import org.openntf.domino.Document; import org.openntf.domino.Item; import org.openntf.domino.Name; import org.openntf.domino.Session; /** * Document Access Control List Tools & Utilities * * @author Devin S. Olson (dolson@czarnowski.com) * */ public enum DACL { ; public static final String ITEMNAME_DACL_READERS = "DACL_Readers"; public static final String ITEMNAME_DACL_AUTHORS = "DACL_Authors"; public static final String DEFAULT_DACL_READERS = "[ReadAll]"; public static final String DEFAULT_DACL_AUTHORS = "[EditAll]"; // starts with "[", has any number of letters, spaces, hyphens, or underscores, ends with "]" public static final String PATTERNTEXT_ROLES = "(?i)^\\[[a-z0-9 -_]+\\]$"; public static enum DACLtype { DACL_AUTHORS, DACL_READERS; @Override public String toString() { return this.name(); } public String getInfo() { return this.getDeclaringClass() + "." + this.getClass() + ":" + this.name(); } }; private static final long serialVersionUID = 1048L; /** * Determines if the passed in name is a member of the DACL_AUTHORS for the document. * * @param session * Current Session * @param document * Document to search for DACL * @param name * Name to check * * @return Flag indicating if the name is a member of the DACL_AUTHORS for the document. */ public static boolean isDACLauthor(final Session session, final Document document, final Name name) { return DACL.isDACLmember(session, document, name, DACLtype.DACL_AUTHORS); } /** * Determines if the current user is a member of the DACL_AUTHORS for the document. * * @param session * Current Session * @param document * Document to search for DACL * * @return Flag indicating if the current user is a member of the DACL_AUTHORS for the document. */ public static boolean isDACLauthor(final Session session, final Document document) { return DACL.isDACLmember(session, document, DACLtype.DACL_AUTHORS); } /** * Gets the DACL_AUTHORS values from the source document. * * @param document * Document from which to retreive the DACL_AUTHORS values. * * @return DACL_AUTHORS values. null if not present or empty. */ public static TreeSet<String> getDACLauthors(final Document document) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (document.hasItem(DACL.ITEMNAME_DACL_AUTHORS)) { final TreeSet<String> result = CollectionUtils.getTreeSetStrings(document.getItemValue(DACL.ITEMNAME_DACL_AUTHORS)); return ((null == result) || (result.size() < 1)) ? null : result; } } catch (final Exception e) { DominoUtils.handleException(e); } return null; } /** * Sets the DACL_AUTHORS item on the source document. * * The value for DEFAULT_DACL_AUTHORS is included. Does NOT save the document. * * @param document * Document upon which to set the DACL_AUTHORS item. * * @param values * Person names or roles to be set as the DACL_AUTHORS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean setDACLauthors(final Document document, final TreeSet<String> values) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (null == values) { throw new IllegalArgumentException("Values is null"); } final TreeSet<String> dacl = new TreeSet<String>(); dacl.add(DACL.DEFAULT_DACL_AUTHORS); for (final String entry : values) { if (!Strings.isBlankString(entry)) { dacl.add(entry); } } final Item item = document.replaceItemValue(DACL.ITEMNAME_DACL_AUTHORS, Strings.getVectorizedStrings(dacl)); item.setAuthors(true); return true; } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Sets the DACL_AUTHORS item on the source document. * * The value for DEFAULT_DACL_AUTHORS is included. Does NOT save the document. * * @param document * Document upon which to set the DACL_AUTHORS item. * * @param values * Person names or roles (convertable to a TreeSet) to be set as the DACL_AUTHORS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean setDACLauthors(final Document document, final Object values) { return DACL.setDACLauthors(document, CollectionUtils.getTreeSetStrings(values)); } /** * Adds a value to the DACL_AUTHORS for the document. * * Existing DACL_AUTHORS are not removed. The value for DEFAULT_DACL_AUTHORS is included. Does NOT save the document. * * @param document * Document upon which to update the DACL_AUTHORS. * * @param values * Person names or roles to be added to the DACL_AUTHORS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean addDACLauthors(final Document document, final TreeSet<String> values) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (null == values) { throw new IllegalArgumentException("Values is null"); } TreeSet<String> dacl = DACL.getDACLauthors(document); if (null == dacl) { dacl = new TreeSet<String>(); } for (final String entry : values) { if (!Strings.isBlankString(entry)) { dacl.add(entry); } } return DACL.setDACLauthors(document, dacl); } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Adds a value to the DACL_AUTHORS for the document. * * Existing DACL_AUTHORS are not removed. The value for DEFAULT_DACL_AUTHORS is included. Does NOT save the document. * * @param document * Document upon which to update the DACL_AUTHORS. * * @param value * Person name or role to be added to the DACL_AUTHORS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean addDACLauthor(final Document document, final String value) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } final TreeSet<String> values = new TreeSet<String>(); if (!Strings.isBlankString(value)) { values.add(value); } return DACL.addDACLauthors(document, values); } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Removes the DACL_AUTHORS item from the source document. * * Does NOT save the document. * * @param document * Document from which to remove the DACL_AUTHORS item. * * @return Flag indicating if the item was successfully removed. */ public static boolean removeDACLauthors(final Document document) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (document.hasItem(DACL.ITEMNAME_DACL_AUTHORS)) { document.removeItem(DACL.ITEMNAME_DACL_AUTHORS); return true; } } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Removes a value from the DACL_AUTHORS item on the source document. * * Does NOT save the document. * * @param document * Document from which to remove the DACL_AUTHORS item. * * @param value * Value to be removed from the DACL_AUTHORS * * @return Flag indicating if the value was successfully removed from the DACL_AUTHORS */ public static boolean removeDACLauthor(final Document document, final String value) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (Strings.isBlankString(value)) { throw new IllegalArgumentException("Value to remove is blank or null"); } final TreeSet<String> dacl = DACL.getDACLauthors(document); return (null == dacl) ? false : (dacl.remove(value)) ? DACL.setDACLauthors(document, dacl) : false; } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Determines if the passed in name is a member of the DACL_READERS for the document. * * @param session * Current Session * @param document * Document to search for DACL * @param name * Name to check * * @return Flag indicating if the name is a member of the DACL_READERS for the document. */ public static boolean isDACLreader(final Session session, final Document document, final Name name) { return DACL.isDACLmember(session, document, name, DACLtype.DACL_READERS); } /** * Determines if the current user is a member of the DACL_READERS for the document. * * @param session * Current Session * @param document * Document to search for DACL * * @return Flag indicating if the current user is a member of the DACL_READERS for the document. */ public static boolean isDACLreader(final Session session, final Document document) { return DACL.isDACLmember(session, document, DACLtype.DACL_READERS); } /** * Gets the DACL_READERS values from the source document. * * @param document * Document from which to retreive the DACL_READERS values. * * @return DACL_READERS values. null if not present or empty. */ public static TreeSet<String> getDACLreaders(final Document document) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (document.hasItem(DACL.ITEMNAME_DACL_READERS)) { final TreeSet<String> result = CollectionUtils.getTreeSetStrings(document.getItemValue(DACL.ITEMNAME_DACL_READERS)); return ((null == result) || (result.size() < 1)) ? null : result; } } catch (final Exception e) { DominoUtils.handleException(e); } return null; } /** * Sets the DACL_READERS item on the source document. * * The value for DEFAULT_DACL_AUTHORS is included. Does NOT save the document. * * @param document * Document upon which to set the DACL_READERS item. * * @param values * Person names or roles to be set as the DACL_READERS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean setDACLreaders(final Document document, final TreeSet<String> values) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (null == values) { throw new IllegalArgumentException("Values is null"); } final TreeSet<String> dacl = new TreeSet<String>(); dacl.add(DACL.DEFAULT_DACL_READERS); for (final String entry : values) { if (!Strings.isBlankString(entry)) { dacl.add(entry); } } final Item item = document.replaceItemValue(DACL.ITEMNAME_DACL_READERS, Strings.getVectorizedStrings(dacl)); item.setReaders(true); return true; } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Sets the DACL_READERS item on the source document. * * The value for DEFAULT_DACL_READERS is included. Does NOT save the document. * * @param document * Document upon which to set the DACL_READERS item. * * @param values * Person names or roles (convertable to a TreeSet) to be set as the DACL_READERS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean setDACLreaders(final Document document, final Object values) { return DACL.setDACLreaders(document, CollectionUtils.getTreeSetStrings(values)); } /** * Adds a value to the DACL_READERS for the document. * * Existing DACL_READERS are not removed. The value for DEFAULT_DACL_READERS is included. Does NOT save the document. * * @param document * Document upon which to update the DACL_READERS. * * @param values * Person names or roles to be added to the DACL_READERS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean addDACLreaders(final Document document, final TreeSet<String> values) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (null == values) { throw new IllegalArgumentException("Values is null"); } TreeSet<String> dacl = DACL.getDACLreaders(document); if (null == dacl) { dacl = new TreeSet<String>(); } for (final String entry : values) { if (!Strings.isBlankString(entry)) { dacl.add(entry); } } return DACL.setDACLreaders(document, dacl); } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Adds a value to the DACL_READERS for the document. * * Existing DACL_READERS are not removed. The value for DEFAULT_DACL_READERS is included. Does NOT save the document. * * @param document * Document upon which to update the DACL_READERS. * * @param value * Person name or role to be added to the DACL_READERS value. * * @return Flag indicating the success / failure of the operation. */ public static boolean addDACLreader(final Document document, final String value) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } final TreeSet<String> values = new TreeSet<String>(); if (!Strings.isBlankString(value)) { values.add(value); } return DACL.addDACLreaders(document, values); } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Removes the DACL_READERS item from the source document. * * Does NOT save the document. * * @param document * Document from which to remove the DACL_READERS item. * * @return Flag indicating if the item was successfully removed. */ public static boolean removeDACLreaders(final Document document) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (document.hasItem(DACL.ITEMNAME_DACL_READERS)) { document.removeItem(DACL.ITEMNAME_DACL_READERS); return true; } } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Removes a value from the DACL_READERS item on the source document. * * Does NOT save the document. * * @param document * Document from which to remove the DACL_READERS item. * * @param value * Value to be removed from the DACL_READERS * * @return Flag indicating if the value was successfully removed from the DACL_READERS */ public static boolean removeDACLreader(final Document document, final String value) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (Strings.isBlankString(value)) { throw new IllegalArgumentException("Value to remove is blank or null"); } final TreeSet<String> dacl = DACL.getDACLreaders(document); return (null == dacl) ? false : (dacl.remove(value)) ? DACL.setDACLreaders(document, dacl) : false; } catch (final Exception e) { DominoUtils.handleException(e); } return false; } public static final Pattern getPatternForRoles() { return Pattern.compile(DACL.PATTERNTEXT_ROLES, Pattern.CASE_INSENSITIVE); } /** * Determines if the passed in name is a member of the set. * * Returns true if the name (in any name format), or any member of roles is a member of the dacl set. * * @param session * Current Session * * @param dacl * DACL entries to check * * @param roles * ACL Roles belonging to the name to check. (No verification is performed) * * @param name * Name to check * * @return Flag indicating if the name (in any form) is a member of the dacl set, or if any intersection exists between dacl and roles. */ public static boolean isDACLmember(final Session session, final TreeSet<String> dacl, final TreeSet<String> roles, final Name name) { try { if (null == session) { throw new IllegalArgumentException("Session is null"); } if (null == name) { throw new IllegalArgumentException("Name is null"); } if ((null != dacl) && (dacl.size() > 0)) { // do an initial check on the name if (dacl.contains(name.getCanonical()) || dacl.contains(name.getAbbreviated())) { return true; } // do an initial check for matching roles if (null != roles) { for (final String role : roles) { if (dacl.contains(role)) { return true; } } } // do a more thorough check for roles final Pattern pattern = DACL.getPatternForRoles(); if (null != roles) { for (final String entry : dacl) { final Matcher matcher = pattern.matcher(entry); if (matcher.matches()) { // entry represents a role if (roles.contains(entry)) { return true; } } } // do a case-insensitive check for roles for (final String entry : dacl) { final Matcher matcher = pattern.matcher(entry); if (matcher.matches()) { // entry represents a role for (final String role : roles) { if (role.equalsIgnoreCase(entry)) { return true; } } } } } return Names.isNamesListMember(session, dacl, name); } } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Determines if the passed in name is a member of the specified DACL for the document. * * @param session * Current Session * @param document * Document to search for DACL * @param name * Name to check * @param dacltype * Type of DACL to check * * @return Flag indicating if the name is a member of the specified DACL for the document. */ public static boolean isDACLmember(final Session session, final Document document, final Name name, final DACLtype dacltype) { try { if (null == session) { throw new IllegalArgumentException("Session is null"); } if (null == name) { throw new IllegalArgumentException("Name is null"); } if (null == document) { throw new IllegalArgumentException("Document is null"); } if (null == dacltype) { throw new IllegalArgumentException("DACLtype is null"); } final TreeSet<String> roles = Names.getRoles(document.getParentDatabase(), name); final TreeSet<String> dacl = (DACLtype.DACL_AUTHORS.equals(dacltype)) ? DACL.getDACLauthors(document) : (DACLtype.DACL_READERS .equals(dacltype)) ? DACL.getDACLreaders(document) : null; return DACL.isDACLmember(session, dacl, roles, name); } catch (final Exception e) { DominoUtils.handleException(e); } return false; } // /** // * Determines if the passed in name is a member of the specified DACL for the document. // * // * @param session // * Current Session // * @param document // * Document to search for DACL // * @param name // * Name to check // * @param dacltype // * Type of DACL to check // * // * @return Flag indicating if the name is a member of the specified DACL for the document. // */ // public static boolean isDACLmember(final Session session, final Document document, final Name name, final DACLtype dacltype) { // try { // if (null == name) { // return DACL.isDACLmember(session, document, new NameHandle(name), dacltype); // } catch (final Exception e) { // DominoUtils.handleException(e); // return false; /** * Determines if the current user is a member of the specified DACL for the document. * * @param session * Current Session * @param document * Document to search for DACL * @param dacltype * Type of DACL to check * * @return Flag indicating if the current user is a member of the specified DACL for the document. */ public static boolean isDACLmember(final Session session, final Document document, final DACLtype dacltype) { return DACL.isDACLmember(session, document, Names.createName(session, ""), dacltype); } /** * Adds a Role to the appropriate DACL on a document if it does not already exist. * * @param document * Document to which the Role shall be added. * @param role * Role to be added to the document. * @param dacltype * Specifies which DACL item (DACL_AUTHORS vs DACL_READERS) should be updated. * @return Flag indicating if the Role was added to the item. */ public static boolean addRole(final Document document, final String role, final DACLtype dacltype) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (Strings.isBlankString(role)) { throw new IllegalArgumentException("Role is null or blank"); } if (null == dacltype) { throw new IllegalArgumentException("DACLtype is null"); } final String newrole = "[" + role.replace("[", "").replace("]", "").trim() + "]"; if ("[]".equals(newrole)) { throw new IllegalArgumentException("Role is null or blank"); } return (DACLtype.DACL_AUTHORS.equals(dacltype)) ? DACL.addDACLauthor(document, newrole) : (DACLtype.DACL_READERS .equals(dacltype)) ? DACL.addDACLreader(document, newrole) : false; } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Removes a Role from the appropriate DACL on a document. * * NOTE: This will NOT remove the DEFAULT_DACL_READERS or DEFAULT_DACL_AUTHORS roles. * * @param document * Document from which the Role shall be removed. * @param role * Role to be removed from the document. * @param dacltype * Specifies which DACL item (DACL_AUTHORS vs DACL_READERS) should be updated. * @return Flag indicating if the Role was removed from the item. */ public static boolean removeRole(final Document document, final String role, final DACLtype dacltype) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (Strings.isBlankString(role)) { throw new IllegalArgumentException("Role is null or blank"); } if (null == dacltype) { throw new IllegalArgumentException("DACLtype is null"); } final String newrole = "[" + role.replace("[", "").replace("]", "").trim() + "]"; if ("[]".equals(newrole)) { throw new IllegalArgumentException("Role is null or blank"); } if (DACL.DEFAULT_DACL_AUTHORS.equalsIgnoreCase(newrole)) { throw new IllegalArgumentException(DACL.DEFAULT_DACL_AUTHORS + " may not be removed"); } if (DACL.DEFAULT_DACL_READERS.equalsIgnoreCase(newrole)) { throw new IllegalArgumentException(DACL.DEFAULT_DACL_READERS + " may not be removed"); } return (DACLtype.DACL_AUTHORS.equals(dacltype)) ? DACL.removeDACLauthor(document, newrole) : (DACLtype.DACL_READERS .equals(dacltype)) ? DACL.removeDACLreader(document, newrole) : false; } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Removes all ACL Roles from a set of strings. * * Removes all bracketed (beginning with "[" and ending with "]") entries from an input set. Optionally comares all entries to all roles * from the passed in database and removes any matching entries. * * * @param source * Set of strings to process * * @param database * Optional database from which to check ACL roles * * @return source with all roles removed. */ public static TreeSet<String> removeRoles(final TreeSet<String> source, final Database database) { ACL acl = null; try { if (null == source) { throw new IllegalArgumentException("Source TreeSet is null"); } final TreeSet<String> result = new TreeSet<String>(); final Pattern pattern = DACL.getPatternForRoles(); for (final String entry : source) { final Matcher matcher = pattern.matcher(entry); if (!matcher.matches()) { // entry is not a role result.add(entry); } } if (null != database) { acl = database.getACL(); final TreeSet<String> roles = CollectionUtils.getTreeSetStrings(acl.getRoles()); if (null != roles) { final TreeSet<String> remove = new TreeSet<String>(); for (final String role : roles) { for (final String string : result) { if (role.equalsIgnoreCase(string)) { remove.add(string); } } } if (remove.size() > 0) { result.removeAll(remove); } } } return result; } catch (final Exception e) { DominoUtils.handleException(e); } finally { DominoUtils.incinerate(acl); } return null; } /** * Replaces a Role on the appropriate DACL on a document. * * NOTE: This will NOT remove the DEFAULT_DACL_READERS or DEFAULT_DACL_AUTHORS roles. * * @param document * Document from which the Role shall be removed. * @param oldrole * Role to be removed from the document. * @param newrole * Role to be added from the document. * @param dacltype * Specifies which DACL item (DACL_AUTHORS vs DACL_READERS) should be updated. * @return Flag indicating if the Role was replaced on the item. */ public static boolean replaceRole(final Document document, final String oldrole, final String newrole, final DACLtype dacltype) { try { if (null == document) { throw new IllegalArgumentException("Document is null"); } if (Strings.isBlankString(newrole)) { throw new IllegalArgumentException("New Role is null or blank"); } if (null == dacltype) { throw new IllegalArgumentException("DACLtype is null"); } if (!Strings.isBlankString(oldrole)) { DACL.removeRole(document, oldrole, dacltype); } return DACL.addRole(document, newrole, dacltype); } catch (final Exception e) { DominoUtils.handleException(e); } return false; } /** * Determines if a specified role is contained within a set of roles. * * Performs a case-insensitive comparison of all entries to check for match. Strips any leading "[" or trailing "]" characters prior to * comparison. * * @param roles * Roles to check for match * * @param role * Role to check for existence in Roles * * @return Flag indicating if the specified Role is contained in the set of Roles. */ public static boolean containsRole(final TreeSet<String> roles, final String role) { try { if (null == roles) { throw new IllegalArgumentException("Roles is null"); } if (Strings.isBlankString(role)) { throw new IllegalArgumentException("Role is null or blank"); } if (roles.size() > 0) { if (roles.contains(role)) { return true; } final Pattern pattern = DACL.getPatternForRoles(); final TreeSet<String> checkroles = new TreeSet<String>(); for (final String string : roles) { final Matcher matcher = pattern.matcher(string); if (matcher.matches()) { checkroles.add(string.substring(string.indexOf('[') + 1, string.indexOf(']')).toLowerCase()); } else { checkroles.add(string.toLowerCase()); } } final Matcher matcher = pattern.matcher(role); final String checkrole = (matcher.matches()) ? role.substring(role.indexOf('[') + 1, role.indexOf(']')).toLowerCase() : role.toLowerCase(); return checkroles.contains(checkrole); } // if (roles.size() > 0) } catch (final Exception e) { DominoUtils.handleException(e); } return false; } }
package mb.statix.spec; import java.util.Optional; import javax.annotation.Nullable; import org.immutables.serial.Serial; import org.immutables.value.Value; import mb.nabl2.terms.unification.u.IUnifier; import mb.nabl2.terms.unification.ud.Diseq; import mb.statix.solver.IConstraint; import mb.statix.solver.IState; import mb.statix.solver.completeness.ICompleteness; @Value.Immutable @Serial.Version(42L) public abstract class AApplyResult { /** * The updated state. */ @Value.Parameter public abstract IState.Immutable state(); /** * All state variables that were instantiated by this application. */ @Value.Parameter public abstract IUnifier.Immutable diff(); /** * Guard constraints necessary for this rule application. The domain of the guard are variables that pre-existed the * rule application. The guard is already applied in the state. */ @Value.Parameter public abstract Optional<Diseq> guard(); /** * The applied rule body. */ @Value.Parameter public abstract IConstraint body(); /** * Critical edges that are introduced by the application of this rule. */ @Value.Parameter public abstract @Nullable ICompleteness.Immutable criticalEdges(); }
package com.nordnetab.chcp.js; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.nordnetab.chcp.events.IPluginEvent; import org.apache.cordova.PluginResult; import java.util.Map; import java.util.Set; public class PluginResultHelper { // keywords for JSON string, that is send to JavaScript side private static class JsParams { private static class General { public static final String ACTION = "action"; public static final String ERROR = "error"; public static final String DATA = "data"; } private static class Error { public static final String CODE = "code"; public static final String DESCRIPTION = "description"; } } /** * Create PluginResult instance from event. * * @param event hot-code-push plugin event * * @return cordova's plugin result * @see PluginResult * @see IPluginEvent */ public static PluginResult pluginResultFromEvent(IPluginEvent event) { JsonNode errorNode = null; JsonNode dataNode = null; if (event.error() != null) { errorNode = createErrorNode(event.error().getErrorCode(), event.error().getErrorDescription()); } if (event.data() != null && event.data().size() > 0) { dataNode = createDataNode(event.data()); } return getResult(event.name(), dataNode, errorNode); } // region Private API private static JsonNode createDataNode(Map<String, Object> data) { JsonNodeFactory factory = JsonNodeFactory.instance; ObjectNode dataNode = factory.objectNode(); Set<Map.Entry<String, Object>> dataSet = data.entrySet(); for (Map.Entry<String, Object> entry : dataSet) { Object value = entry.getValue(); if (value == null) { continue; } dataNode.set(entry.getKey(), factory.textNode(value.toString())); } return dataNode; } private static JsonNode createErrorNode(int errorCode, String errorDescription) { JsonNodeFactory factory = JsonNodeFactory.instance; ObjectNode errorData = factory.objectNode(); errorData.set(JsParams.Error.CODE, factory.numberNode(errorCode)); errorData.set(JsParams.Error.DESCRIPTION, factory.textNode(errorDescription)); return errorData; } private static PluginResult getResult(String action, JsonNode data, JsonNode error) { JsonNodeFactory factory = JsonNodeFactory.instance; ObjectNode resultObject = factory.objectNode(); resultObject.set(JsParams.General.ACTION, factory.textNode(action)); if (data != null) { resultObject.set(JsParams.General.DATA, data); } if (error != null) { resultObject.set(JsParams.General.ERROR, error); } return new PluginResult(PluginResult.Status.OK, resultObject.toString()); } // endregion }
/* * $Id: TdbOut.java,v 1.8 2015-02-03 23:43:47 thib_gc Exp $ */ package org.lockss.tdb; import java.io.*; import java.util.*; import org.apache.commons.cli.*; import org.lockss.tdb.AntlrUtil.SyntaxError; import org.lockss.util.StringUtil; public class TdbOut { /** * <p> * Key for the style option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_STYLE = "style"; /** * <p> * Single letter for the style option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_STYLE = 's'; /** * <p> * The argument name for the style option. * </p> * * @since 1.67 */ protected static final String ARG_STYLE = KEY_STYLE.toUpperCase(); /** * <p> * The CSV style for the style option ({@value}). * </p> * * @since 1.67 */ protected static final String STYLE_CSV = "csv"; /** * <p> * The list style for the style option ({@value}). * </p> * * @since 1.67 */ protected static final String STYLE_LIST = "list"; /** * <p> * The TSV style for the style option ({@value}). * </p> * * @since 1.67 */ protected static final String STYLE_TSV = "tsv"; /** * <p> * The available choices for the style option. * </p> * * @since 1.67 */ protected static final List<String> CHOICES_STYLE = AppUtil.ul(STYLE_CSV, STYLE_LIST, STYLE_TSV); /** * <p> * The style option. * </p> * * @since 1.67 */ protected static final Option OPTION_STYLE = OptionBuilder.withLongOpt(KEY_STYLE) .hasArg() .withArgName(ARG_STYLE) .withDescription(String.format("use output style %s %s", ARG_STYLE, CHOICES_STYLE)) .create(LETTER_STYLE); /** * <p> * Key for the fields option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_FIELDS = "fields"; /** * <p> * Single letter for the fields option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_FIELDS = 'f'; /** * <p> * The argument name for the fields option. * </p> * * @since 1.67 */ protected static final String ARG_FIELDS = KEY_FIELDS.toUpperCase(); /** * <p> * The fields option. * </p> * * @since 1.67 */ protected static final Option OPTION_FIELDS = OptionBuilder.withLongOpt(KEY_FIELDS) .hasArg() .withArgName(ARG_FIELDS) .withDescription("comma-separated list of fields to output") .create(LETTER_FIELDS); /** * <p> * Key for the AUID option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_AUID = "auid"; /** * <p> * Single letter for the AUID option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_AUID = 'a'; /** * <p> * The AUID option. * </p> * * @since 1.67 */ protected static final Option OPTION_AUID = OptionBuilder.withLongOpt(KEY_AUID) .withDescription(String.format("short for --%s=%s --%s=auid", KEY_STYLE, STYLE_LIST, KEY_FIELDS)) .create(LETTER_AUID); /** * <p> * Key for the AUIDplus option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_AUIDPLUS = "auidplus"; /** * <p> * Single letter for the AUIDplus option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_AUIDPLUS = 'p'; /** * <p> * The AUIDplus option. * </p> * * @since 1.67 */ protected static final Option OPTION_AUIDPLUS = OptionBuilder.withLongOpt(KEY_AUIDPLUS) .withDescription(String.format("short for --%s=%s --%s=auidplus", KEY_STYLE, STYLE_LIST, KEY_FIELDS)) .create(LETTER_AUIDPLUS); /** * <p> * Key for the count option ({@value}). * </p> * * @since 1.68 */ protected static final String KEY_COUNT = "count"; /** * <p> * Single letter for the count option ({@value}). * </p> * * @since 1.68 */ protected static final char LETTER_COUNT = 'n'; /** * <p> * The count option. * </p> * * @since 1.68 */ protected static final Option OPTION_COUNT = OptionBuilder.withLongOpt(KEY_COUNT) .withDescription("prints a count of matching AUs") .create(LETTER_COUNT); /** * <p> * Key for the CSV option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_CSV = "csv"; /** * <p> * Single letter for the CSV option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_CSV = 'c'; /** * <p> * The argument name for the CSV option. * </p> * * @since 1.67 */ protected static final String ARG_CSV = ARG_FIELDS; /** * <p> * The CSV option. * </p> * * @since 1.67 */ protected static final Option OPTION_CSV = OptionBuilder.withLongOpt(KEY_CSV) .hasArg() .withArgName(ARG_CSV) .withDescription(String.format("short for --%s=%s --%s=%s", KEY_STYLE, STYLE_CSV, KEY_FIELDS, ARG_CSV)) .create(LETTER_CSV); /** * <p> * Key for the journals option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_JOURNALS = "journals"; /** * <p> * Single letter for the journals option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_JOURNALS = 'j'; /** * <p> * The journals option. * </p> * * @since 1.67 */ protected static final Option OPTION_JOURNALS = OptionBuilder.withLongOpt(KEY_JOURNALS) .withDescription("iterate over titles (not AUs) and output a CSV list of publishers, titles, ISSNs and eISSNs") .create(LETTER_JOURNALS); /** * <p> * Key for the list option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_LIST = "list"; /** * <p> * Single letter for the list option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_LIST = 'l'; /** * <p> * The argument name for the list option. * </p> * * @since 1.67 */ protected static final String ARG_LIST = ARG_FIELDS.substring(0, ARG_FIELDS.length() - 1); /** * <p> * The list option. * </p> * * @since 1.67 */ protected static final Option OPTION_LIST = OptionBuilder.withLongOpt(KEY_LIST) .hasArg() .withArgName(ARG_LIST) .withDescription(String.format("short for --%s=%s --%s=%s", KEY_STYLE, STYLE_LIST, KEY_FIELDS, ARG_LIST)) .create(LETTER_LIST); /** * <p> * Key for the TSV option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_TSV = "tsv"; /** * <p> * Single letter for the TSV option ({@value}). * </p> * * @since 1.67 */ protected static final char LETTER_TSV = 't'; /** * <p> * The argument name for the TSV option. * </p> * * @since 1.67 */ protected static final String ARG_TSV = KEY_FIELDS.toUpperCase(); /** * <p> * The TSV option. * </p> * * @since 1.67 */ protected static final Option OPTION_TSV = OptionBuilder.withLongOpt(KEY_TSV) .hasArg() .withArgName(ARG_TSV) .withDescription(String.format("short for --%s=%s --%s=%s", KEY_STYLE, STYLE_TSV, KEY_FIELDS, ARG_TSV)) .create(LETTER_TSV); /** * <p> * Key for the journal type option ({@value}). * </p> * * @since 1.67 */ protected static final String KEY_TYPE_JOURNAL = "type-journal"; /** * <p> * The journal type option. * </p> * * @since 1.67 */ protected static final Option OPTION_TYPE_JOURNAL = OptionBuilder.withLongOpt(KEY_TYPE_JOURNAL) .withDescription(String.format("with --%s, output only titles of type '%s'", KEY_JOURNALS, Title.TYPE_JOURNAL)) .create(); /** * <p> * A set of options keys; the corresponding options define mutually exclusive * actions. * </p> * * @since 1.67 */ protected static final List<String> mutuallyExclusiveActions = AppUtil.ul(KEY_AUID, KEY_AUIDPLUS, KEY_COUNT, KEY_CSV, KEY_JOURNALS, KEY_LIST, KEY_STYLE, KEY_TSV); /** * <p> * A set of options keys; the corresponding options specify their own fields, * so are mutually exclusive with the fields options. * </p> * * @since 1.67 */ protected static final List<String> mutuallyExclusiveFields = AppUtil.ul(KEY_AUID, KEY_AUIDPLUS, KEY_CSV, KEY_FIELDS, KEY_LIST, KEY_TSV); /** * <p> * A TDB builder. * </p> * * @since 1.67 */ protected TdbBuilder tdbBuilder; /** * <p> * A TDB query builder. * </p> * * @since 1.67 */ protected TdbQueryBuilder tdbQueryBuilder; public TdbOut() { this.tdbBuilder = new TdbBuilder(); this.tdbQueryBuilder = new TdbQueryBuilder(); } /** * <p> * Add this module's options to a Commons CLI {@link Options} instance. * </p> * * @param options * A Commons CLI {@link Options} instance. * @since 1.67 */ public void addOptions(Options options) { // Options from other modules HelpOption.addOptions(options); VerboseOption.addOptions(options); KeepGoingOption.addOptions(options); InputOption.addOptions(options); OutputOption.addOptions(options); tdbQueryBuilder.addOptions(options); // Own options options.addOption(OPTION_AUID); options.addOption(OPTION_AUIDPLUS); options.addOption(OPTION_COUNT); options.addOption(OPTION_CSV); options.addOption(OPTION_FIELDS); options.addOption(OPTION_JOURNALS); options.addOption(OPTION_LIST); options.addOption(OPTION_STYLE); options.addOption(OPTION_TSV); options.addOption(OPTION_TYPE_JOURNAL); } /** * <p> * Processes a {@link CommandLineAccessor} instance and stores appropriate * information in the given options map. * </p> * * @param options * An options map. * @param cmd * A {@link CommandLineAccessor} instance. * @since 1.67 */ public Map<String, Object> processCommandLine(CommandLineAccessor cmd, Map<String, Object> options) { // Options from other modules VerboseOption.processCommandLine(options, cmd); KeepGoingOption.processCommandLine(options, cmd); InputOption.processCommandLine(options, cmd); OutputOption.processCommandLine(options, cmd); tdbQueryBuilder.processCommandLine(options, cmd); // Own options int actions = count(cmd, mutuallyExclusiveActions); if (actions == 0) { AppUtil.error("Specify an action among %s", mutuallyExclusiveActions); } if (actions > 1) { AppUtil.error("Specify only one action among %s", mutuallyExclusiveActions); } if (count(cmd, mutuallyExclusiveFields) > 1) { AppUtil.error("Specify only one option among %s", mutuallyExclusiveFields); } if (cmd.hasOption(KEY_JOURNALS)) { options.put(KEY_JOURNALS, KEY_JOURNALS); } if (cmd.hasOption(KEY_TYPE_JOURNAL)) { if (!options.containsKey(KEY_JOURNALS)) { AppUtil.error("--%s can only be used with --%s", KEY_TYPE_JOURNAL, KEY_JOURNALS); } options.put(KEY_JOURNALS, KEY_TYPE_JOURNAL); } if (cmd.hasOption(KEY_AUID)) { options.put(KEY_STYLE, STYLE_TSV); options.put(KEY_FIELDS, Arrays.asList("auid")); } if (cmd.hasOption(KEY_AUIDPLUS)) { options.put(KEY_STYLE, STYLE_TSV); options.put(KEY_FIELDS, Arrays.asList("auidplus")); } options.put(KEY_COUNT, Boolean.valueOf(cmd.hasOption(KEY_COUNT))); if (cmd.hasOption(KEY_CSV)) { options.put(KEY_STYLE, STYLE_CSV); options.put(KEY_FIELDS, Arrays.asList(cmd.getOptionValue(KEY_CSV).split(","))); } if (cmd.hasOption(KEY_LIST)) { options.put(KEY_STYLE, STYLE_TSV); options.put(KEY_FIELDS, Arrays.asList(cmd.getOptionValue(KEY_LIST))); } if (cmd.hasOption(KEY_TSV)) { options.put(KEY_STYLE, STYLE_TSV); options.put(KEY_FIELDS, Arrays.asList(cmd.getOptionValue(KEY_TSV).split(","))); } if (cmd.hasOption(KEY_STYLE)) { String style = cmd.getOptionValue(KEY_STYLE); if (!CHOICES_STYLE.contains(style)) { AppUtil.error("Invalid style '%s'; must be among %s", style, CHOICES_STYLE); } options.put(KEY_STYLE, STYLE_CSV.equals(style) ? STYLE_CSV : STYLE_TSV); } if (cmd.hasOption(KEY_FIELDS)) { options.put(KEY_FIELDS, Arrays.asList(cmd.getOptionValues(KEY_FIELDS))); } if (getStyle(options) != null) { List<String> fields = getFields(options); if (fields == null || fields.size() == 0) { AppUtil.error("No output fields specified"); } } return options; } /** * <p> * Determines from the options map if the count option was requested. * </p> * * @param options * An options map. * @return Whether the count option has been requested. * @since 1.68 */ public boolean getCount(Map<String, Object> options) { return ((Boolean)options.get(KEY_COUNT)).booleanValue(); } /** * <p> * Determines from the options map the output style. * </p> * * @param options * An options map. * @return The output style -- either {@Link #STYLE_CSV} or * {@link #STYLE_TSV}. * @since 1.67 */ public String getStyle(Map<String, Object> options) { return (String)options.get(KEY_STYLE); } /** * <p> * Determines from the options map the output fields. * </p> * * @param options * An options map. * @return The output fields. * @since 1.67 */ public List<String> getFields(Map<String, Object> options) { return (List<String>)options.get(KEY_FIELDS); } /** * <p> * Parses the TDB files listed in the options map. * </p> * * @param options * The options map. * @return A parsed {@link Tdb} structure. * @throws IOException * if any I/O exceptions occur. * @since 1.67 */ public Tdb processFiles(Map<String, Object> options) throws IOException { List<String> inputFiles = InputOption.getInput(options); for (String f : inputFiles) { try { if ("-".equals(f)) { f = "<stdin>"; tdbBuilder.parse(f, System.in); } else { tdbBuilder.parse(f); } } catch (FileNotFoundException fnfe) { AppUtil.warning(options, fnfe, "%s: file not found", f); KeepGoingOption.addError(options, fnfe); } catch (IOException ioe) { AppUtil.warning(options, ioe, "%s: I/O error", f); KeepGoingOption.addError(options, ioe); } catch (SyntaxError se) { AppUtil.warning(options, se, se.getMessage()); KeepGoingOption.addError(options, se); } } List<Exception> errors = KeepGoingOption.getErrors(options); int errs = errors.size(); if (KeepGoingOption.isKeepGoing(options) && errs > 0) { AppUtil.error(options, errors, "Encountered %d %s; exiting", errs, errs == 1 ? "error" : "errors"); } return tdbBuilder.getTdb(); } /** * <p> * Produces output from a parsed TDB. * </p> * * @param options * The options map. * @param tdb * A TDB structure. * @since 1.67 */ public void produceOutput(Map<String, Object> options, Tdb tdb) { PrintStream out = OutputOption.getSingleOutput(options); Predicate<Au> auPredicate = tdbQueryBuilder.getAuPredicate(options); boolean csv = STYLE_CSV.equals(getStyle(options)); boolean count = getCount(options); List<Functor<Au, String>> traitFunctors = new ArrayList<Functor<Au, String>>(); if (!count) { for (String field : getFields(options)) { Functor<Au, String> traitFunctor = Au.traitFunctor(field); if (traitFunctor == null) { AppUtil.error("Unknown field '%s'", field); } traitFunctors.add(traitFunctor); } } int counter = 0; for (Au au : tdb.getAus()) { if (auPredicate.test(au)) { ++counter; if (count) { continue; } } else { continue; } boolean first = true; StringBuilder sb = new StringBuilder(1024); for (Functor<Au, String> traitFunctor : traitFunctors) { if (!first) { sb.append(csv ? ',' : '\t'); } String output = traitFunctor.apply(au); if (output != null) { sb.append(csv ? csvValue(output) : output); } first = false; } out.println(sb.toString()); } if (count) { out.println(counter); } out.close(); } /** * <p> * Produces output when the journals option is requested on the command line. * </p> * * @param options * The options map. * @param tdb * A TDB structure. * @since 1.67 */ public void produceJournals(Map<String, Object> options, Tdb tdb) { PrintStream out = OutputOption.getSingleOutput(options); boolean typeJournal = KEY_TYPE_JOURNAL.equals(options.get(KEY_JOURNALS)); for (Title title : tdb.getTitles()) { if (typeJournal && !Title.TYPE_JOURNAL.equals(title.getType())) { continue; } out.println(String.format("%s,%s,%s,%s", csvValue(title.getPublisher().getName()), csvValue(title.getName()), csvValue(StringUtil.nonNull(title.getIssn())), csvValue(StringUtil.nonNull(title.getEissn())))); } out.close(); } /** * <p> * Secondary entry point of this class, after the command line has been * parsed. * </p> * * @param cmd * A parsed command line. * @throws IOException * if an I/O error occurs. * @since 1.67 */ public void run(CommandLineAccessor cmd) throws IOException { Map<String, Object> options = new HashMap<String, Object>(); processCommandLine(cmd, options); Tdb tdb = processFiles(options); if (options.containsKey(KEY_JOURNALS)) { produceJournals(options, tdb); } else { produceOutput(options, tdb); } } /** * <p> * Primary entry point of this class, before the command line has been parsed. * </p> * * @param mainArgs * Command line arguments. * @throws Exception if any error occurs. * @since 1.67 */ public void run(String[] mainArgs) throws Exception { AppUtil.fixMainArgsForCommonsCli(mainArgs); Options options = new Options(); addOptions(options); CommandLine clicmd = new PosixParser().parse(options, mainArgs); CommandLineAccessor cmd = new CommandLineAdapter(clicmd); HelpOption.processCommandLine(cmd, options, getClass()); run(cmd); } /** * <p> * Counts how many of the strings in a given set appear in a * {@link CommandLineAccessor} instance. * </p> * * @param cmd * A {@link CommandLineAccessor} instance. * @param optionStrings * The set of strings to be counted in the options. * @return The number of strings from the set that appeared on the command * line. * @since 1.67 */ protected static int count(CommandLineAccessor cmd, List<String> optionStrings) { int c = 0; for (String optionString : optionStrings) { if (cmd.hasOption(optionString)) { ++c; } } return c; } /** * <p> * Returns a string suitable to be used as a CSV value (quoted if it contains * a comma or quotation mark, and with quotation marks doubled). * </p> * * @param str * A plain string. * @return A CSV-encoded string. * @since 1.67 */ protected static String csvValue(String str) { int i1 = str.indexOf('"'); int i2 = str.indexOf(','); if (i1 < 0 && i2 < 0) { return str; } else { return "\"" + str.replace("\"", "\"\"") + "\""; } } /** * <p> * Creates a {@link TdbOut} instance and calls {@link #run(String[])}. * </p> * * @param args * Command line arguments. * @throws Exception * if any error occurs. * @since 1.67 */ public static void main(String[] args) throws Exception { new TdbOut().run(args); } }
package org.nutz.http; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.nutz.json.Json; import org.nutz.lang.ContinueLoop; import org.nutz.lang.Each; import org.nutz.lang.Encoding; import org.nutz.lang.ExitLoop; import org.nutz.lang.Lang; import org.nutz.lang.LoopException; public class Request { public static enum METHOD { GET, POST, OPTIONS, PUT, DELETE, TRACE, CONNECT } public static Request get(String url) { return create(url, METHOD.GET, new HashMap<String, Object>()); } public static Request get(String url, Header header) { return Request.create(url, METHOD.GET, new HashMap<String, Object>(), header); } public static Request post(String url) { return create(url, METHOD.POST, new HashMap<String, Object>()); } public static Request post(String url, Header header) { return Request.create(url, METHOD.POST, new HashMap<String, Object>(), header); } public static Request create(String url, METHOD method) { return create(url, method, new HashMap<String, Object>()); } @SuppressWarnings("unchecked") public static Request create(String url, METHOD method, String paramsAsJson, Header header) { return create(url, method, (Map<String, Object>) Json.fromJson(paramsAsJson), header); } @SuppressWarnings("unchecked") public static Request create(String url, METHOD method, String paramsAsJson) { return create(url, method, (Map<String, Object>) Json.fromJson(paramsAsJson)); } public static Request create(String url, METHOD method, Map<String, Object> params) { return Request.create(url, method, params, Header.create()); } public static Request create(String url, METHOD method, Map<String, Object> params, Header header) { return new Request().setMethod(method).setParams(params).setUrl(url).setHeader(header); } private Request() {} private String url; private METHOD method; private Header header; private Map<String, Object> params; private byte[] data; private URL cacheUrl; private InputStream inputStream; private String enc = Encoding.UTF8; public URL getUrl() { if (cacheUrl != null) { return cacheUrl; } StringBuilder sb = new StringBuilder(url); try { if (this.isGet() && null != params && params.size() > 0) { sb.append(url.indexOf('?') > 0 ? '&' : '?'); sb.append(getURLEncodedParams()); } cacheUrl = new URL(sb.toString()); return cacheUrl; } catch (Exception e) { throw new HttpException(sb.toString(), e); } } public Map<String, Object> getParams() { return params; } public String getURLEncodedParams() { final StringBuilder sb = new StringBuilder(); if (params != null) { for (Entry<String, Object> en : params.entrySet()) { final String key = en.getKey(); Object val = en.getValue(); if (val == null) val = ""; Lang.each(val, new Each<Object>() { public void invoke(int index, Object ele, int length)throws ExitLoop, ContinueLoop, LoopException { sb.append(Http.encode(key, enc)) .append('=') .append(Http.encode(ele, enc)).append('&'); } }); } if (sb.length() > 0) sb.setLength(sb.length() - 1); } return sb.toString(); } public InputStream getInputStream() { if (inputStream != null) { return inputStream; } else { if (null == data) { try { return new ByteArrayInputStream(getURLEncodedParams().getBytes(enc)); } catch (UnsupportedEncodingException e) { throw Lang.wrapThrow(e); } } return new ByteArrayInputStream(data); } } public Request setInputStream(InputStream inputStream) { this.inputStream = inputStream; return this; } public byte[] getData() { return data; } public Request setData(byte[] data) { this.data = data; return this; } public Request setData(String data) { try { this.data = data.getBytes(Encoding.UTF8); } catch (UnsupportedEncodingException e) { } return this; } private Request setParams(Map<String, Object> params) { this.params = params; return this; } public Request setUrl(String url) { if (url != null && url.indexOf(": // http this.url = "http://" + url; else this.url = url; return this; } public METHOD getMethod() { return method; } public boolean isGet() { return METHOD.GET == method; } public boolean isPost() { return METHOD.POST == method; } public boolean isDelete() { return METHOD.DELETE == method; } public boolean isPut() { return METHOD.PUT == method; } public Request setMethod(METHOD method) { this.method = method; return this; } public Header getHeader() { return header; } public Request setHeader(Header header) { this.header = header; return this; } public Request setCookie(Cookie cookie) { header.set("Cookie", cookie.toString()); return this; } public Cookie getCookie() { String s = header.get("Cookie"); if (null == s) return new Cookie(); return new Cookie(s); } /** * ,StringMap<String,Object>data */ public Request setEnc(String reqEnc) { if (reqEnc != null) this.enc = reqEnc; return this; } public String getEnc() { return enc; } }
package org.osgi.test.director; import java.io.InterruptedIOException; import java.net.*; import java.util.*; import org.osgi.framework.BundleContext; import org.osgi.test.service.RemoteService; /** * The Discovery class keeps track remote services on the local net and * registers these in the registry. * * A local net service broadcasts regularly a message with: * * <pre> * * * application=&lt;app&gt; host=&lt;host&gt; port=&lt;port&gt; * * * </pre> * * This class picks these messages up and parses them. If a service is detected * it is registered as a RemoteService object in the framework registry. As a * property, the application is set to the received application. When a * broadcast has not been received for a certain amount of time, the service is * removed again. This allows interested parties to listen to remote services in * the framework. */ public class Discovery extends Thread { public final static int PORT = 2001; BundleContext context; DatagramSocket listener; boolean cont = true; Hashtable services = new Hashtable(); // RemoteService // RemoteServiceImpl static final long LEASE = 20000; // ms == 20 secs /** * Create a discovery object. * * @param context Framework context */ public Discovery(BundleContext context) { this.context = context; start(); } /** * Close the discovery. */ public void close() { cont = false; DatagramSocket l = listener; if (l != null) l.close(); listener = null; } /** * Update the service in the registry. * * If the service already exists, the time is updated. Else it is registered * in the framework. The parameter is a newly created service and is used to * find the same service in the local hashtable. * * @service service a newly created service */ void updateService(RemoteServiceImpl service) { RemoteServiceImpl actual = (RemoteServiceImpl) services.get(service); if (actual == null) addRemote(service); else actual.update(); } public void addRemote(RemoteServiceImpl service) { log("Adding " + service + " App = " + service.getApplication(), null); service.registerAt(context); services.put(service, service); } /** * A service was not found during a certain time, remove it from the * registry. * * @param service service to be removed. */ void removeService(RemoteService service) { RemoteServiceImpl actual = (RemoteServiceImpl) services.get(service); if (actual != null) { log("Removing " + service, null); actual.registration.unregister(); services.remove(actual); } } /** * Thread run. * * Listen to datagrams on port 2001 and parse these. The listening is done * with a time out. In this timeout the existing services are checked and * removed if their lease expired. */ public void run() { try { int port; String application; String comment; String host; try { listener = new DatagramSocket(PORT); } catch( BindException e ) { log("DatagramSockeet for target discovery already in use (" + PORT + ")", null ); return; } listener.setSoTimeout(25000); log("Discovery starts.", null); while (cont) { try { verify(); DatagramPacket packet = new DatagramPacket(new byte[256], 256); listener.receive(packet); String msg = new String(packet.getData(), 0, packet .getLength()); StringTokenizer st = new StringTokenizer(msg, " =\n\r\t"); application = null; comment = ""; host = packet.getAddress().getHostAddress(); port = -1; while (st.hasMoreTokens()) { String key = st.nextToken(); String val = st.nextToken(); if (key.equals("application")) application = val; else if (key.equals("host")) ; else if (key.equals("port")) port = Integer.parseInt(val); else if (key.equals("comment")) comment = val; } if (host != null && application != null && port > 0) { RemoteServiceImpl service = new RemoteServiceImpl( application, host, port, comment); updateService(service); } else log("Invalid remote service request from " + packet.getAddress(), null); } catch (InterruptedIOException e) { } catch (Exception e) { if (cont) log("Receving remote service packets, ignoring", e); } } listener.close(); listener = null; } catch (Exception e) { log("Main discover loop exit", e); } log("Discovery quits.", null); } /** * Check loop to see if services expired their lease. */ void verify() { long now = System.currentTimeMillis(); Hashtable s = new Hashtable(); for (Enumeration e = services.keys(); e.hasMoreElements();) { RemoteServiceImpl service = (RemoteServiceImpl) e.nextElement(); if (service.getModified() + LEASE < now) removeService(service); else s.put(service, service); } services = s; } /** * Temporary log. */ void log(String s, Exception e) { System.out.println(s); if (cont && e != null) e.printStackTrace(); } }
package VASSAL.build; import VASSAL.build.module.Chatter; import VASSAL.build.module.PrototypeDefinition; import java.util.ArrayList; import java.util.HashMap; import VASSAL.build.widget.PieceSlot; import VASSAL.counters.BasicPiece; import VASSAL.counters.Decorator; import VASSAL.counters.GamePiece; import VASSAL.counters.PieceCloner; import VASSAL.counters.PlaceMarker; import VASSAL.counters.Properties; public class GpIdChecker { protected GpIdSupport gpIdSupport; protected int maxId; protected boolean useName = false; protected boolean extensionsLoaded = false; final HashMap<String, SlotElement> goodSlots = new HashMap<>(); final ArrayList<SlotElement> errorSlots = new ArrayList<>(); private Chatter chatter; public GpIdChecker() { this(null); } public GpIdChecker(GpIdSupport gpIdSupport) { this.gpIdSupport = gpIdSupport; maxId = -1; } // This constructor is used by the GameRefresher to refresh a game with extensions possibly loaded public GpIdChecker(boolean useName) { this(); this.useName = useName; this.extensionsLoaded = true; } /** * Add a PieceSlot to our cross-reference and any PlaceMarker * traits it contains. * * @param pieceSlot PieceSlot to add to cross-reference */ public void add(PieceSlot pieceSlot) { testGpId(pieceSlot.getGpId(), new SlotElement(pieceSlot)); // PlaceMarker traits within the PieceSlot definition also contain GpId's. checkTrait(pieceSlot.getPiece()); } /** * Add any PieceSlots contained in traits in a Prototype Definition * @param prototype Prototype Definition to check */ public void add(PrototypeDefinition prototype) { final GamePiece gp = prototype.getPiece(); checkTrait(gp, prototype, gp); } /** * Check for PlaceMarker traits in a GamePiece and add them to * the cross-reference * * @param gp GamePiece to check */ protected void checkTrait(GamePiece gp) { if (gp == null || gp instanceof BasicPiece) { return; } if (gp instanceof PlaceMarker) { final PlaceMarker pm = (PlaceMarker) gp; testGpId (pm.getGpId(), new SlotElement(pm)); } checkTrait(((Decorator) gp).getInner()); } protected void checkTrait(final GamePiece gp, PrototypeDefinition prototype, GamePiece definition) { if (gp == null || gp instanceof BasicPiece) { return; } if (gp instanceof PlaceMarker) { final PlaceMarker pm = (PlaceMarker) gp; testGpId (pm.getGpId(), new SlotElement(pm, prototype, definition)); } checkTrait(((Decorator) gp).getInner(), prototype, definition); } /** * Validate a GamePieceId. * - non-null * - Integer * - Not a duplicate of any other GpId * Keep a list of the good Slots and the slots with errors. * Also track the maximum GpId * * @param id GpId to test * @param element Containing SlotElement */ protected void testGpId(String id, SlotElement element) { /* * If this has been called from a ModuleExtension, the GpId is prefixed with * the Extension Id. Remove the Extension Id and just process the numeric part. * * NOTE: If GpIdChecker is being used by the GameRefesher, then there may be * extensions loaded, so retain the extension prefix to ensure a correct * unique slot id check. */ if (! extensionsLoaded) { if (id.contains(":")) { id = id.split(":")[1]; } } if (id == null || id.length() == 0) { // gpid not generated yet? errorSlots.add(element); } else { if (goodSlots.get(id) != null) { // duplicate gpid? errorSlots.add(element); } try { if (extensionsLoaded) { goodSlots.put(id, element); System.out.println("Add Id " + id); } else { final int iid = Integer.parseInt(id); goodSlots.put(id, element); // gpid is good. if (iid >= maxId) { maxId = iid; } } } catch (Exception e) { errorSlots.add(element); // non-numeric gpid? } } } /** * Where any errors found? * @return Error count */ public boolean hasErrors() { return errorSlots.size() > 0; } private void chat (String text) { if (chatter == null) { chatter = GameModule.getGameModule().getChatter(); } final Chatter.DisplayText mess = new Chatter.DisplayText(chatter, "- " + text); mess.execute(); } /** * Repair any errors * - Update the next GpId in the module if necessary * - Generate new GpId's for slots with errors. */ public void fixErrors() { if (maxId >= gpIdSupport.getNextGpId()) { chat("Next GPID updated from " + gpIdSupport.getNextGpId() + " to " + (maxId + 1)); gpIdSupport.setNextGpId(maxId + 1); } for (SlotElement slotElement : errorSlots) { final String before = slotElement.getGpId(); slotElement.updateGpId(); chat(slotElement.toString() + " GPID updated from " + before + " to " + slotElement.getGpId()); } } /** * Locate the SlotElement that matches oldPiece and return a new GamePiece * created from that Slot. * * @param oldPiece Old GamePiece * @return Newly created GamePiece */ public GamePiece createUpdatedPiece(GamePiece oldPiece) { // Find a slot with a matching gpid final String gpid = (String) oldPiece.getProperty(Properties.PIECE_ID); if (gpid != null && gpid.length() > 0) { final SlotElement element = goodSlots.get(gpid); if (element != null) { return element.createPiece(oldPiece); } } // Failed to find a slot by gpid, try by matching piece name if option selected if (useName) { final String oldPieceName = Decorator.getInnermost(oldPiece).getName(); for (SlotElement el : goodSlots.values()) { final GamePiece newPiece = el.getPiece(); final String newPieceName = Decorator.getInnermost(newPiece).getName(); if (oldPieceName.equals(newPieceName)) { return el.createPiece(oldPiece); } } } return oldPiece; } public boolean findUpdatedPiece(GamePiece oldPiece) { // Find a slot with a matching gpid final String gpid = (String) oldPiece.getProperty(Properties.PIECE_ID); if (gpid != null && gpid.length() > 0) { final SlotElement element = goodSlots.get(gpid); if (element != null) { return true; } } // Failed to find a slot by gpid, try by matching piece name if option selected if (useName) { final String oldPieceName = Decorator.getInnermost(oldPiece).getName(); for (SlotElement el : goodSlots.values()) { final GamePiece newPiece = el.getPiece(); final String newPieceName = Decorator.getInnermost(newPiece).getName(); if (oldPieceName.equals(newPieceName)) { return true; } } } return false; } /** * Wrapper class for components that contain a GpId - They will all be either * PieceSlot components or PlaceMarker Decorator's. * PlaceMarker's may exist inside Prototypes and require special handling * Ideally we would add an interface to these components, but this * will break any custom code based on PlaceMarker * */ static class SlotElement { private PieceSlot slot; private PlaceMarker marker; private String id; private PrototypeDefinition prototype; private GamePiece expandedPrototype; public SlotElement() { slot = null; marker = null; prototype = null; expandedPrototype = null; } public SlotElement(PieceSlot ps) { this(); slot = ps; id = ps.getGpId(); } public SlotElement(PlaceMarker pm) { this(); marker = pm; id = pm.getGpId(); } public SlotElement(PlaceMarker pm, PrototypeDefinition pd, GamePiece definition) { this(); marker = pm; prototype = pd; expandedPrototype = definition; id = pm.getGpId(); } public String getGpId() { return id; } @Override public String toString() { return marker == null ? "PieceSlot " + slot.getConfigureName() : "Place/Replace trait " + marker.getDescription(); } public void updateGpId() { if (marker == null) { slot.updateGpId(); id = slot.getGpId(); } else { marker.updateGpId(); id = marker.getGpId(); // If this PlaceMarker trait lives in a Prototype, then the Prototype definition has to be updated if (prototype != null) { prototype.setPiece(expandedPrototype); } } } public GamePiece getPiece() { if (slot == null) { return marker; } else { return slot.getPiece(); } } /** * Create a new GamePiece based on this Slot Element. Use oldPiece * to copy state information over to the new piece. * * @param oldPiece Old Piece for state information * @return New Piece */ public GamePiece createPiece(GamePiece oldPiece) { GamePiece newPiece = (slot != null) ? slot.getPiece() : marker.createMarker(); // The following two steps create a complete new GamePiece with all // prototypes expanded newPiece = PieceCloner.getInstance().clonePiece(newPiece); copyState(oldPiece, newPiece); newPiece.setProperty(Properties.PIECE_ID, getGpId()); return newPiece; } /** * Copy as much state information as possible from the old * piece to the new piece * * @param oldPiece Piece to copy state from * @param newPiece Piece to copy state to */ protected void copyState(GamePiece oldPiece, GamePiece newPiece) { GamePiece p = newPiece; while (p != null) { if (p instanceof BasicPiece) { p.setState(Decorator.getInnermost(oldPiece).getState()); p = null; } else { final Decorator decorator = (Decorator) p; final String type = decorator.myGetType(); final String newState = findStateFromType(oldPiece, type, p.getClass()); if (newState != null && newState.length() > 0) { decorator.mySetState(newState); } p = decorator.getInner(); } } } /** * Locate a Decorator in the old piece that has the exact same * type as the new Decorator and return it's state * * @param oldPiece Old piece to search * @param typeToFind Type to match * @param classToFind Class to match * @return state of located matching Decorator */ protected String findStateFromType(GamePiece oldPiece, String typeToFind, Class<? extends GamePiece> classToFind) { GamePiece p = oldPiece; while (p != null && !(p instanceof BasicPiece)) { final Decorator d = (Decorator) Decorator.getDecorator(p, classToFind); if (d != null) { if (d.getClass().equals(classToFind)) { if (d.myGetType().equals(typeToFind)) { return d.myGetState(); } } p = d.getInner(); } else p = null; } return null; } } }
package be.ibridge.kettle.trans.step.fileinput; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.regex.Pattern; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.util.StringUtil; public class FileInputList { private List files = new ArrayList(); private List nonExistantFiles = new ArrayList(1); private List nonAccessibleFiles = new ArrayList(1); private static final String YES = "Y"; public static String getRequiredFilesDescription(List nonExistantFiles) { StringBuffer buffer = new StringBuffer(); for (Iterator iter = nonExistantFiles.iterator(); iter.hasNext();) { File file = (File) iter.next(); buffer.append(file.getPath()); buffer.append(Const.CR); } return buffer.toString(); } private static boolean[] includeSubdirsFalse(int iLength) { boolean[] includeSubdirs = new boolean[iLength]; for (int i = 0; i < iLength; i++) includeSubdirs[i] = false; return includeSubdirs; } public static String[] createFilePathList(String[] fileName, String[] fileMask, String[] fileRequired) { boolean[] includeSubdirs = includeSubdirsFalse(fileName.length); return createFilePathList(fileName, fileMask, fileRequired, includeSubdirs); } public static String[] createFilePathList(String[] fileName, String[] fileMask, String[] fileRequired, boolean[] includeSubdirs) { List fileList = createFileList(fileName, fileMask, fileRequired, includeSubdirs).getFiles(); String[] filePaths = new String[fileList.size()]; for (int i = 0; i < filePaths.length; i++) { filePaths[i] = ((File) fileList.get(i)).getPath(); } return filePaths; } public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired) { boolean[] includeSubdirs = includeSubdirsFalse(fileName.length); return createFileList(fileName, fileMask, fileRequired, includeSubdirs); } public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired, boolean[] includeSubdirs) { FileInputList fileInputList = new FileInputList(); // Replace possible environment variables... final String realfile[] = StringUtil.environmentSubstitute(fileName); final String realmask[] = StringUtil.environmentSubstitute(fileMask); for (int i = 0; i < realfile.length; i++) { final String onefile = realfile[i]; final String onemask = realmask[i]; final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]); boolean subdirs = includeSubdirs[i]; // System.out.println("Checking file ["+onefile+"] mask // ["+onemask+"]"); if (onefile == null) continue; if (!Const.isEmpty(onemask)) // If wildcard is set we assume it's a directory { File file = new File(onefile); try { // Find all file names that match the wildcard in this directory String[] fileNames = file.list(new FilenameFilter() { public boolean accept(File dir, String name) { return Pattern.matches(onemask, name); } }); if (subdirs) { Vector matchingFilenames = new Vector(); appendToVector(matchingFilenames, fileNames, ""); findMatchingFiles(file, onemask, matchingFilenames, ""); fileNames = new String[matchingFilenames.size()]; matchingFilenames.copyInto(fileNames); } if (fileNames != null) { for (int j = 0; j < fileNames.length; j++) { File localFile = new File(file, fileNames[j]); if (!localFile.isDirectory() && localFile.isFile()) fileInputList.addFile(localFile); } } if (Const.isEmpty(fileNames)) { if (onerequired) fileInputList.addNonAccessibleFile(file); } } catch (Exception e) { LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e)); } } else // A normal file... { File file = new File(onefile); if (file.exists()) { if (file.canRead() && file.isFile()) { if (file.isFile()) fileInputList.addFile(file); } else { if (onerequired) fileInputList.addNonAccessibleFile(file); } } else { if (onerequired) fileInputList.addNonExistantFile(file); } } } // Sort the list: quicksort fileInputList.sortFiles(); // OK, return the list in filelist... // files = (String[]) filelist.toArray(new String[filelist.size()]); return fileInputList; } /** * Copies all elements of a String array into a Vector * @param sArray The string array * @return The Vector. */ private static void appendToVector(Vector v, String[] sArray, String sPrefix) { if (sArray == null || sArray.length == 0) return; for (int i = 0; i < sArray.length; i++) v.add(sPrefix + sArray[i]); } /** * * @param dir * @param onemask * @param matchingFileNames * @param sPrefix */ private static void findMatchingFiles(File dir, final String onemask, Vector matchingFileNames, String sPrefix) { if (!Const.isEmpty(sPrefix)) { String[] fileNames = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return Pattern.matches(onemask, name); } }); appendToVector(matchingFileNames, fileNames, sPrefix); } String[] files = dir.list(); for (int i = 0; i < files.length; i++) { File f = new File(dir.getAbsolutePath() + Const.FILE_SEPARATOR + files[i]); if (f.isDirectory()) { findMatchingFiles(f, onemask, matchingFileNames, sPrefix + files[i] + Const.FILE_SEPARATOR); } } } public List getFiles() { return files; } public List getNonAccessibleFiles() { return nonAccessibleFiles; } public List getNonExistantFiles() { return nonExistantFiles; } public void addFile(File file) { files.add(file); } public void addNonAccessibleFile(File file) { nonAccessibleFiles.add(file); } public void addNonExistantFile(File file) { nonExistantFiles.add(file); } public void sortFiles() { Collections.sort(files); Collections.sort(nonAccessibleFiles); Collections.sort(nonExistantFiles); } public File getFile(int i) { return (File) files.get(i); } public int nrOfFiles() { return files.size(); } public int nrOfMissingFiles() { return nonAccessibleFiles.size() + nonExistantFiles.size(); } }
package com.github.ukasiu.phpass; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; public class PHPass { private static String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private int iterationCountLog2; private SecureRandom randomGen; public PHPass(int iterationCountLog2) { if (iterationCountLog2 < 4 || iterationCountLog2 > 31) { iterationCountLog2 = 8; } this.iterationCountLog2 = iterationCountLog2; this.randomGen = new SecureRandom(); } private String encode64(byte[] src, int count) { int i, value; String output = ""; i = 0; if (src.length < count) { byte[] t = new byte[count]; System.arraycopy(src, 0, t, 0, src.length); Arrays.fill(t, src.length, count - 1, (byte) 0); src = t; } do { value = src[i] + (src[i] < 0 ? 256 : 0); ++i; output += itoa64.charAt(value & 63); if (i < count) { value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 8; } output += itoa64.charAt((value >> 6) & 63); if (i++ >= count) { break; } if (i < count) { value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 16; } output += itoa64.charAt((value >> 12) & 63); if (i++ >= count) { break; } output += itoa64.charAt((value >> 18) & 63); } while (i < count); return output; } private String cryptPrivate(String password, String setting) { String output = "*0"; if (((setting.length() < 2) ? setting : setting.substring(0, 2)).equalsIgnoreCase(output)) { output = "*1"; } String id = (setting.length() < 3) ? setting : setting.substring(0, 3); if (!(id.equals("$P$") || id.equals("$H$"))) { return output; } int countLog2 = itoa64.indexOf(setting.charAt(3)); if (countLog2 < 7 || countLog2 > 30) { return output; } int count = 1 << countLog2; String salt = setting.substring(4, 4 + 8); if (salt.length() != 8) { return output; } MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return output; } byte[] pass = stringToUtf8(password); byte[] hash = md.digest(stringToUtf8(salt + password)); do { byte[] t = new byte[hash.length + pass.length]; System.arraycopy(hash, 0, t, 0, hash.length); System.arraycopy(pass, 0, t, hash.length, pass.length); hash = md.digest(t); } while (--count > 0); output = setting.substring(0, 12); output += encode64(hash, 16); return output; } private String gensaltPrivate(byte[] input) { String output = "$P$"; output += itoa64.charAt(Math.min(this.iterationCountLog2 + 5, 30)); output += encode64(input, 6); return output; } private byte[] stringToUtf8(String string) { try { return string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException("This system doesn't support UTF-8!", e); } } public String HashPassword(String password) { byte random[] = new byte[6]; this.randomGen.nextBytes(random); // Unportable hashes (Blowfish, EXT_DES) could be added here, but I won't do this. String hash = cryptPrivate(password, gensaltPrivate(stringToUtf8(new String(random)))); if (hash.length() == 34) { return hash; } return "*"; } public boolean CheckPassword(String password, String storedHash) { String hash = cryptPrivate(password, storedHash); MessageDigest md = null; if (hash.startsWith("*")) { // If not phpass, try some algorythms from unix crypt() if (storedHash.startsWith("$6$")) { try { md = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException e) { md = null; } } if (md == null && storedHash.startsWith("$5$")) { try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { md = null; } } if (md == null && storedHash.startsWith("$2")) { return BCrypt.checkpw(password, storedHash); } if (md == null && storedHash.startsWith("$1$")) { try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { md = null; } } // STD_DES and EXT_DES not supported yet. if (md != null) { hash = new String(md.digest(password.getBytes())); } } return hash.equals(storedHash); } }
package ca.eandb.jmist.framework.material; import java.io.Serializable; import ca.eandb.jmist.framework.Painter; import ca.eandb.jmist.framework.Random; import ca.eandb.jmist.framework.ScatteredRay; import ca.eandb.jmist.framework.ScatteredRayRecorder; import ca.eandb.jmist.framework.SurfacePoint; import ca.eandb.jmist.framework.color.Color; import ca.eandb.jmist.framework.color.Spectrum; import ca.eandb.jmist.framework.color.WavelengthPacket; import ca.eandb.jmist.framework.painter.UniformPainter; import ca.eandb.jmist.framework.random.RandomUtil; import ca.eandb.jmist.math.Ray3; import ca.eandb.jmist.math.SphericalCoordinates; import ca.eandb.jmist.math.Vector3; /** * A <code>Material</code> that reflects light equally in all directions in * the upper hemisphere. * @author Brad Kimmel */ public final class LambertianMaterial extends OpaqueMaterial implements Serializable { /** * Creates a new <code>LambertianMaterial</code> that does not emit light. * @param reflectance The reflectance <code>Painter</code>. */ public LambertianMaterial(Painter reflectance) { this(reflectance, null); } /** * Creates a new <code>LambertianMaterial</code> that emits light. * @param reflectance The reflectance <code>Painter</code>. * @param emittance The emission <code>Painter</code>. */ public LambertianMaterial(Painter reflectance, Painter emittance) { this.reflectance = reflectance; this.emittance = emittance; } /** * Creates a new <code>LambertianMaterial</code> that does not emit light. * @param reflectance The reflectance <code>Spectrum</code>. */ public LambertianMaterial(Spectrum reflectance) { this(reflectance != null ? new UniformPainter(reflectance) : null); } /** * Creates a new <code>LambertianMaterial</code> that emits light. * @param reflectance The reflectance <code>Spectrum</code>. * @param emittance The emission <code>Spectrum</code>. */ public LambertianMaterial(Spectrum reflectance, Spectrum emittance) { this(reflectance != null ? new UniformPainter(reflectance) : null, emittance != null ? new UniformPainter(emittance) : null); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.AbstractMaterial#isEmissive() */ @Override public boolean isEmissive() { return (this.emittance != null); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#emission(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.framework.color.WavelengthPacket) */ @Override public Color emission(SurfacePoint x, Vector3 out, WavelengthPacket lambda) { if (this.emittance != null && x.getNormal().dot(out) > 0.0) { return emittance.getColor(x, lambda); } else { return lambda.getColorModel().getBlack(lambda); } } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#emit(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.framework.color.WavelengthPacket, ca.eandb.jmist.framework.Random, ca.eandb.jmist.framework.ScatteredRayRecorder) */ @Override public void emit(SurfacePoint x, WavelengthPacket lambda, Random rng, ScatteredRayRecorder recorder) { if (this.emittance != null) { SphericalCoordinates out = RandomUtil.diffuse(rng); Ray3 ray = new Ray3(x.getPosition(), out.toCartesian(x.getShadingBasis())); if (x.getNormal().dot(ray.direction()) > 0.0) { recorder.add(ScatteredRay.diffuse(ray, emittance.getColor(x, lambda))); } } } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#scatter(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.framework.color.WavelengthPacket, ca.eandb.jmist.framework.Random, ca.eandb.jmist.framework.ScatteredRayRecorder) */ @Override public void scatter(SurfacePoint x, Vector3 v, WavelengthPacket lambda, Random rng, ScatteredRayRecorder recorder) { if (this.reflectance != null) { SphericalCoordinates out = RandomUtil.diffuse(rng); Ray3 ray = new Ray3(x.getPosition(), out.toCartesian(x.getShadingBasis())); if (ray.direction().dot(x.getNormal()) > 0.0) { recorder.add(ScatteredRay.diffuse(ray, reflectance.getColor(x, lambda))); } } } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#scattering(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.framework.color.WavelengthPacket) */ @Override public Color scattering(SurfacePoint x, Vector3 in, Vector3 out, WavelengthPacket lambda) { Vector3 n = x.getNormal(); boolean fromFront = (n.dot(in) < 0.0); boolean toFront = (n.dot(out) > 0.0); if (this.reflectance != null && toFront == fromFront) { return reflectance.getColor(x, lambda); } else { return lambda.getColorModel().getBlack(lambda); } } /** The reflectance <code>Painter</code> of this <code>Material</code>. */ private final Painter reflectance; /** The emittance <code>Painter</code> of this <code>Material</code>. */ private final Painter emittance; /** * Serialization version ID. */ private static final long serialVersionUID = 485410070543495668L; }
package parser.commands; import java.io.File; import java.io.FileNotFoundException; import java.util.AbstractMap.SimpleEntry; import java.util.Enumeration; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Scanner; import java.util.regex.Pattern; import Exceptions.CommandNameNotFoundException; import model.Model; public class Regex { String languageFileString; List<Entry<String, Pattern>> generalPatterns = new ArrayList<>(); List<Entry<String, Pattern>> commandPatterns = new ArrayList<>(); private static Regex instance; private Regex(){ languageFileString = "resources/languages/English"; commandPatterns.addAll(makePatterns(languageFileString)); generalPatterns.addAll(makePatterns("resources/languages/Syntax")); } public static Regex getInstance(){ if(instance == null){ instance = new Regex(); } return instance; } public void changeLanguage(String filePath){ languageFileString = filePath; commandPatterns.clear(); commandPatterns.addAll(makePatterns(languageFileString)); } private boolean match (String input, Pattern regex) { return regex.matcher(input).matches(); } public GeneralType getType(String s){ for (Entry<String, Pattern> p : this.generalPatterns) { if (match(s, p.getValue())) { return GeneralType.findType(p.getKey()); } } return GeneralType.OTHER; } public String getCommandType(String s) throws CommandNameNotFoundException{ for (Entry<String, Pattern> p : this.commandPatterns) { if (match(s, p.getValue())) { return p.getKey(); } } throw new CommandNameNotFoundException(); } private void testMatches (String[] tests, List<Entry<String, Pattern>> patterns) { for (String s : tests) { boolean matched = false; if (s.trim().length() > 0) { for (Entry<String, Pattern> p : patterns) { if (match(s, p.getValue())) { System.out.println(String.format("%s matches %s", s, p.getKey())); matched = true; break; } } if (! matched) { System.out.println(String.format("%s not matched", s)); } } } System.out.println(); } private List<Entry<String, Pattern>> makePatterns (String syntax) { ResourceBundle resources = ResourceBundle.getBundle(syntax); List<Entry<String, Pattern>> patterns = new ArrayList<>(); Enumeration<String> iter = resources.getKeys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); String regex = resources.getString(key); patterns.add(new SimpleEntry<String, Pattern>(key, Pattern.compile(regex, Pattern.CASE_INSENSITIVE))); } return patterns; } }
package peer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import multicast.search.message.RemoteMulticastMessage; import peer.message.ACKMessage; import peer.message.BroadcastMessage; import peer.message.BundleMessage; import peer.messagecounter.MessageCounter; import peer.peerid.PeerID; import peer.peerid.PeerIDSet; import util.WaitableThread; import util.logger.Logger; import config.Configuration; /** * This class implements a message processor used for decoupling it from the * receiving thread. This enables to continue receiving messages when the a * waiting action is being perform (i.e reliableBroadcast) * * @author Unai Aguilera (unai.aguilera@gmail.com) * */ final class MessageProcessor extends WaitableThread { // the communication peer private final BasicPeer peer; private final Logger logger = Logger.getLogger(MessageProcessor.class); private final List<BroadcastMessage> waitingMessages = new ArrayList<BroadcastMessage>(); private final Random r = new Random(); private final MessageCounter msgCounter; // stores the unprocessed messages when the thread is stopped private int unprocessedMessages = 0; private final ReliableBroadcast reliableBroadcast; private final AtomicBoolean delayNext = new AtomicBoolean(false); private final AtomicLong delayTime = new AtomicLong(); // the queue used for storing received messages private final Deque<BroadcastMessage> messageDeque = new ArrayDeque<BroadcastMessage>(); private long waitedTime; private long randomWait; private int RANDOM_WAIT = 200; /** * Constructor of the message processor * * @param peer * the communication peer */ public MessageProcessor(final BasicPeer peer, MessageCounter msgCounter) { this.peer = peer; this.reliableBroadcast = new ReliableBroadcast(peer); this.msgCounter = msgCounter; this.randomWait = r.nextInt(RANDOM_WAIT); } public void init() { try { final String randomWaitStr = Configuration.getInstance().getProperty("messageProcessor.randomWait"); RANDOM_WAIT = Integer.parseInt(randomWaitStr); logger.info("Peer " + peer.getPeerID() + " set RANDOM_WAIT to " + RANDOM_WAIT); } catch (final Exception e) { logger.error("Peer " + peer.getPeerID() + " had problem loading configuration: " + e.getMessage()); } start(); reliableBroadcast.start(); } /** * Enqueues a new message for future processing * * @param message * the message to enqueue */ public void receive(final BroadcastMessage message) { synchronized (messageDeque) { messageDeque.add(message); } } @Override public void run() { // Processor loop while (!Thread.interrupted()) { final long currenTime = System.currentTimeMillis(); final List<BroadcastMessage> messages = new ArrayList<BroadcastMessage>(); synchronized (messageDeque) { while (!messageDeque.isEmpty()) { final BroadcastMessage message = messageDeque.poll(); messages.add(message); } } for (final BroadcastMessage message : messages) peer.processMessage(message); boolean sendMessage = false; if (delayNext.get()) sendMessage = waitedTime >= randomWait + delayTime.get(); else sendMessage = waitedTime >= randomWait; if (sendMessage && !waitingMessages.isEmpty()) { logger.trace("Peer " + peer.getPeerID() + " waited " + waitedTime + " ms (including an extra delay of " + delayTime.get() + ")"); waitedTime = 0; randomWait = r.nextInt(RANDOM_WAIT) + 1; delayNext.set(false); final List<BroadcastMessage> bundleMessages = new ArrayList<BroadcastMessage>(); final PeerIDSet destinations = new PeerIDSet(); for (final BroadcastMessage broadcastMessage : waitingMessages) { if (broadcastMessage instanceof RemoteMulticastMessage) { final RemoteMulticastMessage remoteMulticastMessage = (RemoteMulticastMessage) broadcastMessage; destinations.addPeers(remoteMulticastMessage.getThroughPeers()); } else destinations.addPeers(peer.getDetector().getCurrentNeighbors()); bundleMessages.add(broadcastMessage); } waitingMessages.clear(); final BundleMessage bundleMessage = new BundleMessage(peer.getPeerID(), bundleMessages); List<PeerID> expectedDestinations = new ArrayList<PeerID>(); expectedDestinations.addAll(destinations.getPeerSet()); bundleMessage.setExpectedDestinations(expectedDestinations); msgCounter.addSent(bundleMessage.getClass()); if (Peer.USE_RELIABLE_BROADCAST) reliableBroadcast.broadcast(bundleMessage); else peer.broadcast(bundleMessage); Thread.yield(); } else { Thread.yield(); waitedTime += System.currentTimeMillis() - currenTime; } } finishThread(); } private void finishThread() { logger.trace("Peer " + peer.getPeerID() + " message processor finalized"); this.threadFinished(); } /** * Cancels the execution of the message processor thread * * @return the number of unprocessed messages */ @Override public void stopAndWait() { reliableBroadcast.stopAndWait(); super.stopAndWait(); } public int getUnprocessedMessages() { return unprocessedMessages; } public void addResponse(final BroadcastMessage message) { synchronized (waitingMessages) { waitingMessages.add(message); } } public void addACKResponse(final ACKMessage ackMessage) { reliableBroadcast.addACKResponse(ackMessage); } public void sendACKMessage(final BroadcastMessage broadcastMessage) { final long time = broadcastMessage.getExpectedDestinations().size() * BasicPeer.ACK_TRANSMISSION_TIME + BasicPeer.ACK_TRANSMISSION_TIME; delayNextMessage(time); reliableBroadcast.sendACKMessage(broadcastMessage, msgCounter); } private void delayNextMessage(long time) { delayTime.set(time); delayNext.set(true); } }
package com.afollestad.silk.fragments; import android.os.Bundle; import android.view.View; import com.afollestad.silk.cache.SilkCacheManager; /** * A {@link SilkFeedFragment} that automatically caches loaded feeds locally and loads them again later. * <p/> * The class of type T must implement Serializable, otherwise errors will be thrown while attempting to cache. * * @author Aidan Follestad (afollestad) */ public abstract class SilkCachedFeedFragment<T> extends SilkFeedFragment<T> { private SilkCacheManager cache; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getCacheTitle() != null) cache = new SilkCacheManager<T>(getCacheTitle()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.mCacheEnabled = true; super.onViewCreated(view, savedInstanceState); if (cache != null) cache.readAsync(getAdapter(), this, true); else performRefresh(true); } /** * Gets the name of the fragment's cache, used by a {@link SilkCacheManager} instance and should be unique * from any other cached feed fragment, */ public abstract String getCacheTitle(); /** * Fired from the {@link SilkCacheManager} when the cache was found to be empty during view creation. By default, * causes a refresh, but this can be overridden. */ public void onCacheEmpty() { performRefresh(true); } /** * Notifies the fragment that it is done loading data from the cache. This causes the progress view to become invisible, and the list * or empty text become visible again. * <p/> * This is equivalent to {#setLoadComplete} by default, but can be overridden. * <p/> * * @param error Whether or not an error occurred while loading. This value can be used by overriding classes. */ public void setLoadFromCacheComplete(boolean error) { setLoadComplete(error); } @Override public void onVisibilityChange(boolean visible) { if (cache != null) { if (visible) cache.readAsync(getAdapter(), this, true); else cache.writeAsync(getAdapter()); } } }
// Connect SDK Sample App by LG Electronics // To the extent possible under law, the person who associated CC0 with // to the sample app. package com.connectsdk.sampler.fragments; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.connectsdk.device.ConnectableDevice; import com.connectsdk.sampler.R; import com.connectsdk.service.capability.MediaControl; import com.connectsdk.service.capability.MediaControl.DurationListener; import com.connectsdk.service.capability.MediaControl.PlayStateListener; import com.connectsdk.service.capability.MediaControl.PlayStateStatus; import com.connectsdk.service.capability.MediaControl.PositionListener; import com.connectsdk.service.capability.MediaPlayer; import com.connectsdk.service.capability.MediaPlayer.MediaLaunchObject; import com.connectsdk.service.capability.VolumeControl; import com.connectsdk.service.capability.VolumeControl.VolumeListener; import com.connectsdk.service.capability.listeners.ResponseListener; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.sessions.LaunchSession; public class MediaPlayerFragment extends BaseFragment { public Button photoButton; public Button videoButton; public Button audioButton; public Button playButton; public Button pauseButton; public Button stopButton; public Button rewindButton; public Button fastForwardButton; public Button closeButton; public LaunchSession launchSession; public TextView positionTextView; public TextView durationTextView; public SeekBar mSeekBar; public boolean mIsUserSeeking; public SeekBar mVolumeBar; public boolean mSeeking; public Runnable mRefreshRunnable; public static final int REFRESH_INTERVAL_MS = (int) TimeUnit.SECONDS.toMillis(1); public Handler mHandler; public long totalTimeDuration; public boolean mIsGettingPlayPosition; private MediaControl mMediaControl = null; private Timer refreshTimer; public MediaPlayerFragment(Context context) { super(context); mIsUserSeeking = false; mSeeking = false; mIsGettingPlayPosition = false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate( R.layout.fragment_media_player, container, false); photoButton = (Button) rootView.findViewById(R.id.photoButton); videoButton = (Button) rootView.findViewById(R.id.videoButton); audioButton = (Button) rootView.findViewById(R.id.audioButton); playButton = (Button) rootView.findViewById(R.id.playButton); pauseButton = (Button) rootView.findViewById(R.id.pauseButton); stopButton = (Button) rootView.findViewById(R.id.stopButton); rewindButton = (Button) rootView.findViewById(R.id.rewindButton); fastForwardButton = (Button) rootView.findViewById(R.id.fastForwardButton); closeButton = (Button) rootView.findViewById(R.id.closeButton); positionTextView = (TextView) rootView.findViewById(R.id.stream_position); durationTextView = (TextView) rootView.findViewById(R.id.stream_duration); mSeekBar = (SeekBar) rootView.findViewById(R.id.stream_seek_bar); mVolumeBar = (SeekBar) rootView.findViewById(R.id.volume_seek_bar); buttons = new Button[] { photoButton, videoButton, audioButton, playButton, pauseButton, stopButton, rewindButton, fastForwardButton, closeButton }; mHandler = new Handler(); return rootView; } @Override public void setTv(ConnectableDevice tv) { super.setTv(tv); if (tv == null) { stopUpdating(); mMediaControl = null; } } @Override public void onPause() { stopUpdating(); super.onPause(); } @Override public void enableButtons() { if ( getTv().hasCapability(MediaPlayer.Display_Image) ) { photoButton.setEnabled(true); photoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (launchSession != null) { launchSession.close(null); launchSession = null; closeButton.setEnabled(false); closeButton.setOnClickListener(null); stopUpdating(); } disableMedia(); String imagePath = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/photo.jpg"; String mimeType = "image/jpeg"; String title = "Sintel Character Design"; String description = "Blender Open Movie Project"; String icon = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/photoIcon.jpg"; getMediaPlayer().displayImage(imagePath, mimeType, title, description, icon, new MediaPlayer.LaunchListener() { @Override public void onSuccess(MediaLaunchObject object) { launchSession = object.launchSession; closeButton.setEnabled(true); closeButton.setOnClickListener(closeListener); stopUpdating(); } @Override public void onError(ServiceCommandError error) { } }); } }); } else { disableButton(photoButton); } totalTimeDuration = -1; if ( getTv().hasCapability(MediaPlayer.Display_Video) ) { videoButton.setEnabled(true); videoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (launchSession != null) { launchSession.close(null); launchSession = null; stopUpdating(); disableMedia(); } String videoPath = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/video.mp4"; String mimeType = "video/mp4"; String title = "Sintel Trailer"; String description = "Blender Open Movie Project"; String icon = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/videoIcon.jpg"; getMediaPlayer().playMedia(videoPath, mimeType, title, description, icon, false, new MediaPlayer.LaunchListener() { public void onSuccess(MediaLaunchObject object) { launchSession = object.launchSession; mMediaControl = object.mediaControl; stopUpdating(); enableMedia(); } @Override public void onError(ServiceCommandError error) { } }); } }); } else { disableButton(videoButton); } if (getTv().hasCapability(MediaPlayer.Display_Audio)) { audioButton.setEnabled(true); audioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (launchSession != null) { launchSession.close(null); launchSession = null; stopUpdating(); disableMedia(); } String mediaURL = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/audio.mp3"; String iconURL = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/audioIcon.jpg"; String title = "The Song that Doesn't End"; String description = "Lamb Chop's Play Along"; String mimeType = "audio/mp3"; boolean shouldLoop = false; getMediaPlayer().playMedia(mediaURL, mimeType, title, description, iconURL, shouldLoop, new MediaPlayer.LaunchListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "Error playing audio"); } @Override public void onSuccess(MediaLaunchObject object) { Log.d("LG", "Started playing audio"); launchSession = object.launchSession; mMediaControl = object.mediaControl; stopUpdating(); enableMedia(); } }); } }); } else { disableButton(audioButton); } mVolumeBar.setEnabled(getTv().hasCapability(VolumeControl.Volume_Set)); mVolumeBar.setOnSeekBarChangeListener(volumeListener); if (getTv().hasCapability(VolumeControl.Volume_Get)) { getVolumeControl().getVolume(getVolumeListener); } if (getTv().hasCapability(VolumeControl.Volume_Subscribe)) { getVolumeControl().subscribeVolume(getVolumeListener); } disableMedia(); } @Override public void disableButtons() { mSeekBar.setEnabled(false); mVolumeBar.setEnabled(false); mVolumeBar.setOnSeekBarChangeListener(null); positionTextView.setEnabled(false); durationTextView.setEnabled(false); super.disableButtons(); } protected void onSeekBarMoved(long position) { if (mMediaControl != null && getTv().hasCapability(MediaControl.Seek)) { mSeeking = true; mMediaControl.seek(position, new ResponseListener<Object>() { @Override public void onSuccess(Object response) { Log.d("LG", "Success on Seeking"); mSeeking = false; startUpdating(); } @Override public void onError(ServiceCommandError error) { Log.w("Connect SDK", "Unable to seek: " + error.getCode()); mSeeking = false; startUpdating(); } }); } } public void enableMedia() { playButton.setEnabled(getTv().hasCapability(MediaControl.Play)); pauseButton.setEnabled(getTv().hasCapability(MediaControl.Pause)); stopButton.setEnabled(getTv().hasCapability(MediaControl.Stop)); rewindButton.setEnabled(getTv().hasCapability(MediaControl.Rewind)); fastForwardButton.setEnabled(getTv().hasCapability(MediaControl.FastForward)); mSeekBar.setEnabled(getTv().hasCapability(MediaControl.Seek)); closeButton.setEnabled(getTv().hasCapability(MediaPlayer.Close)); fastForwardButton.setOnClickListener(fastForwardListener); mSeekBar.setOnSeekBarChangeListener(seekListener); rewindButton.setOnClickListener(rewindListener); stopButton.setOnClickListener(stopListener); playButton.setOnClickListener(playListener); pauseButton.setOnClickListener(pauseListener); closeButton.setOnClickListener(closeListener); if (getTv().hasCapability(MediaControl.PlayState_Subscribe)) { mMediaControl.subscribePlayState(playStateListener); } else { mMediaControl.getDuration(durationListener); startUpdating(); } } public void disableMedia() { playButton.setEnabled(false); playButton.setOnClickListener(null); pauseButton.setEnabled(false); pauseButton.setOnClickListener(null); stopButton.setEnabled(false); stopButton.setOnClickListener(null); rewindButton.setEnabled(false); rewindButton.setOnClickListener(null); fastForwardButton.setEnabled(false); fastForwardButton.setOnClickListener(null); mSeekBar.setEnabled(false); mSeekBar.setOnSeekBarChangeListener(null); mSeekBar.setProgress(0); closeButton.setEnabled(false); closeButton.setOnClickListener(null); positionTextView.setText(" durationTextView.setText(" totalTimeDuration = -1; } public View.OnClickListener playListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.play(null); } }; public View.OnClickListener pauseListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.pause(null); } }; public View.OnClickListener closeListener = new View.OnClickListener() { @Override public void onClick(View view) { if (getMediaPlayer() != null) { if (launchSession != null) launchSession.close(null); launchSession = null; disableMedia(); stopUpdating(); } } }; public View.OnClickListener stopListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.stop(new ResponseListener<Object>() { @Override public void onSuccess(Object response) { stopUpdating(); positionTextView.setText(" durationTextView.setText(" mSeekBar.setProgress(0); } @Override public void onError(ServiceCommandError error) { } }); } }; public View.OnClickListener rewindListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.rewind(null); } }; public View.OnClickListener fastForwardListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.fastForward(null); } }; public OnSeekBarChangeListener seekListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mIsUserSeeking = false; mSeekBar.setSecondaryProgress(0); onSeekBarMoved(seekBar.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { mIsUserSeeking = true; mSeekBar.setSecondaryProgress(seekBar.getProgress()); stopUpdating(); } @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { } }; public OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar arg0) { } @Override public void onStartTrackingTouch(SeekBar arg0) { } @Override public void onProgressChanged(SeekBar seekBar, int position, boolean fromUser) { if (fromUser) getVolumeControl().setVolume((float) mVolumeBar.getProgress() / 100.0f, null); } }; public VolumeListener getVolumeListener = new VolumeListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "Error getting Volume: " + error); } @Override public void onSuccess(Float object) { mVolumeBar.setProgress((int) (object * 100.0f)); } }; public PlayStateListener playStateListener = new PlayStateListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "Playstate Listener error = " + error); } @Override public void onSuccess(PlayStateStatus playState) { Log.d("LG", "Playstate changed | playState = " + playState); switch (playState) { case Playing: // if (!mSeeking) startUpdating(); if (mMediaControl != null && getTv().hasCapability(MediaControl.Duration)) { mMediaControl.getDuration(durationListener); } break; case Finished: positionTextView.setText(" durationTextView.setText(" mSeekBar.setProgress(0); case Paused: stopUpdating(); break; default: break; } } }; private void startUpdating() { if (refreshTimer != null) { refreshTimer.cancel(); refreshTimer = null; } refreshTimer = new Timer(); refreshTimer.schedule(new TimerTask() { @Override public void run() { Log.d("LG", "Updating information"); if (mMediaControl != null && getTv() != null && getTv().hasCapability(MediaControl.Position)) { mMediaControl.getPosition(positionListener); } if (mMediaControl != null && getTv() != null && getTv().hasCapability(MediaControl.Duration) && !getTv().hasCapability(MediaControl.PlayState_Subscribe) && totalTimeDuration <= 0) { mMediaControl.getDuration(durationListener); } } }, 0, REFRESH_INTERVAL_MS); } private void stopUpdating() { if (refreshTimer == null) return; refreshTimer.cancel(); refreshTimer = null; } private PositionListener positionListener = new PositionListener() { @Override public void onError(ServiceCommandError error) { } @Override public void onSuccess(Long position) { positionTextView.setText(formatTime(position.intValue())); mSeekBar.setProgress(position.intValue()); } }; private DurationListener durationListener = new DurationListener() { @Override public void onError(ServiceCommandError error) { } @Override public void onSuccess(Long duration) { totalTimeDuration = duration; mSeekBar.setMax(duration.intValue()); durationTextView.setText(formatTime(duration.intValue())); } }; private String formatTime(long millisec) { int seconds = (int) (millisec / 1000); int hours = seconds / (60 * 60); seconds %= (60 * 60); int minutes = seconds / 60; seconds %= 60; String time; if (hours > 0) { time = String.format(Locale.US, "%d:%02d:%02d", hours, minutes, seconds); } else { time = String.format(Locale.US, "%d:%02d", minutes, seconds); } return time; } }
package com.edinarobotics.zed.commands; import com.edinarobotics.utils.pid.PIDConfig; import com.edinarobotics.utils.pid.PIDTuningManager; import com.edinarobotics.zed.Components; import com.edinarobotics.zed.subsystems.DrivetrainRotation; import com.edinarobotics.zed.subsystems.Lifter; import com.edinarobotics.zed.vision.LifterTargetY; import com.edinarobotics.zed.vision.PIDTargetX; import com.edinarobotics.zed.vision.Target; import com.edinarobotics.zed.vision.TargetCollection; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.networktables.NetworkTable; public class VisionTrackingCommand extends Command { public static final byte HIGH_GOAL = 1; public static final byte MIDDLE_GOAL = 2; public static final byte ANY_GOAL = 3; private NetworkTable visionTable = NetworkTable.getTable("vision"); private TargetCollection targetCollection; private DrivetrainRotation drivetrainRotation; private Lifter lifter; private byte goalType; // X Fields private PIDController pidControllerX; private PIDTargetX pidTargetX; private PIDConfig xPIDConfig; private double xSetpoint; private double xTolerance; // Y Fields LifterTargetY lifterTargetY; private double ySetpoint; private double yTolerance; private final double X_P = -0.99; private final double X_I = -0.01; private final double X_D = -3.25; public VisionTrackingCommand() { this(ANY_GOAL); } public VisionTrackingCommand(byte goalType) { super("VisionTracking"); this.goalType = goalType; drivetrainRotation = Components.getInstance().drivetrainRotation; lifter = Components.getInstance().lifter; pidTargetX = new PIDTargetX(); pidControllerX = new PIDController(X_P, X_I, X_D, pidTargetX, drivetrainRotation); xPIDConfig = PIDTuningManager.getInstance().getPIDConfig("Vision Horizontal"); xSetpoint = 0; xTolerance = 0; lifterTargetY = new LifterTargetY(); ySetpoint = 0; yTolerance = 0.1; requires(drivetrainRotation); requires(lifter); } protected void initialize() { pidControllerX.setSetpoint(0); pidControllerX.enable(); pidControllerX.setAbsoluteTolerance(0); } protected void execute() { targetCollection = new TargetCollection(visionTable.getString("vtdata", "")); Target target; if(goalType == HIGH_GOAL) { target = targetCollection.getClosestTarget(xSetpoint, ySetpoint, true); } else if(goalType == MIDDLE_GOAL) { target = targetCollection.getClosestTarget(xSetpoint, ySetpoint, false); } else { target = targetCollection.getClosestTarget(xSetpoint, ySetpoint); } if(target != null) { xSetpoint = getXSetpoint(target.getDistance()); ySetpoint = getYSetpoint(target.getDistance()); pidTargetX.setTarget(target); pidControllerX.setSetpoint(xSetpoint); pidControllerX.setAbsoluteTolerance(xTolerance); lifterTargetY.setTarget(target); lifterTargetY.setYSetpoint(ySetpoint); lifterTargetY.setYTolerance(yTolerance); lifter.setLifterDirection(lifterTargetY.targetY()); } else { drivetrainRotation.update(); lifter.update(); } //PID tuning code pidControllerX.setPID(xPIDConfig.getP(X_P), xPIDConfig.getI(X_I), xPIDConfig.getD(X_D)); xPIDConfig.setSetpoint(pidControllerX.getSetpoint()); xPIDConfig.setValue(pidTargetX.pidGet()); } protected boolean isFinished() { return pidControllerX.onTarget() && lifterTargetY.onTarget(); } protected void end() { pidControllerX.disable(); pidControllerX.reset(); lifter.setLifterDirection(Lifter.LifterDirection.LIFTER_STOP); drivetrainRotation.mecanumPolarRotate(0); System.out.println("VISION TRACKING DONE"); } protected void interrupted() { end(); } private double getXSetpoint(double distance){ return 0.0278026829*distance - 0.6818562776; } private double getYSetpoint(double distance){ return -0.023267714*distance + 0.4098144504; } }
package com.j256.ormlite.android; import android.test.AndroidTestCase; import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.DatabaseConnection; public class AndroidConnectionSourceTest extends AndroidTestCase { public void testSimpleDataSource() throws Exception { AndroidConnectionSource sds = new AndroidConnectionSource(getHelper()); DatabaseConnection conn = sds.getReadOnlyConnection(); assertNotNull(conn); sds.releaseConnection(conn); sds.close(); } public void testConnectionAlreadyClosed() throws Exception { AndroidConnectionSource sds = new AndroidConnectionSource(getHelper()); DatabaseConnection conn = sds.getReadOnlyConnection(); assertNotNull(conn); sds.releaseConnection(conn); sds.close(); // this actually works because we don't enforce the close sds.getReadOnlyConnection(); } public void testSaveAndClear() throws Exception { AndroidConnectionSource sds = new AndroidConnectionSource(getHelper()); DatabaseConnection conn1 = sds.getReadOnlyConnection(); DatabaseConnection conn2 = sds.getReadOnlyConnection(); assertSame(conn1, conn2); sds.saveSpecialConnection(conn1); sds.clearSpecialConnection(conn1); sds.releaseConnection(conn1); } public void testIsOpen() throws Exception { AndroidConnectionSource sds = new AndroidConnectionSource(getHelper()); sds.releaseConnection(sds.getReadOnlyConnection()); assertTrue(sds.isOpen()); sds.close(); assertFalse(sds.isOpen()); } private OrmLiteSqliteOpenHelper getHelper() throws Exception { OpenHelperManager.setOpenHelperClass(DatabaseHelper.class); return OpenHelperManager.getHelper(getContext()); } }
package com.normalexception.forum.rx8club.html; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import ch.boye.httpclientandroidlib.HttpEntity; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.NameValuePair; import ch.boye.httpclientandroidlib.StatusLine; import ch.boye.httpclientandroidlib.client.ClientProtocolException; import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpPost; import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest; import ch.boye.httpclientandroidlib.entity.mime.HttpMultipartMode; import ch.boye.httpclientandroidlib.entity.mime.MultipartEntity; import ch.boye.httpclientandroidlib.entity.mime.content.FileBody; import ch.boye.httpclientandroidlib.entity.mime.content.StringBody; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.message.BasicNameValuePair; import ch.boye.httpclientandroidlib.protocol.ExecutionContext; import ch.boye.httpclientandroidlib.protocol.HttpContext; import ch.boye.httpclientandroidlib.util.EntityUtils; import com.normalexception.forum.rx8club.Log; import com.normalexception.forum.rx8club.WebUrls; import com.normalexception.forum.rx8club.httpclient.ClientUtils; import com.normalexception.forum.rx8club.user.UserProfile; import com.normalexception.forum.rx8club.utils.Utils; public class HtmlFormUtils { private static String responseUrl = ""; private static final String TAG = "HtmlFormUtils"; /** * Submit a form and its contents * @param url The url to submit the form to * @param nvps The name value pair of form contents * @return True if it worked * @throws ClientProtocolException * @throws IOException */ private static boolean formSubmit(String url, List<NameValuePair> nvps) throws ClientProtocolException, IOException { return formSubmit(url, nvps, false); } /** * Submit a form and its contents * @param url The url to submit the form to * @param nvps The name value pair of the contents * @param attachment If true, add attachment headers * @return True if it worked * @throws ClientProtocolExecption * @throws IOException */ private static boolean formSubmit(String url, List<NameValuePair> nvps, boolean attachment) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = LoginFactory.getInstance().getClient(); HttpPost httpost = ClientUtils.getHttpPost(url); Log.d(TAG, "[Submit] Submit URL: " + url); // If there is an attachment, we need to add some data // to the post header if(attachment) { String pN = ""; for(NameValuePair nvp : nvps) { if(nvp.getName().equals("p")) { pN = nvp.getValue(); break; } } httpost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpost.setHeader("Referer", WebUrls.postSubmitAddress + pN); } httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpContext context = LoginFactory.getInstance().getHttpContext(); HttpResponse response = httpclient.execute(httpost, context); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); Log.d(TAG, "[Submit] Status: " + statusLine.getStatusCode()); if (entity != null) { httpost.releaseConnection(); HttpUriRequest request = (HttpUriRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); responseUrl = request.getURI().toString(); Log.d(TAG, "[Submit] Response URL: " + responseUrl); return true; } return false; } /** * Update user profile * @param token The users security token * @param title The user title * @param homepage The users homepage * @param bio The users bio * @param location The users location * @param interests The users interests * @param occupation The users occupation * @return True if success * @throws ClientProtocolException * @throws IOException */ public static boolean updateProfile(String token, String title, String homepage, String bio, String location, String interests, String occupation) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("loggedinuser", UserProfile.getUserId())); nvps.add(new BasicNameValuePair("securitytoken", token)); nvps.add(new BasicNameValuePair("do", "updateprofile")); nvps.add(new BasicNameValuePair("customtext", title)); nvps.add(new BasicNameValuePair("homepage", homepage)); nvps.add(new BasicNameValuePair("userfield[field1]", bio)); nvps.add(new BasicNameValuePair("userfield[field2]", location)); nvps.add(new BasicNameValuePair("userfield[field3]", interests)); nvps.add(new BasicNameValuePair("userfield[field4]", occupation)); return formSubmit(WebUrls.profileUrl, nvps); } /** * Delete private message * @param securityToken Users security token * @param pmid The private message id number * @return True if success * @throws ClientProtocolException * @throws IOException */ public static boolean deletePM(String securityToken, String pmid) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("loggedinuser", UserProfile.getUserId())); nvps.add(new BasicNameValuePair("securitytoken", securityToken)); nvps.add(new BasicNameValuePair("do", "managepm")); nvps.add(new BasicNameValuePair("dowhat", "delete")); nvps.add(new BasicNameValuePair("pm[" + pmid + "]","0_today")); return formSubmit(WebUrls.pmUrl, nvps); } /** * Convenience method to send a private message * @param doType Submit type * @param securityToken User's security token * @param post The text from the PM * @param subject The subject of the PM * @param recips The recipient of the PM * @param pmid The pm id number * @return True if the submit worked * @throws ClientProtocolException * @throws IOException */ public static boolean submitPM(String doType, String securityToken, String post, String subject, String recips, String pmid) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("message", post)); nvps.add(new BasicNameValuePair("loggedinuser", UserProfile.getUserId())); nvps.add(new BasicNameValuePair("securitytoken", securityToken)); nvps.add(new BasicNameValuePair("do", doType)); nvps.add(new BasicNameValuePair("recipients", recips)); nvps.add(new BasicNameValuePair("title", subject)); nvps.add(new BasicNameValuePair("pmid", pmid)); return formSubmit(WebUrls.pmSubmitAddress + pmid, nvps); } /** * Submit a post to the server * @param securityToken The posting security token * @param thread The thread number * @param postNumber The post number * @param post The actual post * @return True if the post was successful * @throws ClientProtocolException * @throws IOException */ public static boolean submitPost(String doType, String securityToken, String thread, String postNumber, String attId, String post) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(attId != null) { post += "\n\n[ATTACH]" + attId + "[/ATTACH]"; } nvps.add(new BasicNameValuePair("message", post)); nvps.add(new BasicNameValuePair("t", thread)); nvps.add(new BasicNameValuePair("p", postNumber)); nvps.add(new BasicNameValuePair("specifiedpost", "0")); nvps.add(new BasicNameValuePair("loggedinuser", UserProfile.getUserId())); nvps.add(new BasicNameValuePair("securitytoken", securityToken)); nvps.add(new BasicNameValuePair("parseurl", "1")); nvps.add(new BasicNameValuePair("parseame", "1")); nvps.add(new BasicNameValuePair("parseame_check", "1")); nvps.add(new BasicNameValuePair("vbseo_retrtitle", "1")); nvps.add(new BasicNameValuePair("vbseo_is_retrtitle", "1")); nvps.add(new BasicNameValuePair("emailupdate", "9999")); nvps.add(new BasicNameValuePair("do", doType)); return formSubmit(WebUrls.quickPostAddress + thread, nvps, attId != null); } /** * Submit a post edit * @param securityToken The security token of the posting * @param postNumber The post number being edited * @param posthash The post hash number * @param poststart The post start time * @param post The post text * @return True if submit successful * @throws ClientProtocolException * @throws IOException */ public static boolean submitEdit(String securityToken, String postNumber, String posthash, String poststart, String post) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("message", post)); nvps.add(new BasicNameValuePair("p", postNumber)); nvps.add(new BasicNameValuePair("securitytoken", securityToken)); nvps.add(new BasicNameValuePair("do","updatepost")); nvps.add(new BasicNameValuePair("posthash", posthash)); nvps.add(new BasicNameValuePair("poststarttime", poststart)); return formSubmit(WebUrls.updatePostAddress + postNumber, nvps); } /** * Submit a request to the server to delete the post * @param securityToken The session security token * @param postNum The post number to delete * @return True if delete successful * @throws ClientProtocolException * @throws IOException */ public static boolean submitDelete(String securityToken, String postNum) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("postid", postNum)); nvps.add(new BasicNameValuePair("securitytoken", securityToken)); nvps.add(new BasicNameValuePair("do","deletepost")); nvps.add(new BasicNameValuePair("deletepost", "delete")); return formSubmit(WebUrls.deletePostAddress + postNum, nvps); } /** * Submit a request to upload an attachment to the server * @param securityToken * @param bmapList * @param postnum * @return * @throws ClientProtocolException * @throws IOException */ public static String submitAttachment(String securityToken, List<String> bmapList, String postnum) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = LoginFactory.getInstance().getClient(); String posthash = "", t = "", p = "", attId = "", poststarttime = ""; // Ok, the first thing we need to do is to grab some token and hash // information. This information isn't displayed on the thread page, // but instead on the thread's full reply page. Lets GET the page, // and then grab the input params we need. HttpGet httpGet = ClientUtils.getHttpGet(WebUrls.postSubmitAddress + postnum); HttpResponse respo = httpclient.execute(httpGet, LoginFactory.getInstance().getHttpContext()); HttpEntity respoEnt = respo.getEntity(); if(respoEnt != null) { String output = EntityUtils.toString(respoEnt, "UTF-8" ); //entity.consumeContent(); httpGet.releaseConnection(); Document doc = Jsoup.parse(output); posthash = HtmlFormUtils.getInputElementValue(doc, "posthash"); t = HtmlFormUtils.getInputElementValue(doc, "t"); p = HtmlFormUtils.getInputElementValue(doc, "p"); poststarttime = HtmlFormUtils.getInputElementValue(doc, "poststarttime"); } // We need to make sure that we got all of the information before // proceeding, or else the attachment will not work MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("s", new StringBody("")); entity.addPart("securitytoken", new StringBody(securityToken)); entity.addPart("do", new StringBody("manageattach")); entity.addPart("t", new StringBody(t)); entity.addPart("f", new StringBody("6")); entity.addPart("p", new StringBody(p)); entity.addPart("poststarttime", new StringBody(poststarttime)); entity.addPart("editpost", new StringBody("0")); entity.addPart("posthash", new StringBody(posthash)); entity.addPart("MAX_FILE_SIZE", new StringBody("2097152")); entity.addPart("upload", new StringBody("Upload")); entity.addPart("attachmenturl[]", new StringBody("")); for(String bmap : bmapList) { File fileToUpload = new File(bmap); FileBody fileBody = new FileBody(fileToUpload, "image/png"); entity.addPart("attachment[]", fileBody); } // Now post the page parameters. This will go ahead and attach the // image to our profile. HttpPost httpPost = ClientUtils.getHttpPost(WebUrls.postAttachmentAddress); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost, LoginFactory.getInstance().getHttpContext()); // Read our response HttpEntity ent = response.getEntity(); if(ent != null) { String output = EntityUtils.toString(ent, "UTF-8" ); Document doc = Jsoup.parse(output); String attachment = doc.select("a[href^=attachment.php?attachmentid]").first().attr("href"); if(attachment != null) { final String attStr = "attachmentid="; final String ampStr = "&"; attId = attachment.substring(attachment.indexOf(attStr)); attId = attId.substring(attStr.length(), attId.indexOf(ampStr)); } httpPost.releaseConnection(); } // NOTE: Now we have an issue that so far I am unable to emulate // in Java. What this has done, is upload an attachment to // the server, but, it only exists in our profile. The attachment // hasn't been registered to a thread. You can confirm this // by going to the user control panel on the forum, click the // attachments section, and you will see the attachment that // says "in progress". return attId; } /** * Report the contents of the post that we are intending * on editing * @param securityToken The security token of the session * @return The response page * @throws ClientProtocolException * @throws IOException */ public static Document getEditPostPage(String securityToken, String postid) throws ClientProtocolException, IOException { String output = ""; DefaultHttpClient httpclient = LoginFactory.getInstance().getClient(); HttpPost httpost = ClientUtils.getHttpPost(WebUrls.editPostAddress + postid); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("securitytoken", securityToken)); httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpost, LoginFactory.getInstance().getHttpContext()); HttpEntity entity = response.getEntity(); if(entity != null) { output = EntityUtils.toString(entity, "UTF-8" ); } return Jsoup.parse(output); } /** * Submit a new thread to the server * @param forumId The category id * @param s ? not sure ? * @param token The security token * @param posthash The post hash code * @param subject The user defined subject * @param post The user defined initial post * @return True if successful * @throws ClientProtocolException * @throws IOException */ public static boolean newThread(String forumId, String s, String token, String posthash, String subject, String post) throws ClientProtocolException, IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("s", s)); nvps.add(new BasicNameValuePair("securitytoken", token)); nvps.add(new BasicNameValuePair("f", forumId)); nvps.add(new BasicNameValuePair("do", "postthread")); nvps.add(new BasicNameValuePair("posthash", posthash)); nvps.add(new BasicNameValuePair("poststarttime", Long.toString(Utils.getTime()))); nvps.add(new BasicNameValuePair("subject", subject)); nvps.add(new BasicNameValuePair("message", post)); nvps.add(new BasicNameValuePair("loggedinuser", UserProfile.getUserId())); return formSubmit(WebUrls.newThreadAddress + forumId, nvps); } /** * Report the response url * @return The response url */ public static String getResponseUrl() { return WebUrls.rootUrl + responseUrl; } /** * Report the value inside of an input element * @param pan The panel where all of the input elements reside * @param name The name of the input to get the value for * @return The string value of the input */ public static String getInputElementValue(Document pan, String name) { try { return pan.select("input[name=" + name + "]").attr("value"); } catch (NullPointerException npe) { return ""; } } }
package com.redhat.ceylon.compiler.typechecker.analyzer; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.model.BottomType; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Import; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree; public class Util { public static Declaration getDeclaration(Scope scope, Unit unit, Tree.Identifier id, Context context) { return getDeclaration(scope, unit, true, id.getText(), context); } public static Declaration getMemberDeclaration(TypeDeclaration scope, Tree.Identifier id, Context context) { return getDeclaration(scope, null, false, id.getText()); } public static Declaration getExternalDeclaration(Package pkg, Tree.Identifier id, Context context) { return getDeclaration(pkg, null, false, id.getText(), context); } private static Declaration getDeclaration(Scope scope, Unit unit, boolean includeParameters, String name, Context context) { Declaration d = getDeclaration(scope, unit, includeParameters, name); return d==null ? getLanguageModuleDeclaration(name, context) : d; } private static Declaration getDeclaration(Scope scope, Unit unit, boolean includeParameters, String name) { while (scope!=null) { //imports hide declarations in same package //but not declarations in local scopes if (scope instanceof Package && unit!=null) { Declaration d = getImportedDeclaration(unit, name); if (d!=null) { return d; } } Declaration d = getLocalDeclaration(scope, includeParameters, name); if (d!=null) { return d; } scope = scope.getContainer(); } return null; } public static Declaration getLanguageModuleDeclaration(String name, Context context) { //all elements in ceylon.language are auto-imported //traverse all default module packages provided they have not been traversed yet if (context==null) return null; final Module languageModule = context.getLanguageModule(); if ( languageModule != null && languageModule.isAvailable() ) { if ("Bottom".equals(name)) { return new BottomType(); } for (Scope languageScope : languageModule.getPackages() ) { final Declaration d = getLocalDeclarationIgnoringSupertypes(languageScope, false, name); if (d != null) { return d; } } } return null; } /** * Search only directly inside the given scope, * without considering containing scopes or * imports. */ private static Declaration getLocalDeclaration(Scope scope, boolean includeParameters, String name) { Declaration d = getLocalDeclarationIgnoringSupertypes(scope, includeParameters, name); if (d!=null) { return d; } else { if (scope instanceof TypeDeclaration) { return getSupertypeDeclaration( (TypeDeclaration) scope, name ); } else { return null; } } } private static Declaration getSupertypeDeclaration(TypeDeclaration td, String name) { for (ProducedType st: td.getType().getSupertypes()) { TypeDeclaration std = st.getDeclaration(); if (std!=td) { Declaration d = getLocalDeclaration(std, false, name); if (d!=null) { return d; } } } return null; } private static Declaration getLocalDeclarationIgnoringSupertypes(Scope scope, boolean includeParameters, String name) { for ( Declaration d: scope.getMembers() ) { if ( !(d instanceof Setter) && (includeParameters || !(d instanceof Parameter)) ) { if (d.getName()!=null && d.getName().equals(name)) { return d; } } } return null; } /** * Search the imports of a compilation unit * for the declaration. */ private static Declaration getImportedDeclaration(Unit u, String name) { for (Import i: u.getImports()) { Declaration d = i.getDeclaration(); if (d.getName().equals(name)) { return d; } } return null; } public static String name(Tree.Identifier id) { if (id==null) { return "program element with missing name"; } else { return id.getText(); } } }
package com.team254.frc2015.behavior.routines; import com.team254.frc2015.behavior.Commands; import com.team254.frc2015.behavior.RobotSetpoints; import edu.wpi.first.wpilibj.Timer; import java.util.Optional; public class CanGrabRoutine extends Routine { public enum States { START, OPENING_FLAPS, MOVE_CARRIAGES, ROTATE_DOWN, OPEN_GRABBER, CLOSE_GRABBER, CENTER_DOWN, DRIVE_UP, ROTATE_UP, BEFORE_CLOSE_GRABBER, DONE } States m_state = States.START; private boolean m_is_new_state = false; Timer m_state_timer = new Timer(); RobotSetpoints setpoints; @Override public void reset() { m_state_timer.start(); m_state_timer.reset(); m_state = States.START; } @Override public RobotSetpoints update(Commands commands, RobotSetpoints existing_setpoints) { setpoints = existing_setpoints; States new_state = m_state; // Set defaults so manual control can't kick us out setpoints.flapper_action = RobotSetpoints.BottomCarriageFlapperAction.OPEN; setpoints.intake_action = RobotSetpoints.IntakeAction.PREFER_OPEN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; // Do state machine switch(m_state) { case START: new_state = States.OPENING_FLAPS; break; case OPENING_FLAPS: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_UP; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (m_state_timer.get() > .125) { new_state = States.MOVE_CARRIAGES; } break; case MOVE_CARRIAGES: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_UP; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (m_is_new_state) { setpoints.m_elevator_setpoints.bottom_setpoint = Optional.of(2.0); setpoints.m_elevator_setpoints.top_setpoint = Optional.of(6.5); } if (!m_is_new_state && bottom_carriage.isOnTarget() && top_carriage.isOnTarget()) { new_state = States.ROTATE_DOWN; } else if (!m_is_new_state && m_state_timer.get() > 2.3) { setpoints.bottom_open_loop_jog = Optional.of(0.0); setpoints.top_open_loop_jog = Optional.of(0.0); new_state = States.ROTATE_DOWN; } break; case ROTATE_DOWN: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_DOWN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (m_state_timer.get() > .55) { new_state = States.OPEN_GRABBER; } break; case OPEN_GRABBER: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_DOWN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.OPEN; if (commands.can_grabber_request == Commands.CanGrabberRequests.TOGGLE_GRAB) { new_state = States.BEFORE_CLOSE_GRABBER; } break; case BEFORE_CLOSE_GRABBER: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_DOWN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.OPEN; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (m_state_timer.get() > .125) { new_state = States.CLOSE_GRABBER; } break; case CLOSE_GRABBER: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_DOWN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (commands.can_grabber_request == Commands.CanGrabberRequests.DO_STAGE) { new_state = States.CENTER_DOWN; } if (commands.can_grabber_request == Commands.CanGrabberRequests.TOGGLE_GRAB) { new_state = States.OPEN_GRABBER; } break; case CENTER_DOWN: setpoints.roller_action = RobotSetpoints.RollerAction.INTAKE; setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_DOWN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (m_is_new_state) { setpoints.m_elevator_setpoints.top_setpoint = Optional.of(5.0); } if (m_state_timer.get() > .35) { new_state = States.DRIVE_UP; } break; case DRIVE_UP: setpoints.roller_action = RobotSetpoints.RollerAction.INTAKE; setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_DOWN; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; setpoints.intake_action = RobotSetpoints.IntakeAction.OPEN; if (m_is_new_state) { setpoints.m_elevator_setpoints.top_setpoint = Optional.of(55.0); } if (!m_is_new_state && top_carriage.getHeight() > 40.0) { new_state = States.ROTATE_UP; } break; case ROTATE_UP: setpoints.pivot_action = RobotSetpoints.TopCarriagePivotAction.PIVOT_UP; setpoints.claw_action = RobotSetpoints.TopCarriageClawAction.CLOSE; if (m_state_timer.get() > .125 && top_carriage.isOnTarget()) { new_state = States.DONE; } default: break; } m_is_new_state = false; if (new_state != m_state) { m_state = new_state; m_state_timer.reset(); m_is_new_state = true; } return setpoints; } @Override public void cancel() { m_state = States.START; m_state_timer.stop(); } @Override public boolean isFinished() { return m_state == States.DONE; } @Override public String getName() { return "Can Grab"; } }
package de.geeksfactory.opacclient.storage; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import de.geeksfactory.opacclient.objects.Account; public class AccountDataSource { // Database fields private SQLiteDatabase database; private AccountDatabase dbHelper; private String[] allColumns = AccountDatabase.COLUMNS; public AccountDataSource(Context context) { dbHelper = new AccountDatabase(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public long addAccount(Account acc) { ContentValues values = new ContentValues(); values.put("bib", acc.getBib()); values.put("label", acc.getLabel()); values.put("name", acc.getName()); values.put("password", acc.getPassword()); return database.insert("accounts", null, values); } public void update(Account acc) { ContentValues values = new ContentValues(); values.put("bib", acc.getBib()); values.put("label", acc.getLabel()); values.put("name", acc.getName()); values.put("password", acc.getPassword()); database.update("accounts", values, "id = ?", new String[] { acc.getId() + "" }); } public long addAccount(String bib, String label, String name, String password) { ContentValues values = new ContentValues(); values.put("bib", bib); values.put("label", label); values.put("name", name); values.put("password", password); return database.insert("accounts", null, values); } public List<Account> getAllAccounts() { List<Account> accs = new ArrayList<Account>(); Cursor cursor = database.query("accounts", allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Account acc = cursorToAccount(cursor); accs.add(acc); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return accs; } public List<Account> getAllAccounts(String bib) { List<Account> accs = new ArrayList<Account>(); String[] selA = { bib }; Cursor cursor = database.query("accounts", allColumns, "bib = ?", selA, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Account acc = cursorToAccount(cursor); accs.add(acc); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return accs; } public Account getAccount(long id) { String[] selA = { "" + id }; Cursor cursor = database.query("accounts", allColumns, "id = ?", selA, null, null, null); Account acc = null; cursor.moveToFirst(); if (!cursor.isAfterLast()) { acc = cursorToAccount(cursor); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return acc; } private Account cursorToAccount(Cursor cursor) { Account acc = new Account(); acc.setId(cursor.getLong(0)); acc.setBib(cursor.getString(1)); acc.setLabel(cursor.getString(2)); acc.setName(cursor.getString(3)); acc.setPassword(cursor.getString(4)); return acc; } public void remove(Account acc) { String[] selA = { "" + acc.getId() }; database.delete("accounts", "id=?", selA); } }
package de.hotware.blockbreaker.android; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Random; import org.andengine.engine.camera.Camera; import org.andengine.engine.camera.hud.HUD; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.EngineOptions.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.SpriteBackground; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.Text; import org.andengine.entity.util.FPSCounter; import org.andengine.entity.util.FPSLogger; import org.andengine.opengl.font.Font; import org.andengine.opengl.font.FontFactory; import org.andengine.opengl.font.FontManager; import org.andengine.opengl.texture.TextureManager; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.input.sensor.orientation.IOrientationListener; import org.andengine.input.sensor.orientation.OrientationData; import org.andengine.ui.activity.BaseGameActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.graphics.Color; import android.preference.PreferenceManager; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.FrameLayout; import de.hotware.blockbreaker.android.view.LevelSceneHandler; import de.hotware.blockbreaker.android.view.UIConstants; import de.hotware.blockbreaker.model.generator.LevelGenerator; import de.hotware.blockbreaker.model.listeners.IGameEndListener; import de.hotware.blockbreaker.model.listeners.IGameEndListener.GameEndEvent.GameEndType; import de.hotware.blockbreaker.model.Level; import de.hotware.blockbreaker.util.misc.StreamUtil; public class BlockBreakerActivity extends BaseGameActivity implements IOrientationListener { //// Constants //// static final String DEFAULT_LEVEL_PATH = "levels/default.lev"; static final boolean USE_MENU_WORKAROUND = Integer.valueOf(android.os.Build.VERSION.SDK) < 7; static final String HIGHSCORE_NUM_KEY = "high_score_num_key"; static final String HIGHSCORE_PLAYER_KEY = "high_score_player_key"; //// Fields //// static final Random sRandomSeedObject = new Random(); boolean mUseOrientSensor = false; boolean mTimeAttackMode = false; int mNumberOfTurns = 16; BitmapTextureAtlas mBlockBitmapTextureAtlas; TiledTextureRegion mBlockTiledTextureRegion; BitmapTextureAtlas mArrowBitmapTextureAtlas; TiledTextureRegion mArrowTiledTextureRegion; BitmapTextureAtlas mSceneBackgroundBitmapTextureAtlas; TextureRegion mSceneBackgroundTextureRegion; Properties mStringProperties; Camera mCamera; Scene mLevelScene; Font mMiscFont; Font mSceneUIFont; Text mSeedText; LevelSceneHandler mLevelSceneHandler; Level mBackupLevel; Level mLevel; boolean mIgnoreInput = false; //currently not used String mLevelPath = DEFAULT_LEVEL_PATH; boolean mIsAsset = true; //not used end private BaseGameTypeHandler mGameTypeHandler; //// Overridden Methods //// @Override public void onStart() { super.onStart(); boolean oldTimeAttackMode = this.mTimeAttackMode; int oldNumberOfTurns = this.mNumberOfTurns; this.getPrefs(); if(oldTimeAttackMode ^ this.mTimeAttackMode || this.mGameTypeHandler == null) { if(this.mGameTypeHandler != null) { this.mGameTypeHandler.cleanUp(); } this.mGameTypeHandler = this.mTimeAttackMode ? new TimeAttackGameHandler() : new DefaultGameHandler(); if(this.mLevel != null) { this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mGameTypeHandler.start(); } } else if(oldNumberOfTurns != this.mNumberOfTurns) { this.mGameTypeHandler.onNumberOfTurnsPropertyChanged(); } } /** * sets the EngineOptions to the needs of the game */ @Override public EngineOptions onCreateEngineOptions() { this.mCamera = new Camera(0, 0, UIConstants.LEVEL_WIDTH, UIConstants.LEVEL_HEIGHT); EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(UIConstants.LEVEL_WIDTH, UIConstants.LEVEL_HEIGHT), this.mCamera); return engineOptions; } /** * Load all the textures we need */ @Override public void onCreateResources(OnCreateResourcesCallback pCallback) { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); //TODO: Language choosing this.mStringProperties = new Properties(); AssetManager assetManager = this.getResources().getAssets(); InputStream is = null; boolean fail = false; try { is = assetManager.open(UIConstants.DEFAULT_PROPERTIES_PATH); this.mStringProperties.load(is); } catch (IOException e) { fail = true; this.showFailDialog(e.getMessage()); } finally { StreamUtil.closeQuietly(is); } if(fail) { this.finish(); } TextureManager textureManager = this.mEngine.getTextureManager(); //loading block textures this.mBlockBitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 276, 46, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBlockTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBlockBitmapTextureAtlas, this, "blocks_tiled.png", 0,0, 6,1); this.mEngine.getTextureManager().loadTexture(this.mBlockBitmapTextureAtlas); //loading arrow sprites this.mArrowBitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 512, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mArrowTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mArrowBitmapTextureAtlas, this, "arrow_tiled.png", 0,0, 4,1); this.mEngine.getTextureManager().loadTexture(this.mArrowBitmapTextureAtlas); //Loading Background this.mSceneBackgroundBitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 960, 640, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mSceneBackgroundTextureRegion = (TextureRegion) BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSceneBackgroundBitmapTextureAtlas, this, "background.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mSceneBackgroundBitmapTextureAtlas); FontManager fontManager = this.mEngine.getFontManager(); //loading fps font BitmapTextureAtlas fpsFontTexture = new BitmapTextureAtlas(textureManager, 256, 256, TextureOptions.BILINEAR); this.mEngine.getTextureManager().loadTexture(fpsFontTexture); FontFactory.setAssetBasePath("font/"); this.mMiscFont = FontFactory.createFromAsset(fontManager, fpsFontTexture, assetManager, "Droid.ttf", 12, true, Color.BLACK); this.mEngine.getFontManager().loadFont(this.mMiscFont); //loading scene font BitmapTextureAtlas sceneFontTexture = new BitmapTextureAtlas(textureManager, 256, 256, TextureOptions.BILINEAR); this.mEngine.getTextureManager().loadTexture(sceneFontTexture); this.mSceneUIFont = FontFactory.createFromAsset(fontManager, sceneFontTexture, assetManager, "Plok.ttf", 18, true, Color.BLACK); this.mEngine.getFontManager().loadFont(this.mSceneUIFont); pCallback.onCreateResourcesFinished(); } /** * initialization of the Activity is done here. */ @Override public void onCreateScene(OnCreateSceneCallback pCallback) { this.mEngine.registerUpdateHandler(new FPSLogger()); pCallback.onCreateSceneFinished(new Scene()); } @Override public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pCallback) { this.loadFirstLevel(); this.initLevel(); this.mCamera.getHUD().attachChild(this.mSeedText); //TODO: setting scene only for testing purposes!!! this.mEngine.setScene(this.mLevelScene); pCallback.onPopulateSceneFinished(); this.mGameTypeHandler.start(); } @Override public void onResumeGame() { super.onResumeGame(); if(this.mUseOrientSensor) { this.enableOrientationSensor(this); } else { this.disableOrientationSensor(); } this.mGameTypeHandler.onEnterFocus(); } @Override public void onPauseGame() { super.onPauseGame(); this.disableOrientationSensor(); this.mGameTypeHandler.onLeaveFocus(); } /** * Listener method for Changes of the devices Orientation. * sets the Levels Gravity to the overwhelming Gravity */ @Override public void onOrientationChanged(OrientationData pOrientData) { if(this.mUseOrientSensor) { if(this.mLevel != null) { float pitch = pOrientData.getPitch(); float roll = pOrientData.getRoll(); if(roll == 0 && pitch == 0) { this.mLevel.setGravity(Level.Gravity.NORTH); } else if(Math.max(Math.abs(pitch), Math.abs(roll)) == Math.abs(pitch)) { if(-pitch < 0) { this.mLevel.setGravity(Level.Gravity.SOUTH); } else { this.mLevel.setGravity(Level.Gravity.NORTH); } } else { if(roll < 0) { this.mLevel.setGravity(Level.Gravity.EAST); } else { this.mLevel.setGravity(Level.Gravity.WEST); } } } } } /** * creates the menu defined in the corresponding xml file */ @Override public boolean onCreateOptionsMenu(Menu menu) { if(this.mStringProperties != null) { menu.add(Menu.NONE, UIConstants.MENU_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.MENU_PROPERTY_KEY)); menu.add(Menu.NONE, UIConstants.FROM_SEED_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.FROM_SEED_PROPERTY_KEY)); menu.add(Menu.NONE, UIConstants.RESTART_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.RESTART_PROPERTY_KEY)); menu.add(Menu.NONE, UIConstants.NEXT_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.NEXT_PROPERTY_KEY)); return true; } return false; } /** * shows the Activities Menu */ @Override public boolean onOptionsItemSelected(MenuItem item) { //TODO use AndEngines Menu System! switch(item.getItemId()) { case UIConstants.MENU_MENU_ID: { if(this.mGameTypeHandler.requestLeaveToMenu()) { Intent settingsActivity = new Intent(getBaseContext(), BlockBreakerPreferencesActivity.class); this.startActivity(settingsActivity); } return true; } case UIConstants.FROM_SEED_MENU_ID: { if(!this.mTimeAttackMode) { this.showInputSeedDialog(); } return true; } case UIConstants.RESTART_MENU_ID: { this.mGameTypeHandler.requestRestart(); return true; } case UIConstants.NEXT_MENU_ID: { this.mGameTypeHandler.requestNextLevel(); return true; } default: { return super.onOptionsItemSelected(item); } } } /** * Fix for older SDK versions which don't have onBackPressed() */ @Override public boolean onKeyDown(int pKeyCode, KeyEvent pEvent) { if(USE_MENU_WORKAROUND && pKeyCode == KeyEvent.KEYCODE_BACK && pEvent.getRepeatCount() == 0) { this.onBackPressed(); } return super.onKeyDown(pKeyCode, pEvent); } /** * If the user presses the back button he is asked if he wants to quit */ @Override public void onBackPressed() { this.showCancelDialog(); } @Override public void onOrientationAccuracyChanged(OrientationData pOrientationData) { } //// Private/Package Methods //// void updateLevel(String pLevelPath, boolean pIsAsset) throws Exception { this.mSeedText.setText(""); this.mLevelPath = pLevelPath; this.mIsAsset = pIsAsset; this.loadLevelFromAsset(); this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mLevelSceneHandler.updateLevel(this.mLevel); } void loadLevelFromAsset() throws Exception{ throw new Exception("not Implemented!"); } void restartLevel() { this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mLevelSceneHandler.updateLevel(this.mLevel); } void randomLevel() { long seed = sRandomSeedObject.nextLong(); this.randomLevelFromSeed(seed); } void randomLevelFromSeed(long pSeed) { this.mSeedText.setText("Seed: " + Long.toString(pSeed)); this.mBackupLevel = LevelGenerator.createRandomLevelFromSeed(pSeed, this.mNumberOfTurns); this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mLevelSceneHandler.updateLevel(this.mLevel); } private void initLevel() { final Scene scene = new Scene(); this.mLevelScene = scene; this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); VertexBufferObjectManager vboManager = this.mEngine.getVertexBufferObjectManager(); this.mLevelSceneHandler = new LevelSceneHandler(scene, vboManager); this.mLevelSceneHandler.initLevelScene(BlockBreakerActivity.this.mLevel, this.mSceneUIFont, this.mBlockTiledTextureRegion, this.mArrowTiledTextureRegion, this.mStringProperties); final HUD hud = new HUD(); final FPSCounter counter = new FPSCounter(); this.mEngine.registerUpdateHandler(counter); final int maxLength = "FPS: XXXXXXX".length(); final Text fps = new Text(1, 1, this.mMiscFont, "FPS:", maxLength, vboManager); hud.attachChild(fps); this.mCamera.setHUD(hud); scene.registerUpdateHandler(new TimerHandler(1/20F, true, new ITimerCallback() { @Override public void onTimePassed(TimerHandler arg0) { String fpsString = Float.toString(counter.getFPS()); int length = fpsString.length(); fps.setText("FPS: " + fpsString.substring(0, length >= 5 ? 5 : length)); } } )); scene.setBackground(new SpriteBackground(new Sprite(0,0,UIConstants.LEVEL_WIDTH, UIConstants.LEVEL_HEIGHT, BlockBreakerActivity.this.mSceneBackgroundTextureRegion, vboManager))); } void showEndDialog(final GameEndType pResult) { String resString; switch(pResult) { case WIN: { resString = this.mStringProperties.getProperty(UIConstants.WIN_GAME_PROPERTY_KEY); break; } case LOSE: { resString = this.mStringProperties.getProperty(UIConstants.LOSE_GAME_PROPERTY_KEY); break; } default: { resString = "WTF?"; break; } } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(resString + " " + this.mStringProperties.getProperty(UIConstants.RESTART_QUESTION_PROPERTY_KEY)) .setCancelable(true) .setPositiveButton(this.mStringProperties.getProperty(UIConstants.YES_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); BlockBreakerActivity.this.restartLevel(); } }) .setNegativeButton(this.mStringProperties.getProperty(UIConstants.NO_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); //TODO: Testing purposes! BlockBreakerActivity.this.randomLevel(); } }); builder.create().show(); } void showCancelDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(this.mStringProperties.getProperty(UIConstants.EXIT_GAME_QUESTION_PROPERTY_KEY)) .setCancelable(true) .setPositiveButton(this.mStringProperties.getProperty(UIConstants.YES_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); BlockBreakerActivity.this.finish(); } }) .setNegativeButton(this.mStringProperties.getProperty(UIConstants.NO_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); } }); builder.create().show(); } void showFailDialog(String pMessage) { //Don't use Properties here because this is used for failures in property loading as well AlertDialog.Builder builder = new AlertDialog.Builder(BlockBreakerActivity.this); builder.setMessage(pMessage + "\nQuitting!") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { BlockBreakerActivity.this.finish(); } }); builder.create().show(); } void showInputSeedDialog() { this.showInputSeedDialog( this.mStringProperties.getProperty(UIConstants.INPUT_SEED_QUESTION_PROPERTY_KEY)); } void showInputSeedDialog(String pText) { FrameLayout fl = new FrameLayout(this); final EditText input = new EditText(this); input.setGravity(Gravity.CENTER); fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(pText) .setView(fl) .setCancelable(true) .setPositiveButton(this.mStringProperties.getProperty(UIConstants.OK_PROPERTY_KEY), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface pDialog, int pId) { try { long seed = Long.parseLong(input.getText().toString()); BlockBreakerActivity.this.randomLevelFromSeed(seed); pDialog.dismiss(); } catch (NumberFormatException e) { BlockBreakerActivity.this.showInputSeedDialog( BlockBreakerActivity.this.mStringProperties.getProperty( UIConstants.WRONG_SEED_INPUT_PROPERTY_KEY)); } } }) .setNegativeButton(this.mStringProperties.getProperty(UIConstants.CANCEL_PROPERTY_KEY), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); } } ); builder.create().show(); } /** * loads the first randomly generated Level and initializes the SeedText */ private void loadFirstLevel() { long seed = sRandomSeedObject.nextLong(); this.mBackupLevel = LevelGenerator.createRandomLevelFromSeed(seed, this.mNumberOfTurns); int maxLength = "Seed: ".length() + Long.toString(Long.MAX_VALUE).length() + 1; this.mSeedText = new Text(1, UIConstants.LEVEL_HEIGHT - 15, this.mMiscFont, "Seed: " + seed, maxLength, this.mEngine.getVertexBufferObjectManager()); } private void getPrefs() { // Get the xml/preferences.xml preferences // Don't save this in a constant, because it will only be used in code here SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); this.mUseOrientSensor = prefs.getBoolean("orient_sens_pref", false); this.mTimeAttackMode = prefs.getBoolean("time_attack_pref", false); this.mNumberOfTurns = Integer.parseInt(prefs.getString("number_of_turns_pref", "16")); } //// Inner Classes & Interfaces //// public abstract class BaseGameTypeHandler implements IGameEndListener { /** * called if Activity loses Focus */ public void onLeaveFocus(){} /** * called if Activity gains Focus */ public void onEnterFocus(){} /** * called if the user requests the next Level, which is the same as losing in TimeAttack */ public void requestNextLevel(){} /** * called if the user requests to leave to the menu Activity * @return true if menu will be shown, false otherwise * @return default version returns true */ public boolean requestLeaveToMenu(){return true;} /** * called if the user requests a restart of the game */ public void requestRestart(){} /** * called upon first start of the game */ public void start(){} /** * called when before the GameHandler is changed */ public void cleanUp(){} /** * called if the number of turns property has changed, only used for notifying, no information */ public void onNumberOfTurnsPropertyChanged(){} } private class DefaultGameHandler extends BaseGameTypeHandler { @Override public void onGameEnd(final GameEndEvent pEvt) { BlockBreakerActivity.this.runOnUiThread(new Runnable() { public void run() { BlockBreakerActivity.this.showEndDialog(pEvt.getType()); } }); } @Override public void requestRestart() { BlockBreakerActivity.this.restartLevel(); } @Override public void requestNextLevel() { BlockBreakerActivity.this.randomLevel(); } @Override public void cleanUp() { BlockBreakerActivity.this.randomLevel(); } } //TODO: Implement all this stuff private class TimeAttackGameHandler extends BaseGameTypeHandler { private static final int DEFAULT_DURATION_IN_SECONDS = 120; private static final int DEFAULT_NUMBER_OF_ALLOWED_LOSES = 2; int mDurationInSeconds; int mNumberOfAllowedLoses; int mGamesLost; int mGamesWon; TimerHandler mTimeMainHandler; TimerHandler mTimeUpdateHandler; Text mTimeText; Text mTimeLeftText; public TimeAttackGameHandler() { this(DEFAULT_DURATION_IN_SECONDS, DEFAULT_NUMBER_OF_ALLOWED_LOSES); } public TimeAttackGameHandler(int pDurationInSeconds, int pNumberOfAllowedLoses) { this.mDurationInSeconds = pDurationInSeconds; this.mNumberOfAllowedLoses = pNumberOfAllowedLoses; this.mGamesWon = 0; this.mGamesLost = 0; this.mTimeMainHandler = new TimerHandler(this.mDurationInSeconds, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { BlockBreakerActivity.this.mLevelSceneHandler.setIgnoreInput(true); } }); this.mTimeUpdateHandler = new TimerHandler(1.0F, true, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { if(!TimeAttackGameHandler.this.mTimeMainHandler.isTimerCallbackTriggered()) { Log.d("DEBUG", "MainHandler has elapsed: " + TimeAttackGameHandler.this.mTimeMainHandler.getTimerSecondsElapsed() + "sec."); TimeAttackGameHandler.this.mTimeLeftText.setText( Integer.toString((int)Math.round(TimeAttackGameHandler.this.mTimeMainHandler.getTimerSecondsElapsed()))); } else { TimeAttackGameHandler.this.mTimeLeftText.setText( Integer.toString(TimeAttackGameHandler.this.mDurationInSeconds)); pTimerHandler.setAutoReset(false); } } }); } @Override public void onGameEnd(GameEndEvent pEvt) { switch(pEvt.getType()) { case WIN: { ++this.mGamesWon; BlockBreakerActivity.this.randomLevel(); break; } case LOSE: { this.requestNextLevel(); break; } } } @Override public void onEnterFocus() { BlockBreakerActivity.this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(BlockBreakerActivity.this); builder.setMessage("Press OK to start!") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface pDialog, int pId) { BlockBreakerActivity.this.mLevelSceneHandler.setIgnoreInput(false); BlockBreakerActivity.this.mEngine.registerUpdateHandler(TimeAttackGameHandler.this.mTimeMainHandler); BlockBreakerActivity.this.mEngine.registerUpdateHandler(TimeAttackGameHandler.this.mTimeUpdateHandler); } } ); builder.create().show(); } }); } @Override public void onLeaveFocus() { //Show stop dialog here BlockBreakerActivity.this.mLevelSceneHandler.setIgnoreInput(true); BlockBreakerActivity.this.mEngine.unregisterUpdateHandler(this.mTimeMainHandler); BlockBreakerActivity.this.mEngine.unregisterUpdateHandler(this.mTimeUpdateHandler); } public boolean requestLeaveToMenu() { return true; } @Override public void requestRestart() { this.reset(); } private void reset() { this.mGamesWon = 0; this.mTimeMainHandler.reset(); this.mTimeUpdateHandler.reset(); BlockBreakerActivity.this.mLevelSceneHandler.setIgnoreInput(false); } @Override public void requestNextLevel() { ++this.mGamesLost; if(this.mGamesLost >= this.mNumberOfAllowedLoses) { Log.d("DEBUG", "Loser!"); this.requestRestart(); //Dialog for restarting here } } @Override public void start() { this.mTimeLeftText = BlockBreakerActivity.this.mLevelSceneHandler.getTimeLeftText(); this.mTimeLeftText.setVisible(true); this.mTimeLeftText.setText(""); this.mTimeText = BlockBreakerActivity.this.mLevelSceneHandler.getTimeText(); this.mTimeText.setVisible(true); } @Override public void cleanUp() { BlockBreakerActivity.this.mEngine.unregisterUpdateHandler(this.mTimeMainHandler); BlockBreakerActivity.this.mEngine.unregisterUpdateHandler(this.mTimeUpdateHandler); BlockBreakerActivity.this.mLevelSceneHandler.setIgnoreInput(false); BlockBreakerActivity.this.randomLevel(); this.mTimeLeftText.setVisible(false); this.mTimeLeftText.setText(""); this.mTimeText.setVisible(false); } @Override public void onNumberOfTurnsPropertyChanged() { this.reset(); } } }
package de.lmu.ifi.dbs.elki.visualization.svg; import java.util.BitSet; import org.w3c.dom.Element; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.distance.distancevalue.NumberDistance; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; import de.lmu.ifi.dbs.elki.visualization.projections.Projection2D; /** * Utility class to draw hypercubes, wireframe and filled. * * @author Erich Schubert * * @apiviz.uses SVGPath * @apiviz.uses Projection2D */ public class SVGHyperSphere { /** * Factor used for approximating circles with cubic beziers. * * kappa = 4 * (Math.sqrt(2)-1)/3 */ public final static double EUCLIDEAN_KAPPA = 0.5522847498; /** * Wireframe "manhattan" hypersphere * * @param <V> vector type * @param <D> radius * @param svgp SVG Plot * @param proj Visualization projection * @param mid mean vector * @param rad radius * @return path element */ public static <V extends NumberVector<V, ?>, D extends NumberDistance<?, ?>> Element drawManhattan(SVGPlot svgp, Projection2D proj, V mid, D rad) { Vector v_mid = mid.getColumnVector(); BitSet dims = proj.getVisibleDimensions2D(); SVGPath path = new SVGPath(); for(int dim = dims.nextSetBit(0); dim >= 0; dim = dims.nextSetBit(dim + 1)) { Vector v1 = v_mid.copy(); v1.set(dim, v1.get(dim) + rad.doubleValue()); Vector v2 = v_mid.copy(); v2.set(dim, v2.get(dim) - rad.doubleValue()); double[] p1 = proj.fastProjectDataToRenderSpace(v1); double[] p2 = proj.fastProjectDataToRenderSpace(v2); for(int dim2 = dims.nextSetBit(0); dim2 >= 0; dim2 = dims.nextSetBit(dim2 + 1)) { if(dim < dim2) { Vector v3 = v_mid.copy(); v3.set(dim2, v3.get(dim2) + rad.doubleValue()); Vector v4 = v_mid.copy(); v4.set(dim2, v4.get(dim2) - rad.doubleValue()); double[] p3 = proj.fastProjectDataToRenderSpace(v3); double[] p4 = proj.fastProjectDataToRenderSpace(v4); path.moveTo(p1[0], p1[1]); path.drawTo(p3[0], p3[1]); path.moveTo(p1[0], p1[1]); path.drawTo(p4[0], p4[1]); path.moveTo(p2[0], p2[1]); path.drawTo(p3[0], p3[1]); path.moveTo(p2[0], p2[1]); path.drawTo(p4[0], p4[1]); path.close(); } } } return path.makeElement(svgp); } /** * Wireframe "euclidean" hypersphere * * @param <V> vector type * @param <D> radius * @param svgp SVG Plot * @param proj Visualization projection * @param mid mean vector * @param rad radius * @return path element */ public static <V extends NumberVector<V, ?>, D extends NumberDistance<?, ?>> Element drawEuclidean(SVGPlot svgp, Projection2D proj, V mid, D rad) { Vector v_mid = mid.getColumnVector(); BitSet dims = proj.getVisibleDimensions2D(); SVGPath path = new SVGPath(); for(int dim = dims.nextSetBit(0); dim >= 0; dim = dims.nextSetBit(dim + 1)) { Vector v1 = v_mid.copy(); v1.set(dim, v1.get(dim) + rad.doubleValue()); Vector v2 = v_mid.copy(); v2.set(dim, v2.get(dim) - rad.doubleValue()); double[] p1 = proj.fastProjectDataToRenderSpace(v1); double[] p2 = proj.fastProjectDataToRenderSpace(v2); // delta vector Vector dt1 = new Vector(v1.getDimensionality()); dt1.set(dim, rad.doubleValue()); double[] d1 = proj.fastProjectRelativeDataToRenderSpace(dt1); for(int dim2 = dims.nextSetBit(0); dim2 >= 0; dim2 = dims.nextSetBit(dim2 + 1)) { if(dim < dim2) { Vector v3 = v_mid.copy(); v3.set(dim2, v3.get(dim2) + rad.doubleValue()); Vector v4 = v_mid.copy(); v4.set(dim2, v4.get(dim2) - rad.doubleValue()); double[] p3 = proj.fastProjectDataToRenderSpace(v3); double[] p4 = proj.fastProjectDataToRenderSpace(v4); // delta vector Vector dt2 = new Vector(v2.getDimensionality()); dt2.set(dim2, rad.doubleValue()); double[] d2 = proj.fastProjectRelativeDataToRenderSpace(dt2); path.moveTo(p1[0], p1[1]); path.cubicTo(p1[0] + d2[0] * EUCLIDEAN_KAPPA, p1[1] + d2[1] * EUCLIDEAN_KAPPA, p3[0] + d1[0] * EUCLIDEAN_KAPPA, p3[1] + d1[1] * EUCLIDEAN_KAPPA, p3[0], p3[1]); path.cubicTo(p3[0] - d1[0] * EUCLIDEAN_KAPPA, p3[1] - d1[1] * EUCLIDEAN_KAPPA, p2[0] + d2[0] * EUCLIDEAN_KAPPA, p2[1] + d2[1] * EUCLIDEAN_KAPPA, p2[0], p2[1]); path.cubicTo(p2[0] - d2[0] * EUCLIDEAN_KAPPA, p2[1] - d2[1] * EUCLIDEAN_KAPPA, p4[0] - d1[0] * EUCLIDEAN_KAPPA, p4[1] - d1[1] * EUCLIDEAN_KAPPA, p4[0], p4[1]); path.cubicTo(p4[0] + d1[0] * EUCLIDEAN_KAPPA, p4[1] + d1[1] * EUCLIDEAN_KAPPA, p1[0] - d2[0] * EUCLIDEAN_KAPPA, p1[1] - d2[1] * EUCLIDEAN_KAPPA, p1[0], p1[1]); path.close(); } } } return path.makeElement(svgp); } /** * Wireframe "Lp" hypersphere * * @param <V> vector type * @param <D> radius * @param svgp SVG Plot * @param proj Visualization projection * @param mid mean vector * @param rad radius * @param p L_p value * @return path element */ public static <V extends NumberVector<V, ?>, D extends NumberDistance<?, ?>> Element drawLp(SVGPlot svgp, Projection2D proj, V mid, D rad, double p) { Vector v_mid = mid.getColumnVector(); BitSet dims = proj.getVisibleDimensions2D(); final double kappax, kappay; if(p > 1.) { double kappal = Math.pow(0.5, 1. / p); kappax = Math.min(1.3, 4. * (2 * kappal - 1) / 3.); kappay = 0; } else if(p < 1.) { double kappal = 1 - Math.pow(0.5, 1. / p); kappax = 0; kappay = Math.min(1.3, 4. * (2 * kappal - 1) / 3.); } else { kappax = 0; kappay = 0; } // LoggingUtil.warning("kappax: " + kappax + " kappay: " + kappay); SVGPath path = new SVGPath(); for(int dim = dims.nextSetBit(0); dim >= 0; dim = dims.nextSetBit(dim + 1)) { Vector vp0 = v_mid.copy(); vp0.set(dim, vp0.get(dim) + rad.doubleValue()); Vector vm0 = v_mid.copy(); vm0.set(dim, vm0.get(dim) - rad.doubleValue()); double[] pvp0 = proj.fastProjectDataToRenderSpace(vp0); double[] pvm0 = proj.fastProjectDataToRenderSpace(vm0); // delta vector Vector tvd0 = new Vector(vp0.getDimensionality()); tvd0.set(dim, rad.doubleValue()); double[] vd0 = proj.fastProjectRelativeDataToRenderSpace(tvd0); for(int dim2 = dims.nextSetBit(0); dim2 >= 0; dim2 = dims.nextSetBit(dim2 + 1)) { if(dim < dim2) { Vector v0p = v_mid.copy(); v0p.set(dim2, v0p.get(dim2) + rad.doubleValue()); Vector v0m = v_mid.copy(); v0m.set(dim2, v0m.get(dim2) - rad.doubleValue()); double[] pv0p = proj.fastProjectDataToRenderSpace(v0p); double[] pv0m = proj.fastProjectDataToRenderSpace(v0m); // delta vector Vector tv0d = new Vector(vm0.getDimensionality()); tv0d.set(dim2, rad.doubleValue()); double[] v0d = proj.fastProjectRelativeDataToRenderSpace(tv0d); if(p > 1) { // p > 1 path.moveTo(pvp0[0], pvp0[1]); // support points, p0 to 0p final double s_pp1_x = pvp0[0] + v0d[0] * kappax; final double s_pp1_y = pvp0[1] + v0d[1] * kappax; final double s_pp2_x = pv0p[0] + vd0[0] * kappax; final double s_pp2_y = pv0p[1] + vd0[1] * kappax; path.cubicTo(s_pp1_x, s_pp1_y, s_pp2_x, s_pp2_y, pv0p[0], pv0p[1]); // support points, 0p to m0 final double s_mp1_x = pv0p[0] - vd0[0] * kappax; final double s_mp1_y = pv0p[1] - vd0[1] * kappax; final double s_mp2_x = pvm0[0] + v0d[0] * kappax; final double s_mp2_y = pvm0[1] + v0d[1] * kappax; path.cubicTo(s_mp1_x, s_mp1_y, s_mp2_x, s_mp2_y, pvm0[0], pvm0[1]); // support points, m0 to 0m final double s_mm1_x = pvm0[0] - v0d[0] * kappax; final double s_mm1_y = pvm0[1] - v0d[1] * kappax; final double s_mm2_x = pv0m[0] - vd0[0] * kappax; final double s_mm2_y = pv0m[1] - vd0[1] * kappax; path.cubicTo(s_mm1_x, s_mm1_y, s_mm2_x, s_mm2_y, pv0m[0], pv0m[1]); // support points, 0m to p0 final double s_pm1_x = pv0m[0] + vd0[0] * kappax; final double s_pm1_y = pv0m[1] + vd0[1] * kappax; final double s_pm2_x = pvp0[0] - v0d[0] * kappax; final double s_pm2_y = pvp0[1] - v0d[1] * kappax; path.cubicTo(s_pm1_x, s_pm1_y, s_pm2_x, s_pm2_y, pvp0[0], pvp0[1]); path.close(); } else if(p < 1) { // p < 1 // support points, p0 to 0p final double s_vp0_x = pvp0[0] - vd0[0] * kappay; final double s_vp0_y = pvp0[1] - vd0[1] * kappay; final double s_v0p_x = pv0p[0] - v0d[0] * kappay; final double s_v0p_y = pv0p[1] - v0d[1] * kappay; final double s_vm0_x = pvm0[0] + vd0[0] * kappay; final double s_vm0_y = pvm0[1] + vd0[1] * kappay; final double s_v0m_x = pv0m[0] + v0d[0] * kappay; final double s_v0m_y = pv0m[1] + v0d[1] * kappay; // Draw the star path.moveTo(pvp0[0], pvp0[1]); path.cubicTo(s_vp0_x, s_vp0_y, s_v0p_x, s_v0p_y, pv0p[0], pv0p[1]); path.cubicTo(s_v0p_x, s_v0p_y, s_vm0_x, s_vm0_y, pvm0[0], pvm0[1]); path.cubicTo(s_vm0_x, s_vm0_y, s_v0m_x, s_v0m_y, pv0m[0], pv0m[1]); path.cubicTo(s_v0m_x, s_v0m_y, s_vp0_x, s_vp0_y, pvp0[0], pvp0[1]); path.close(); } else { // p == 1 - Manhattan path.moveTo(pvp0[0], pvp0[1]); path.lineTo(pv0p[0], pv0p[1]); path.lineTo(pvm0[0], pvm0[1]); path.lineTo(pv0m[0], pv0m[1]); path.lineTo(pvp0[0], pvp0[1]); path.close(); } } } } return path.makeElement(svgp); } /** * Wireframe "cross" hypersphere * * @param <V> vector type * @param <D> radius * @param svgp SVG Plot * @param proj Visualization projection * @param mid mean vector * @param rad radius * @return path element */ public static <V extends NumberVector<V, ?>, D extends NumberDistance<?, ?>> Element drawCross(SVGPlot svgp, Projection2D proj, V mid, D rad) { Vector v_mid = mid.getColumnVector(); BitSet dims = proj.getVisibleDimensions2D(); SVGPath path = new SVGPath(); for(int dim = dims.nextSetBit(0); dim >= 0; dim = dims.nextSetBit(dim + 1)) { Vector v1 = v_mid.copy(); v1.set(dim, v1.get(dim) + rad.doubleValue()); Vector v2 = v_mid.copy(); v2.set(dim, v2.get(dim) - rad.doubleValue()); double[] p1 = proj.fastProjectDataToRenderSpace(v1); double[] p2 = proj.fastProjectDataToRenderSpace(v2); path.moveTo(p1[0], p1[1]); path.drawTo(p2[0], p2[1]); path.close(); } return path.makeElement(svgp); } }
package de.mrapp.android.preference; import android.annotation.TargetApi; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.preference.Preference; import android.util.AttributeSet; import android.view.Window; import android.view.WindowManager; import de.mrapp.android.dialog.MaterialDialogBuilder; /** * An abstract base class for all preferences, which will show a dialog when * clicked by the user. * * @author Michael Rapp * * @since 1.0.0 */ public abstract class AbstractDialogPreference extends Preference implements OnClickListener, OnDismissListener { /** * A data structure, which allows to save the internal state of an * {@link AbstractDialogPreference}. */ public static class SavedState extends BaseSavedState { /** * A creator, which allows to create instances of the class * {@link SavedState} from parcels. */ public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(final Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(final int size) { return new SavedState[size]; } }; /** * True, if the dialog of the {@link AbstractDialogPreference}, whose * state is saved by the data structure, is currently shown, false * otherwise. */ public boolean dialogShown; /** * The saved state of the dialog of the {@link AbstractDialogPreference} * , whose state is saved by the data structure. */ public Bundle dialogState; /** * Creates a new data structure, which allows to store the internal * state of an {@link AbstractDialogPreference}. This constructor is * used when reading from a parcel. It reads the state of the * superclass. * * @param source * The parcel to read read from as a instance of the class * {@link Parcel} */ public SavedState(final Parcel source) { super(source); dialogShown = source.readInt() == 1; dialogState = source.readBundle(); } /** * Creates a new data structure, which allows to store the internal * state of an {@link AbstractDialogPreference}. This constructor is * called by derived classes when saving their states. * * @param superState * The state of the superclass of this view, as an instance * of the type {@link Parcelable} */ public SavedState(final Parcelable superState) { super(superState); } @Override public final void writeToParcel(final Parcel destination, final int flags) { super.writeToParcel(destination, flags); destination.writeInt(dialogShown ? 1 : 0); destination.writeBundle(dialogState); } }; /** * The preference's dialog. */ private Dialog dialog; /** * True, if the preference's dialog has been closed affirmatively, false * otherwise. */ private boolean dialogResultPositive; /** * The title of the preference's dialog. */ private CharSequence dialogTitle; /** * The message of the preference's dialog. */ private CharSequence dialogMessage; /** * The icon of the preference's dialog. */ private Drawable dialogIcon; /** * The text of the positive button of the preference's dialog. */ private CharSequence positiveButtonText; /** * The text of the negative button of the preference's dialog. */ private CharSequence negativeButtonText; /** * The color of the title of the preference's dialog. */ private int dialogTitleColor; /** * The color of the button text of the preference's dialog. */ private int dialogButtonTextColor; /** * True, if the currently persisted value should be shown as the summary, * instead of the given summaries, false otherwise. */ private boolean showValueAsSummary; /** * Obtains all attributes from a specific attribute set. * * @param attributeSet * The attribute set, the attributes should be obtained from, as * an instance of the type {@link AttributeSet} */ private void obtainStyledAttributes(final AttributeSet attributeSet) { TypedArray typedArray = getContext().obtainStyledAttributes(attributeSet, R.styleable.AbstractDialogPreference); try { obtainDialogTitle(typedArray); obtainDialogMessage(typedArray); obtainDialogIcon(typedArray); obtainPositiveButtonText(typedArray); obtainNegativeButtonText(typedArray); obtainDialogTitleColor(typedArray); obtainDialogButtonTextColor(typedArray); obtainShowValueAsSummary(typedArray); } finally { typedArray.recycle(); } } /** * Obtains the title of the dialog, which is shown by the preference, from a * specific typed array. * * @param typedArray * The typed array, the title should be obtained from, as an * instance of the class {@link TypedArray} */ private void obtainDialogTitle(final TypedArray typedArray) { CharSequence title = typedArray.getText(R.styleable.AbstractDialogPreference_android_dialogTitle); setDialogTitle(title != null ? title : getTitle()); } /** * Obtains the message of the dialog, which is shown by the preference, from * a specific typed array. * * @param typedArray * The typed array, the message should be obtained from, as an * instance of the class {@link TypedArray} */ private void obtainDialogMessage(final TypedArray typedArray) { setDialogMessage(typedArray.getText(R.styleable.AbstractDialogPreference_android_dialogMessage)); } /** * Obtains the icon of the dialog, which is shown by the preference, from a * specific typed array. * * @param typedArray * The typed array, the icon should be obtained from, as an * instance of the class {@link TypedArray} */ private void obtainDialogIcon(final TypedArray typedArray) { int resourceId = typedArray.getResourceId(R.styleable.AbstractDialogPreference_android_dialogIcon, -1); if (resourceId != -1) { setDialogIcon(resourceId); } } /** * Obtains the positive button text of the dialog, which is shown by the * preference, from a specific typed array. * * @param typedArray * The typed array, the positive button text should be obtained * from, as an instance of the class {@link TypedArray} */ private void obtainPositiveButtonText(final TypedArray typedArray) { setPositiveButtonText(typedArray.getText(R.styleable.AbstractDialogPreference_android_positiveButtonText)); } /** * Obtains the negative button text of the dialog, which is shown by the * preference, from a specific typed array. * * @param typedArray * The typed array, the negative button text should be obtained * from, as an instance of the class {@link TypedArray} */ private void obtainNegativeButtonText(final TypedArray typedArray) { setNegativeButtonText(typedArray.getText(R.styleable.AbstractDialogPreference_android_negativeButtonText)); } /** * Obtains the title color of the dialog, which is shown by the preference, * from a specific typed array. * * @param typedArray * The typed array, the title color should be obtained from, as * an instance of the class {@link TypedArray} */ private void obtainDialogTitleColor(final TypedArray typedArray) { setDialogTitleColor(typedArray.getColor(R.styleable.AbstractDialogPreference_dialogTitleColor, -1)); } /** * Obtains the button text color of the dialog, which is shown by the * preference, from a specific typed array. * * @param typedArray * The typed array, the button text color should be obtained * from, as an instance of the class {@link TypedArray} */ private void obtainDialogButtonTextColor(final TypedArray typedArray) { setDialogButtonTextColor(typedArray.getColor(R.styleable.AbstractDialogPreference_dialogButtonTextColor, -1)); } /** * Obtains the boolean value, which specifies whether the currently * persisted value should be shown as the summary, instead of the given * summaries, from a specific typed array. * * @param typedArray * The typed array, the boolean value should be obtained from, as * an instance of the class {@link TypedArray} */ private void obtainShowValueAsSummary(final TypedArray typedArray) { boolean defaultValue = getContext().getResources() .getBoolean(R.bool.dialog_preference_default_show_value_as_summary); showValueAsSummary( typedArray.getBoolean(R.styleable.AbstractDialogPreference_showValueAsSummary, defaultValue)); } /** * Shows the preference's dialog. * * @param dialogState * The dialog's saved state as an instance of the class * {@link Bundle} or null, if the dialog should be created from * scratch */ private void showDialog(final Bundle dialogState) { MaterialDialogBuilder dialogBuilder = new MaterialDialogBuilder(getContext()); dialogBuilder.setTitle(getDialogTitle()); dialogBuilder.setMessage(getDialogMessage()); dialogBuilder.setIcon(getDialogIcon()); dialogBuilder.setPositiveButton(getPositiveButtonText(), this); dialogBuilder.setNegativeButton(getNegativeButtonText(), this); dialogBuilder.setTitleColor(getDialogTitleColor()); dialogBuilder.setButtonTextColor(getDialogButtonTextColor()); onPrepareDialog(dialogBuilder); dialog = dialogBuilder.create(); dialog.setOnDismissListener(this); if (dialogState != null) { dialog.onRestoreInstanceState(dialogState); } requestInputMode(); dialogResultPositive = false; dialog.show(); } /** * Requests the soft input method to be shown. */ private void requestInputMode() { if (needInputMethod()) { Window window = dialog.getWindow(); window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } /** * The method, which is invoked on subclasses to determine, whether the soft * input mode should be requested when the preference's dialog becomes * shown, or not. * * @return True, if the soft input mode should be requested when the * preference's dialog becomes shown, false otherwise */ protected abstract boolean needInputMethod(); /** * The method, which is invoked on subclasses when the preference's dialog * is about to be created. The builder, which is passed as a method * parameter may be manipulated by subclasses in order to change the * appearance of the dialog. * * @param dialogBuilder * The builder, which is used to create the preference's dialog, * as an instance of the class {@link MaterialDialogBuilder} */ protected abstract void onPrepareDialog(MaterialDialogBuilder dialogBuilder); /** * The method, which is invoked on subclasses when the preference's dialog * has been closed. This method may be used within subclasses to evaluate * the changes, which have been made while the dialog was shown. * * @param positiveResult * True, if the dialog has been close affirmatively, false * otherwise */ protected abstract void onDialogClosed(final boolean positiveResult); /** * Creates a new preference, which will show a dialog when clicked by the * user. * * @param context * The context, which should be used by the preference, as an * instance of the class {@link Context} */ public AbstractDialogPreference(final Context context) { this(context, null); } /** * Creates a new preference, which will show a dialog when clicked by the * user. * * @param context * The context, which should be used by the preference, as an * instance of the class {@link Context} * @param attributeSet * The attributes of the XML tag that is inflating the * preference, as an instance of the type {@link AttributeSet} */ public AbstractDialogPreference(final Context context, final AttributeSet attributeSet) { this(context, attributeSet, android.R.attr.dialogPreferenceStyle); } /** * Creates a new preference, which will show a dialog when clicked by the * user. * * @param context * The context, which should be used by the preference, as an * instance of the class {@link Context} * @param attributeSet * The attributes of the XML tag that is inflating the * preference, as an instance of the type {@link AttributeSet} * @param defaultStyle * The default style to apply to this preference. If 0, no style * will be applied (beyond what is included in the theme). This * may either be an attribute resource, whose value will be * retrieved from the current theme, or an explicit style * resource */ public AbstractDialogPreference(final Context context, final AttributeSet attributeSet, final int defaultStyle) { super(context, attributeSet, defaultStyle); obtainStyledAttributes(attributeSet); } /** * Creates a new preference, which will show a dialog when clicked by the * user. * * @param context * The context, which should be used by the preference, as an * instance of the class {@link Context} * @param attributeSet * The attributes of the XML tag that is inflating the * preference, as an instance of the type {@link AttributeSet} * @param defaultStyle * The default style to apply to this preference. If 0, no style * will be applied (beyond what is included in the theme). This * may either be an attribute resource, whose value will be * retrieved from the current theme, or an explicit style * resource * @param defaultStyleResource * A resource identifier of a style resource that supplies * default values for the preference, used only if the default * style is 0 or can not be found in the theme. Can be 0 to not * look for defaults */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public AbstractDialogPreference(final Context context, final AttributeSet attributeSet, final int defaultStyle, final int defaultStyleResource) { super(context, attributeSet, defaultStyle, defaultStyleResource); obtainStyledAttributes(attributeSet); } /** * Returns the dialog, which is shown by the preference. * * @return The dialog, which is shown by the preference, as an instance of * the class {@link Dialog} or null, if the dialog is currently not * shown */ public final Dialog getDialog() { if (isDialogShown()) { return dialog; } else { return null; } } /** * Returns, whether the preference's dialog is currently shown, or not. * * @return True, if the preference's dialog is currently shown, false * otherwise */ public final boolean isDialogShown() { return dialog != null && dialog.isShowing(); } /** * Returns the title of the preference's dialog. * * @return The title of the preference's dialog as an instance of the class * {@link CharSequence} or null, if the preference's title is used * instead */ public final CharSequence getDialogTitle() { return dialogTitle; } /** * Sets the title of the preference's dialog. * * @param dialogTitle * The title, which should be set, as an instance of the class * {@link CharSequence} or null, if the preference's title should * be used instead */ public final void setDialogTitle(final CharSequence dialogTitle) { this.dialogTitle = dialogTitle; } /** * Sets the title of the preference's dialog. * * @param resourceId * The resource id of the title, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource */ public final void setDialogTitle(final int resourceId) { setDialogTitle(getContext().getString(resourceId)); } /** * Returns the message of the preference's dialog. * * @return The message of the preference's dialog as an instance of the * class {@link CharSequence} or null, if no message is shown in the * dialog */ public final CharSequence getDialogMessage() { return dialogMessage; } /** * Sets the message of the preference's dialog. * * @param dialogMessage * The message, which should be set, as an instance of the class * {@link CharSequence} or null, if no message should be shown in * the dialog */ public final void setDialogMessage(final CharSequence dialogMessage) { this.dialogMessage = dialogMessage; } /** * Sets the message of the preference's dialog. * * @param resourceId * The resource id of the message, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource */ public final void setDialogMessage(final int resourceId) { setDialogMessage(getContext().getString(resourceId)); } /** * Returns the icon of the preference's dialog. * * @return The icon of the preference's dialog as an instance of the class * {@link Drawable} or null, if no icon is shown in the dialog */ public final Drawable getDialogIcon() { return dialogIcon; } /** * Sets the icon of the preference's dialog. * * @param dialogIcon * The dialog, which should be set, as an instance of the class * {@link Drawable} or null, if no icon should be shown in the * dialog */ public final void setDialogIcon(final Drawable dialogIcon) { this.dialogIcon = dialogIcon; } /** * Sets the icon of the preference's dialog. * * @param resourceId * The resource id of the icon, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid drawable resource */ @SuppressWarnings("deprecation") public final void setDialogIcon(final int resourceId) { dialogIcon = getContext().getResources().getDrawable(resourceId); } /** * Returns the text of the positive button of the preference's dialog. * * @return The text of the positive button as an instance of the class * {@link CharSequence} or null, if no positive button is shown in * the dialog */ public final CharSequence getPositiveButtonText() { return positiveButtonText; } /** * Sets the text of the positive button of the preference's dialog. * * @param positiveButtonText * The text, which should be set, as an instance of the class * {@link CharSequence} or null, if no positive button should be * shown in the dialog */ public final void setPositiveButtonText(final CharSequence positiveButtonText) { this.positiveButtonText = positiveButtonText; } /** * Sets the text of the positive button of the preference's dialog. * * @param resourceId * The resource id of the text, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource */ public final void setPositiveButtonText(final int resourceId) { setPositiveButtonText(getContext().getString(resourceId)); } /** * Returns the text of the negative button of the preference's dialog. * * @return The text of the negative button as an instance of the class * {@link CharSequence} or null, if no negative button is shown in * the dialog */ public final CharSequence getNegativeButtonText() { return negativeButtonText; } /** * Sets the text of the negative button of the preference's dialog. * * @param negativeButtonText * The text, which should be set, as an instance of the class * {@link CharSequence} or null, if no negative button should be * shown in the dialog */ public final void setNegativeButtonText(final CharSequence negativeButtonText) { this.negativeButtonText = negativeButtonText; } /** * Sets the text of the negative button of the preference's dialog. * * @param resourceId * The resource id of the text, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource */ public final void setNegativeButtonText(final int resourceId) { setNegativeButtonText(getContext().getString(resourceId)); } /** * Returns the color of the title of the preference's dialog. * * @return The color of the title as an {@link Integer} value or -1, if no * custom title color is set */ public final int getDialogTitleColor() { return dialogTitleColor; } /** * Sets the color of the title of the preference's dialog. * * @param color * The color, which should be set, as an {@link Integer} value or * -1, if no custom title should be set */ public final void setDialogTitleColor(final int color) { this.dialogTitleColor = color; } /** * Returns the color of the button text of the preference's dialog. * * @return The color of the button text as an {@link Integer} value or -1, * if no custom text color is set */ public final int getDialogButtonTextColor() { return dialogButtonTextColor; } /** * Sets the color of the button text of the preference's dialog. * * @param color * The color, which should be set, as an {@link Integer} value or * -1, if no custom text color should be set */ public final void setDialogButtonTextColor(final int color) { this.dialogButtonTextColor = color; } /** * Returns, whether the currently persisted value is shown instead of the * summary, or not. * * @return True, if the currently persisted value is shown instead of the * summary, false otherwise */ public final boolean isValueShownAsSummary() { return showValueAsSummary; } /** * Sets, whether the currently persisted value should be shown instead of * the summary, or not. * * @param showValueAsSummary * True, if the currently persisted value should be shown instead * of the summary, false otherwise */ public final void showValueAsSummary(final boolean showValueAsSummary) { this.showValueAsSummary = showValueAsSummary; } @Override public final void onClick(final DialogInterface dialog, final int which) { dialogResultPositive = (which == Dialog.BUTTON_POSITIVE); } @Override public final void onDismiss(final DialogInterface dialog) { this.dialog = null; onDialogClosed(dialogResultPositive); } @Override protected final void onClick() { if (!isDialogShown()) { showDialog(null); } } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.dialogShown = isDialogShown(); if (isDialogShown()) { savedState.dialogState = dialog.onSaveInstanceState(); dialog.dismiss(); dialog = null; } return savedState; } @Override protected void onRestoreInstanceState(final Parcelable state) { if (state != null && state instanceof SavedState) { SavedState savedState = (SavedState) state; if (savedState.dialogShown) { showDialog(savedState.dialogState); } super.onRestoreInstanceState(savedState.getSuperState()); } else { super.onRestoreInstanceState(state); } } }
package edu.afs.subsystems.autoranger; import edu.wpi.first.wpilibj.command.PIDSubsystem; import edu.wpi.first.wpilibj.AnalogChannel; import edu.afs.robot.RobotMap; import edu.afs.subsystems.drivesubsystem.DrivePIDSubsystem; /** * * @author User */ public class AutoRangerPIDSubsystem extends PIDSubsystem { // PID tuning parameters //TODO: Pick tuning parameters. private static final double K_PROPORTIONAL = 1.0; private static final double K_INTEGRAL = 0.0; private static final double K_DERIVATIVE = 0.0; private static final double ABSOLUE_RANGER_TOLERANCE = 6.0; // In inches. private static final double MAX_ULTRASONIC_RANGER_VOLTAGE = 10.0; private static final double MIN_ULTRASONIC_RANGER_VOLTAGE = -10.0; private double m_autoRangeOutput; private AnalogChannel m_ultraSonicRanger; private double m_autoRangeSetPoint; private RangeBeacon m_rangeBeacon; // Implement Singleton design pattern. There // can be only one instance of this subsystem. private static AutoRangerPIDSubsystem instance = null; public static AutoRangerPIDSubsystem getInstance () { if (instance == null) { instance = new AutoRangerPIDSubsystem(); } return instance; } // Constructor is private to enforce Singelton. private AutoRangerPIDSubsystem() { super("autoRangerPIDSubsystem", K_PROPORTIONAL, K_INTEGRAL, K_DERIVATIVE); getPIDController().disable(); m_autoRangeOutput = 0.0; m_autoRangeSetPoint = 0.0; m_ultraSonicRanger = new AnalogChannel (RobotMap.ULTRASONIC_RANGER_CHANNEL); m_rangeBeacon = RangeBeacon.getInstance(); // Set beacon to indicate AUTO_RANGE_DISABLED m_rangeBeacon.setRangeBeaconState(RangeBeaconState.AUTO_RANGE_DISABLED); } public void initAutoRanger(){ // Add Ultrasonic Ranger and PID set-up code. // TODO: Determine correct tolerance for "close enough" to set point. getPIDController().setAbsoluteTolerance(ABSOLUE_RANGER_TOLERANCE); // Input range is not continuous. getPIDController().setContinuous(false); //TODO: Verify output range from US Ranger (-10.0 to 10.0 volts?????) getPIDController().setInputRange(MIN_ULTRASONIC_RANGER_VOLTAGE, MAX_ULTRASONIC_RANGER_VOLTAGE); // Set output range to match Drive. getPIDController().setOutputRange(DrivePIDSubsystem.DRIVE_MIN_INPUT, DrivePIDSubsystem.DRIVE_MAX_INPUT); // Establish set point for auto-ranging. // Assume that bot is oriented perpendicular to 10-point goal. //TODO: Verify that this makes sense given PID input range/units. getPIDController().setSetpoint(m_autoRangeSetPoint); getPIDController().enable(); // Set beacon to AUTO_RANGE_ENABLED. m_rangeBeacon.setRangeBeaconState(RangeBeaconState.AUTO_RANGE_ENABLED); } public void disableAutoRanger(){ getPIDController().reset(); getPIDController().disable(); // Set beacon to AUTO_RANGE_DISABLED. m_rangeBeacon.setRangeBeaconState (RangeBeaconState.AUTO_RANGE_DISABLED); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public double getAutoRangerOutput(){ return m_autoRangeOutput; } //TODO: Make sure that units and range of values make sense for PID inputs // and outputs!!!!!!!!!!!!!! // Called every 20 ms by PID Controller. protected double returnPIDInput() { // Return your input value for the PID loop // e.g. a sensor, like a potentiometer: // yourPot.getAverageVoltage() / kYourMaxVoltage; return (m_ultraSonicRanger.getAverageVoltage()/ MAX_ULTRASONIC_RANGER_VOLTAGE); } //TODO: Make sure that units and range of values make sense for PID inputs // and outputs!!!!!!!!!!!!!! // Called every 20 ms by PID Controller. protected void usePIDOutput(double output) { // Use output to drive your system. m_autoRangeOutput = output; } public double GetRange(){ //TODO: Verify return is range in TBD units. return (m_ultraSonicRanger.getAverageVoltage()/ MAX_ULTRASONIC_RANGER_VOLTAGE); } }
package se.fnord.katydid.examples; import java.nio.ByteBuffer; import static se.fnord.katydid.DataTesters.*; import org.junit.Test; import se.fnord.katydid.DataAsserts; import se.fnord.katydid.DataTester; public class TestDiameter { private static int AVP_SIZE = 8; private static int AVP_VENDOR_SIZE = 12; private static final int HEADER_SIZE = 20; private static int REQ = 0x80; private static int PXY = 0x40; private static int V = 0x80; private static int M = 0x40; private static final String SESSION_ID = "pcef1.fnord.se;0;0"; private static final String ORIGIN_HOST = "pcef1.fnord.se"; private static final String REALM = "fnord.se"; private DataTester padFor(int length) { switch (length & 3) { case 0: return zero("pad", 0); case 1: return zero("pad", 3); case 2: return zero("pad", 2); case 3: return zero("pad", 1); } throw new IllegalStateException(Integer.toString(length)); } private DataTester commandHeader(int flags, int code, int application, int avpLength) { return struct("commandHeader", u8("version", 1), defer(u24("length", avpLength + HEADER_SIZE)), // Check the message length field after all other values have been checked. u8("flags", flags), u24("commandCode", code), u32("application", application), skip("hopByHop", 4), // Skip validation of Hop-By-Hop and End-To-End values skip("endToEnd", 4)); } private DataTester avpHead(int vendorId, int code, int flags, int valueLength) { if (vendorId > 0) return struct("avpHead", u32("code", code), u8("flags", flags), u24("length", valueLength + AVP_VENDOR_SIZE), u32("vendorId", vendorId)); return struct("avpHead", u32("code", code), u8("flags", flags), u24("length", valueLength + AVP_SIZE)); } protected DataTester avp(String name, int vendorId, int code, int flags, DataTester value) { return struct(name, avpHead(vendorId, code, flags, value.length()), value, padFor(value.length())); } protected DataTester command(String name, int flags, int app, int code, DataTester ...avps) { DataTester avpList = struct("avps", avps); return struct(name, commandHeader(flags, code, app, avpList.length()), avpList ); } @Test(expected = AssertionError.class) public void failingCCRTest() { DataTester correctClassCode = command("Credit-Control", PXY | REQ, 4, 272, avp("Session-Id", 0, 263, M, utf8(SESSION_ID)), avp("Origin-Host", 0, 264, M, utf8(ORIGIN_HOST)), avp("Origin-Realm", 0, 296, M, utf8(REALM)), avp("Destination-Realm", 0, 293, M, utf8(REALM)), avp("Auth-Application-Id", 0, 259, M, u32(0)), avp("Service-Context-Id", 0, 461, M, utf8("6.32260@3gpp.org")), avp("CC-Request-Type", 0, 416, M, u32(1)), avp("CC-Request-Number", 0, 415, M, u32(0)), avp("Class", 0, 25, M, utf8("class")) ); DataTester incorrectClassCode = command("Credit-Control", PXY | REQ, 4, 272, avp("Session-Id", 0, 263, M, utf8(SESSION_ID)), avp("Origin-Host", 0, 264, M, utf8(ORIGIN_HOST)), avp("Origin-Realm", 0, 296, M, utf8(REALM)), avp("Destination-Realm", 0, 293, M, utf8(REALM)), avp("Auth-Application-Id", 0, 259, M, u32(0)), avp("Service-Context-Id", 0, 461, M, utf8("6.32260@3gpp.org")), avp("CC-Request-Type", 0, 416, M, u32(1)), avp("CC-Request-Number", 0, 415, M, u32(0)), avp("Class", 0, 26, M, utf8("class")) ); ByteBuffer buffer = ByteBuffer.allocate(incorrectClassCode.length()); incorrectClassCode.toBuffer(buffer); buffer.flip(); DataAsserts.assertExact(correctClassCode, buffer); } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import java.awt.*; import java.awt.event.*; import javax.swing.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; /** * Wizard step to choose run mode * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class ModeSelectionPanel extends JPanel { private JRadioButton unannotatedXmiOption, roundtripOption, annotateOption, reviewOption, curateOption; private ButtonGroup group; private JPanel _this = this; private UserSelections userSelections = UserSelections.getInstance(); private UserPreferences prefs = UserPreferences.getInstance(); private JCheckBox privateApiCb = new JCheckBox("Use Private API", prefs.isUsePrivateApi()); public ModeSelectionPanel() { initUI(); } public void addActionListener(ActionListener l) { unannotatedXmiOption.addActionListener(l); roundtripOption.addActionListener(l); annotateOption.addActionListener(l); curateOption.addActionListener(l); reviewOption.addActionListener(l); } public String getSelection() { return group.getSelection().getActionCommand(); } public boolean usePrivateApi() { return privateApiCb.isSelected(); } private void initUI() { this.setLayout(new BorderLayout()); JPanel infoPanel = new JPanel(); infoPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); infoPanel.setBackground(Color.WHITE); infoPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); infoPanel.add(new JLabel(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("siw-logo3_2.gif")))); JLabel infoLabel = new JLabel("<html>Welcome to the Semantic Integration Workbench</html>"); infoPanel.add(infoLabel); this.add(infoPanel, BorderLayout.NORTH); group = new ButtonGroup(); unannotatedXmiOption = new JRadioButton("Review un-annotated XMI File"); unannotatedXmiOption.setActionCommand(RunMode.UnannotatedXmi.toString()); roundtripOption = new JRadioButton("Perform XMI Roundtrip"); roundtripOption.setActionCommand(RunMode.Roundtrip.toString()); annotateOption = new JRadioButton("Run Semantic Connector"); annotateOption.setActionCommand(RunMode.GenerateReport.toString()); reviewOption = new JRadioButton("Review Annotated Model"); reviewOption.setActionCommand(RunMode.Reviewer.toString()); curateOption = new JRadioButton("Curate XMI File"); curateOption.setActionCommand(RunMode.Curator.toString()); if(prefs.getModeSelection() == null) unannotatedXmiOption.setSelected(true); else if(prefs.getModeSelection().equals(RunMode.AnnotateXMI.toString())) reviewOption.setSelected(true); else if(prefs.getModeSelection().equals(RunMode.Curator.toString())) curateOption.setSelected(true); else if(prefs.getModeSelection().equals(RunMode.Roundtrip.toString())) reviewOption.setSelected(true); else if(prefs.getModeSelection().equals(RunMode.Reviewer.toString())) reviewOption.setSelected(true); else unannotatedXmiOption.setSelected(true); group.add(unannotatedXmiOption); group.add(roundtripOption); group.add(annotateOption); group.add(curateOption); group.add(reviewOption); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(0, 1)); buttonPanel.add (new JLabel("<html>Choose from the following SIW Options:</html>")); buttonPanel.add(unannotatedXmiOption); buttonPanel.add(roundtripOption); buttonPanel.add(annotateOption); buttonPanel.add(curateOption); buttonPanel.add(reviewOption); this.setLayout(new BorderLayout()); this.add(infoPanel, BorderLayout.NORTH); this.add(buttonPanel, BorderLayout.CENTER); Font font = new Font("Serif", Font.PLAIN, 11); privateApiCb.setFont(font); JLabel privateApiLabel = new JLabel("<html><body>The private API is offered as an alternative to the caCORE public API.<br> It requires that the user be inside the NCI network or use VPN.</body></html>"); privateApiLabel.setFont(font); JPanel privateApiPanel = new JPanel(); privateApiPanel.setLayout(new FlowLayout()); privateApiPanel.add(privateApiCb); privateApiPanel.add(privateApiLabel); this.add(privateApiPanel, BorderLayout.SOUTH); } private void insertInBag(JPanel bagComp, Component comp, int x, int y) { insertInBag(bagComp, comp, x, y, 1, 1); } private void insertInBag(JPanel bagComp, Component comp, int x, int y, int width, int height) { JPanel p = new JPanel(); p.add(comp); bagComp.add(p, new GridBagConstraints(x, y, width, height, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); } public static void main(String[] args) { JFrame frame = new JFrame("Prototype"); frame.getContentPane().add(new ModeSelectionPanel()); frame.setVisible(true); } }
// $Id: DropBoardView.java,v 1.9 2004/10/21 18:07:37 mdb Exp $ // Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.puzzle.drop.client; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.util.Iterator; import com.threerings.media.image.Mirage; import com.threerings.media.sprite.ImageSprite; import com.threerings.media.sprite.PathAdapter; import com.threerings.media.sprite.Sprite; import com.threerings.media.util.LinePath; import com.threerings.media.util.Path; import com.threerings.puzzle.Log; import com.threerings.puzzle.client.PuzzleBoardView; import com.threerings.puzzle.client.ScoreAnimation; import com.threerings.puzzle.data.Board; import com.threerings.puzzle.data.PuzzleConfig; import com.threerings.puzzle.util.PuzzleContext; import com.threerings.puzzle.drop.data.DropBoard; import com.threerings.puzzle.drop.data.DropConfig; import com.threerings.puzzle.drop.data.DropPieceCodes; /** * The drop board view displays a drop puzzle game in progress for a * single player. */ public abstract class DropBoardView extends PuzzleBoardView implements DropPieceCodes { /** The color used to render normal scoring text. */ public static final Color SCORE_COLOR = Color.white; /** The color used to render chain reward scoring text. */ public static final Color CHAIN_COLOR = Color.yellow; /** * Constructs a drop board view. */ public DropBoardView (PuzzleContext ctx, int pwid, int phei) { super(ctx); // save off piece dimensions _pwid = pwid; _phei = phei; // determine distance to float score animations _scoreDist = 2 * _phei; } /** * Initializes the board with the board dimensions. */ public void init (PuzzleConfig config) { DropConfig dconfig = (DropConfig)config; // save off the board dimensions in pieces _bwid = dconfig.getBoardWidth(); _bhei = dconfig.getBoardHeight(); super.init(config); } /** * Returns the width in pixels of a single board piece. */ public int getPieceWidth () { return _pwid; } /** * Returns the height in pixels of a single board piece. */ public int getPieceHeight () { return _phei; } /** * Called by the {@link DropSprite} to populate <code>pos</code> with * the screen coordinates in pixels at which a piece at <code>(col, * row)</code> in the board should be drawn. Derived classes may wish * to override this method to allow specialised positioning of * sprites. */ public void getPiecePosition (int col, int row, Point pos) { pos.setLocation(col * _pwid, (row * _phei) - _roff); } /** * Called by the {@link DropSprite} to get the dimensions of the area * that will be occupied by rendering a piece segment of the given * orientation and length whose bottom-leftmost corner is at * <code>(col, row)</code>. */ public Dimension getPieceSegmentSize (int col, int row, int orient, int len) { if (orient == NORTH || orient == SOUTH) { return new Dimension(_pwid, len * _phei); } else { return new Dimension(len * _pwid, _phei); } } /** * Creates a new piece sprite and places it directly in it's correct * position. */ public void createPiece (int piece, int sx, int sy) { if (sx < 0 || sy < 0 || sx >= _bwid || sy >= _bhei) { Log.warning("Requested to create piece in invalid location " + "[sx=" + sx + ", sy=" + sy + "]."); Thread.dumpStack(); return; } createPiece(piece, sx, sy, sx, sy, 0L); } /** * Refreshes the piece sprite at the specified location, if no sprite * exists at the location, one will be created. <em>Note:</em> this * method assumes the default {@link ImageSprite} is being used to * display pieces. If {@link #createPieceSprite} is overridden to * return a non-ImageSprite, this method must also be customized. */ public void updatePiece (int sx, int sy) { updatePiece(_dboard.getPiece(sx, sy), sx, sy); } /** * Updates the piece sprite at the specified location, if no sprite * exists at the location, one will be created. <em>Note:</em> this * method assumes the default {@link ImageSprite} is being used to * display pieces. If {@link #createPieceSprite} is overridden to * return a non-ImageSprite, this method must also be customized. */ public void updatePiece (int piece, int sx, int sy) { if (sx < 0 || sy < 0 || sx >= _bwid || sy >= _bhei) { Log.warning("Requested to update piece in invalid location " + "[sx=" + sx + ", sy=" + sy + "]."); Thread.dumpStack(); return; } int spos = sy * _bwid + sx; if (_pieces[spos] != null) { ((ImageSprite)_pieces[spos]).setMirage( getPieceImage(piece, sx, sy, NORTH)); } else { createPiece(piece, sx, sy); } } /** * Creates a new piece sprite and moves it into position on the board. */ public void createPiece (int piece, int sx, int sy, int tx, int ty, long duration) { if (tx < 0 || ty < 0 || tx >= _bwid || ty >= _bhei) { Log.warning("Requested to create and move piece to invalid " + "location [tx=" + tx + ", ty=" + ty + "]."); Thread.dumpStack(); return; } Sprite sprite = createPieceSprite(piece, sx, sy); if (sprite != null) { // position the piece properly to start Point start = new Point(); getPiecePosition(sx, sy, start); sprite.setLocation(start.x, start.y); // now add it to the view addSprite(sprite); // and potentially move it into place movePiece(sprite, sx, sy, tx, ty, duration); } } /** * Instructs the view to move the piece at the specified starting * position to the specified destination position. There must be a * sprite at the starting position, if there is a sprite at the * destination position, it must also be moved immediately following * this call (as in the case of a swap) to avoid badness. * * @return the piece sprite that is being moved. */ public Sprite movePiece (int sx, int sy, int tx, int ty, long duration) { int spos = sy * _bwid + sx; Sprite piece = _pieces[spos]; if (piece == null) { Log.warning("Missing source sprite for drop [sx=" + sx + ", sy=" + sy + ", tx=" + tx + ", ty=" + ty + "]."); return null; } _pieces[spos] = null; movePiece(piece, sx, sy, tx, ty, duration); return piece; } /** * A helper function for moving pieces into place. */ protected void movePiece (Sprite piece, final int sx, final int sy, final int tx, final int ty, long duration) { final Exception where = new Exception(); // if the sprite needn't move, then just position it and be done Point start = new Point(); getPiecePosition(sx, sy, start); if (sx == tx && sy == ty) { int tpos = ty * _bwid + tx; if (_pieces[tpos] != null) { Log.warning("Zoiks! Asked to add a piece where we already " + "have one [sx=" + sx + ", sy=" + sy + ", tx=" + tx + ", ty=" + ty + "]."); Log.logStackTrace(where); return; } _pieces[tpos] = piece; piece.setLocation(start.x, start.y); return; } // note that this piece is moving toward its destination final int tpos = ty * _bwid + tx; _moving[tpos] = true; // then create a path and do some bits Point end = new Point(); getPiecePosition(tx, ty, end); piece.addSpriteObserver(new PathAdapter() { public void pathCompleted (Sprite sprite, Path path, long when) { sprite.removeSpriteObserver(this); if (_pieces[tpos] != null) { Log.warning("Oh god, we're dropping onto another piece " + "[sx=" + sx + ", sy=" + sy + ", tx=" + tx + ", ty=" + ty + "]."); Log.logStackTrace(where); return; } _pieces[tpos] = sprite; if (_actionSprites.remove(sprite)) { maybeFireCleared(); } pieceArrived(when, sprite, tx, ty); } }); _actionSprites.add(piece); piece.move(new LinePath(start, end, duration)); } /** * Called when a piece is finished moving into its requested position. * Derived classes may wish to take this opportunity to play a sound * or whatnot. */ protected void pieceArrived (long tickStamp, Sprite sprite, int px, int py) { _moving[py * _bwid + px] = false; } /** * Returns true if the piece that is supposed to be at the specified * coordinates is not yet there but is actually en route to that * location (due to a call to {@link #movePIece}). */ protected boolean isMoving (int px, int py) { return _moving[py * _bwid + px]; } /** * Returns the image used to display the given piece at coordinates * <code>(0, 0)</code> with an orientation of {@link #NORTH}. This * serves as a convenience routine for those puzzles that don't bother * rendering their pieces differently when placed at different board * coordinates or in different orientations. */ public Mirage getPieceImage (int piece) { return getPieceImage(piece, 0, 0, NORTH); } /** * Returns the image used to display the given piece at the specified * column and row with the given orientation. */ public abstract Mirage getPieceImage ( int piece, int col, int row, int orient); // documentation inherited public void setBoard (Board board) { // when a new board arrives, we want to remove all drop sprites // so that they don't modify the new board with their old ideas for (Iterator iter = _actionSprites.iterator(); iter.hasNext(); ) { Sprite s = (Sprite) iter.next(); if (s instanceof DropSprite) { // remove it from _sprites safely iter.remove(); // but then use the standard removal method removeSprite(s); } } // remove all of this board's piece sprites int pcount = (_pieces == null) ? 0 : _pieces.length; for (int ii = 0; ii < pcount; ii++) { if (_pieces[ii] != null) { removeSprite(_pieces[ii]); } } super.setBoard(board); _dboard = (DropBoard)board; // create the pieces for the new board Point spos = new Point(); int width = _dboard.getWidth(), height = _dboard.getHeight(); _pieces = new Sprite[width * height]; for (int yy = 0; yy < height; yy++) { for (int xx = 0; xx < width; xx++) { Sprite piece = createPieceSprite( _dboard.getPiece(xx, yy), xx, yy); if (piece != null) { int ppos = yy * width + xx; getPiecePosition(xx, yy, spos); piece.setLocation(spos.x, spos.y); addSprite(piece); _pieces[ppos] = piece; } } } // we use this to track when pieces are animating toward their new // position and are not yet in place _moving = new boolean[width * height]; } /** * Returns the piece sprite at the specified location. */ public Sprite getPieceSprite (int xx, int yy) { return _pieces[yy * _dboard.getWidth() + xx]; } /** * Clears the specified piece from the board. */ public void clearPieceSprite (int xx, int yy) { int ppos = yy * _dboard.getWidth() + xx; if (_pieces[ppos] != null) { removeSprite(_pieces[ppos]); _pieces[ppos] = null; } } /** * Clears out a piece from the board along with its piece sprite. */ public void clearPiece (int xx, int yy) { _dboard.setPiece(xx, yy, PIECE_NONE); clearPieceSprite(xx, yy); } /** * Creates a new drop sprite used to animate the given pieces falling * in the specified column. */ public DropSprite createPieces (int col, int row, int[] pieces, int dist) { return new DropSprite(this, col, row, pieces, dist); } /** * Dirties the rectangle encompassing the segment with the given * direction and length whose bottom-leftmost corner is at <code>(col, * row)</code>. */ public void dirtySegment (int dir, int col, int row, int len) { int x = _pwid * col, y = (_phei * row) - _roff; int wid = (dir == VERTICAL) ? _pwid : len * _pwid; int hei = (dir == VERTICAL) ? _phei * len : _phei; _remgr.invalidateRegion(x, y, wid, hei); } /** * Creates and returns an animation which makes use of a label sprite * that is assigned a path that floats it a short distance up the * view, with the label initially centered within the view. * * @param score the score text to display. * @param color the color of the text. */ public ScoreAnimation createScoreAnimation (String score, Color color) { return createScoreAnimation( score, color, MEDIUM_FONT_SIZE, 0, _bhei - 1, _bwid, _bhei); } /** * Creates and returns an animation showing the specified score * floating up the view, with the label initially centered within the * view. * * @param score the score text to display. * @param color the color of the text. * @param fontSize the size of the text; a value between 0 and {@link * #getPuzzleFontSizeCount} - 1. */ public ScoreAnimation createScoreAnimation ( String score, Color color, int fontSize) { return createScoreAnimation( score, color, fontSize, 0, _bhei - 1, _bwid, _bhei); } /** * Creates and returns an animation showing the specified score * floating up the view. * * @param score the score text to display. * @param color the color of the text. * @param x the left coordinate in board coordinates of the rectangle * within which the score is to be centered. * @param y the bottom coordinate in board coordinates of the * rectangle within which the score is to be centered. * @param width the width in board coordinates of the rectangle within * which the score is to be centered. * @param height the height in board coordinates of the rectangle * within which the score is to be centered. */ public ScoreAnimation createScoreAnimation ( String score, Color color, int x, int y, int width, int height) { return createScoreAnimation( score, color, MEDIUM_FONT_SIZE, x, y, width, height); } /** * Creates and returns an animation showing the specified score * floating up the view. * * @param score the score text to display. * @param color the color of the text. * @param fontSize the size of the text; a value between 0 and {@link * #getPuzzleFontSizeCount} - 1. * @param x the left coordinate in board coordinates of the rectangle * within which the score is to be centered. * @param y the bottom coordinate in board coordinates of the * rectangle within which the score is to be centered. * @param width the width in board coordinates of the rectangle within * which the score is to be centered. * @param height the height in board coordinates of the rectangle * within which the score is to be centered. */ public ScoreAnimation createScoreAnimation (String score, Color color, int fontSize, int x, int y, int width, int height) { // create the score animation ScoreAnimation anim = createScoreAnimation(score, color, fontSize, x, y); // position the label within the specified rectangle Dimension lsize = anim.getLabel().getSize(); Point pos = new Point(); centerRectInBoardRect( x, y, width, height, lsize.width, lsize.height, pos); anim.setLocation(pos.x, pos.y); return anim; } /** * Creates the sprite that is used to display the specified piece. If * the piece represents no piece, this method should return null. */ protected Sprite createPieceSprite (int piece, int px, int py) { if (piece == PIECE_NONE) { return null; } ImageSprite sprite = new ImageSprite( getPieceImage(piece, px, py, NORTH)); sprite.setRenderOrder(-1); return sprite; } /** * Populates <code>pos</code> with the most appropriate screen * coordinates to center a rectangle of the given width and height (in * pixels) within the specified rectangle (in board coordinates). * * @param bx the bounding rectangle's left board coordinate. * @param by the bounding rectangle's bottom board coordinate. * @param bwid the bounding rectangle's width in board coordinates. * @param bhei the bounding rectangle's height in board coordinates. * @param rwid the width of the rectangle to position in pixels. * @param rhei the height of the rectangle to position in pixels. * @param pos the point to populate with the rectangle's final * position. */ protected void centerRectInBoardRect ( int bx, int by, int bwid, int bhei, int rwid, int rhei, Point pos) { getPiecePosition(bx, by + 1, pos); pos.x += (((bwid * _pwid) - rwid) / 2); pos.y -= ((((bhei * _phei) - rhei) / 2) + rhei); // constrain to fit wholly within the board bounds pos.x = Math.max(Math.min(pos.x, _bounds.width - rwid), 0); } /** * Rotates the given drop block sprite to the specified orientation, * updating the image as necessary. Derived classes that make use of * block dropping functionality should override this method to do the * right thing. */ public void rotateDropBlock (DropBlockSprite sprite, int orient) { // nothing for now } // documentation inherited public void paintBetween (Graphics2D gfx, Rectangle dirtyRect) { gfx.translate(0, -_roff); renderBoard(gfx, dirtyRect); renderRisingPieces(gfx, dirtyRect); gfx.translate(0, _roff); } // documentation inherited public Dimension getPreferredSize () { int wid = _bwid * _pwid; int hei = _bhei * _phei; return new Dimension(wid, hei); } /** * Renders the row of rising pieces to the given graphics context. * Sub-classes that make use of board rising functionality should * override this method to draw the rising piece row. */ protected void renderRisingPieces (Graphics2D gfx, Rectangle dirtyRect) { // nothing for now } /** * Sets the board rising offset to the given y-position. */ protected void setRiseOffset (int y) { if (y != _roff) { _roff = y; _remgr.invalidateRegion(_bounds); } } /** The drop board. */ protected DropBoard _dboard; /** A sprite for every piece displayed in the drop board. */ protected Sprite[] _pieces; /** Indicates whether a piece is en route to its destination. */ protected boolean[] _moving; /** The piece dimensions in pixels. */ protected int _pwid, _phei; /** The board rising offset. */ protected int _roff; /** The board dimensions in pieces. */ protected int _bwid, _bhei; }
package fr.paris.lutece.util.datatable; import fr.paris.lutece.portal.service.util.AppLogService; import fr.paris.lutece.portal.web.constants.Parameters; import fr.paris.lutece.portal.web.util.LocalizedDelegatePaginator; import fr.paris.lutece.portal.web.util.LocalizedPaginator; import fr.paris.lutece.util.ReferenceList; import fr.paris.lutece.util.html.IPaginator; import fr.paris.lutece.util.html.Paginator; import fr.paris.lutece.util.sort.AttributeComparator; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.lang.StringUtils; /** * Class to manage data tables with freemarker macros * @param <T> Type of data to display */ public class DataTableManager<T> { private static final String CONSTANT_GET = "get"; private static final String CONSTANT_IS = "is"; private String _strSortUrl; private List<DataTableColumn> _listColumn = new ArrayList<DataTableColumn>( ); private FilterPanel _filterPanel; private IPaginator<T> _paginator; private String _strCurrentPageIndex = StringUtils.EMPTY; private int _nItemsPerPage; private int _nDefautlItemsPerPage; private boolean _bEnablePaginator; private Locale _locale; private String _strSortedAttributeName; private boolean _bIsAscSort; /** * Private constructor */ protected DataTableManager( ) { } /** * Constructor of the DataTableManager class * @param strSortUrl URL used by the paginator and to sort data * @param strFilterUrl URL used to filter data * @param nDefautlItemsPerPage Default number of items to display per page * @param bEnablePaginator True to enable pagination, false to disable it */ public DataTableManager( String strSortUrl, String strFilterUrl, int nDefautlItemsPerPage, boolean bEnablePaginator ) { _strSortUrl = strSortUrl; _filterPanel = new FilterPanel( strFilterUrl ); _nDefautlItemsPerPage = nDefautlItemsPerPage; _bEnablePaginator = bEnablePaginator; } /** * Add a column to this DataTableManager * @param strColumnTitle I18n key of the title of the column * @param strObjectName Name of the property of objects that should be displayed in this column.<br /> * For example, if a class "Data" contains a property named "title", then the value of the parameter <i>strObjectName</i> should be "title". * @param bSortable True if the column is sortable, false otherwise */ public void addColumn( String strColumnTitle, String strObjectName, boolean bSortable ) { _listColumn.add( new DataTableColumn( strColumnTitle, strObjectName, bSortable, DataTableColumnType.STRING ) ); } /** * Add a label column to this DataTableManager. Values of cells of this column will be interpreted as i18n keys. * @param strColumnTitle I18n key of the title of the column * @param strObjectName Name of the property of objects that should be displayed in this column. This properties must be i18n keys.<br /> * For example, if a class "Data" contains a property named "title", then the value of the parameter <i>strObjectName</i> should be "title". * @param bSortable True if the column is sortable, false otherwise */ public void addLabelColumn( String strColumnTitle, String strObjectName, boolean bSortable ) { _listColumn.add( new DataTableColumn( strColumnTitle, strObjectName, bSortable, DataTableColumnType.LABEL ) ); } /** * Add an column to this DataTableManager that will display actions on items. Actions are usually parameterized links. A DataTableManager can only have 1 action column. The content of the action * column must be generated by a macro.this macro must have one parameter named "item", and its name must be given to the macro <i>@tableData</i>. * @param strColumnTitle I18n key of the title of the column */ public void addActionColumn( String strColumnTitle ) { _listColumn.add( new DataTableColumn( strColumnTitle, null, false, DataTableColumnType.ACTION ) ); } /** * Add a column to this DataTableManager * @param strColumnTitle I18n key of the title of the column * @param strObjectName Name of the property of objects that should be displayed in this column.<br /> * For example, if a class "Data" contains a property named "title", then the value of the parameter <i>strObjectName</i> should be "title". * @param strLabelTrue I18n key of the label to display when the value is true * @param strLabelFalse I18n key of the label to display when the value is false */ public void addBooleanColumn( String strColumnTitle, String strObjectName, String strLabelTrue, String strLabelFalse ) { _listColumn.add( new DataTableColumn( strColumnTitle, strObjectName, false, DataTableColumnType.BOOLEAN, strLabelTrue, strLabelFalse ) ); } /** * Add a free column to this DataTableManager. The content of this column must be generated by a macro. The macro must have one parameter named "item". * @param strColumnTitle I18n key of the title of the column * @param strFreemarkerMacroName Name of the freemarker macro that will display the content of the column.<br /> * The macro must have a single parameter named <i>item</i> of type T that will contain the object associated with a row of the table. */ public void addFreeColumn( String strColumnTitle, String strFreemarkerMacroName ) { _listColumn.add( new DataTableColumn( strColumnTitle, strFreemarkerMacroName, false, DataTableColumnType.ACTION ) ); } /** * Add an email column to this DataTableManager. Displayed cell will be a "mailto:" link. * @param strColumnTitle I18n key of the title of the column * @param strObjectName Name of the property of objects that should be displayed in this column.<br /> * For example, if a class "Data" contains a property named "title", then the value of the parameter <i>strObjectName</i> should be "title". * @param bSortable True if the column is sortable, false otherwise */ public void addEmailColumn( String strColumnTitle, String strObjectName, boolean bSortable ) { _listColumn.add( new DataTableColumn( strColumnTitle, strObjectName, bSortable, DataTableColumnType.EMAIL ) ); } /** * Add a filter to the filter panel of this DataTableManager * @param filterType data type of the filter. For drop down list, use {@link DataTableManager#addDropDownListFilter(String, String, ReferenceList) addDropDownListFilter} instead * @param strParameterName Name of the parameter of the object to filter.<br/> * For example, if this filter should be applied on the parameter "title" of a class named "Data", then the value of the parameter <i>strParameterName</i> should be "title". * @param strFilterLabel Label describing the filter */ public void addFilter( DataTableFilterType filterType, String strParameterName, String strFilterLabel ) { _filterPanel.addFilter( filterType, strParameterName, strFilterLabel ); } /** * Add a drop down list filter to the filter panel of this DataTableManager * @param strParameterName Name of the parameter of the object to filter.<br/> * For example, if this filter should be applied on the parameter "title" of a class named "Data", then the value of the parameter <i>strParameterName</i> should be "title". * @param strFilterLabel Label describing the filter * @param refList Reference list containing data of the drop down list */ public void addDropDownListFilter( String strParameterName, String strFilterLabel, ReferenceList refList ) { _filterPanel.addDropDownListFilter( strParameterName, strFilterLabel, refList ); } /** * Apply filters on an objects list, sort it and update pagination values. * @param request The request * @param items Collection of objects to filter, sort and paginate */ public void filterSortAndPaginate( HttpServletRequest request, List<T> items ) { List<T> filteredSortedPaginatedItems = new ArrayList<T>( items ); // FILTER Collection<DataTableFilter> listFilters = _filterPanel.getListFilter( ); boolean bResetFilter = StringUtils.equals( request.getParameter( FilterPanel.PARAM_FILTER_PANEL_PREFIX + FilterPanel.PARAM_RESET_FILTERS ), Boolean.TRUE.toString( ) ); boolean bUpdateFilter = true; if ( !bResetFilter ) { bUpdateFilter = StringUtils.equals( request.getParameter( FilterPanel.PARAM_FILTER_PANEL_PREFIX + FilterPanel.PARAM_UPDATE_FILTERS ), Boolean.TRUE.toString( ) ); } for ( DataTableFilter filter : listFilters ) { String strFilterValue; if ( bUpdateFilter ) { strFilterValue = request.getParameter( FilterPanel.PARAM_FILTER_PANEL_PREFIX + filter.getParameterName( ) ); if ( !bResetFilter && ( filter.getFilterType( ) == DataTableFilterType.BOOLEAN ) && ( strFilterValue == null ) ) { strFilterValue = Boolean.FALSE.toString( ); } filter.setValue( strFilterValue ); } else { strFilterValue = filter.getValue( ); } if ( StringUtils.isNotBlank( strFilterValue ) ) { List<T> bufferList = new ArrayList<T>( ); for ( T item : filteredSortedPaginatedItems ) { Method method = getMethod( item, filter.getParameterName( ), CONSTANT_GET ); if ( ( method == null ) && ( filter.getFilterType( ) == DataTableFilterType.BOOLEAN ) ) { method = getMethod( item, filter.getParameterName( ), CONSTANT_IS ); } if ( method != null ) { try { Object value = method.invoke( item ); if ( ( value != null ) && strFilterValue.equals( value.toString( ) ) ) { bufferList.add( item ); } } catch ( Exception e ) { AppLogService.error( e.getMessage( ), e ); } } } filteredSortedPaginatedItems.retainAll( bufferList ); } } // SORT String strSortedAttributeName = request.getParameter( Parameters.SORTED_ATTRIBUTE_NAME ); if ( strSortedAttributeName != null ) { // We update sort properties _strSortedAttributeName = strSortedAttributeName; _bIsAscSort = Boolean.parseBoolean( request.getParameter( Parameters.SORTED_ASC ) ); } if ( _strSortedAttributeName != null ) { Collections.sort( filteredSortedPaginatedItems, new AttributeComparator( _strSortedAttributeName, _bIsAscSort ) ); } // PAGINATION if ( _bEnablePaginator ) { _strCurrentPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex ); _nItemsPerPage = Paginator.getItemsPerPage( request, Paginator.PARAMETER_ITEMS_PER_PAGE, _nItemsPerPage, _nDefautlItemsPerPage ); } else { _strCurrentPageIndex = Integer.toString( 1 ); _nItemsPerPage = filteredSortedPaginatedItems.size( ); } _paginator = new LocalizedPaginator<T>( filteredSortedPaginatedItems, _nItemsPerPage, getSortUrl( ), Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex, request.getLocale( ) ); } /** * Get the filter panel of the DataTableManager * @return The filter panel of the DataTableManager */ public FilterPanel getFilterPanel( ) { return _filterPanel; } /** * Set the filter panel of the DataTableManager * @param filterPanel Filter panel */ public void setFilterPanel( FilterPanel filterPanel ) { _filterPanel = filterPanel; } /** * Get the list of columns of this DataTableManager * @return The list of columns of this DataTableManager */ public List<DataTableColumn> getListColumn( ) { return _listColumn; } /** * Set the list of columns of this DataTableManager * @param listColumn The list of columns of this DataTableManager */ public void setListColumn( List<DataTableColumn> listColumn ) { _listColumn = listColumn; } /** * Get the sort url of this DataTableManager * @return The sort url of this DataTableManager */ public String getSortUrl( ) { return _strSortUrl; } /** * Set the sort url of this DataTableManager * @param strSortUrl The sort url of this DataTableManager */ public void setSortUrl( String strSortUrl ) { _strSortUrl = strSortUrl; } /** * Get the filtered, sorted and paginated items collection of this DataTableManager * @return The filtered, sorted and paginated items collection of this DataTableManager */ public List<T> getItems( ) { return _paginator.getPageItems( ); } /** * Set the items to display. The list of items must be fintered, sorted and paginated. Methods {@link DataTableManager#getAndUpdatePaginator(HttpServletRequest ) getAndUpdatePaginator}, * {@link DataTableManager#getAndUpdateSort(HttpServletRequest ) getAndUpdateSort} and {@link DataTableManager#getAndUpdateFilter(HttpServletRequest, Object) getAndUpdateFilter} must have been * called before the generation of the list of items. * @param items The filtered sorted and paginated list of items to display * @param nTotalItemsNumber The total number of items */ public void setItems( List<T> items, int nTotalItemsNumber ) { _paginator = new LocalizedDelegatePaginator<T>( items, _nItemsPerPage, getSortUrl( ), Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex, nTotalItemsNumber, _locale ); } /** * Clear the items stored by this DataTableManager so that the garbage collector can free the memory they use. */ public void clearItems( ) { _paginator = null; _locale = null; } /** * Internal method. Get the paginator.<br/> * Do not use this method, use {@link DataTableManager#getAndUpdatePaginator(HttpServletRequest ) getAndUpdatePaginator} instead to get up to date values ! * @return The paginator */ public IPaginator<T> getPaginator( ) { return _paginator; } /** * Get the enable paginator boolean * @return True if pagination is active, false otherwise */ public boolean getEnablePaginator( ) { return _bEnablePaginator; } /** * Get the locale * @return The locale */ public Locale getLocale( ) { return _locale; } /** * Set the locale * @param locale The locale */ public void setLocale( Locale locale ) { _locale = locale; } /** * Get the paginator updated with values in the request * @param request The request * @return The paginator up to date */ public DataTablePaginationProperties getAndUpdatePaginator( HttpServletRequest request ) { DataTablePaginationProperties paginationProperties = null; if ( _bEnablePaginator ) { paginationProperties = new DataTablePaginationProperties( ); _strCurrentPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex ); _nItemsPerPage = Paginator.getItemsPerPage( request, Paginator.PARAMETER_ITEMS_PER_PAGE, _nItemsPerPage, _nDefautlItemsPerPage ); paginationProperties.setItemsPerPage( _nItemsPerPage ); int nCurrentPageIndex = 1; if ( !StringUtils.isEmpty( _strCurrentPageIndex ) ) { nCurrentPageIndex = Integer.parseInt( _strCurrentPageIndex ); } paginationProperties.setCurrentPageIndex( nCurrentPageIndex ); } _locale = request.getLocale( ); return paginationProperties; } /** * Get sort properties updated with values in the request * @param request The request * @return The sort properties up to date */ public DataTableSort getAndUpdateSort( HttpServletRequest request ) { String strSortedAttributeName = request.getParameter( Parameters.SORTED_ATTRIBUTE_NAME ); if ( strSortedAttributeName != null ) { // We update sort properties _strSortedAttributeName = strSortedAttributeName; _bIsAscSort = Boolean.parseBoolean( request.getParameter( Parameters.SORTED_ASC ) ); } DataTableSort sort = new DataTableSort( _strSortedAttributeName, _bIsAscSort ); return sort; } /** * Get filter properties updated with values in the request * @param request The request * @param <K> Type of the filter to use. This type must have accessors for * every declared filter. * @param filterObject Filter to apply. * @return The filter properties up to date */ public <K> K getAndUpdateFilter( HttpServletRequest request, K filterObject ) { List<DataTableFilter> listFilters = _filterPanel.getListFilter( ); boolean bResetFilter = StringUtils.equals( request.getParameter( FilterPanel.PARAM_FILTER_PANEL_PREFIX + FilterPanel.PARAM_RESET_FILTERS ), Boolean.TRUE.toString( ) ); boolean bUpdateFilter = true; if ( !bResetFilter ) { bUpdateFilter = StringUtils.equals( request.getParameter( FilterPanel.PARAM_FILTER_PANEL_PREFIX + FilterPanel.PARAM_UPDATE_FILTERS ), Boolean.TRUE.toString( ) ); } Map<String, Object> mapFilter = new HashMap<String, Object>( ); for ( DataTableFilter filter : listFilters ) { String strFilterValue = request.getParameter( FilterPanel.PARAM_FILTER_PANEL_PREFIX + filter.getParameterName( ) ); if ( bUpdateFilter ) { filter.setValue( strFilterValue ); } if ( StringUtils.isNotBlank( strFilterValue ) ) { mapFilter.put( filter.getParameterName( ), strFilterValue ); } } try { BeanUtilsBean.getInstance( ).populate( filterObject, mapFilter ); } catch ( IllegalAccessException e ) { AppLogService.error( e.getMessage( ), e ); return null; } catch ( InvocationTargetException e ) { AppLogService.error( e.getMessage( ), e ); return null; } return filterObject; } /** * Internal method. Get the prefix of html attributes used by filters * @return The prefix of html attributes used by filters */ public String getFilterPanelPrefix( ) { return FilterPanel.PARAM_FILTER_PANEL_PREFIX; } /** * Return the getter method of the object obj for the attribute <i>strAttributName</i> * @param obj the object * @param strAttributName The name of the attribute to get the getter * @param strMethodPrefix Prefix of the name of the method * @return method Method of the object obj for the attribute <i>strAttributName</i> */ private Method getMethod( Object obj, String strAttributName, String strMethodPrefix ) { Method method = null; String strFirstLetter = strAttributName.substring( 0, 1 ).toUpperCase( ); String strMethodName = strMethodPrefix + strFirstLetter + strAttributName.substring( 1, strAttributName.length( ) ); try { method = obj.getClass( ).getMethod( strMethodName ); } catch ( Exception e ) { AppLogService.debug( e ); } return method; } }
package org.apache.james.transport.mailets; import org.apache.james.util.RFC822DateFormat; import org.apache.mailet.GenericMailet; import org.apache.mailet.Mail; import org.apache.mailet.MailAddress; import org.apache.mailet.MailetException; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Sends an error message to the sender of a message (that's typically landed in * the error mail repository). You can optionally specify a sender of the error * message. If you do not specify one, it will use the postmaster's address * * Sample configuration: * <mailet match="All" class="NotifySender"> * <sendingAddress>nobounce@localhost</sendingAddress> * <attachStackTrace>true</attachStackTrace> * <notice>Notice attached to the message (optional)</notice> * </mailet> * * @author Serge Knystautas <sergek@lokitech.com> * @author Ivan Seskar <iseskar@upsideweb.com> * @author Danny Angus <danny@thought.co.uk> */ public class NotifySender extends GenericMailet { MailAddress notifier = null; boolean attachStackTrace = false; String noticeText = null; private RFC822DateFormat rfc822DateFormat = new RFC822DateFormat(); public void init() throws MessagingException { if (getInitParameter("sendingAddress") == null) { notifier = getMailetContext().getPostmaster(); } else { notifier = new MailAddress(getInitParameter("sendingAddress")); } if (getInitParameter("notice") == null) { noticeText = "We were unable to deliver the attached message because of an error in the mail server."; } else { noticeText = getInitParameter("notice"); } try { attachStackTrace = new Boolean(getInitParameter("attachStackTrace")).booleanValue(); } catch (Exception e) { } } /** * Sends a message back to the sender with the message as to why it failed. */ public void service(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); //Create the reply message MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); //Create the list of recipients in the Address[] format InternetAddress[] rcptAddr = new InternetAddress[1]; rcptAddr[0] = getMailetContext().getPostmaster().toInternetAddress(); reply.setRecipients(Message.RecipientType.TO, rcptAddr); //Set the sender... reply.setFrom(notifier.toInternetAddress()); //Create the message StringWriter sout = new StringWriter(); PrintWriter out = new PrintWriter(sout, true); // First add the "local" notice // (either from conf or generic error message) out.println(noticeText); // And then the message from other mailets if (mail.getErrorMessage() != null) { out.println(); out.println("Error message below:"); out.println(mail.getErrorMessage()); } out.println(); out.println("Message details:"); if (message.getSubject() != null) { out.println(" Subject: " + message.getSubject()); } if (message.getSentDate() != null) { out.println(" Sent date: " + message.getSentDate()); } Address[] rcpts = message.getRecipients(Message.RecipientType.TO); if (rcpts != null) { out.print(" To: "); for (int i = 0; i < rcpts.length; i++) { out.print(rcpts[i] + " "); } out.println(); } rcpts = message.getRecipients(Message.RecipientType.CC); if (rcpts != null) { out.print(" CC: "); for (int i = 0; i < rcpts.length; i++) { out.print(rcpts[i] + " "); } out.println(); } out.println(" Size (in bytes): " + message.getSize()); if (message.getLineCount() >= 0) { out.println(" Number of lines: " + message.getLineCount()); } try { //Create the message body MimeMultipart multipart = new MimeMultipart(); //Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(sout.toString(), "text/plain"); part.setHeader("Content-Type", "text/plain"); multipart.addBodyPart(part); //Add the original message as the second mime body part part = new MimeBodyPart(); part.setContent(message.getContent(), message.getContentType()); part.setHeader("Content-Type", message.getContentType()); multipart.addBodyPart(part); //if set, attach the full stack trace if (attachStackTrace && mail.getErrorMessage() != null) { part = new MimeBodyPart(); part.setContent(mail.getErrorMessage(), "text/plain"); part.setHeader("Content-Type", "text/plain"); multipart.addBodyPart(part); } reply.setContent(multipart); reply.setHeader("Content-Type", multipart.getContentType()); } catch (IOException ioe) { throw new MailetException("Unable to create multipart body"); } //Create the list of recipients in our MailAddress format Set recipients = new HashSet(); recipients.add(mail.getSender()); //Set additional headers if (reply.getHeader("Date")==null){ reply.setHeader("Date", rfc822DateFormat.format(new Date())); } String subject = message.getSubject(); if (subject == null) { subject = ""; } if (subject.indexOf("Re:") == 0){ reply.setSubject(subject); } else { reply.setSubject("Re:" + subject); } reply.setHeader("In-Reply-To", message.getMessageID()); //Send it off... getMailetContext().sendMail(notifier, recipients, reply); } public String getMailetInfo() { return "NotifySender Mailet"; } }
package org.jdesktop.swingx.tree; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellEditor; /** * Subclassed to hack around core bug with RtoL editing (#4980473). * * The price to pay is currently is to guarantee a minimum size of the * editing field (is only one char wide if the node value is null). * * PENDING: any possibility to position the editorContainer? * BasicTreeUI adds it to the tree and positions at the node location. * That's not a problem in LToR, only * in RToL * * * @author Jeanette Winzenburg */ public class DefaultXTreeCellEditor extends DefaultTreeCellEditor { public DefaultXTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { super(tree, renderer); } public DefaultXTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { super(tree, renderer, editor); } public void setRenderer(DefaultTreeCellRenderer renderer) { this.renderer = renderer; } public class XEditorContainer extends EditorContainer { @Override public Dimension getPreferredSize() { if (isRightToLeft()) { if(editingComponent != null) { Dimension pSize = editingComponent.getPreferredSize(); pSize.width += offset + 5; Dimension rSize = (renderer != null) ? renderer.getPreferredSize() : null; if(rSize != null) pSize.height = Math.max(pSize.height, rSize.height); if(editingIcon != null) pSize.height = Math.max(pSize.height, editingIcon.getIconHeight()); // trying to enforce a minimum size leads to field being painted over the icon // Make sure width is at least 100. // pSize.width = Math.max(pSize.width, 100); return pSize; } return new Dimension(0, 0); } return super.getPreferredSize(); } @Override public void doLayout() { if (isRightToLeft()) { Dimension cSize = getSize(); editingComponent.getPreferredSize(); editingComponent.setLocation(0, 0); editingComponent.setBounds(0, 0, cSize.width - offset, cSize.height); } else { super.doLayout(); } } @Override public void paint(Graphics g) { if (isRightToLeft()) { Dimension size = getSize(); // Then the icon. if (editingIcon != null) { int yLoc = Math.max(0, (size.height - editingIcon .getIconHeight()) / 2); int xLoc = Math.max(0, size.width - offset); editingIcon.paintIcon(this, g, xLoc, yLoc); } // need to prevent super from painting the icon Icon rememberIcon = editingIcon; editingIcon = null; super.paint(g); editingIcon = rememberIcon; } else { super.paint(g); } } } @Override protected Container createContainer() { return new XEditorContainer(); } @Override protected void prepareForEditing() { super.prepareForEditing(); applyComponentOrientation(); } protected void applyComponentOrientation() { if (tree != null) { editingContainer.applyComponentOrientation(tree.getComponentOrientation()); } } /** * @return */ private boolean isRightToLeft() { return (tree != null) && (!tree.getComponentOrientation().isLeftToRight()); } }
package org.jivesoftware.messenger.net; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.audit.Auditor; import org.jivesoftware.messenger.auth.UnauthorizedException; import java.io.EOFException; import java.io.InputStreamReader; import java.net.Socket; import javax.xml.stream.*; /** * @author Iain Shigeoka */ public class SocketReadThread extends Thread { private Socket sock; /** * The utf-8 charset for decoding and encoding Jabber packet streams. */ private String charset = "UTF-8"; private XMLInputFactory xppFactory; private XMLStreamReader xpp; private Session session; private Connection connection; private static final String ETHERX_NAMESPACE = "http://etherx.jabber.org/streams"; private String serverName; /** * Router used to route incoming packets to the correct channels. */ private PacketRouter router; /** * Audits incoming data */ private Auditor auditor; private PacketFactory packetFactory; private boolean clearSignout = false; /** * Create dedicated read thread for this socket. * * @param router The router for sending packets that were read * @param serverName The name of the server this socket is working for * @param auditor The audit manager that will audit incoming packets * @param sock The socket to read from * @param session The session being read */ public SocketReadThread(PacketRouter router, PacketFactory packetFactory, String serverName, Auditor auditor, Socket sock, Session session) { super("SRT reader"); this.serverName = serverName; this.router = router; this.packetFactory = packetFactory; this.auditor = auditor; this.session = session; connection = session.getConnection(); this.sock = sock; xppFactory = XMLInputFactory.newInstance(); xppFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); } /** * A dedicated thread loop for reading the stream and sending incoming * packets to the appropriate router. */ public void run() { try { xpp = xppFactory.createXMLStreamReader(new InputStreamReader(sock.getInputStream(), charset)); // Read in the opening tag and prepare for packet stream createSession(); // Read the packet stream until it ends if (session != null) { readStream(); } } catch (EOFException eof) { // Normal disconnect } catch (XMLStreamException ie) { // Check if the user abruptly cut the connection without sending previously an // unavailable presence if (clearSignout == false) { if (session != null && session.getStatus() == Session.STATUS_AUTHENTICATED) { Presence presence = session.getPresence(); if (presence != null) { // Simulate an unavailable presence sent by the user. Presence packet = (Presence) presence.createDeepCopy(); packet.setType(Presence.UNAVAILABLE); try { packet.setAvailable(false); packet.setVisible(false); } catch (UnauthorizedException e) {} packet.setOriginatingSession(session); packet.setSender(session.getAddress()); packet.setSending(false); router.route(packet); clearSignout = true; } } } // It is normal for clients to abruptly cut a connection // rather than closing the stream document // Since this is normal behavior, we won't log it as an error // Log.error(LocaleUtils.getLocalizedString("admin.disconnect"),ie); } catch (Exception e) { if (session != null) { Log.warn(LocaleUtils.getLocalizedString("admin.error.stream"), e); } } finally { if (session != null) { Log.debug("Logging off " + session.getAddress() + " on " + connection); try { // Allow everything to settle down after a disconnect // e.g. presence updates to avoid sending double // presence unavailable's sleep(3000); session.getConnection().close(); } catch (Exception e) { Log.warn(LocaleUtils.getLocalizedString("admin.error.connection") + "\n" + sock.toString()); } } else { Log.error(LocaleUtils.getLocalizedString("admin.error.connection") + "\n" + sock.toString()); } } } /** * Read the incoming stream until it ends. Much of the reading * will actually be done in the channel handlers as they run the * XPP through the data. This method mostly handles the idle waiting * for incoming data. To prevent clients from stalling channel handlers, * a watch dog timer is used. Packets that take longer than the watch * dog limit to read will cause the session to be closed. * * @throws XMLStreamException if there is trouble reading from the socket */ private void readStream() throws UnauthorizedException, XMLStreamException { while (true) { for (int eventType = xpp.next(); eventType != XMLStreamConstants.START_ELEMENT; eventType = xpp.next()) { if (eventType == XMLStreamConstants.CHARACTERS) { if (!xpp.isWhiteSpace()) { throw new XMLStreamException(LocaleUtils.getLocalizedString("admin.error.packet.text")); } } else if (eventType == XMLStreamConstants.END_DOCUMENT) { return; } } String tag = xpp.getLocalName(); if ("message".equals(tag)) { Message packet = packetFactory.getMessage(xpp); packet.setOriginatingSession(session); packet.setSender(session.getAddress()); packet.setSending(false); auditor.audit(packet); router.route(packet); session.incrementClientPacketCount(); } else if ("presence".equals(tag)) { Presence packet = packetFactory.getPresence(xpp); packet.setOriginatingSession(session); packet.setSender(session.getAddress()); packet.setSending(false); auditor.audit(packet); router.route(packet); session.incrementClientPacketCount(); // Update the flag that indicates if the user made a clean sign out clearSignout = (Presence.UNAVAILABLE == packet.getType() ? true : false); } else if ("iq".equals(tag)) { IQ packet = packetFactory.getIQ(xpp); packet.setOriginatingSession(session); packet.setSender(session.getAddress()); packet.setSending(false); auditor.audit(packet); router.route(packet); session.incrementClientPacketCount(); } else { throw new XMLStreamException(LocaleUtils.getLocalizedString("admin.error.packet.tag") + tag); } } } private void createSession() throws UnauthorizedException, XMLStreamException { for (int eventType = xpp.getEventType(); eventType != XMLStreamConstants.START_ELEMENT; eventType = xpp.next()) { } // Conduct error checking, the opening tag should be 'stream' // in the 'etherx' namespace if (!xpp.getLocalName().equals("stream")) { throw new XMLStreamException(LocaleUtils.getLocalizedString("admin.error.bad-stream")); } if (!xpp.getNamespaceURI(xpp.getPrefix()).equals(ETHERX_NAMESPACE)) { throw new XMLStreamException(LocaleUtils.getLocalizedString("admin.error.bad-namespace")); } XMLStreamWriter xser = connection.getSerializer(); xser.writeStartDocument(); xser.writeStartElement("stream", "stream", "http://etherx.jabber.org/streams"); xser.writeNamespace("stream", "http://etherx.jabber.org/streams"); xser.writeDefaultNamespace("jabber:client"); xser.writeAttribute("from", serverName); xser.writeAttribute("id", session.getStreamID().toString()); xser.writeCharacters(" "); xser.flush(); // TODO: check for SASL support in opening stream tag } }
package org.jivesoftware.openfire.session; import org.jivesoftware.openfire.Connection; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.StreamID; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.auth.AuthToken; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.openfire.net.SASLAuthentication; import org.jivesoftware.openfire.net.SSLConfig; import org.jivesoftware.openfire.net.SocketConnection; import org.jivesoftware.openfire.privacy.PrivacyList; import org.jivesoftware.openfire.privacy.PrivacyListManager; import org.jivesoftware.openfire.user.PresenceEventDispatcher; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.Presence; import org.xmpp.packet.StreamError; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; /** * Represents a session between the server and a client. * * @author Gaston Dombiak */ public class ClientSession extends Session { private static final String ETHERX_NAMESPACE = "http://etherx.jabber.org/streams"; private static final String FLASH_NAMESPACE = "http: /** * Keep the list of IP address that are allowed to connect to the server. If the list is * empty then anyone is allowed to connect to the server.<p> * * Note: Key = IP address or IP range; Value = empty string. A hash map is being used for * performance reasons. */ private static Map<String,String> allowedIPs = new HashMap<String,String>(); private static Connection.TLSPolicy tlsPolicy; private static Connection.CompressionPolicy compressionPolicy; /** * The authentication token for this session. */ protected AuthToken authToken; /** * Flag indicating if this session has been initialized yet (upon first available transition). */ private boolean initialized; /** * Flag that indicates if the session was available ever. */ private boolean wasAvailable = false; private boolean offlineFloodStopped = false; private Presence presence = null; private int conflictCount = 0; /** * Privacy list that overrides the default privacy list. This list affects only this * session and only for the duration of the session. */ private String activeList; /** * Default privacy list used for the session's user. This list is processed if there * is no active list set for the session. */ private String defaultList; static { // Fill out the allowedIPs with the system property String allowed = JiveGlobals.getProperty("xmpp.client.login.allowed", ""); StringTokenizer tokens = new StringTokenizer(allowed, ", "); while (tokens.hasMoreTokens()) { String address = tokens.nextToken().trim(); allowedIPs.put(address, ""); } // Set the TLS policy stored as a system property String policyName = JiveGlobals.getProperty("xmpp.client.tls.policy", Connection.TLSPolicy.optional.toString()); tlsPolicy = Connection.TLSPolicy.valueOf(policyName); // Set the Compression policy stored as a system property policyName = JiveGlobals.getProperty("xmpp.client.compression.policy", Connection.CompressionPolicy.optional.toString()); compressionPolicy = Connection.CompressionPolicy.valueOf(policyName); } /** * Returns the list of IP address that are allowed to connect to the server. If the list is * empty then anyone is allowed to connect to the server. * * @return the list of IP address that are allowed to connect to the server. */ public static Map<String, String> getAllowedIPs() { return allowedIPs; } /** * Returns a newly created session between the server and a client. The session will * be created and returned only if correct name/prefix (i.e. 'stream' or 'flash') * and namespace were provided by the client. * * @param serverName the name of the server where the session is connecting to. * @param xpp the parser that is reading the provided XML through the connection. * @param connection the connection with the client. * @return a newly created session between the server and a client. * @throws org.xmlpull.v1.XmlPullParserException if an error occurs while parsing incoming data. */ public static Session createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException { boolean isFlashClient = xpp.getPrefix().equals("flash"); connection.setFlashClient(isFlashClient); // Conduct error checking, the opening tag should be 'stream' // in the 'etherx' namespace if (!xpp.getName().equals("stream") && !isFlashClient) { throw new XmlPullParserException( LocaleUtils.getLocalizedString("admin.error.bad-stream")); } if (!xpp.getNamespace(xpp.getPrefix()).equals(ETHERX_NAMESPACE) && !(isFlashClient && xpp.getNamespace(xpp.getPrefix()).equals(FLASH_NAMESPACE))) { throw new XmlPullParserException(LocaleUtils.getLocalizedString( "admin.error.bad-namespace")); } if (!allowedIPs.isEmpty()) { boolean forbidAccess = false; String hostAddress = "Unknown"; // The server is using a whitelist so check that the IP address of the client // is authorized to connect to the server try { hostAddress = connection.getInetAddress().getHostAddress(); if (!allowedIPs.containsKey(hostAddress)) { byte[] address = connection.getInetAddress().getAddress(); String range1 = (address[0] & 0xff) + "." + (address[1] & 0xff) + "." + (address[2] & 0xff) + ".*"; String range2 = (address[0] & 0xff) + "." + (address[1] & 0xff) + ".*.*"; String range3 = (address[0] & 0xff) + ".*.*.*"; if (!allowedIPs.containsKey(range1) && !allowedIPs.containsKey(range2) && !allowedIPs.containsKey(range3)) { forbidAccess = true; } } } catch (UnknownHostException e) { forbidAccess = true; } if (forbidAccess) { // Client cannot connect from this IP address so end the stream and // TCP connection Log.debug("Closed connection to client attempting to connect from: " + hostAddress); // Include the not-authorized error in the response StreamError error = new StreamError(StreamError.Condition.not_authorized); connection.deliverRawText(error.toXML()); // Close the underlying connection connection.close(); return null; } } // Default language is English ("en"). String language = "en"; // Default to a version of "0.0". Clients written before the XMPP 1.0 spec may // not report a version in which case "0.0" should be assumed (per rfc3920 // section 4.4.1). int majorVersion = 0; int minorVersion = 0; for (int i = 0; i < xpp.getAttributeCount(); i++) { if ("lang".equals(xpp.getAttributeName(i))) { language = xpp.getAttributeValue(i); } if ("version".equals(xpp.getAttributeName(i))) { try { int[] version = decodeVersion(xpp.getAttributeValue(i)); majorVersion = version[0]; minorVersion = version[1]; } catch (Exception e) { Log.error(e); } } } // If the client supports a greater major version than the server, // set the version to the highest one the server supports. if (majorVersion > MAJOR_VERSION) { majorVersion = MAJOR_VERSION; minorVersion = MINOR_VERSION; } else if (majorVersion == MAJOR_VERSION) { // If the client supports a greater minor version than the // server, set the version to the highest one that the server // supports. if (minorVersion > MINOR_VERSION) { minorVersion = MINOR_VERSION; } } // Store language and version information in the connection. connection.setLanaguage(language); connection.setXMPPVersion(majorVersion, minorVersion); // Indicate the TLS policy to use for this connection if (!connection.isSecure()) { boolean hasCertificates = false; try { hasCertificates = SSLConfig.getKeyStore().size() > 0; } catch (Exception e) { Log.error(e); } if (Connection.TLSPolicy.required == tlsPolicy && !hasCertificates) { Log.error("Client session rejected. TLS is required but no certificates " + "were created."); return null; } // Set default TLS policy connection.setTlsPolicy(hasCertificates ? tlsPolicy : Connection.TLSPolicy.disabled); } else { // Set default TLS policy connection.setTlsPolicy(Connection.TLSPolicy.disabled); } // Indicate the compression policy to use for this connection connection.setCompressionPolicy(compressionPolicy); // Create a ClientSession for this user. Session session = SessionManager.getInstance().createClientSession(connection); // Build the start packet response StringBuilder sb = new StringBuilder(200); sb.append("<?xml version='1.0' encoding='"); sb.append(CHARSET); sb.append("'?>"); if (isFlashClient) { sb.append("<flash:stream xmlns:flash=\"http: } else { sb.append("<stream:stream "); } sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\" from=\""); sb.append(serverName); sb.append("\" id=\""); sb.append(session.getStreamID().toString()); sb.append("\" xml:lang=\""); sb.append(language); // Don't include version info if the version is 0.0. if (majorVersion != 0) { sb.append("\" version=\""); sb.append(majorVersion).append(".").append(minorVersion); } sb.append("\">"); connection.deliverRawText(sb.toString()); // If this is a "Jabber" connection, the session is now initialized and we can // return to allow normal packet parsing. if (majorVersion == 0) { return session; } // Otherwise, this is at least XMPP 1.0 so we need to announce stream features. sb = new StringBuilder(490); sb.append("<stream:features>"); if (connection.getTlsPolicy() != Connection.TLSPolicy.disabled) { sb.append("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">"); if (connection.getTlsPolicy() == Connection.TLSPolicy.required) { sb.append("<required/>"); } sb.append("</starttls>"); } // Include available SASL Mechanisms sb.append(SASLAuthentication.getSASLMechanisms(session)); // Include Stream features String specificFeatures = session.getAvailableStreamFeatures(); if (specificFeatures != null) { sb.append(specificFeatures); } sb.append("</stream:features>"); connection.deliverRawText(sb.toString()); return session; } /** * Sets the list of IP address that are allowed to connect to the server. If the list is * empty then anyone is allowed to connect to the server. * * @param allowed the list of IP address that are allowed to connect to the server. */ public static void setAllowedIPs(Map<String, String> allowed) { allowedIPs = allowed; if (allowedIPs.isEmpty()) { JiveGlobals.deleteProperty("xmpp.client.login.allowed"); } else { // Iterate through the elements in the map. StringBuilder buf = new StringBuilder(); Iterator<String> iter = allowedIPs.keySet().iterator(); if (iter.hasNext()) { buf.append(iter.next()); } while (iter.hasNext()) { buf.append(", ").append(iter.next()); } JiveGlobals.setProperty("xmpp.client.login.allowed", buf.toString()); } } /** * Returns whether TLS is mandatory, optional or is disabled for clients. When TLS is * mandatory clients are required to secure their connections or otherwise their connections * will be closed. On the other hand, when TLS is disabled clients are not allowed to secure * their connections using TLS. Their connections will be closed if they try to secure the * connection. in this last case. * * @return whether TLS is mandatory, optional or is disabled. */ public static SocketConnection.TLSPolicy getTLSPolicy() { return tlsPolicy; } /** * Sets whether TLS is mandatory, optional or is disabled for clients. When TLS is * mandatory clients are required to secure their connections or otherwise their connections * will be closed. On the other hand, when TLS is disabled clients are not allowed to secure * their connections using TLS. Their connections will be closed if they try to secure the * connection. in this last case. * * @param policy whether TLS is mandatory, optional or is disabled. */ public static void setTLSPolicy(SocketConnection.TLSPolicy policy) { tlsPolicy = policy; JiveGlobals.setProperty("xmpp.client.tls.policy", tlsPolicy.toString()); } /** * Returns whether compression is optional or is disabled for clients. * * @return whether compression is optional or is disabled. */ public static SocketConnection.CompressionPolicy getCompressionPolicy() { return compressionPolicy; } /** * Sets whether compression is optional or is disabled for clients. * * @param policy whether compression is optional or is disabled. */ public static void setCompressionPolicy(SocketConnection.CompressionPolicy policy) { compressionPolicy = policy; JiveGlobals.setProperty("xmpp.client.compression.policy", compressionPolicy.toString()); } /** * Returns the Privacy list that overrides the default privacy list. This list affects * only this session and only for the duration of the session. * * @return the Privacy list that overrides the default privacy list. */ public PrivacyList getActiveList() { if (activeList != null) { try { return PrivacyListManager.getInstance().getPrivacyList(getUsername(), activeList); } catch (UserNotFoundException e) { Log.error(e); } } return null; } /** * Sets the Privacy list that overrides the default privacy list. This list affects * only this session and only for the duration of the session. * * @param activeList the Privacy list that overrides the default privacy list. */ public void setActiveList(PrivacyList activeList) { this.activeList = activeList != null ? activeList.getName() : null; } /** * Returns the default Privacy list used for the session's user. This list is * processed if there is no active list set for the session. * * @return the default Privacy list used for the session's user. */ public PrivacyList getDefaultList() { if (defaultList != null) { try { return PrivacyListManager.getInstance().getPrivacyList(getUsername(), defaultList); } catch (UserNotFoundException e) { Log.error(e); } } return null; } /** * Sets the default Privacy list used for the session's user. This list is * processed if there is no active list set for the session. * * @param defaultList the default Privacy list used for the session's user. */ public void setDefaultList(PrivacyList defaultList) { this.defaultList = defaultList != null ? defaultList.getName() : null; } public ClientSession(String serverName, Connection connection, StreamID streamID) { super(serverName, connection, streamID); // Set an unavailable initial presence presence = new Presence(); presence.setType(Presence.Type.unavailable); } /** * Returns the username associated with this session. Use this information * with the user manager to obtain the user based on username. * * @return the username associated with this session * @throws UserNotFoundException if a user is not associated with a session * (the session has not authenticated yet) */ public String getUsername() throws UserNotFoundException { if (authToken == null) { throw new UserNotFoundException(); } return getAddress().getNode(); } /** * Sets the new Authorization Token for this session. The session is not yet considered fully * authenticated (i.e. active) since a resource has not been binded at this point. This * message will be sent after SASL authentication was successful but yet resource binding * is required. * * @param auth the authentication token obtained from SASL authentication. */ public void setAuthToken(AuthToken auth) { authToken = auth; } /** * Initialize the session with a valid authentication token and * resource name. This automatically upgrades the session's * status to authenticated and enables many features that are not * available until authenticated (obtaining managers for example). * * @param auth the authentication token obtained from the AuthFactory. * @param resource the resource this session authenticated under. */ public void setAuthToken(AuthToken auth, String resource) { setAddress(new JID(auth.getUsername(), getServerName(), resource)); authToken = auth; sessionManager.addSession(this); setStatus(Session.STATUS_AUTHENTICATED); // Set default privacy list for this session setDefaultList(PrivacyListManager.getInstance().getDefaultPrivacyList(auth.getUsername())); } /** * Initialize the session as an anonymous login. This automatically upgrades the session's * status to authenticated and enables many features that are not available until * authenticated (obtaining managers for example).<p> */ public void setAnonymousAuth() { // Anonymous users have a full JID. Use the random resource as the JID's node String resource = getAddress().getResource(); setAddress(new JID(resource, getServerName(), resource)); sessionManager.addAnonymousSession(this); setStatus(Session.STATUS_AUTHENTICATED); } /** * Returns the authentication token associated with this session. * * @return the authentication token associated with this session (can be null). */ public AuthToken getAuthToken() { return authToken; } /** * Flag indicating if this session has been initialized once coming * online. Session initialization occurs after the session receives * the first "available" presence update from the client. Initialization * actions include pushing offline messages, presence subscription requests, * and presence statuses to the client. Initialization occurs only once * following the first available presence transition. * * @return True if the session has already been initializsed */ public boolean isInitialized() { return initialized; } /** * Sets the initialization state of the session. * * @param isInit True if the session has been initialized * @see #isInitialized */ public void setInitialized(boolean isInit) { initialized = isInit; } /** * Returns true if the session was available ever. * * @return true if the session was available ever. */ public boolean wasAvailable() { return wasAvailable; } public boolean canFloodOfflineMessages() { if(offlineFloodStopped) { return false; } String username = getAddress().getNode(); for (ClientSession session : sessionManager.getSessions(username)) { if (session.isOfflineFloodStopped()) { return false; } } return true; } public boolean isOfflineFloodStopped() { return offlineFloodStopped; } public void setOfflineFloodStopped(boolean offlineFloodStopped) { this.offlineFloodStopped = offlineFloodStopped; } /** * Obtain the presence of this session. * * @return The presence of this session or null if not authenticated */ public Presence getPresence() { return presence; } /** * Set the presence of this session * * @param presence The presence for the session * @return The old priority of the session or null if not authenticated */ public Presence setPresence(Presence presence) { Presence oldPresence = this.presence; this.presence = presence; if (oldPresence.isAvailable() && !this.presence.isAvailable()) { // The client is no longer available sessionManager.sessionUnavailable(this); // Mark that the session is no longer initialized. This means that if the user sends // an available presence again the session will be initialized again thus receiving // offline messages and offline presence subscription requests setInitialized(false); // Notify listeners that the session is no longer available PresenceEventDispatcher.unavailableSession(this, presence); } else if (!oldPresence.isAvailable() && this.presence.isAvailable()) { // The client is available sessionManager.sessionAvailable(this); wasAvailable = true; // Notify listeners that the session is now available PresenceEventDispatcher.availableSession(this, presence); } else if (this.presence.isAvailable() && oldPresence.getPriority() != this.presence.getPriority()) { // The client has changed the priority of his presence sessionManager.changePriority(getAddress(), this.presence.getPriority()); // Notify listeners that the priority of the session/resource has changed PresenceEventDispatcher.presencePriorityChanged(this, presence); } else if (this.presence.isAvailable()) { // Notify listeners that the show or status value of the presence has changed PresenceEventDispatcher.presenceChanged(this, presence); } return oldPresence; } /** * Returns the number of conflicts detected on this session. * Conflicts typically occur when another session authenticates properly * to the user account and requests to use a resource matching the one * in use by this session. Administrators may configure the server to automatically * kick off existing sessions when their conflict count exceeds some limit including * 0 (old sessions are kicked off immediately to accommodate new sessions). Conflicts * typically signify the existing (old) session is broken/hung. * * @return The number of conflicts detected for this session */ public int getConflictCount() { return conflictCount; } public String getAvailableStreamFeatures() { // Offer authenticate and registration only if TLS was not required or if required // then the connection is already secured if (conn.getTlsPolicy() == Connection.TLSPolicy.required && !conn.isSecure()) { return null; } StringBuilder sb = new StringBuilder(200); // Include Stream Compression Mechanism if (conn.getCompressionPolicy() != Connection.CompressionPolicy.disabled && !conn.isCompressed()) { sb.append( "<compression xmlns=\"http://jabber.org/features/compress\"><method>zlib</method></compression>"); } if (getAuthToken() == null) { // Advertise that the server supports Non-SASL Authentication sb.append("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>"); // Advertise that the server supports In-Band Registration if (XMPPServer.getInstance().getIQRegisterHandler().isInbandRegEnabled()) { sb.append("<register xmlns=\"http://jabber.org/features/iq-register\"/>"); } } else { // If the session has been authenticated then offer resource binding // and session establishment sb.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"); sb.append("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"); } return sb.toString(); } /** * Increments the conflict by one. */ public void incrementConflictCount() { conflictCount++; } /** * Returns true if the specified packet must not be blocked based on the active or default * privacy list rules. The active list will be tried first. If none was found then the * default list is going to be used. If no default list was defined for this user then * allow the packet to flow. * * @param packet the packet to analyze if it must be blocked. * @return true if the specified packet must be blocked. */ public boolean canProcess(Packet packet) { PrivacyList list = getActiveList(); if (list != null) { // If a privacy list is active then make sure that the packet is not blocked return !list.shouldBlockPacket(packet); } else { list = getDefaultList(); // There is no active list so check if there exists a default list and make // sure that the packet is not blocked return list == null || !list.shouldBlockPacket(packet); } } void deliver(Packet packet) throws UnauthorizedException { if (conn != null && !conn.isClosed()) { conn.deliver(packet); } } public String toString() { return super.toString() + " presence: " + presence; } }
package org.opentdc.events.mongo; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletContext; import org.bson.Document; import org.bson.types.ObjectId; import org.opentdc.mongo.AbstractMongodbServiceProvider; import org.opentdc.events.EventModel; import org.opentdc.events.InvitationState; import org.opentdc.events.SalutationType; import org.opentdc.events.ServiceProvider; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.InternalServerErrorException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.ValidationException; import org.opentdc.util.PrettyPrinter; /** * A MongoDB-based implementation of the Events service. * @author Bruno Kaiser * */ public class MongodbServiceProvider extends AbstractMongodbServiceProvider<EventModel> implements ServiceProvider { private static final Logger logger = Logger.getLogger(MongodbServiceProvider.class.getName()); /** * Constructor. * @param context the servlet context. * @param prefix the simple class name of the service provider; this is also used as the collection name. */ public MongodbServiceProvider( ServletContext context, String prefix) { super(context); connect(); collectionName = prefix; getCollection(collectionName); logger.info("MongodbServiceProvider(context, " + prefix + ") -> OK"); } private Document convert(EventModel eventModel, boolean withId) { Document _doc = new Document("firstName", eventModel.getFirstName()) .append("lastName", eventModel.getLastName()) .append("email", eventModel.getEmail()) .append("comment", eventModel.getComment()) .append("salutation", eventModel.getSalutation().toString()) .append("invitationState", eventModel.getInvitationState().toString()) .append("createdAt", eventModel.getCreatedAt()) .append("createdBy", eventModel.getCreatedBy()) .append("modifiedAt", eventModel.getModifiedAt()) .append("modifiedBy", eventModel.getModifiedBy()); if (withId == true) { _doc.append("_id", new ObjectId(eventModel.getId())); } return _doc; } private EventModel convert(Document doc) { EventModel _model = new EventModel(); _model.setId(doc.getObjectId("_id").toString()); _model.setFirstName(doc.getString("firstName")); _model.setLastName(doc.getString("lastName")); _model.setEmail(doc.getString("email")); _model.setComment(doc.getString("comment")); _model.setSalutation(SalutationType.valueOf(doc.getString("salutation"))); _model.setInvitationState(InvitationState.valueOf(doc.getString("invitationState"))); _model.setCreatedAt(doc.getDate("createdAt")); _model.setCreatedBy(doc.getString("createdBy")); _model.setModifiedAt(doc.getDate("modifiedAt")); _model.setModifiedBy(doc.getString("modifiedBy")); return _model; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#list(java.lang.String, java.lang.String, long, long) */ @Override public ArrayList<EventModel> list( String queryType, String query, int position, int size) { List<Document> _docs = list(position, size); ArrayList<EventModel> _selection = new ArrayList<EventModel>(); for (Document doc : _docs) { _selection.add(convert(doc)); } logger.info("list(<" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " events."); return _selection; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#create(org.opentdc.events.EventsModel) */ @Override public EventModel create( EventModel event) throws DuplicateException, ValidationException { logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")"); if (event.getId() != null && !event.getId().isEmpty()) { throw new ValidationException("event <" + event.getId() + "> contains an id generated on the client."); } // enforce mandatory fields if (event.getFirstName() == null || event.getFirstName().length() == 0) { throw new ValidationException("event must contain a valid firstName."); } if (event.getLastName() == null || event.getLastName().length() == 0) { throw new ValidationException("event must contain a valid lastName."); } if (event.getEmail() == null || event.getEmail().length() == 0) { throw new ValidationException("event must contain a valid email address."); } // set default values if (event.getInvitationState() == null) { event.setInvitationState(InvitationState.INITIAL); } if (event.getSalutation() == null) { event.setSalutation(SalutationType.DU_M); } // set modification / creation values Date _date = new Date(); event.setCreatedAt(_date); event.setCreatedBy(getPrincipal()); event.setModifiedAt(_date); event.setModifiedBy(getPrincipal()); create(convert(event, false)); logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")"); return event; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#read(java.lang.String) */ @Override public EventModel read( String id) throws NotFoundException { EventModel _event = convert(readOne(id)); if (_event == null) { throw new NotFoundException("no event with ID <" + id + "> was found."); } logger.info("read(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event)); return _event; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#update(java.lang.String, org.opentdc.events.EventsModel) */ @Override public EventModel update( String id, EventModel event ) throws NotFoundException, ValidationException { EventModel _event = read(id); if (! _event.getCreatedAt().equals(event.getCreatedAt())) { logger.warning("event <" + id + ">: ignoring createdAt value <" + event.getCreatedAt().toString() + "> because it was set on the client."); } if (! _event.getCreatedBy().equalsIgnoreCase(event.getCreatedBy())) { logger.warning("event <" + id + ">: ignoring createdBy value <" + event.getCreatedBy() + "> because it was set on the client."); } if (event.getFirstName() == null || event.getFirstName().length() == 0) { throw new ValidationException("event <" + id + "> must contain a valid firstName."); } if (event.getLastName() == null || event.getLastName().length() == 0) { throw new ValidationException("event <" + id + "> must contain a valid lastName."); } if (event.getEmail() == null || event.getEmail().length() == 0) { throw new ValidationException("event <" + id + "> must contain a valid email address."); } if (event.getInvitationState() == null) { event.setInvitationState(InvitationState.INITIAL); } if (event.getSalutation() == null) { event.setSalutation(SalutationType.DU_M); } _event.setFirstName(event.getFirstName()); _event.setLastName(event.getLastName()); _event.setEmail(event.getEmail()); _event.setSalutation(event.getSalutation()); _event.setInvitationState(event.getInvitationState()); _event.setComment(event.getComment()); _event.setModifiedAt(new Date()); _event.setModifiedBy(getPrincipal()); update(id, convert(_event, true)); logger.info("update(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event)); return _event; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#delete(java.lang.String) */ @Override public void delete( String id) throws NotFoundException, InternalServerErrorException { read(id); deleteOne(id); logger.info("delete(" + id + ") -> OK"); } }
package jp.ne.sakura.kkkon.android.reinstallapk; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; import jp.ne.sakura.kkkon.android.exceptionhandler.SettingsCompat; public class MainActivity extends Activity implements ListView.OnItemClickListener { private static final String TAG = "kk-ReInstall-Apk"; private List<MyListData> mDataList = new ArrayList<MyListData>(128); private ListView mListView; private TextView mUnknownSourceTextView; public class MyListData { private Drawable image; private String text; private String packageName; private long firstInstallTime; private long lastUpdateTime; private String apkPath; public void setImage( final Drawable image ) { this.image = image; } public Drawable getImage() { return this.image; } public void setPackageName( final String packageName ) { this.packageName = packageName; } public String getPackageName() { return this.packageName; } public void setText( final String text ) { this.text = text; } public String getText() { return this.text; } public long getFirstInstallTime() { return firstInstallTime; } public void setFirstInstallTime(long firstInstallTime) { this.firstInstallTime = firstInstallTime; } public long getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(long lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public String getApkPath() { return apkPath; } public void setApkPath(String apkPath) { this.apkPath = apkPath; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.d( TAG, "onCreate:"); super.onCreate(savedInstanceState); LinearLayout layout = new LinearLayout( this ); layout.setOrientation( LinearLayout.VERTICAL ); mUnknownSourceTextView = new TextView( this ); { final StringBuilder sb = new StringBuilder(); { final String label = this.getString( R.string.system_setting ); if ( null != label ) { sb.append( label ); } } sb.append( ": " ); { final String label = this.getString( R.string.unknown_sources ); if ( null != label ) { sb.append( label ); } } sb.append( " " ); SettingsCompat.initialize( this.getApplicationContext() ); final boolean isAllow = SettingsCompat.isAllowedNonMarketApps(); if ( isAllow ) { final String label = this.getString( R.string.unknown_sources_ok ); if ( null != label ) { sb.append( label ); } else { sb.append( "OK" ); } } else { final String label = this.getString( R.string.unknown_sources_ng ); if ( null != label ) { sb.append( label ); } else { sb.append( "NG" ); } } mUnknownSourceTextView.setGravity( Gravity.RIGHT ); mUnknownSourceTextView.setText( sb.toString() ); } layout.addView( mUnknownSourceTextView ); ImageView imageView = new ImageView( this ); layout.addView( imageView); mListView = new ListView( this ); TextView emptyTextView = new TextView( this ); emptyTextView.setText( "No items found" ); mListView.setEmptyView( emptyTextView ); makeApplicationList(); MyAdapter adapter = new MyAdapter( this ); mListView.setAdapter( adapter ); mListView.setOnItemClickListener( this ); layout.addView( mListView ); setContentView( layout ); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } private void makeApplicationList() { PackageManager pm = getPackageManager(); if ( null == pm ) { return; } final List<ApplicationInfo> listApplicationInfo = pm.getInstalledApplications( 0 ); if ( null == listApplicationInfo ) { return; } for ( final ApplicationInfo appInfo : listApplicationInfo ) { if ( null == appInfo ) { continue; } if ( null != appInfo.sourceDir ) { if ( appInfo.sourceDir.startsWith( "/system/" ) ) { continue; } if ( null != appInfo.packageName ) { if ( appInfo.packageName.startsWith( "com.example." ) ) { continue; } if ( appInfo.packageName.startsWith( "com.android." ) ) { continue; } if ( appInfo.packageName.startsWith( "com.google.android." ) ) { continue; } } Log.d( TAG, "package=" + appInfo.packageName ); Log.d( TAG, "name=" + appInfo.name ); Log.d( TAG, "sourcedir=" + appInfo.sourceDir ); Log.d( TAG, "label=" + appInfo.loadLabel( pm ) ); MyListData item = new MyListData(); item.setApkPath( appInfo.sourceDir ); { final CharSequence label = appInfo.loadLabel( pm ); if ( null == label ) { item.setText( appInfo.packageName ); } else { item.setText( label.toString() ); } } item.setPackageName( appInfo.packageName ); final Drawable drawable = appInfo.loadIcon(pm); if ( null != drawable ) { Log.d( TAG, "icon: w=" + drawable.getIntrinsicWidth() + ",h=" + drawable.getIntrinsicHeight() ); } item.setImage( drawable ); { try { final PackageInfo packageInfo = pm.getPackageInfo( appInfo.packageName, 0 ); if ( null != packageInfo ) { final long firstInstallTime = packageInfo.firstInstallTime; // API9 final long lastUpdateTime = packageInfo.firstInstallTime; // API9 Log.d( TAG, "firstInstallTime=" + firstInstallTime ); Log.d( TAG, "lastUpdateTime=" + lastUpdateTime ); item.setFirstInstallTime( firstInstallTime ); item.setLastUpdateTime( lastUpdateTime ); } } catch ( PackageManager.NameNotFoundException e ) { Log.e( TAG, "got Exception=" + e.toString(), e ); } } Log.d( TAG, "" ); mDataList.add( item ); } } } public class MyAdapter extends BaseAdapter { private Context mContext; public MyAdapter( Context context ) { this.mContext = context; } @Override public int getCount() { if ( null != mDataList ) { return mDataList.size(); } return 0; } @Override public Object getItem(int i) { if ( null != mDataList ) { return mDataList.get(i); } return null; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup vg) { View v = view; if ( null == v ) { LinearLayout layout = new LinearLayout( mContext ); layout.setOrientation( LinearLayout.HORIZONTAL ); ImageView imageView = new ImageView( mContext ); imageView.setId( 0 ); imageView.setScaleType( ImageView.ScaleType.FIT_XY ); imageView.setLayoutParams( new ViewGroup.LayoutParams( 144, 144 ) ); imageView.setAdjustViewBounds( true ); TextView textView = new TextView( mContext ); textView.setId( 1 ); textView.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT ) ); textView.setGravity( Gravity.CENTER_VERTICAL ); textView.setPadding( 20, 20, 20, 20 ); layout.addView( imageView ); layout.addView( textView ); v = layout; } MyListData itemData = (MyListData)this.getItem(i); if ( null != itemData ) { ImageView imageView = (ImageView) v.findViewById(0); TextView textView = (TextView) v.findViewById(1); if ( null != imageView ) { imageView.setBackgroundDrawable( itemData.getImage() ); } if ( null != textView ) { textView.setText( itemData.getText() ); } } return v; } } public void onItemClick(AdapterView<?> av, View view, int position, long id) { if ( this.mListView == av ) { if ( null == this.mDataList ) { Log.d( TAG, "mDataList is null " ); return; } final MyListData itemData = this.mDataList.get( position ); if ( null == itemData ) { Log.d( TAG, "itemData is null index=" + position ); return; } { final String apkPath = itemData.getApkPath(); boolean installCalled = false; if ( null != apkPath ) { final File fileApk = new File(apkPath); if ( fileApk.exists() ) { installCalled = true; Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile( fileApk ), "application/vnd.android.package-archive"); //promptInstall.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); this.startActivity( promptInstall ); } else { Log.d( TAG, "fileApk not exists. path=" + fileApk.getAbsolutePath() ); } } else { Log.d( TAG, "apkPath is null" ); } if ( !installCalled ) { Toast toast = Toast.makeText( this, R.string.apk_not_found, Toast.LENGTH_LONG ); toast.show(); } else { boolean needRefresh = false; { final String packageName = itemData.getPackageName(); { final PackageManager pm = this.getPackageManager(); if ( null != pm ) { try { final ApplicationInfo appInfo = pm.getApplicationInfo( packageName, 0 ); if ( null != appInfo ) { itemData.setApkPath( appInfo.sourceDir ); this.mDataList.set( position, itemData ); needRefresh = true; } } catch ( PackageManager.NameNotFoundException e ) { Log.d( TAG, "got Exception: " + e.toString(), e); } } } } } } } } }
package aeronicamc.mods.mxtune.caches; import aeronicamc.libs.mml.util.TestData; import aeronicamc.mods.mxtune.config.MXTuneConfig; import aeronicamc.mods.mxtune.util.MXTuneRuntimeException; import net.minecraftforge.fml.LogicalSide; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.h2.mvstore.MVMap; import org.h2.mvstore.MVStore; import javax.annotation.Nullable; import java.io.IOException; import java.time.Duration; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Map; import static aeronicamc.mods.mxtune.caches.FileHelper.SERVER_FOLDER; import static aeronicamc.mods.mxtune.caches.FileHelper.getCacheFile; public class ModDataStore { private static final Logger LOGGER = LogManager.getLogger(ModDataStore.class); private static final String SERVER_DATA_STORE_FILENAME = "music.mv"; private static final ZoneId ROOT_ZONE = ZoneId.of("GMT0"); private static final ArrayList<LocalDateTime> reapDateTimeKeyList = new ArrayList<>(); private static LocalDateTime lastDateTime = LocalDateTime.now(ROOT_ZONE); private static MVStore mvStore; public static void start() { String pathFileName = String.format("Folder: '%s', Filename: '%s'", SERVER_FOLDER, SERVER_DATA_STORE_FILENAME); try { pathFileName = getCacheFile(SERVER_FOLDER, SERVER_DATA_STORE_FILENAME, LogicalSide.SERVER).toString(); mvStore = new MVStore.Builder() .fileName(pathFileName) .compress() .open(); } catch (IOException e) { LOGGER.error("Big OOPS here! Out of disk space? {}", pathFileName); LOGGER.error(e); throw new MXTuneRuntimeException("Unable to create mxtune data store.", e); } finally { if (getMvStore() != null) LOGGER.debug("MVStore Started. Commit Version: {}, file: {}", getMvStore().getCurrentVersion(), getMvStore().getFileStore()); } testGet(); long count = reapSheetMusic(true); } public static void shutdown() { if (getMvStore() != null) getMvStore().close(); mvStore = null; LOGGER.debug("MVStore Shutdown."); } @Nullable private static MVStore getMvStore() { return mvStore; } private static void testPut() { for (TestData c : TestData.values()) { String index; if ((index = addMusicText(c.getMML())) == null) LOGGER.warn("Duplicate record: {}, musicText: {}", String.format("%s", index), c.getMML().substring(0, Math.min(24, c.getMML().length()))); } } private static void testGet() { if (getMvStore() != null) { MVStore.TxCounter using = getMvStore().registerVersionUsage(); MVMap<LocalDateTime, String> indexToMusicText = getMvStore().openMap("MusicTexts"); for (Map.Entry<LocalDateTime, String> c : indexToMusicText.entrySet()) { LOGGER.debug("id: {}, musicText: {}", String.format("%s", c.getKey()), c.getValue().substring(0, Math.min(24, c.getValue().length()))); } LOGGER.debug("Last key: {}", indexToMusicText.lastKey()); getMvStore().deregisterVersionUsage(using); } } private static LocalDateTime nextKey() { LocalDateTime now; do { now = LocalDateTime.now(ROOT_ZONE); } while (now.equals(lastDateTime)); lastDateTime = now; return now; } public static void removeSheetMusic(String musicIndex) { LocalDateTime localDateTime = null; try { localDateTime = LocalDateTime.parse(musicIndex); } catch (DateTimeParseException e) { LOGGER.warn("Invalid SheetMusic musicIndex. Can't remove SheetMusic mapping"); } finally { if (getMvStore() != null && localDateTime != null) { MVStore.TxCounter using = getMvStore().registerVersionUsage(); MVMap<LocalDateTime, String> indexToMusicText = getMvStore().openMap("MusicTexts"); try { indexToMusicText.remove(localDateTime); } catch (ClassCastException | UnsupportedOperationException | NullPointerException e) { LOGGER.error("removeSheetMusic: " + localDateTime.toString(), e); } getMvStore().deregisterVersionUsage(using); } } } private static synchronized ArrayList<LocalDateTime> getReapDateTimeKeyList() { return reapDateTimeKeyList; } private static boolean canReapSheetMusic(LocalDateTime localDateTime) { LocalDateTime keyPlusDaysLeft = localDateTime.plusDays(MXTuneConfig.getSheetMusicLifeInDays()); LocalDateTime now = LocalDateTime.now(ZoneId.of("GMT0")); return Math.max((Duration.between(now, keyPlusDaysLeft).getSeconds() / 86400), 0) <= 0; } private static long reapSheetMusic(boolean whatIf) { getReapDateTimeKeyList().clear(); long reapCount = 0; if (getMvStore() != null) { MVStore.TxCounter using = getMvStore().registerVersionUsage(); MVMap<LocalDateTime, String> indexToMusicText = getMvStore().openMap("MusicTexts"); for (Map.Entry<LocalDateTime, String> entry : indexToMusicText.entrySet()) { if (canReapSheetMusic(entry.getKey())) getReapDateTimeKeyList().add(entry.getKey()); } getMvStore().deregisterVersionUsage(using); reapCount = getReapDateTimeKeyList().size(); if (!getReapDateTimeKeyList().isEmpty() && !whatIf) { // List and Reap for(LocalDateTime entry : getReapDateTimeKeyList()) { LOGGER.info("Reap SheetMusic key: {}", entry); indexToMusicText.remove(entry); } LOGGER.info("Reaped {} entries", getReapDateTimeKeyList().size()); } else { // whatIf is true: List only for(LocalDateTime entry : getReapDateTimeKeyList()) { LOGGER.info("Can Reap SheetMusic key: {}", entry); } LOGGER.info("{} entries could be reaped", getReapDateTimeKeyList().size()); } getReapDateTimeKeyList().clear(); } return reapCount; } @Nullable public static String addMusicText(String musicText) { LocalDateTime key = null; if (getMvStore() != null) { key = nextKey(); MVMap<LocalDateTime, String> indexToMusicText = getMvStore().openMap("MusicTexts"); try { indexToMusicText.put(key, musicText); getMvStore().commit(); } catch (UnsupportedOperationException | ClassCastException | NullPointerException | IllegalArgumentException e) { LOGGER.error("addMusicText: key: " + key.toString() + ", musicText: " + "", e); } } return key != null ? key.toString() : null; } @Nullable public static String getMusicText(String key) { String musicText = null; if (getMvStore() != null) { MVMap<LocalDateTime, String> indexToMusicText = getMvStore().openMap("MusicTexts"); LocalDateTime localDateTime = LocalDateTime.parse(key); try { musicText = indexToMusicText.get(localDateTime); } catch (ClassCastException | NullPointerException e) { LOGGER.error("getMusicText error or key : " + key, e); } } return musicText; } }
package aeronicamc.mods.mxtune.events; import aeronicamc.mods.mxtune.Reference; import aeronicamc.mods.mxtune.init.ModBlocks; import aeronicamc.mods.mxtune.init.ModItems; import aeronicamc.mods.mxtune.items.StageToolItem; import aeronicamc.mods.mxtune.render.ModRenderType; import aeronicamc.mods.mxtune.render.StageAreaRenderer; import aeronicamc.mods.mxtune.util.IInstrument; import aeronicamc.mods.mxtune.util.SheetMusicHelper; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.block.BlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.AbstractGui; import net.minecraft.client.renderer.ActiveRenderInfo; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.culling.ClippingHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.shapes.ISelectionContext; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.vector.Matrix4f; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.DrawHighlightEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT) public class RenderEvents { static final Minecraft mc = Minecraft.getInstance(); @SubscribeEvent public static void event(ItemTooltipEvent event) { if (event.getItemStack().getItem().equals(ModBlocks.MUSIC_BLOCK.get().asItem())) event.getToolTip().add(new TranslationTextComponent("tooltip.mxtune.block_music.help").withStyle(TextFormatting.YELLOW)); else if (event.getItemStack().getItem().equals(ModItems.MUSIC_PAPER.get())) event.getToolTip().add(new TranslationTextComponent("tooltip.mxtune.music_paper.help").withStyle(TextFormatting.YELLOW)); } static ResourceLocation TEXTURE = new ResourceLocation("textures/gui/toasts.png"); static int width = 160; static int height = 32; static int blitOffset = 0; @SubscribeEvent public static void event(DrawHighlightEvent.HighlightBlock event) { if (mc.player == null ) return; if (mc.options.renderDebug) return; if (!(mc.player.inventory.getSelected().getItem() instanceof StageToolItem)) return; if (event.isCancelable()) event.setCanceled(true); final BlockRayTraceResult blockRayTraceResult = event.getTarget(); final IRenderTypeBuffer renderTypeBuffer = event.getBuffers(); final ActiveRenderInfo activeRenderInfo = event.getInfo(); final MatrixStack matrixStack = event.getMatrix(); Vector3d vector3d = activeRenderInfo.getPosition(); double camX = vector3d.x(); double camY = vector3d.y(); double camZ = vector3d.z(); World level = mc.player.level; BlockPos blockPos = blockRayTraceResult.getBlockPos(); BlockState blockState = level.getBlockState(blockRayTraceResult.getBlockPos()); if (!blockState.isAir(level, blockPos) && level.getWorldBorder().isWithinBounds(blockPos)) { IVertexBuilder ivertexBuilder = renderTypeBuffer.getBuffer(ModRenderType.OVERLAY_LINES); renderHitOutline(level, matrixStack, ivertexBuilder, activeRenderInfo.getEntity(), camX, camY, camZ, blockPos, blockState); } } private static void renderHitOutline(World level, MatrixStack pMatrixStack, IVertexBuilder pBuffer, Entity pEntity, double pX, double pY, double pZ, BlockPos pBlockPos, BlockState pBlockState) { renderShape(pMatrixStack, pBuffer, pBlockState.getShape(level, pBlockPos, ISelectionContext.of(pEntity)), (double)pBlockPos.getX() - pX, (double)pBlockPos.getY() - pY, (double)pBlockPos.getZ() - pZ, 1.0F, 0.0F, 1.0F, 0.4F); } private static void renderShape(MatrixStack pMatrixStack, IVertexBuilder pBuffer, VoxelShape pShape, double pX, double pY, double pZ, float pRed, float pGreen, float pBlue, float pAlpha) { Matrix4f matrix4f = pMatrixStack.last().pose(); pShape.forAllEdges((edgeVertexBegin_X, edgeVertexBegin_Y, edgeVertexBegin_Z, edgeVertexEnd_X, edgeVertexEnd_Y, edgeVertexEnd_Z) -> { pBuffer.vertex(matrix4f, (float)(edgeVertexBegin_X + pX), (float)(edgeVertexBegin_Y + pY), (float)(edgeVertexBegin_Z + pZ)).color(pRed, pGreen, pBlue, pAlpha).endVertex(); pBuffer.vertex(matrix4f, (float)(edgeVertexEnd_X + pX), (float)(edgeVertexEnd_Y + pY), (float)(edgeVertexEnd_Z + pZ)).color(pRed, pGreen, pBlue, pAlpha).endVertex(); }); } @SubscribeEvent public static void event(RenderGameOverlayEvent.Post event) { if (mc.player == null ) return; if (mc.options.renderDebug) return; PlayerEntity player = mc.player; ItemStack itemStack = player.inventory.getSelected(); // borrow toast render for testing some ideas. if (event.getType() == RenderGameOverlayEvent.ElementType.ALL && (mc.screen == null) && itemStack.getItem() instanceof IInstrument) { ItemStack sheetMusic = SheetMusicHelper.getIMusicFromIInstrument(itemStack); int offset = Math.max(mc.font.width(SheetMusicHelper.getFormattedMusicTitle(sheetMusic)) + 40, width); MatrixStack pPoseStack = event.getMatrixStack(); mc.getTextureManager().bind(TEXTURE); RenderSystem.color3f(1.0F, 1.0F, 1.0F); blit(pPoseStack, 0, 0, 0, 0, width, height); blit(pPoseStack, ((offset - width)/2) + 5, 0, 10, 0, width-10, height); blit(pPoseStack, offset - width + 10, 0, 10, 0, width, height); mc.font.draw(pPoseStack, SheetMusicHelper.getFormattedMusicTitle(sheetMusic), 30.0F, 7.0F, -11534256); mc.font.draw(pPoseStack, SheetMusicHelper.getFormattedMusicDuration(sheetMusic), 30.0F, 17.0F, -11534256); mc.getItemRenderer().renderAndDecorateItem(itemStack, 8, 8); } if (event.getType() == RenderGameOverlayEvent.ElementType.ALL && (mc.screen == null) && itemStack.getItem() instanceof StageToolItem) { MatrixStack pPoseStack = event.getMatrixStack(); ActiveRenderInfo activeRenderInfo = mc.gameRenderer.getMainCamera(); RayTraceResult raytraceresult = mc.hitResult; ITextComponent textComponent = new StringTextComponent("test").withStyle(TextFormatting.WHITE); int offset = Math.max(mc.font.width(textComponent) + 40, width); if (raytraceresult != null && raytraceresult.getType() == RayTraceResult.Type.BLOCK) StageAreaRenderer.renderFloatingText(textComponent, raytraceresult.getLocation(), pPoseStack , mc.renderBuffers().bufferSource(), activeRenderInfo, -1); mc.renderBuffers().bufferSource().endBatch(); mc.getTextureManager().bind(TEXTURE); RenderSystem.color3f(1.0F, 1.0F, 1.0F); blit(pPoseStack, 0, 0, 0, 0, width, height); blit(pPoseStack, ((offset - width)/2) + 5, 0, 10, 0, width-10, height); blit(pPoseStack, offset - width + 10, 0, 10, 0, width, height); mc.font.draw(pPoseStack, textComponent, 30.0F, 7.0F, -11534256); mc.font.draw(pPoseStack, textComponent, 30.0F, 17.0F, -11534256); mc.getItemRenderer().renderAndDecorateItem(itemStack, 8, 8); } } static void blit(MatrixStack pMatrixStack, int pX, int pY, int pUOffset, int pVOffset, int pUWidth, int pVHeight) { AbstractGui.blit(pMatrixStack, pX, pY, blitOffset, (float)pUOffset, (float)pVOffset, pUWidth, pVHeight, 256, 256); } // It's absolutely Fabulous... or maybe not, but at least in Fabulous Graphics mode it's not bad. public static void renderLast(MatrixStack pMatrixStack, IRenderTypeBuffer.Impl pBuffer, LightTexture pLightTexture, ActiveRenderInfo pActiveRenderInfo, float pPartialTicks, ClippingHelper pClippingHelper) { StageAreaRenderer.render(pMatrixStack, pBuffer, pLightTexture, pActiveRenderInfo, pPartialTicks, pClippingHelper); } }
package co.phoenixlab.discord.api; import co.phoenixlab.discord.api.entities.*; import com.google.common.eventbus.EventBus; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.http.HttpHeaders; import org.apache.http.entity.ContentType; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; public class DiscordApiClient { private static final Logger LOGGER = LoggerFactory.getLogger("DiscordApiClient"); private final ScheduledExecutorService executorService; private String email; private String password; private String token; private AtomicReference<String> sessionId; private AtomicReference<User> clientUser; private DiscordWebSocketClient webSocketClient; private List<Server> servers; private Map<String, Server> serverMap; private final EventBus eventBus; private final Gson gson; public DiscordApiClient() { sessionId = new AtomicReference<>(); clientUser = new AtomicReference<>(); executorService = Executors.newScheduledThreadPool(4); servers = new ArrayList<>(); serverMap = new HashMap<>(); eventBus = new EventBus((e, c) -> { LOGGER.warn("Error while handling event {} when calling {}", c.getEvent(), c.getSubscriberMethod().toGenericString()); LOGGER.warn("EventBus dispatch exception", e); }); gson = new GsonBuilder().serializeNulls().create(); } public void logIn(String email, String password) throws IOException { LOGGER.info("Attempting to log in as {}...", email); this.email = email; this.password = password; Map<String, String> authObj = new HashMap<>(); authObj.put("email", email); authObj.put("password", password); JSONObject auth = new JSONObject(authObj); HttpResponse<JsonNode> response; try { response = Unirest.post(ApiConst.LOGIN_ENDPOINT). header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()). body(auth.toJSONString()). asJson(); } catch (UnirestException e) { throw new IOException("Unable to log in", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_FORBIDDEN) { // Servers return FORBIDDEN for bad credentials LOGGER.warn("Unable to log in with given credentials: ", response.getStatusText()); } else { LOGGER.warn("Unable to log in, Discord may be having issues"); } throw new IOException("Unable to log in: HTTP " + response.getStatus() + ": " + response.getStatusText()); } token = response.getBody().getObject().getString("token"); LOGGER.info("Successfully logged in, token is {}", token); openWebSocket(); } private void openWebSocket() throws IOException { final String gateway = getWebSocketGateway(); try { webSocketClient = new DiscordWebSocketClient(this, new URI(gateway)); } catch (URISyntaxException e) { LOGGER.warn("Bad gateway", e); throw new IOException(e); } webSocketClient.connect(); } private String getWebSocketGateway() throws IOException { HttpResponse<JsonNode> response; try { response = Unirest.get(ApiConst.WEBSOCKET_GATEWAY). header("authorization", token). asJson(); } catch (UnirestException e) { throw new IOException("Unable to retrieve websocket gateway", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { LOGGER.warn("Unable to retrieve websocket gateway: HTTP {}: {}", status, response.getStatusText()); throw new IOException("Unable to retrieve websocket : HTTP " + status + ": " + response.getStatusText()); } String gateway = response.getBody().getObject().getString("url"); gateway = "w" + gateway.substring(2); LOGGER.info("Found WebSocket gateway at {}", gateway); return gateway; } public void sendMessage(String body, String channelId) { sendMessage(body, channelId, new String[0]); } public void sendMessage(String body, String channelId, String[] mentions) { OutboundMessage outboundMessage = new OutboundMessage(body, false, mentions); String content = gson.toJson(outboundMessage); HttpResponse<JsonNode> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.post(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages"). headers(headers). body(content). asJson(); } catch (UnirestException e) { LOGGER.warn("Unable to send message", e); return; } int status = response.getStatus(); if (status != 200) { LOGGER.warn("Unable to send message: HTTP {}: {}", status, response.getStatusText()); return; } } public void deleteMessage(String messageId, String channelId) throws IOException { // TODO } public String getToken() { return token; } public String getSessionId() { return sessionId.get(); } public void setSessionId(String sessionId) { this.sessionId.set(sessionId); } public User getClientUser() { return clientUser.get(); } public void setClientUser(User user) { clientUser.set(user); } public List<Server> getServers() { return servers; } public Map<String, Server> getServerMap() { return serverMap; } public Server getServerByID(String id) { return serverMap.get(id); } public void remapServers() { serverMap.clear(); serverMap.putAll(servers.stream().collect(Collectors.toMap(Server::getId, Function.identity()))); servers.forEach(server -> server.getChannels().forEach(channel -> channel.setParent(server))); } public Channel getChannelById(String id) { return servers.stream(). map(Server::getChannels). flatMap(Set::stream). filter(c -> id.equals(c.getId())). findFirst().orElse(null); } public User findUser(String username) { username = username.toLowerCase(); for (Server server : servers) { User user = findUser(username, server); if (user != null) { return user; } } return null; } public User findUser(String username, Server server) { username = username.toLowerCase(); for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getUsername().equalsIgnoreCase(username)) { return user; } } // No match? Try matching start for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getUsername().toLowerCase().startsWith(username)) { return user; } } // Still no match? Try fuzzy match // TODO return null; } public User getUserById(String userId) { for (Server server : servers) { User user = getUserById(userId, server); if (user != null) { return user; } } return null; } public User getUserById(String userId, Server server) { for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getId().equals(userId)) { return user; } } return null; } public ScheduledExecutorService getExecutorService() { return executorService; } public EventBus getEventBus() { return eventBus; } }
package co.phoenixlab.discord.api; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Server; import co.phoenixlab.discord.api.entities.User; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.http.HttpHeaders; import org.apache.http.entity.ContentType; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; public class DiscordApiClient { private static final Logger LOGGER = LoggerFactory.getLogger("DiscordApiClient"); private final ScheduledExecutorService executorService; private String email; private String password; private String token; private AtomicReference<String> sessionId; private AtomicReference<User> clientUser; private DiscordWebSocketClient webSocketClient; private List<Server> servers; private Map<String, Server> serverMap; public DiscordApiClient() { sessionId = new AtomicReference<>(); clientUser = new AtomicReference<>(); executorService = Executors.newScheduledThreadPool(4); servers = new ArrayList<>(); serverMap = new HashMap<>(); } public void logIn(String email, String password) throws IOException { LOGGER.info("Attempting to log in as {}...", email); this.email = email; this.password = password; Map<String, String> authObj = new HashMap<>(); authObj.put("email", email); authObj.put("password", password); JSONObject auth = new JSONObject(authObj); HttpResponse<JsonNode> response; try { response = Unirest.post(ApiConst.LOGIN_ENDPOINT). header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()). body(auth.toJSONString()). asJson(); } catch (UnirestException e) { throw new IOException("Unable to log in", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_FORBIDDEN) { // Servers return FORBIDDEN for bad credentials LOGGER.warn("Unable to log in with given credentials: ", response.getStatusText()); } else { LOGGER.warn("Unable to log in, Discord may be having issues"); } throw new IOException("Unable to log in: HTTP " + response.getStatus() + ": " + response.getStatusText()); } token = response.getBody().getObject().getString("token"); LOGGER.info("Successfully logged in, token is {}", token); openWebSocket(); } private void openWebSocket() throws IOException { final String gateway = getWebSocketGateway(); try { webSocketClient = new DiscordWebSocketClient(this, new URI(gateway)); } catch (URISyntaxException e) { LOGGER.warn("Bad gateway", e); throw new IOException(e); } webSocketClient.connect(); } private String getWebSocketGateway() throws IOException { HttpResponse<JsonNode> response; try { response = Unirest.get(ApiConst.WEBSOCKET_GATEWAY). header("authorization", token). asJson(); } catch (UnirestException e) { throw new IOException("Unable to retrieve websocket gateway", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { LOGGER.warn("Unable to retrieve websocket gateway: HTTP {}: {}", status, response.getStatusText()); throw new IOException("Unable to retrieve websocket : HTTP " + status + ": " + response.getStatusText()); } String gateway = response.getBody().getObject().getString("url"); gateway = "w" + gateway.substring(2); LOGGER.info("Found WebSocket gateway at {}", gateway); return gateway; } public void sendMessage(String body, String channelId) throws IOException { // TODO } public void deleteMessage(String messageId, String channelId) throws IOException { // TODO } public boolean isOpen() { // TODO return false; } public String getToken() { return token; } public String getSessionId() { return sessionId.get(); } public void setSessionId(String sessionId) { this.sessionId.set(sessionId); } public User getClientUser() { return clientUser.get(); } public void setClientUser(User user) { clientUser.set(user); } public List<Server> getServers() { return servers; } public Map<String, Server> getServerMap() { return serverMap; } public Server getServerByID(String id) { return serverMap.get(id); } public void remapServers() { serverMap.clear(); serverMap.putAll(servers.stream().collect(Collectors.toMap(Server::getId, Function.identity()))); } public Channel getChannelById(String id) { return servers.stream(). map(Server::getChannels). flatMap(Set::stream). filter(c -> id.equals(c.getId())). findFirst().orElse(null); } public ScheduledExecutorService getExecutorService() { return executorService; } }
package com.almondtools.regexbench; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.util.stream.Collectors.toMap; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GenerateSamples { private static final Pattern PATTERN_LINE = Pattern.compile(":(\\d+)$"); private static final Path BASE = Paths.get("samples"); private static Map<String, File> files = new LinkedHashMap<>(); private GenerateSamples() { } public static File locateFile(String sampleKey) { File file = files.computeIfAbsent(sampleKey, key -> createTempFile(key)); file.deleteOnExit(); return file; } private static File createTempFile(String sampleKey) { try { String file = sampleKey + ".sample"; InputStream resourceAsStream = GenerateSamples.class.getClassLoader().getResourceAsStream(BASE.resolve(file).toString()); Path tempFile = Files.createTempFile(file, ""); Files.copy(resourceAsStream, tempFile, REPLACE_EXISTING); return tempFile.toFile(); } catch (IOException e) { return null; } } public static String readSample(String sampleKey) throws IOException { try (BufferedReader reader = open(sampleKey + ".sample")) { StringBuilder buffer = new StringBuilder(); char[] chars = new char[8192]; int n = 0; while ((n = reader.read(chars)) > -1) { buffer.append(chars, 0, n); } return buffer.toString(); } } public static Map<String, Integer> readPatterns(String resultKey) throws IOException { try (BufferedReader reader = open(resultKey + ".result")) { return reader.lines() .map(line -> unescape(line)) .map(line -> splitPattern(line)) .collect(toMap(value -> value[0], value -> Integer.parseInt(value[1]), (v1, v2) -> Math.max(v1, v2), LinkedHashMap::new)); } } public static Map<Integer, Integer> readAll(String resultKey) throws IOException { try (BufferedReader reader = open(resultKey + ".multi.result")) { return reader.lines() .map(line -> unescape(line)) .map(line -> splitPattern(line)) .collect(toMap(value -> Integer.parseInt(value[0]), value -> Integer.parseInt(value[1]))); } } public static BufferedReader open(String fileName) throws IOException { fileName = BASE.resolve(fileName).toString(); System.out.println(fileName); return new BufferedReader(new InputStreamReader(GenerateSamples.class.getClassLoader().getResourceAsStream(fileName), "UTF-8")); } private static String[] splitPattern(String line) { Matcher m = PATTERN_LINE.matcher(line); if (m.find()) { int pos = m.start(); return new String[] { line.substring(0, pos), m.group(1) }; } else { return new String[] { line, "0" }; } } private static String unescape(String str) { StringBuilder buffer = new StringBuilder(); boolean escaped = false; for (char c : str.toCharArray()) { if (escaped) { if (c == 'r') { buffer.append('\r'); } else if (c == 'n') { buffer.append('\n'); } else { buffer.append(c); } escaped = false; } else if (c == '\\') { escaped = true; } else { buffer.append(c); } } return buffer.toString(); } }
package com.celements.web.service; import java.util.Date; import java.util.List; import java.util.Map; import org.xwiki.component.annotation.ComponentRole; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.SpaceReference; import org.xwiki.model.reference.WikiReference; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.web.XWikiMessageTool; @ComponentRole public interface IWebUtilsService { public static final Date DATE_LOW = new Date(-62135773200000L); /** * {@value #DATE_HIGH} has the value [Fri Dec 31 23:59:00 CET 9999] */ public static final Date DATE_HIGH = new Date(253402297140000L); /** * Returns level of hierarchy with level=1 returning root which is null, else * corresponding DocumentReference or throws IndexOutOfBoundsException * @param level * @return DocumentReference of level * @throws IndexOutOfBoundsException - if level above root or below lowest */ public DocumentReference getParentForLevel(int level) throws IndexOutOfBoundsException; public List<DocumentReference> getDocumentParentsList(DocumentReference docRef, boolean includeDoc); public String getDocSectionAsJSON(String regex, DocumentReference docRef, int section ) throws XWikiException; public String getDocSection(String regex, DocumentReference docRef, int section ) throws XWikiException; public int countSections(String regex, DocumentReference docRef) throws XWikiException; public List<String> getAllowedLanguages(); public Date parseDate(String date, String format); public XWikiMessageTool getMessageTool(String adminLanguage); public XWikiMessageTool getAdminMessageTool(); public String getDefaultAdminLanguage(); public String getAdminLanguage(); /** * @deprecated since 2.34.0 instead use getAdminLanguage(DocumentReference userRef) */ @Deprecated public String getAdminLanguage(String userFullName); public String getAdminLanguage(DocumentReference userRef); public String getDefaultLanguage(); public String getDefaultLanguage(String spaceName); public boolean hasParentSpace(); public boolean hasParentSpace(String spaceName); public String getParentSpace(); public String getParentSpace(String spaceName); public DocumentReference resolveDocumentReference(String fullName); public DocumentReference resolveDocumentReference(String fullName, WikiReference wikiRef); public SpaceReference resolveSpaceReference(String spaceName); public SpaceReference resolveSpaceReference(String spaceName, WikiReference wikiRef); public AttachmentReference resolveAttachmentReference(String fullName); public AttachmentReference resolveAttachmentReference(String fullName, WikiReference wikiRef); public EntityReference resolveEntityReference(String name, EntityType type); public EntityReference resolveEntityReference(String name, EntityType type, WikiReference wikiRef); public boolean isAdminUser(); public boolean isAdvancedAdmin(); public boolean isSuperAdminUser(); public XWikiAttachment getAttachment(AttachmentReference attRef) throws XWikiException; public Attachment getAttachmentApi(AttachmentReference attRef) throws XWikiException; public List<Attachment> getAttachmentListSortedSpace(String spaceName, String comparator, boolean imagesOnly, int start, int nb ) throws ClassNotFoundException; public List<Attachment> getAttachmentListForTagSortedSpace(String spaceName, String tagName, String comparator, boolean imagesOnly, int start, int nb ) throws ClassNotFoundException; //TODO change signature requirement to XWikiDocument instead of document and mark // the old version as deprecated public List<Attachment> getAttachmentListSorted(Document doc, String comparator) throws ClassNotFoundException; //TODO change signature requirement to XWikiDocument instead of document and mark // the old version as deprecated public List<Attachment> getAttachmentListSorted(Document doc, String comparator, boolean imagesOnly); //TODO change signature requirement to XWikiDocument instead of document and mark // the old version as deprecated public List<Attachment> getAttachmentListSorted(Document doc, String comparator, boolean imagesOnly, int start, int nb); //TODO change signature requirement to XWikiDocument instead of document and mark // the old version as deprecated public List<Attachment> getAttachmentListForTagSorted(Document doc, String tagName, String comparator, boolean imagesOnly, int start, int nb); //TODO change signature requirement to XWikiDocument instead of document and mark // the old version as deprecated public String getAttachmentListSortedAsJSON(Document doc, String comparator, boolean imagesOnly); //TODO change signature requirement to XWikiDocument instead of document and mark // the old version as deprecated public String getAttachmentListSortedAsJSON(Document doc, String comparator, boolean imagesOnly, int start, int nb); public List<BaseObject> getObjectsOrdered(XWikiDocument doc, DocumentReference classRef, String orderField, boolean asc); public List<BaseObject> getObjectsOrdered(XWikiDocument doc, DocumentReference classRef, String orderField1, boolean asc1, String orderField2, boolean asc2); public String[] splitStringByLength(String inStr, int maxLength); public String getJSONContent(XWikiDocument cdoc); public String getJSONContent(DocumentReference docRef); public String getUserNameForDocRef(DocumentReference authDocRef) throws XWikiException; public String getMajorVersion(XWikiDocument doc); public WikiReference getWikiRef(); public WikiReference getWikiRef(XWikiDocument doc); public WikiReference getWikiRef(DocumentReference docRef); public WikiReference getWikiRef(EntityReference ref); public List<String> getAllowedLanguages(String spaceName); public DocumentReference getWikiTemplateDocRef(); public XWikiDocument getWikiTemplateDoc(); public EntityReferenceSerializer<String> getRefDefaultSerializer(); public EntityReferenceSerializer<String> getRefLocalSerializer(); public String serializeRef(EntityReference entityRef); public String serializeRef(EntityReference entityRef, boolean local); public Map<String, String[]> getRequestParameterMap(); public String getInheritedTemplatedPath(DocumentReference localTemplateRef); public void deleteDocument(XWikiDocument doc, boolean totrash) throws XWikiException; public void deleteAllDocuments(XWikiDocument doc, boolean totrash ) throws XWikiException; public String getTemplatePathOnDisk(String renderTemplatePath); public String getTemplatePathOnDisk(String renderTemplatePath, String lang); public String renderInheritableDocument(DocumentReference docRef, String lang ) throws XWikiException; public String renderInheritableDocument(DocumentReference docRef, String lang, String defLang) throws XWikiException; public boolean isLayoutEditor(); public String cleanupXHTMLtoHTML5(String xhtml); public String cleanupXHTMLtoHTML5(String xhtml, DocumentReference doc); public String cleanupXHTMLtoHTML5(String xhtml, SpaceReference layoutRef); public List<Attachment> getAttachmentsForDocs(List<String> docsFN); public String getTranslatedDiscTemplateContent(String renderTemplatePath, String lang, String defLang); public boolean existsInheritableDocument(DocumentReference docRef, String lang); public boolean existsInheritableDocument(DocumentReference docRef, String lang, String defLang); /** * used to send an email if result of <param>jobMailName</param> is not empty * * @param jobMailName inheritable Mails document name * @param fromAddr sender address * @param toAddr recipients * @param params list of strings passed through to dictionary subject resolving */ public void sendCheckJobMail(String jobMailName, String fromAddr, String toAddr, List<String> params); public WikiReference getCentralWikiRef(); /** * resolves the {@link EntityType} for the given fullName.<br> * <br> * Simple names will return {@link EntityType#WIKI}. * * @param fullName * @return */ public EntityType resolveEntityTypeForFullName(String fullName); /** * resolves the {@link EntityType} for the given fullName. * * @param fullName * @param defaultNameType EntityType used if given fullName is just a simple name * @return */ public EntityType resolveEntityTypeForFullName(String fullName, EntityType defaultNameType); }
package com.conveyal.r5.api.util; import java.io.Serializable; import java.util.Set; /** * Information about Bike rental station */ public class BikeRentalStation implements Serializable { //@notnull public String id; public String name; //Coordinates @notnull public float lat, lon; public int bikesAvailable; public int spacesAvailable; public boolean allowDropoff = true; public Set<String> networks; public boolean realTimeData = false; @Override public String toString() { String sb = "BikeRentalStation{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", lat=" + lat + ", lon=" + lon + ", bikesAvailable=" + bikesAvailable + ", spacesAvailable=" + spacesAvailable + ", allowDropoff=" + allowDropoff + ", networks=" + networks + ", realTimeData=" + realTimeData + '}'; return sb; } }
package com.orhanobut.wasp; import com.orhanobut.wasp.http.Body; import com.orhanobut.wasp.http.BodyMap; import com.orhanobut.wasp.http.Header; import com.orhanobut.wasp.http.Path; import com.orhanobut.wasp.http.Query; import com.orhanobut.wasp.http.RetryPolicy; import com.orhanobut.wasp.parsers.Parser; import com.orhanobut.wasp.utils.AuthToken; import com.orhanobut.wasp.utils.RequestInterceptor; import com.orhanobut.wasp.utils.CollectionUtils; import com.orhanobut.wasp.utils.WaspRetryPolicy; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * @author Orhan Obut */ final class WaspRequest { private final String url; private final String method; private final Map<String, String> headers; private final String body; private final WaspRetryPolicy retryPolicy; private final WaspMock mock; private final MethodInfo methodInfo; private WaspRequest(Builder builder) { this.url = builder.getUrl(); this.method = builder.getHttpMethod(); this.headers = builder.getHeaders(); this.body = builder.getBody(); this.retryPolicy = builder.getRetryPolicy(); this.mock = builder.getMock(); this.methodInfo = builder.getMethodInfo(); } String getUrl() { return url; } String getMethod() { return method; } Map<String, String> getHeaders() { return headers != null ? headers : Collections.<String, String>emptyMap(); } String getBody() { return body; } WaspMock getMock() { return mock; } WaspRetryPolicy getRetryPolicy() { return retryPolicy; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Request URL : ").append(url); if (body != null) { builder.append(", Body: ").append(body); } if (!getHeaders().isEmpty()) { //TODO add header output } return builder.toString(); } public MethodInfo getMethodInfo() { return methodInfo; } static class Builder { private static final String KEY_AUTH = "Authorization"; private final MethodInfo methodInfo; private final String baseUrl; private final Object[] args; private final Parser parser; private String body; private String relativeUrl; private WaspRetryPolicy retryPolicy; private StringBuilder queryParamBuilder; private Map<String, String> headers; private RequestInterceptor requestInterceptor; Builder(MethodInfo methodInfo, Object[] args, String baseUrl, Parser parser) { this.methodInfo = methodInfo; this.baseUrl = baseUrl; this.args = args; this.parser = parser; this.relativeUrl = methodInfo.getRelativeUrl(); initParams(); } private void initParams() { Annotation[] annotations = methodInfo.getMethodAnnotations(); int count = annotations.length; for (int i = 0; i < count; i++) { Object value = args[i]; if (value == null) { throw new NullPointerException("Value cannot be null"); } Annotation annotation = annotations[i]; if (annotation == null) { continue; } Class<? extends Annotation> annotationType = annotation.annotationType(); if (annotationType == Path.class) { String key = ((Path) annotation).value(); addPathParam(key, String.valueOf(value)); continue; } if (annotationType == Query.class) { String key = ((Query) annotation).value(); addQueryParam(key, value); continue; } if (annotationType == Header.class) { String key = ((Header) annotation).value(); addHeaderParam(key, (String) value); continue; } if (annotationType == Body.class) { body = getBody(value); } if (annotationType == BodyMap.class) { if (!(value instanceof Map)) { throw new IllegalArgumentException("BodyMap accepts only Map instances"); } Map<String, Object> map; try { map = (Map<String, Object>) value; } catch (Exception e) { throw new ClassCastException("Map type should be Map<String,Object>"); } body = CollectionUtils.toJson(map); } } } Builder setRequestInterceptor(RequestInterceptor interceptor) { this.requestInterceptor = interceptor; return this; } /** * Merges static and param headers and create a request. * * @return WaspRequest */ WaspRequest build() { postInit(); return new WaspRequest(this); } /** * It is called right before building a request, this method will add * intercepted headers, params, static headers and retry policy */ private void postInit() { //Add static headers for (Map.Entry<String, String> entry : methodInfo.getHeaders().entrySet()) { addHeaderParam(entry.getKey(), entry.getValue()); } //Set retry policy if (methodInfo.getRetryPolicy() != null) { retryPolicy = methodInfo.getRetryPolicy(); } if (requestInterceptor == null) { return; } //Add intercepted query params Map<String, Object> tempQueryParams = new HashMap<>(); requestInterceptor.onQueryParamsAdded(tempQueryParams); for (Map.Entry<String, Object> entry : tempQueryParams.entrySet()) { addQueryParam(entry.getKey(), entry.getValue()); } //Add intercepted headers Map<String, String> tempHeaders = new HashMap<>(); requestInterceptor.onHeadersAdded(tempHeaders); for (Map.Entry<String, String> entry : tempHeaders.entrySet()) { addHeaderParam(entry.getKey(), entry.getValue()); } //If retry policy is not already set via annotations than set it via requestInterceptor WaspRetryPolicy waspRetryPolicy = requestInterceptor.getRetryPolicy(); if (retryPolicy == null && waspRetryPolicy != null) { retryPolicy = waspRetryPolicy; } // If authToken is set, it will check if the filter is enabled // it will add token to each request if the filter is not enabled // If the filter is enabled, it will be added to request which has @Auth annotation AuthToken authToken = requestInterceptor.getAuthToken(); if (authToken != null) { String token = authToken.getToken(); if (!authToken.isFilterEnabled()) { addHeaderParam(KEY_AUTH, token); return; } if (methodInfo.isAuthTokenEnabled()) { addHeaderParam(KEY_AUTH, token); } } } private String getBody(Object body) { return parser.toJson(body); } /** * If endpoint is set as annotation, it uses that endpoint for the call, otherwise it uses endpoint * * @return full url */ private String getUrl() { String endpoint = methodInfo.getBaseUrl(); if (endpoint == null) { endpoint = baseUrl; } return endpoint + relativeUrl + getQueryString(); } private String getQueryString() { if (queryParamBuilder == null) { return ""; } return queryParamBuilder.toString(); } private void addPathParam(String key, String value) { relativeUrl = relativeUrl.replace("{" + key + "}", value); } private void addQueryParam(String key, Object value) { StringBuilder builder = this.queryParamBuilder; if (queryParamBuilder == null) { this.queryParamBuilder = builder = new StringBuilder(); } builder.append(queryParamBuilder.length() == 0 ? "?" : "&"); builder.append(key).append("=").append(value); } private void addHeaderParam(String key, String value) { Map<String, String> headers = this.headers; if (headers == null) { this.headers = headers = new LinkedHashMap<>(); } headers.put(key, value); } String getHttpMethod() { return methodInfo.getHttpMethod(); } Map<String, String> getHeaders() { return headers; } String getBody() { return body; } WaspRetryPolicy getRetryPolicy() { return retryPolicy; } WaspMock getMock() { return methodInfo.getMock(); } MethodInfo getMethodInfo() { return methodInfo; } } }
package com.ctrip.zeus.tag.impl; import com.ctrip.zeus.dal.core.*; import com.ctrip.zeus.exceptions.ValidationException; import com.ctrip.zeus.tag.PropertyBox; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.*; @Component("propertyBox") public class DefaultPropertyBox implements PropertyBox { @Resource private PropertyDao propertyDao; @Resource private PropertyKeyDao propertyKeyDao; @Resource private PropertyItemDao propertyItemDao; @Override public void removeProperty(String pname, boolean force) throws Exception { PropertyKeyDo d = propertyKeyDao.findByName(pname, PropertyKeyEntity.READSET_FULL); if (d == null) return; List<PropertyDo> properties = propertyDao.findAllByKey(d.getId(), PropertyEntity.READSET_FULL); if (properties.size() == 0) return; PropertyItemDo[] pitems = new PropertyItemDo[properties.size()]; for (int i = 0; i < pitems.length; i++) { pitems[i] = new PropertyItemDo().setPropertyId(properties.get(i).getId()); } if (force) { propertyItemDao.deleteByProperty(pitems); } else { Long[] propertyIds = new Long[properties.size()]; for (int i = 0; i < propertyIds.length; i++) { propertyIds[i] = properties.get(i).getId(); } List<PropertyItemDo> check = propertyItemDao.findAllByProperties(propertyIds, PropertyItemEntity.READSET_FULL); if (check.size() > 0) { throw new ValidationException("Dependency exists with property named - " + pname + "."); } } propertyDao.delete(properties.toArray(new PropertyDo[properties.size()])); propertyKeyDao.delete(d); } @Override public void renameProperty(String originPname, String updatedPname) throws Exception { PropertyKeyDo kd = propertyKeyDao.findByName(originPname, PropertyKeyEntity.READSET_FULL); if (kd == null) return; propertyKeyDao.update(kd.setName(updatedPname), PropertyKeyEntity.UPDATESET_FULL); } @Override public boolean set(String pname, String pvalue, String type, Long itemId) throws Exception { PropertyKeyDo pkd = propertyKeyDao.findByName(pname, PropertyKeyEntity.READSET_FULL); if (pkd == null) { pkd = new PropertyKeyDo().setName(pname); propertyKeyDao.insert(pkd); } Set<Long> properties = new HashSet<>(); PropertyDo targetProperty = null; for (PropertyDo e : propertyDao.findAllByKey(pkd.getId(), PropertyEntity.READSET_FULL)) { properties.add(e.getId()); if (e.getPropertyValue().equals(pvalue)) { targetProperty = e; } } if (targetProperty == null) { targetProperty = new PropertyDo().setPropertyKeyId(pkd.getId()).setPropertyValue(pvalue); propertyDao.insert(targetProperty); } List<PropertyItemDo> items = propertyItemDao.findAllByItemAndProperties(itemId, properties.toArray(new Long[properties.size()]), PropertyItemEntity.READSET_FULL); PropertyItemDo d = null; Iterator<PropertyItemDo> iter = items.iterator(); while (iter.hasNext()) { PropertyItemDo n = iter.next(); if (n.getType().equals(type)) { d = n; iter.remove(); } else { iter.remove(); } } if (items.size() > 0) { propertyItemDao.deleteById(items.toArray(new PropertyItemDo[items.size()])); } if (d == null) { propertyItemDao.insert(new PropertyItemDo().setPropertyId(targetProperty.getId()).setItemId(itemId).setType(type)); } else { if (d.getPropertyId() == targetProperty.getId()) return false; d.setPropertyId(targetProperty.getId()); propertyItemDao.update(d, PropertyItemEntity.UPDATESET_FULL); } return true; } @Override public void set(String pname, String pvalue, String type, Long[] itemIds) throws Exception { PropertyKeyDo pkd = propertyKeyDao.findByName(pname, PropertyKeyEntity.READSET_FULL); if (pkd == null) { pkd = new PropertyKeyDo().setName(pname); propertyKeyDao.insert(pkd); } Set<Long> properties = new HashSet<>(); PropertyDo targetProperty = null; for (PropertyDo e : propertyDao.findAllByKey(pkd.getId(), PropertyEntity.READSET_FULL)) { properties.add(e.getId()); if (e.getPropertyValue().equals(pvalue)) { targetProperty = e; } } if (targetProperty == null) { targetProperty = new PropertyDo().setPropertyKeyId(pkd.getId()).setPropertyValue(pvalue); propertyDao.insert(targetProperty); } List<PropertyItemDo> adding = new ArrayList<>(); List<PropertyItemDo> removing = new ArrayList<>(); List<PropertyItemDo> updating = new ArrayList<>(); Set<Long> uniqItemIds = new HashSet<>(); for (Long itemId : itemIds) { uniqItemIds.add(itemId); } Map<Long, PropertyItemDo> items = new HashMap<>(); for (PropertyItemDo e : propertyItemDao.findAllByProperties(properties.toArray(new Long[properties.size()]), PropertyItemEntity.READSET_FULL)) { if (uniqItemIds.contains(e.getItemId())) { if (e.getType().equals(type)) { PropertyItemDo dup = items.put(e.getItemId(), e); if (dup != null) { removing.add(dup); } } } } for (Long itemId : uniqItemIds) { PropertyItemDo d = items.get(itemId); if (d == null) { adding.add(new PropertyItemDo().setPropertyId(targetProperty.getId()).setItemId(itemId).setType(type)); } else { if (d.getPropertyId() == targetProperty.getId()) continue; d.setPropertyId(targetProperty.getId()); updating.add(d); } } if (adding.size() > 0) { propertyItemDao.insert(adding.toArray(new PropertyItemDo[adding.size()])); } if (removing.size() > 0) { propertyItemDao.deleteById(removing.toArray(new PropertyItemDo[removing.size()])); } if (updating.size() > 0) { propertyItemDao.update(updating.toArray(new PropertyItemDo[updating.size()]), PropertyItemEntity.UPDATESET_FULL); } } @Override public boolean clear(String type, Long itemId) throws Exception { List<PropertyItemDo> list = propertyItemDao.findAllByItemAndType(itemId, type, PropertyItemEntity.READSET_FULL); if (list.size() > 0) { propertyItemDao.deleteById(list.toArray(new PropertyItemDo[list.size()])); return true; } return false; } @Override public boolean clear(String pname, String pvalue, String type, Long itemId) throws Exception { PropertyKeyDo pkd = propertyKeyDao.findByName(pname, PropertyKeyEntity.READSET_FULL); if (pkd == null) return false; PropertyDo pd = propertyDao.findByKeyAndValue(pkd.getId(), pvalue, PropertyEntity.READSET_FULL); if (pd == null) return false; PropertyItemDo pid = propertyItemDao.findByPropertyAndItem(pd.getId(), itemId, type, PropertyItemEntity.READSET_FULL); if (pid == null) return false; propertyItemDao.deleteById(pid); return true; } @Override public void clear(String pname, String pvalue, String type, Long[] itemIds) throws Exception { PropertyKeyDo pkd = propertyKeyDao.findByName(pname, PropertyKeyEntity.READSET_FULL); if (pkd == null) return; PropertyDo pd = propertyDao.findByKeyAndValue(pkd.getId(), pvalue, PropertyEntity.READSET_FULL); if (pd == null) return; List<PropertyItemDo> removing = new ArrayList<>(); for (Long itemId : itemIds) { PropertyItemDo pid = propertyItemDao.findByPropertyAndItem(pd.getId(), itemId, type, PropertyItemEntity.READSET_FULL); if (pid == null) continue; removing.add(pid); } if (removing.size() > 0) { propertyItemDao.deleteById(removing.toArray(new PropertyItemDo[removing.size()])); } } }
package com.foodrater.verticles; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.mongo.MongoClient; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.core.logging.Logger; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; public class RestServerVerticle extends AbstractVerticle { private static final Logger LOGGER = LoggerFactory.getLogger(RestServerVerticle.class.getSimpleName()); private Map<String, JsonObject> products = new HashMap<>(); public static final String ADDRESS = "mongodb-persistor"; public static final String DEFAULT_MONGODB_CONFIG = "{" + " \"address\": \"" + ADDRESS + "\"," + " \"host\": \"localhost\"," + " \"port\": 27017," + " \"db_name\": \"bs\"," + " \"useObjectId\" : true" + "}"; MongoClient mongo; @Override public void start() { mongo = MongoClient.createShared(vertx, new JsonObject(DEFAULT_MONGODB_CONFIG)); LOGGER.info("MongoClient is started with this config: " + new JsonObject(DEFAULT_MONGODB_CONFIG).encodePrettily()); //setUpInitialData(); Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.get("/products/:productID").handler(this::handleGetProduct); router.get("/products/search/:words").handler(this::searchProduct); router.put("/products/:productID").handler(this::handleAddProduct); router.get("/products").handler(this::handleListProducts); router.get("/initialize").handler(this::setUpInitialData); router.get("/myproducts/:userID").handler(this::getAllProductsForUser); router.get("/user/:userID").handler(this::getUserInformation); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } private void getUserInformation(RoutingContext routingContext) { // return all user info } private void getAllProductsForUser(RoutingContext routingContext) { // return all products for user as json -> {prodId:{productjson1}, {productjson2}, ... } } private void searchProduct(RoutingContext routingContext) { // return all products with name inside as json // { {product1}, {product2}, {product3}.. } } private void setUpInitialData(RoutingContext routingContext) { addProduct(new JsonObject().put("id", "prod3568").put("name", "Egg Whisk").put("price", 3.99).put("weight", 150)); addProduct(new JsonObject().put("id", "prod7340").put("name", "Tea Cosy").put("price", 5.99).put("weight", 100)); addProduct(new JsonObject().put("id", "prod8643").put("name", "Spatula").put("price", 1.00).put("weight", 80)); // + average rating and amount of ratings HttpServerResponse response = routingContext.response(); response.putHeader("content-type", "application/json").end("initialized"); } private void handleGetProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { //JsonObject product = products.get(productID); JsonObject product = findProductInMongoDB(productID); if (product == null) { sendError(404, response); } else { response.putHeader("content-type", "application/json").end(product.encode()); } } } private JsonObject findProductInMongoDB(String productID) { JsonObject query = new JsonObject(); query.put(productID + ".id", productID); JsonObject result = new JsonObject(); CountDownLatch latch = new CountDownLatch(1); LOGGER.info("Trying to find " + query.encodePrettily()); mongo.find("products", query, res -> { if (res.succeeded()) { for (JsonObject json : res.result()) { LOGGER.info("Found product:" + json.encodePrettily()); result.put(productID, json); LOGGER.info("Result Json:" + result.encodePrettily()); } } latch.countDown(); }); LOGGER.info("Final result Json:" + result.encodePrettily()); try { latch.await(); } catch (InterruptedException e) { LOGGER.error("latch error: " + e.getMessage()); } return result; } private void handleAddProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { JsonObject product = routingContext.getBodyAsJson(); // change product to user if (product == null) { sendError(400, response); } else { products.put(productID, product); JsonObject productAsJson = new JsonObject(); productAsJson.put(productID, product); insertInMongo(productAsJson); response.end(); } } } private void insertInMongo(JsonObject productAsJson) { // calculate average rating + update product database averageRating + update user database add userproducts : {productId : , userRating : } mongo.insert(("products"), productAsJson, res -> { if (res.succeeded()) { String id = res.result(); } else { res.cause().printStackTrace(); } }); } private void handleListProducts(RoutingContext routingContext) { JsonArray arr = new JsonArray(); products.forEach((k, v) -> arr.add(v)); routingContext.response().putHeader("content-type", "application/json").end(arr.encodePrettily()); } private void sendError(int statusCode, HttpServerResponse response) { response.setStatusCode(statusCode).end(); } private void addProduct(JsonObject product) { products.put(product.getString("id"), product); JsonObject jsonObject = new JsonObject(); jsonObject.put(product.getString("id"), product); LOGGER.info("JsonObject to insert: " + jsonObject.encodePrettily()); insertInMongo(jsonObject); } }
package com.github.ferstl; import java.util.IntSummaryStatistics; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.PrimitiveIterator.OfInt; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.function.BiConsumer; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.ObjIntConsumer; import java.util.function.Supplier; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import static java.util.concurrent.ForkJoinTask.adapt; public class ParallelIntStreamSupport implements IntStream { private IntStream delegate; private final ForkJoinPool workerPool; ParallelIntStreamSupport(IntStream delegate, ForkJoinPool workerPool) { this.delegate = delegate; this.workerPool = workerPool; } @Override public IntStream filter(IntPredicate predicate) { this.delegate = this.delegate.filter(predicate); return this; } @Override public boolean isParallel() { return this.delegate.isParallel(); } @Override public IntStream map(IntUnaryOperator mapper) { this.delegate = this.delegate.map(mapper); return this; } @Override public <U> Stream<U> mapToObj(IntFunction<? extends U> mapper) { return new ParallelStreamSupport<U>(this.delegate.mapToObj(mapper), this.workerPool); } @Override public IntStream unordered() { this.delegate = this.delegate.unordered(); return this; } @Override public LongStream mapToLong(IntToLongFunction mapper) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public IntStream onClose(Runnable closeHandler) { this.delegate = this.delegate.onClose(closeHandler); return this; } @Override public DoubleStream mapToDouble(IntToDoubleFunction mapper) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void close() { this.delegate.close(); } @Override public IntStream flatMap(IntFunction<? extends IntStream> mapper) { this.delegate = this.delegate.flatMap(mapper); return this; } @Override public IntStream distinct() { this.delegate = this.delegate.distinct(); return this; } @Override public IntStream sorted() { this.delegate = this.delegate.sorted(); return this; } @Override public IntStream peek(IntConsumer action) { this.delegate = this.delegate.peek(action); return this; } @Override public IntStream limit(long maxSize) { this.delegate = this.delegate.limit(maxSize); return this; } @Override public IntStream skip(long n) { this.delegate = this.delegate.skip(n); return this; } @Override public void forEach(IntConsumer action) { if (isParallel()) { ForkJoinTask<?> task = adapt(() -> this.delegate.forEach(action)); this.workerPool.invoke(task); } else { this.delegate.forEach(action); } } @Override public void forEachOrdered(IntConsumer action) { if (isParallel()) { ForkJoinTask<?> task = adapt(() -> this.delegate.forEachOrdered(action)); this.workerPool.invoke(task); } else { this.delegate.forEachOrdered(action); } } @Override public int[] toArray() { if (isParallel()) { ForkJoinTask<int[]> task = adapt(() -> this.delegate.toArray()); return this.workerPool.invoke(task); } return this.delegate.toArray(); } @Override public int reduce(int identity, IntBinaryOperator op) { if (isParallel()) { ForkJoinTask<Integer> task = adapt(() -> this.delegate.reduce(identity, op)); return this.workerPool.invoke(task); } return this.delegate.reduce(identity, op); } @Override public OptionalInt reduce(IntBinaryOperator op) { if (isParallel()) { ForkJoinTask<OptionalInt> task = adapt(() -> this.delegate.reduce(op)); return this.workerPool.invoke(task); } return this.delegate.reduce(op); } @Override public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) { if (isParallel()) { ForkJoinTask<R> task = adapt(() -> this.delegate.collect(supplier, accumulator, combiner)); return this.workerPool.invoke(task); } return this.delegate.collect(supplier, accumulator, combiner); } @Override public int sum() { if (isParallel()) { ForkJoinTask<Integer> task = adapt(() -> this.delegate.sum()); return this.workerPool.invoke(task); } return this.delegate.sum(); } @Override public OptionalInt min() { if (isParallel()) { ForkJoinTask<OptionalInt> task = adapt(() -> this.delegate.min()); return this.workerPool.invoke(task); } return this.delegate.min(); } @Override public OptionalInt max() { if (isParallel()) { ForkJoinTask<OptionalInt> task = adapt(() -> this.delegate.max()); return this.workerPool.invoke(task); } return this.delegate.max(); } @Override public long count() { if (isParallel()) { ForkJoinTask<Long> task = adapt(() -> this.delegate.count()); return this.workerPool.invoke(task); } return this.delegate.count(); } @Override public OptionalDouble average() { if (isParallel()) { ForkJoinTask<OptionalDouble> task = adapt(() -> this.delegate.average()); return this.workerPool.invoke(task); } return this.delegate.average(); } @Override public IntSummaryStatistics summaryStatistics() { if (isParallel()) { ForkJoinTask<IntSummaryStatistics> task = adapt(() -> this.delegate.summaryStatistics()); return this.workerPool.invoke(task); } return this.delegate.summaryStatistics(); } @Override public boolean anyMatch(IntPredicate predicate) { if (isParallel()) { ForkJoinTask<Boolean> task = adapt(() -> this.delegate.anyMatch(predicate)); return this.workerPool.invoke(task); } return this.delegate.anyMatch(predicate); } @Override public boolean allMatch(IntPredicate predicate) { if (isParallel()) { ForkJoinTask<Boolean> task = adapt(() -> this.delegate.allMatch(predicate)); return this.workerPool.invoke(task); } return this.delegate.allMatch(predicate); } @Override public boolean noneMatch(IntPredicate predicate) { if (isParallel()) { ForkJoinTask<Boolean> task = adapt(() -> this.delegate.noneMatch(predicate)); return this.workerPool.invoke(task); } return this.delegate.noneMatch(predicate); } @Override public OptionalInt findFirst() { if (isParallel()) { ForkJoinTask<OptionalInt> task = adapt(() -> this.delegate.findFirst()); return this.workerPool.invoke(task); } return this.delegate.findFirst(); } @Override public OptionalInt findAny() { if (isParallel()) { ForkJoinTask<OptionalInt> task = adapt(() -> this.delegate.findAny()); return this.workerPool.invoke(task); } return this.delegate.findAny(); } @Override public LongStream asLongStream() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public DoubleStream asDoubleStream() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Stream<Integer> boxed() { return new ParallelStreamSupport<Integer>(this.delegate.boxed(), this.workerPool); } @Override public IntStream sequential() { this.delegate = this.delegate.sequential(); return this; } @Override public IntStream parallel() { this.delegate = this.delegate.parallel(); return this; } @Override public OfInt iterator() { return this.delegate.iterator(); } @Override public java.util.Spliterator.OfInt spliterator() { return this.delegate.spliterator(); } }
package com.gmail.nossr50.listeners; import java.util.Iterator; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.chat.ChatManager; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.party.ShareHandler; import com.gmail.nossr50.runnables.skills.BleedTimerTask; import com.gmail.nossr50.skills.fishing.FishingManager; import com.gmail.nossr50.skills.herbalism.HerbalismManager; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.ChimaeraWing; import com.gmail.nossr50.util.HardcoreManager; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Motd; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillUtils; public class PlayerListener implements Listener { private final mcMMO plugin; public PlayerListener(final mcMMO plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerDeathHighest(PlayerDeathEvent event) { String deathMessage = event.getDeathMessage(); deathMessage.replaceAll("(?:\u00A7(?:[0-9A-FK-ORa-fk-or]){1}(?:[\u2764\u25A0]{1,10})){1,2}", "a mob"); event.setDeathMessage(deathMessage); } /** * Monitor PlayerDeath events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { if (!Config.getInstance().getHardcoreEnabled()) { return; } Player player = event.getEntity(); if (Misc.isNPCEntity(player)) { return; } if (!Permissions.hardcoreBypass(player)) { Player killer = player.getKiller(); if (killer != null && Config.getInstance().getHardcoreVampirismEnabled()) { HardcoreManager.invokeVampirism(killer, player); } HardcoreManager.invokeStatPenalty(player); } } /** * Monitor PlayerChangedWorld events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerWorldChangeEvent(PlayerChangedWorldEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player)) { return; } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); if (mcMMOPlayer.getGodMode() && !Permissions.mcgod(player)) { mcMMOPlayer.toggleGodMode(); player.sendMessage(LocaleLoader.getString("Commands.GodMode.Forbidden")); } if (mcMMOPlayer.inParty() && !Permissions.party(player)) { mcMMOPlayer.removeParty(); player.sendMessage(LocaleLoader.getString("Party.Forbidden")); } } /** * Monitor PlayerLogin events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerLoginEvent(PlayerLoginEvent event) { if (event.getResult() == Result.ALLOWED) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player)) { return; } UserManager.addUser(player).actualizeRespawnATS(); } } /** * Handle PlayerDropItem events that involve modifying the event. * * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerDropItemEvent(PlayerDropItemEvent event) { Player player = event.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); if (mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER) || mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER)) { event.setCancelled(true); return; } SkillUtils.removeAbilityBuff(event.getItemDrop().getItemStack()); } /** * Monitor PlayerFish events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFish(PlayerFishEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player) || !Permissions.skillEnabled(player, SkillType.FISHING)) { return; } FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); switch (event.getState()) { case FISHING: if (fishingManager.canMasterAngler()) { fishingManager.masterAngler(event.getHook()); } break; case CAUGHT_FISH: fishingManager.handleFishing((Item) event.getCaught()); if (Permissions.vanillaXpBoost(player, SkillType.FISHING)) { event.setExpToDrop(fishingManager.handleVanillaXpBoost(event.getExpToDrop())); } break; case CAUGHT_ENTITY: Entity entity = event.getCaught(); if (fishingManager.canShake(entity)) { fishingManager.shakeCheck((LivingEntity) entity); } break; default: break; } } /** * Monitor PlayerPickupItem events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerPickupItem(PlayerPickupItemEvent event) { Player player = event.getPlayer(); Item drop = event.getItem(); ItemStack dropStack = drop.getItemStack(); if (Misc.isNPCEntity(player)) { return; } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); if (mcMMOPlayer.inParty() && ItemUtils.isShareable(dropStack)) { event.setCancelled(ShareHandler.handleItemShare(drop, mcMMOPlayer)); } if (event.isCancelled()) { return; } PlayerInventory inventory = player.getInventory(); int firstEmpty = inventory.firstEmpty(); if (mcMMOPlayer.isUsingUnarmed() && ItemUtils.isShareable(dropStack) && firstEmpty == inventory.getHeldItemSlot()) { int nextSlot = firstEmpty + 1; for (Iterator<ItemStack> iterator = inventory.iterator(nextSlot); iterator.hasNext();) { ItemStack itemstack = iterator.next(); if (itemstack == null) { drop.remove(); inventory.setItem(nextSlot, dropStack); player.updateInventory(); event.setCancelled(true); return; } nextSlot++; } } } /** * Monitor PlayerQuit events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player)) { return; } if (UserManager.getPlayer(player).getAbilityMode(AbilityType.BERSERK)) { player.setCanPickupItems(true); } /* GARBAGE COLLECTION */ BleedTimerTask.bleedOut(player); // Bleed it out } /** * Monitor PlayerJoin events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (UserManager.getPlayer(player).getAbilityMode(AbilityType.BERSERK)) { player.setCanPickupItems(false); } if (Config.getInstance().getMOTDEnabled() && Permissions.motd(player)) { Motd.displayAll(player); } if (plugin.isXPEventEnabled()) { player.sendMessage(LocaleLoader.getString("XPRate.Event", Config.getInstance().getExperienceGainsGlobalMultiplier())); } if (Permissions.updateNotifications(player) && mcMMO.p.updateAvailable) { player.sendMessage(LocaleLoader.getString("UpdateChecker.outdated")); player.sendMessage(LocaleLoader.getString("UpdateChecker.newavailable")); } } /** * Monitor PlayerRespawn events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerRespawn(PlayerRespawnEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player)) { return; } UserManager.getPlayer(player).actualizeRespawnATS(); } /** * Handle PlayerInteract events that involve modifying the event. * * @param event The event to modify */ @EventHandler(priority = EventPriority.LOWEST) public void onPlayerInteractLowest(PlayerInteractEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player) || player.getGameMode() == GameMode.CREATIVE) { return; } Block block = event.getClickedBlock(); ItemStack heldItem = player.getItemInHand(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); MiningManager miningManager = mcMMOPlayer.getMiningManager(); switch (event.getAction()) { case RIGHT_CLICK_BLOCK: int blockID = block.getTypeId(); /* REPAIR CHECKS */ if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.repairableManager.isRepairable(heldItem)) { UserManager.getPlayer(player).getRepairManager().handleRepair(heldItem); event.setCancelled(true); player.updateInventory(); } /* SALVAGE CHECKS */ else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem)) { UserManager.getPlayer(player).getRepairManager().handleSalvage(block.getLocation(), heldItem); event.setCancelled(true); player.updateInventory(); } /* BLAST MINING CHECK */ else if (miningManager.canDetonate()) { if (blockID == Material.TNT.getId()) { event.setCancelled(true); // Don't detonate the TNT if they're too close } else { miningManager.remoteDetonation(); } } break; case RIGHT_CLICK_AIR: /* BLAST MINING CHECK */ if (miningManager.canDetonate()) { miningManager.remoteDetonation(); } break; default: break; } } /** * Monitor PlayerInteract events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player) || player.getGameMode() == GameMode.CREATIVE) { return; } ItemStack heldItem = player.getItemInHand(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); switch (event.getAction()) { case RIGHT_CLICK_BLOCK: Block block = event.getClickedBlock(); BlockState blockState = block.getState(); /* ACTIVATION & ITEM CHECKS */ if (BlockUtils.canActivateAbilities(blockState)) { if (Config.getInstance().getAbilitiesEnabled()) { if (BlockUtils.canActivateHerbalism(blockState)) { SkillUtils.activationCheck(player, SkillType.HERBALISM); } SkillUtils.activationCheck(player, SkillType.AXES); SkillUtils.activationCheck(player, SkillType.EXCAVATION); SkillUtils.activationCheck(player, SkillType.MINING); SkillUtils.activationCheck(player, SkillType.SWORDS); SkillUtils.activationCheck(player, SkillType.UNARMED); SkillUtils.activationCheck(player, SkillType.WOODCUTTING); } ChimaeraWing.activationCheck(player); } /* GREEN THUMB CHECK */ HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager(); if (herbalismManager.canGreenThumbBlock(blockState)) { player.setItemInHand(new ItemStack(Material.SEEDS, heldItem.getAmount() - 1)); if (herbalismManager.processGreenThumbBlocks(blockState) && SkillUtils.blockBreakSimulate(block, player, false)) { blockState.update(true); } } /* SHROOM THUMB CHECK */ else if (herbalismManager.canUseShroomThumb(blockState)) { if (herbalismManager.processShroomThumb(blockState) && SkillUtils.blockBreakSimulate(block, player, false)) { blockState.update(true); } } break; case RIGHT_CLICK_AIR: /* ACTIVATION CHECKS */ if (Config.getInstance().getAbilitiesEnabled()) { SkillUtils.activationCheck(player, SkillType.AXES); SkillUtils.activationCheck(player, SkillType.EXCAVATION); SkillUtils.activationCheck(player, SkillType.HERBALISM); SkillUtils.activationCheck(player, SkillType.MINING); SkillUtils.activationCheck(player, SkillType.SWORDS); SkillUtils.activationCheck(player, SkillType.UNARMED); SkillUtils.activationCheck(player, SkillType.WOODCUTTING); } /* ITEM CHECKS */ ChimaeraWing.activationCheck(player); break; case LEFT_CLICK_AIR: case LEFT_CLICK_BLOCK: /* CALL OF THE WILD CHECKS */ if (player.isSneaking() && Permissions.callOfTheWild(player)) { Material type = heldItem.getType(); TamingManager tamingManager = mcMMOPlayer.getTamingManager(); if (type == Material.RAW_FISH) { tamingManager.summonOcelot(); } else if (type == Material.BONE) { tamingManager.summonWolf(); } } break; default: break; } } /** * Monitor PlayerChat events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); if (Misc.isNPCEntity(player)) { return; } boolean isAsync = event.isAsynchronous(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); if (mcMMOPlayer.getPartyChatMode()) { Party party = mcMMOPlayer.getParty(); if (party == null) { player.sendMessage(LocaleLoader.getString("Commands.Party.None")); return; } ChatManager.handlePartyChat(plugin, party, player.getName(), player.getDisplayName(), event.getMessage(), isAsync); event.setCancelled(true); } else if (mcMMOPlayer.getAdminChatMode()) { ChatManager.handleAdminChat(plugin, player.getName(), player.getDisplayName(), event.getMessage(), isAsync); event.setCancelled(true); } } /** * Handle "ugly" aliasing /skillname commands, since setAliases doesn't work. * * @param event The event to watch */ @EventHandler(priority = EventPriority.LOWEST) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { if (!Config.getInstance().getLocale().equalsIgnoreCase("en_US")) { String message = event.getMessage(); String command = message.substring(1).split(" ")[0]; String lowerCaseCommand = command.toLowerCase(); // Do these ACTUALLY have to be lower case to work properly? for (SkillType skill : SkillType.values()) { String skillName = skill.toString().toLowerCase(); String localizedName = SkillUtils.getSkillName(skill).toLowerCase(); if (lowerCaseCommand.equals(localizedName)) { event.setMessage(message.replace(command, skillName)); break; } if (lowerCaseCommand.equals(skillName)) { break; } } } } }
package com.google.common.html.plugin.js; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.json.simple.JSONArray; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.html.plugin.common.Ingredients.OptionsIngredient; import com.google.common.html.plugin.common.Ingredients.PathValue; import com.google.common.html.plugin.common.Ingredients .SerializedObjectIngredient; import com.google.common.html.plugin.plan.Ingredient; import com.google.common.html.plugin.plan.PlanKey; import com.google.common.html.plugin.plan.Step; import com.google.common.html.plugin.plan.StepSource; import com.google.javascript.jscomp.CommandLineRunner; final class CompileJs extends Step { public CompileJs( OptionsIngredient<JsOptions> optionsIng, SerializedObjectIngredient<Modules> modulesIng, PathValue jsOutputDir) { super( PlanKey.builder("compile-js") .addInp(optionsIng, modulesIng, jsOutputDir) .build(), ImmutableList.<Ingredient>of(optionsIng, modulesIng, jsOutputDir), Sets.immutableEnumSet(StepSource.JS_SRC, StepSource.JS_GENERATED), Sets.immutableEnumSet(StepSource.JS_COMPILED, StepSource.JS_SOURCE_MAP) ); } @Override public void execute(Log log) throws MojoExecutionException { OptionsIngredient<JsOptions> optionsIng = ((OptionsIngredient<?>) inputs.get(0)).asSuperType(JsOptions.class); SerializedObjectIngredient<Modules> modulesIng = ((SerializedObjectIngredient<?>) inputs.get(1)) .asSuperType(Modules.class); PathValue jsOutputDir = (PathValue) inputs.get(2); Modules modules = modulesIng.getStoredObject().get(); if (modules.modules.isEmpty()) { log.info("Skipping JS compilation -- zero modules"); return; } jsOutputDir.value.mkdirs(); ImmutableList.Builder<String> argvBuilder = ImmutableList.builder(); optionsIng.getOptions().addArgv(log, argvBuilder); argvBuilder.add("--manage_closure_dependencies").add("true"); argvBuilder.add("--js_output_file") .add(jsOutputDir.value.getPath() // The %outname% substitution is defined in // AbstractCommandLineRunner. + File.separator + "compiled-%outname%.js"); modules.addClosureCompilerFlags(argvBuilder); final ImmutableList<String> argv = argvBuilder.build(); if (log.isDebugEnabled()) { log.debug("Executing JSCompiler: " + JSONArray.toJSONString(argv)); } // TODO: Fix jscompiler so I can thread MavenLogJSErrorManager // through instead of mucking around with stdout, stderr. try { logViaErrStreams( "jscomp: ", log, new WithStdOutAndStderrAndWithoutStdin() { @Override void run(InputStream stdin, PrintStream stdout, PrintStream stderr) throws IOException, MojoExecutionException { CommandLineRunner runner = new CommandLineRunner( argv.toArray(new String[0]), stdin, stdout, stderr) { // Subclass to get access to the constructor. }; runner.setExitCodeReceiver(Functions.constant(null)); runner.run(); if (runner.hasErrors()) { throw new MojoExecutionException("JS compilation failed"); } } }); } catch (IOException ex) { throw new MojoExecutionException("JS compilation failed", ex); } } @Override public void skip(Log log) throws MojoExecutionException { // Done. } @Override public ImmutableList<Step> extraSteps(Log log) throws MojoExecutionException { return ImmutableList.of(); } static abstract class PrefixingOutputStream extends FilterOutputStream { private final String prefix; @SuppressWarnings("resource") PrefixingOutputStream(String prefix) { super(new ByteArrayOutputStream()); this.prefix = prefix; } protected abstract void onLine(CharSequence cs); @Override public void flush() throws IOException { ByteArrayOutputStream bytes = (ByteArrayOutputStream) this.out; byte[] byteArray = bytes.toByteArray(); bytes.reset(); onLine( new StringBuilder() .append(prefix) .append(new String(byteArray, "UTF-8"))); } } static final class DevNullInputStream extends InputStream { @Override public int read() throws IOException { return -1; } } private static void logViaErrStreams( String prefix, final Log log, WithStdOutAndStderrAndWithoutStdin withStdOutAndStderrAndWithoutStdin) throws IOException, MojoExecutionException { try (InputStream in = new DevNullInputStream()) { try (PrefixingOutputStream infoWriter = new PrefixingOutputStream(prefix) { @Override protected void onLine(CharSequence line) { log.info(line); } }) { try (PrintStream out = new PrintStream(infoWriter, true, "UTF-8")) { try (PrefixingOutputStream warnWriter = new PrefixingOutputStream(prefix) { @Override protected void onLine(CharSequence line) { log.warn(line); } }) { try (PrintStream err = new PrintStream(warnWriter, true, "UTF-8")) { withStdOutAndStderrAndWithoutStdin.run(in, out, err); } } } } } } abstract class WithStdOutAndStderrAndWithoutStdin { abstract void run(InputStream stdin, PrintStream stdout, PrintStream stderr) throws IOException, MojoExecutionException; } }
package com.infogen.server.cache; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import com.infogen.server.cache.zookeeper.InfoGen_Zookeeper_Handle_Expired; import com.infogen.server.cache.zookeeper.InfoGen_Zookeeper_Handle_Watcher_Children; import com.infogen.tools.Scheduled; /** * zookeeper * * @author larry/larrylv@outlook.com/ 201583 11:30:44 * @since 1.0 * @version 1.0 */ public class InfoGen_ZooKeeper { private static final Logger LOGGER = LogManager.getLogger(InfoGen_ZooKeeper.class.getName()); private static class InnerInstance { public static final InfoGen_ZooKeeper instance = new InfoGen_ZooKeeper(); } public static InfoGen_ZooKeeper getInstance() { return InnerInstance.instance; } private InfoGen_ZooKeeper() { Scheduled.executors_single.scheduleWithFixedDelay(() -> { rewatcher_childrens(); } , 16, 16, TimeUnit.SECONDS); } private String host_port; private ZooKeeper zookeeper; private InfoGen_Zookeeper_Handle_Expired expired_handle; private Map<String, Set<String>> map_auth_info = new HashMap<>(); public static final String CONTEXT = "/infogen"; public static final String CONTEXT_FUNCTIONS = "/infogen_functions"; protected static String functions_path(String server_name) { return CONTEXT_FUNCTIONS.concat("/").concat(server_name); } protected static String path() { return CONTEXT; } protected static String path(String server_name) { return CONTEXT.concat("/").concat(server_name); } protected static String path(String server_name, String node_name) { return CONTEXT.concat("/").concat(server_name).concat("/").concat(node_name); } /** * * * @param host_port * @throws IOException */ public void start_zookeeper(String host_port, InfoGen_Zookeeper_Handle_Expired expired_handle) throws IOException { if (zookeeper == null) { this.expired_handle = expired_handle; LOGGER.info("zookeeper:".concat(host_port)); this.host_port = host_port; this.zookeeper = new ZooKeeper(host_port, 10000, connect_watcher); for (Entry<String, Set<String>> entry : map_auth_info.entrySet()) { String scheme = entry.getKey(); for (String auth : entry.getValue()) { zookeeper.addAuthInfo(scheme, auth.getBytes()); } } LOGGER.info("zookeeper:".concat(host_port)); } else { LOGGER.info("zookeeper"); } } /** * zookeeper * * @throws InterruptedException */ public void stop_zookeeper() throws InterruptedException { LOGGER.info("zookeeper"); zookeeper.close(); zookeeper = null; LOGGER.info("zookeeper"); } public Boolean available() { return (zookeeper != null); } public void add_auth_info(String scheme, String auth) { Set<String> set_auth = map_auth_info.getOrDefault(scheme, new HashSet<String>()); if (!set_auth.contains(auth)) { set_auth.add(auth); zookeeper.addAuthInfo(scheme, auth.getBytes()); } } /** * ,, * * @param path * @param data * @return path * @throws KeeperException * @throws InterruptedException */ public String create(String path, byte[] data, List<ACL> acls, CreateMode create_mode) { String _return = null; try { LOGGER.info(":".concat(path)); _return = zookeeper.create(path, data, acls, create_mode); LOGGER.info(":".concat(_return)); } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: LOGGER.warn(",...: " + path); create(path, data, create_mode); break; case NODEEXISTS: LOGGER.warn(": " + path); _return = Code.NODEEXISTS.name(); break; default: LOGGER.error(": ", KeeperException.create(e.code(), path)); } } catch (Exception e) { LOGGER.error(": ", e); } return _return; } public String create(String path, byte[] data, CreateMode create_mode) { return create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, create_mode); } public Stat exists(String path) { Stat exists = null; try { LOGGER.info(":".concat(path)); exists = zookeeper.exists(path, false); LOGGER.info(":".concat(path)); } catch (Exception e) { LOGGER.error(": ", e); } return exists; } public void delete(String path) { try { LOGGER.info(":".concat(path)); zookeeper.delete(path, -1); LOGGER.info(":".concat(path)); } catch (Exception e) { LOGGER.error(": ", e); } } public String get_data(String path) { try { LOGGER.info(":".concat(path)); byte[] data = zookeeper.getData(path, false, null); if (data != null) { LOGGER.info(":".concat(path)); return new String(data); } } catch (Exception e) { LOGGER.error(": ", e); } return null; } public Stat set_data(String path, byte[] data, int version) { try { LOGGER.info(":".concat(path)); Stat setData = zookeeper.setData(path, data, version); LOGGER.info(":".concat(path)); return setData; } catch (Exception e) { LOGGER.error(": ", e); } return null; } public List<String> get_childrens(String path) { List<String> list = new ArrayList<String>(); try { LOGGER.info(":".concat(path)); list = zookeeper.getChildren(path, false); LOGGER.info(":".concat(path)); } catch (Exception e) { LOGGER.error(": ", e); } return list; } // public List<String> get_childrens_data(String path) { // List<String> list = new ArrayList<String>(); // try { // LOGGER.info(":".concat(path)); // List<String> childrens = zookeeper.getChildren(path, false); // for (String service_path : childrens) { // try { // StringBuilder service_path_sbf = new StringBuilder(path); // if (!path.equals("/")) { // service_path_sbf.append("/"); // service_path_sbf.append(service_path); // byte[] data = zookeeper.getData(service_path_sbf.toString(), false, null); // if (data != null) { // list.add(new String(data)); // } catch (Exception e) { // LOGGER.error(":", e); // LOGGER.info(":".concat(path)); // } catch (Exception e) { // LOGGER.error(": ", e); // return list; // ////////////////////////////////////////////// Watcher//////////////////////////////////////////////////////////////// private Set<String> all_watcher_children_paths = new HashSet<String>(); private Set<String> rewatcher_children_paths = new HashSet<String>(); private Map<String, InfoGen_Zookeeper_Handle_Watcher_Children> watcher_children_handle_map = new HashMap<>(); public void watcher_children_single(String path, InfoGen_Zookeeper_Handle_Watcher_Children watcher_children_handle) { if (watcher_children_handle_map.get(path) != null) { LOGGER.info(":".concat(path)); return; } if (watcher_children_handle != null) { watcher_children_handle_map.put(path, watcher_children_handle); } all_watcher_children_paths.add(path); watcher_children(path); } private void watcher_children(String path) { try { LOGGER.info(":".concat(path)); zookeeper.getChildren(path, (event) -> { LOGGER.info(" path:" + event.getPath() + " state:" + event.getState().name() + " type:" + event.getType().name()); if (event.getType() == EventType.NodeChildrenChanged) { LOGGER.info(" :".concat(path)); watcher_children(path); InfoGen_Zookeeper_Handle_Watcher_Children watcher_children_handle = watcher_children_handle_map.get(path); if (watcher_children_handle != null) { watcher_children_handle.handle_event(path); } } else if (event.getType() == EventType.None) { // event.getType() == EventType.None if (event.getState() == KeeperState.Expired) { // Session } } else if (event.getType() == EventType.NodeDeleted) { LOGGER.info(" :".concat(path)); watcher_children(path); } else { LOGGER.error("".concat(event.getType().toString())); } }); LOGGER.info(":".concat(path)); } catch (Exception e) { rewatcher_children_paths.add(path); LOGGER.error(": ", e); } } // /////////////////////////////////////// Watcher/////////////////////////////////////////////////// /** * Client */ private Watcher connect_watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOGGER.info(" path:" + event.getPath() + " state:" + event.getState().name() + " type:" + event.getType().name()); if (event.getType() == Watcher.Event.EventType.None) { switch (event.getState()) { case SyncConnected: break; case Expired: try { LOGGER.error("zookeeper "); LOGGER.info(" zookeeper"); /** rewatcher_children_paths.addAll(all_watcher_children_paths); **/ synchronized (rewatcher_children_lock) { stop_zookeeper(); start_zookeeper(host_port, expired_handle); rewatcher_children_paths.addAll(all_watcher_children_paths); } rewatcher_childrens(); LOGGER.info(""); if (expired_handle != null) { expired_handle.handle_event(); } } catch (Exception e) { LOGGER.error("zookeeper ", e); } break; case Disconnected: break; default: break; } } } }; // //////////////////////////////////////////GETTER SETTER///////////////////////////////////////////////////// public String getHost_port() { return host_port; } public void setHost_port(String host_port) { this.host_port = host_port; } // ////////////////////////////////////////////Scheduled//////////////////////////////////////////////////////////////// private byte[] rewatcher_children_lock = new byte[0]; private void rewatcher_childrens() { synchronized (rewatcher_children_lock) { Set<String> paths = new HashSet<String>(); paths.addAll(rewatcher_children_paths); for (String server_name : paths) { LOGGER.info(":".concat(server_name)); /** removewatcher watcherserver_name **/ rewatcher_children_paths.remove(server_name); watcher_children(server_name); } } } }
package com.lothrazar.samspowerups; import java.util.ArrayList; import java.util.List; import com.lothrazar.samspowerups.block.*; import com.lothrazar.samspowerups.command.*; import com.lothrazar.samspowerups.modules.*; import com.lothrazar.samspowerups.net.*; import com.lothrazar.samspowerups.gui.GUIHandler; import com.lothrazar.samspowerups.handler.*; import com.lothrazar.samspowerups.item.*; import com.lothrazar.samspowerups.util.*; import net.minecraftforge.event.entity.player.PlayerEvent.*; import net.minecraft.block.Block; import net.minecraft.block.BlockPumpkin; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.command.ICommand; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.item.EntityBoat; import net.minecraft.entity.monster.EntityMagmaCube; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.BlockEvent; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import net.minecraft.block.BlockLilyPad; import org.apache.logging.log4j.Logger; @Mod(modid = ModSamsPowerups.MODID, version = ModSamsPowerups.VERSION,guiFactory = "com.lothrazar.samspowerups.gui.ConfigGuiFactory") public class ModSamsPowerups { public static final String MODID = "samspowerups"; public static final String VERSION = "1.7.10-1.0"; @Instance(value = ModSamsPowerups.MODID) public static ModSamsPowerups instance; public static ModSamsPowerups getInstance() { return instance; } @SidedProxy(clientSide="com.lothrazar.samspowerups.net.ClientProxy", serverSide="com.lothrazar.samspowerups.net.CommonProxy") public static CommonProxy proxy; public static SimpleNetworkWrapper network; public static ConfigHandler configHandler; public static Configuration config; private static Logger logger; private ArrayList<BaseModule> modules; private boolean inSandboxMode = true; public ArrayList<ICommand> ModuleCommands = new ArrayList<ICommand>(); //TODO: merge fishing block, command blocks, and cave finder into blocks module //TODO: merge ender chest, quick sort, rich loot, villager trades, into some sort of "tweaks" module //TODO: fix iron boat texture OR make it a base edit public static void LogInfo(String s) { //TODO: also add to my own documentation and/or log file logger.info(s); } private void logBaseChanges() { LogInfo("Base Edit: net.minecraft.client.gui.inventory.GuiInventory.java"); LogInfo("Base Edit: net.minecraft.inventory.ContainerPlayer.java"); LogInfo("Base Edit: net.minecraft.block.BlockFenceGate.java"); LogInfo("Base Edit: net.minecraft.block.BlockHugeMushroom.java"); LogInfo("Base Edit: net.minecraft.block.BlockPumpkin.java"); LogInfo("Base Edit: net.minecraft.block.BlockSnow.java"); //TODO baseedits: //C:\Users\Samson\Desktop\Minecraft\BACKUPS\146 src //silk touch on farm and mushroom and snow // pumkin and fence gate placing rules //also carpet? //DOORS: creative iron doors //BlockPumpkin p; // BlockPumpkin.class.canPlaceBlockAt = //door, what did i change there? } @EventHandler public void onPreInit(FMLPreInitializationEvent event) //fired on startup when my mod gets loaded { modules = new ArrayList<BaseModule>(); modules.add(new CommandPowersModule()); modules.add(new CreativeInventoryModule()); modules.add(new EnderBookModule()); modules.add(new EnderChestModule()); modules.add(new ExtraCraftingModule()); modules.add(new IronBoatModule()); modules.add(new ItemBlockModule()); modules.add(new KeySliderModule()); modules.add(new MagicApplesModule()); modules.add(new MasterWandModule()); modules.add(new MissingTradeModule()); modules.add(new QuickDepositModule()); modules.add(new DifficultyTweaksModule()); modules.add(new RichLootModule()); modules.add(new ScreenInfoModule()); modules.add(new SmartPlantsModule()); modules.add(new StackSizeModule()); modules.add(new SurvivalFlyingModule()); modules.add(new UncraftingModule()); logger = event.getModLog(); logBaseChanges(); network = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); configHandler = new ConfigHandler(); configHandler.onPreInit(event);//this fires syncConfig. comes BEFORE the modules loadConfig syncConfig(); MinecraftForge.EVENT_BUS.register(configHandler); loadModules(); if(inSandboxMode) //experimenting with new unfinished features { logger.warn("SANDBOX MODE ENGAGING: Experimental Features may crash the game!"); MinecraftForge.EVENT_BUS.register(new SandboxHandler()); } } private void loadModules() { BaseModule current; for(int i = 0; i < modules.size(); i++) { current = modules.get(i); if(current.isEnabled()) { current.init(); if(current.Handler != null) { MinecraftForge.EVENT_BUS.register(current.Handler); } if(current.FuelHandler != null) { GameRegistry.registerFuelHandler(current.FuelHandler); } for(ICommand c : current.Commands)//commands get loaded in a different event, but we prepare them here { ModuleCommands.add(c); } logLoadedModule(current); } else { logger.info("Module DISABLED : " + current.Name); } } } private void logLoadedModule(BaseModule current) { logger.info("Module Activated : " + current.Name); for(String c : current.FeatureList) { logger.info(" " + c); } } public void syncConfig() { for(int i = 0; i < modules.size(); i++) { modules.get(i).loadConfig(); } if(config.hasChanged()) { config.save(); } } @EventHandler public void init (FMLInitializationEvent evt) { //TODO: research, should init - block recipes shoud go here? NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GUIHandler()); proxy.registerRenderers(); } @EventHandler public void onServerLoad(FMLServerStartingEvent event) { for(ICommand c : ModuleCommands) { event.registerServerCommand(c); } } }
package com.metaweb.gridworks.expr; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyFunction; import org.python.core.PyNone; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class JythonEvaluable implements Evaluable { private static final String s_functionName = "___temp___"; private static PythonInterpreter _engine; static { File libPath = new File("lib/jython"); if (libPath.exists()) { Properties props = new Properties(); props.setProperty("python.path", libPath.getAbsolutePath()); PythonInterpreter.initialize(System.getProperties(),props, new String[] { "" }); } _engine = new PythonInterpreter(); } public JythonEvaluable(String s) { // indent and create a function out of the code String[] lines = s.split("\r\n|\r|\n"); StringBuffer sb = new StringBuffer(1024); sb.append("def "); sb.append(s_functionName); sb.append("(value, cell, cells, row, rowIndex):"); for (int i = 0; i < lines.length; i++) { sb.append("\n "); sb.append(lines[i]); } _engine.exec(sb.toString()); } public Object evaluate(Properties bindings) { try { // call the temporary PyFunction directly Object result = ((PyFunction)_engine.get(s_functionName)).__call__( new PyObject[] { Py.java2py( bindings.get("value") ), new JythonHasFieldsWrapper((HasFields) bindings.get("cell"), bindings), new JythonHasFieldsWrapper((HasFields) bindings.get("cells"), bindings), new JythonHasFieldsWrapper((HasFields) bindings.get("row"), bindings), Py.java2py( bindings.get("rowIndex") ) } ); return unwrap(result); } catch (PyException e) { return new EvalError(e.getMessage()); } } protected Object unwrap(Object result) { if (result != null) { if (result instanceof JythonObjectWrapper) { return ((JythonObjectWrapper) result)._obj; } else if (result instanceof JythonHasFieldsWrapper) { return ((JythonHasFieldsWrapper) result)._obj; } else if (result instanceof PyString) { return ((PyString) result).asString(); } else if (result instanceof PyObject) { return unwrap((PyObject) result); } } return result; } protected Object unwrap(PyObject po) { if (po instanceof PyNone) { return null; } else if (po.isNumberType()) { return po.asDouble(); } else if (po.isSequenceType()) { Iterator<PyObject> i = po.asIterable().iterator(); List<Object> list = new ArrayList<Object>(); while (i.hasNext()) { list.add(unwrap((Object) i.next())); } return list.toArray(); } else { return po; } } }
package com.siemens.ct.exi.types; import java.util.HashMap; import java.util.Map; import javax.xml.namespace.QName; import com.siemens.ct.exi.Constants; import com.siemens.ct.exi.context.QNameContext; import com.siemens.ct.exi.datatype.BinaryBase64Datatype; import com.siemens.ct.exi.datatype.BinaryHexDatatype; import com.siemens.ct.exi.datatype.BooleanDatatype; import com.siemens.ct.exi.datatype.Datatype; import com.siemens.ct.exi.datatype.DatetimeDatatype; import com.siemens.ct.exi.datatype.DecimalDatatype; import com.siemens.ct.exi.datatype.EnumerationDatatype; import com.siemens.ct.exi.datatype.FloatDatatype; import com.siemens.ct.exi.datatype.IntegerDatatype; import com.siemens.ct.exi.datatype.ListDatatype; import com.siemens.ct.exi.datatype.StringDatatype; import com.siemens.ct.exi.exceptions.EXIException; import com.siemens.ct.exi.util.xml.QNameUtilities; /** * * @author Daniel.Peintner.EXT@siemens.com * @author Joerg.Heuer@siemens.com * * @version 0.9.7-SNAPSHOT */ public abstract class AbstractTypeCoder implements TypeCoder { // DTR maps protected final QName[] dtrMapTypes; protected final QName[] dtrMapRepresentations; protected final Map<QName, Datatype> dtrMapRepresentationsDatatype; protected Map<QName, Datatype> dtrMap; protected final boolean dtrMapInUse; public AbstractTypeCoder() throws EXIException { this(null, null, null); } public AbstractTypeCoder(QName[] dtrMapTypes, QName[] dtrMapRepresentations, Map<QName, Datatype> dtrMapRepresentationsDatatype) throws EXIException { this.dtrMapTypes = dtrMapTypes; this.dtrMapRepresentations = dtrMapRepresentations; this.dtrMapRepresentationsDatatype = dtrMapRepresentationsDatatype; if (dtrMapTypes == null) { dtrMapInUse = false; } else { dtrMapInUse = true; dtrMap = new HashMap<QName, Datatype>(); assert (dtrMapTypes.length == dtrMapRepresentations.length); this.initDtrMaps(); } } private void initDtrMaps() throws EXIException { assert (dtrMapInUse); // binary dtrMap.put( BuiltIn.XSD_BASE64BINARY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_BASE64BINARY)); dtrMap.put( BuiltIn.XSD_HEXBINARY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_HEXBINARY)); // boolean dtrMap.put( BuiltIn.XSD_BOOLEAN, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_BOOLEAN)); // date-times dtrMap.put( BuiltIn.XSD_DATETIME, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DATETIME)); dtrMap.put( BuiltIn.XSD_TIME, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_TIME)); dtrMap.put( BuiltIn.XSD_DATE, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DATE)); dtrMap.put( BuiltIn.XSD_GYEARMONTH, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GYEARMONTH)); dtrMap.put( BuiltIn.XSD_GYEAR, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GYEAR)); dtrMap.put( BuiltIn.XSD_GMONTHDAY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GMONTHDAY)); dtrMap.put( BuiltIn.XSD_GDAY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GDAY)); dtrMap.put( BuiltIn.XSD_GMONTH, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GMONTH)); // decimal dtrMap.put( BuiltIn.XSD_DECIMAL, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DECIMAL)); // float dtrMap.put( BuiltIn.XSD_FLOAT, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DOUBLE)); dtrMap.put( BuiltIn.XSD_DOUBLE, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DOUBLE)); // integer dtrMap.put( BuiltIn.XSD_INTEGER, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_INTEGER)); // string dtrMap.put( BuiltIn.XSD_STRING, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_STRING)); dtrMap.put( BuiltIn.XSD_ANY_SIMPLE_TYPE, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_STRING)); // all types derived by union are done differently for (int i = 0; i < dtrMapTypes.length; i++) { QName dtrMapRepr = dtrMapRepresentations[i]; Datatype representation = getDatatypeRepresentation( dtrMapRepr.getNamespaceURI(), dtrMapRepr.getLocalPart()); QName type = dtrMapTypes[i]; dtrMap.put(type, representation); } } protected Datatype getDtrDatatype(final Datatype datatype) { assert (dtrMapInUse); Datatype dtrDatatype = null; if (datatype == BuiltIn.DEFAULT_DATATYPE) { // e.g., untyped values are encoded always as String dtrDatatype = datatype; } else { // check mappings QName schemaType = datatype.getSchemaType().getQName(); // unions if ( dtrDatatype == null && datatype.getBuiltInType() == BuiltInType.STRING && ((StringDatatype) datatype).isDerivedByUnion()) { if (dtrMap.containsKey(schemaType)) { // direct DTR mapping dtrDatatype = dtrMap.get(schemaType); } else { Datatype baseDatatype = datatype.getBaseDatatype(); QName schemBaseType = baseDatatype.getSchemaType().getQName(); if(baseDatatype.getBuiltInType() == BuiltInType.STRING && ((StringDatatype) baseDatatype).isDerivedByUnion() && dtrMap.containsKey(schemBaseType)) { dtrDatatype = dtrMap.get(schemBaseType); } else { dtrDatatype = datatype; } } // dtrDatatype = datatype; // // union ancestors of interest // // Datatype dtBase = qncSchemaType.getSimpleBaseDatatype(); // Datatype dtBase = datatype.getBaseDatatype(); // if (dtBase != null // && dtBase.getBuiltInType() == BuiltInType.STRING // && ((StringDatatype) dtBase).isDerivedByUnion()) { // // check again // dtrDatatype = null; } // lists if ( dtrDatatype == null && datatype.getBuiltInType() == BuiltInType.LIST) { if (dtrMap.containsKey(schemaType)) { // direct DTR mapping dtrDatatype = dtrMap.get(schemaType); } else { Datatype baseDatatype = datatype.getBaseDatatype(); QName schemBaseType = baseDatatype.getSchemaType().getQName(); if( // baseDatatype.getBuiltInType() == BuiltInType.LIST && dtrMap.containsKey(schemBaseType)) { dtrDatatype = dtrMap.get(schemBaseType); } else { dtrDatatype = datatype; } // ListDatatype ldt = (ListDatatype) datatype; // Datatype datatypeList = ldt.getListDatatype(); // Datatype dtrDatatypeList = getDtrDatatype(datatypeList); // if(datatypeList.getBuiltInType() == dtrDatatypeList.getBuiltInType()) { // dtrDatatype = datatype; // } else { // // update DTR for list datatype // dtrDatatype = new ListDatatype(dtrDatatypeList, ldt.getSchemaType()); } // dtrDatatype = datatype; // // list ancestors of interest // // Datatype dtBase = qncSchemaType.getSimpleBaseDatatype(); // Datatype dtBase = datatype.getBaseDatatype(); // if (dtBase != null // && dtBase.getBuiltInType() == BuiltInType.LIST) { // // check again // dtrDatatype = null; } // enums if ( dtrDatatype == null && datatype.getBuiltInType() == BuiltInType.ENUMERATION) { if (dtrMap.containsKey(schemaType)) { // direct DTR mapping dtrDatatype = dtrMap.get(schemaType); } else { Datatype baseDatatype = datatype.getBaseDatatype(); QName schemBaseType = baseDatatype.getSchemaType().getQName(); if(baseDatatype.getBuiltInType() == BuiltInType.ENUMERATION && dtrMap.containsKey(schemBaseType)) { dtrDatatype = dtrMap.get(schemBaseType); } else { dtrDatatype = datatype; } // Datatype dtrDatatypeBase = getDtrDatatype(datatype.getBaseDatatype()); // dtrDatatype = dtrDatatypeBase; // dtrMap.put(schemaType, dtrDatatype); // EnumerationDatatype edt = (EnumerationDatatype) datatype; // Datatype datatypeEnum = edt.getEnumValueDatatype(); // Datatype dtrDatatypeEnum = getDtrDatatype(datatypeEnum); // if(datatypeEnum.getBuiltInType() == dtrDatatypeEnum.getBuiltInType()) { // dtrDatatype = datatype; // } else { // // update DTR for list datatype // dtrDatatype = dtrDatatypeEnum; } // dtrDatatype = datatype; // // only ancestor types that have enums are of interest // // Datatype dtBase = qncSchemaType.getSimpleBaseDatatype(); // Datatype dtBase = datatype.getBaseDatatype(); // if (dtBase != null // && dtBase.getBuiltInType() == BuiltInType.ENUMERATION) { // // check again // dtrDatatype = null; } if (dtrDatatype == null) { // QNameContext qncSchemaType = datatype.getSchemaType(); dtrDatatype = dtrMap.get(schemaType); if (dtrDatatype == null) { // no mapping yet // dtrDatatype = updateDtrDatatype(qncSchemaType); dtrDatatype = updateDtrDatatype(datatype); // // special integer handling // if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER // && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype // .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) { // dtrDatatype = datatype; // dtrMap.put(qncSchemaType.getQName(), dtrDatatype); } } } // // list item types // assert (dtrDatatype != null); // if (dtrDatatype.getBuiltInType() == BuiltInType.LIST) { // Datatype prev = dtrDatatype; // ListDatatype ldt = (ListDatatype) dtrDatatype; // Datatype dtList = ldt.getListDatatype(); // dtrDatatype = this.getDtrDatatype(dtList); // if (dtrDatatype != dtList) { // // update item codec // dtrDatatype = new ListDatatype(dtrDatatype, ldt.getSchemaType()); // } else { // dtrDatatype = prev; return dtrDatatype; } // protected Datatype updateDtrDatatype(QNameContext qncSchemaType) { protected Datatype updateDtrDatatype(Datatype datatype) { // protected Datatype updateDtrDatatype(QNameContext qncSchemaType) { assert (dtrMapInUse); // // QNameContext qncSchemaType = datatype.getSchemaType(); // QNameContext qncBase = qncSchemaType.getSimpleBaseType(); // assert(qncSchemaType != null); //// // special integer handling //// if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER //// && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype //// .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) { //// dtrDatatype = datatype; // Datatype dt = dtrMap.get(qncBase.getQName()); // if (dt == null) { // // dt = updateDtrDatatype(simpleBaseType); // // dt = updateDtrDatatype(qncSchemaType.getSimpleBaseDatatype()); // dt = updateDtrDatatype(qncBase); //baseDatatype); //// dtrMap.put(qncBase.getQName(), dt); // } else { // // save new mapping in map //// dtrMap.put(qncSchemaType.getQName(), dt); // return dt; Datatype baseDatatype = datatype.getBaseDatatype(); // QNameContext qncSchemaType = datatype.getSchemaType(); // QNameContext simpleBaseType = qncSchemaType.getSimpleBaseDatatype().getSchemaType(); QNameContext simpleBaseType = baseDatatype.getSchemaType(); Datatype dtrDatatype = dtrMap.get(simpleBaseType.getQName()); if (dtrDatatype == null) { // dt = updateDtrDatatype(simpleBaseType); // dt = updateDtrDatatype(qncSchemaType.getSimpleBaseDatatype()); dtrDatatype = updateDtrDatatype(baseDatatype); } // special integer handling if ((dtrDatatype.getBuiltInType() == BuiltInType.INTEGER || dtrDatatype.getBuiltInType() == BuiltInType.UNSIGNED_INTEGER) && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) { dtrDatatype = datatype; } // save new mapping in map dtrMap.put(datatype.getSchemaType().getQName(), dtrDatatype); return dtrDatatype; } protected Datatype getDatatypeRepresentation(String reprUri, String reprLocalPart) throws EXIException { assert (dtrMapInUse); try { // find datatype for given representation Datatype datatype = null; if (Constants.W3C_EXI_NS_URI.equals(reprUri)) { // EXI built-in datatypes // see http://www.w3.org/TR/exi/#builtInEXITypes if ("base64Binary".equals(reprLocalPart)) { datatype = new BinaryBase64Datatype(null); } else if ("hexBinary".equals(reprLocalPart)) { datatype = new BinaryHexDatatype(null); } else if ("boolean".equals(reprLocalPart)) { datatype = new BooleanDatatype(null); } else if ("dateTime".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.dateTime, null); } else if ("time".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.time, null); } else if ("date".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.date, null); } else if ("gYearMonth".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gYearMonth, null); } else if ("gYear".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gYear, null); } else if ("gMonthDay".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gMonthDay, null); } else if ("gDay".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gDay, null); } else if ("gMonth".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gMonth, null); } else if ("decimal".equals(reprLocalPart)) { datatype = new DecimalDatatype(null); } else if ("double".equals(reprLocalPart)) { datatype = new FloatDatatype(null); } else if ("integer".equals(reprLocalPart)) { datatype = new IntegerDatatype(null); } else if ("string".equals(reprLocalPart)) { datatype = new StringDatatype(null); } else { throw new EXIException( "[EXI] Unsupported datatype representation: {" + reprUri + "}" + reprLocalPart); } } else { // try to load datatype QName qn = new QName(reprUri, reprLocalPart); if(this.dtrMapRepresentationsDatatype != null) { datatype = this.dtrMapRepresentationsDatatype.get(qn); } if(datatype == null) { // final try: load class with this qname String className = QNameUtilities.getClassName(qn); @SuppressWarnings("rawtypes") Class c = Class.forName(className); Object o = c.newInstance(); if (o instanceof Datatype) { datatype = (Datatype) o; } else { throw new Exception("[EXI] no Datatype instance"); } } } return datatype; } catch (Exception e) { throw new EXIException(e); } } }
package com.socrata.balboa.server.rest; import com.socrata.balboa.metrics.Metrics; import com.socrata.balboa.metrics.data.DataStore; import com.socrata.balboa.metrics.data.DataStoreFactory; import com.socrata.balboa.metrics.data.DateRange; import com.socrata.balboa.metrics.impl.MessageProtos; import com.socrata.balboa.metrics.impl.ProtocolBuffersMetrics; import com.socrata.balboa.server.ServiceUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; @Path("/{entityId}") public class MetricsRest { @GET @Produces({"application/json", "application/x-protobuf"}) public Response get( @PathParam("entityId") String entityId, @QueryParam("period") DateRange.Period period, @QueryParam("date") String date, @QueryParam("combine") String combine, @QueryParam("field") String field, @Context HttpHeaders headers ) throws IOException { DataStore ds = DataStoreFactory.get(); DateRange range = DateRange.create(period, ServiceUtils.parseDate(date)); Iterator<Metrics> iter = ds.find(entityId, period, range.start, range.end); Metrics metrics = Metrics.summarize(iter); metrics.setTimestamp(null); return render(getMediaType(headers), metrics); } @GET @Path("range") @Produces({"application/json", "application/x-protobuf"}) public Response range( @PathParam("entityId") String entityId, @QueryParam("start") String start, @QueryParam("end") String end, @Context HttpHeaders headers ) throws IOException { DataStore ds = DataStoreFactory.get(); Date startDate = ServiceUtils.parseDate(start); Date endDate = ServiceUtils.parseDate(end); Iterator<Metrics> iter = ds.find(entityId, startDate, endDate); Metrics metrics = Metrics.summarize(iter); metrics.setTimestamp(null); return render(getMediaType(headers), metrics); } @GET @Path("series") @Produces({"application/json", "application/x-protobuf"}) public Response series( @PathParam("entityId") String entityId, @QueryParam("period") DateRange.Period period, @QueryParam("start") String start, @QueryParam("end") String end, @Context HttpHeaders headers ) throws IOException { DataStore ds = DataStoreFactory.get(); Date startDate = ServiceUtils.parseDate(start); Date endDate = ServiceUtils.parseDate(end); Iterator<? extends Metrics> iter = ds.find(entityId, period, startDate, endDate); return render(getMediaType(headers), iter); } MediaType getMediaType(HttpHeaders headers) { MediaType format = headers.getMediaType(); if (format == null) { for (MediaType type : headers.getAcceptableMediaTypes()) { format = type; break; } } return format; } private Response render(MediaType format, Iterator<? extends Metrics> metrics) throws IOException { if (format.getSubtype().equals("x-protobuf")) { List<MessageProtos.PBMetrics> list = new ArrayList<MessageProtos.PBMetrics>(); while (metrics.hasNext()) { Metrics m = metrics.next(); ProtocolBuffersMetrics pbm = new ProtocolBuffersMetrics(m); list.add(pbm.proto()); } MessageProtos.PBMetricsSeries series = MessageProtos.PBMetricsSeries.newBuilder().addAllSeries(list).build(); return Response.ok(series.toByteArray(), "application/x-protobuf").build(); } else { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); return Response.ok(mapper.writeValueAsString(metrics), "application/json").build(); } } private Response render(MediaType format, Metrics metrics) throws IOException { if (format.getSubtype().equals("x-protobuf")) { ProtocolBuffersMetrics mapper = new ProtocolBuffersMetrics(); mapper.merge(metrics); return Response.ok(mapper.serialize(), "application/x-protobuf").build(); } else { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); return Response.ok(mapper.writeValueAsString(metrics), "application/json").build(); } } }
package com.tagtraum.jipes.audio; import javax.sound.sampled.AudioFormat; import java.util.Arrays; public class MultiBandSpectrum extends AbstractAudioSpectrum implements Cloneable { private static final double LOG2 = Math.log(2.0); private int numberOfBands; private float[] bandBoundariesInHz; /** * Creates a multi band spectrum from another spectrum. * * @param frameNumber frame number * @param audioSpectrum audio spectrum to copy data from * @param bandBoundariesInHz band boundaries in Hz */ public MultiBandSpectrum(int frameNumber, final AudioSpectrum audioSpectrum, final float[] bandBoundariesInHz) { super(frameNumber, null, null, audioSpectrum.getAudioFormat()); this.bandBoundariesInHz = bandBoundariesInHz; this.numberOfBands = bandBoundariesInHz.length-1; final float[] frequencies = audioSpectrum.getFrequencies(); this.powers = computeBins(frequencies, audioSpectrum.getPowers()); this.realData = new float[powers.length]; this.imaginaryData = new float[powers.length]; this.magnitudes = new float[powers.length]; for (int i=0; i<bandBoundariesInHz.length-1; i++) { final float m = (float) Math.sqrt(powers[i]); this.magnitudes[i] = m; this.realData[i] = m; } } /** * Constructs a new multi band spectrum. Important: Provided real/imaginary data must already * be in bins. The provided band boundaries merely describe those bins. * * @param frameNumber frame number * @param real real * @param imaginary imaginary * @param audioFormat audio format * @param bandBoundariesInHz band boundaries in Hz */ public MultiBandSpectrum(int frameNumber, final float[] real, final float[] imaginary, final AudioFormat audioFormat, final float[] bandBoundariesInHz) { super(frameNumber, null, null, audioFormat); this.realData = real; this.imaginaryData = imaginary; this.magnitudes = new float[real.length]; this.powers = new float[real.length]; for (int i=0; i<real.length; i++) { if (imaginary == null || imaginary[i] == 0) { this.magnitudes[i] = Math.abs(real[i]); this.powers[i] = real[i]*real[i]; } else { this.powers[i] = real[i]*real[i] + imaginary[i]*imaginary[i]; this.magnitudes[i] = (float)Math.sqrt(powers[i]); } } this.bandBoundariesInHz = bandBoundariesInHz; this.numberOfBands = bandBoundariesInHz.length-1; } public MultiBandSpectrum(final MultiBandSpectrum multiBandSpectrum) { super(multiBandSpectrum); this.bandBoundariesInHz = multiBandSpectrum.bandBoundariesInHz; this.numberOfBands = multiBandSpectrum.numberOfBands; if (multiBandSpectrum.magnitudes != null) this.magnitudes = multiBandSpectrum.magnitudes.clone(); if (multiBandSpectrum.realData != null) this.realData = multiBandSpectrum.realData.clone(); if (multiBandSpectrum.imaginaryData != null) this.imaginaryData = multiBandSpectrum.imaginaryData.clone(); if (multiBandSpectrum.powers != null) this.powers = multiBandSpectrum.powers.clone(); } /** * Creates logarithmically spaced frequency bands. * * @param lowFrequency lower boundary in Hz * @param highFrequency upper boundary in Hz * @param numberOfBands number of bands in between lower and upper boundary * @return array of frequency boundaries in Hz */ public static float[] createLogarithmicBands(final float lowFrequency, final float highFrequency, final int numberOfBands) { if (numberOfBands == 1) return new float[] {lowFrequency, highFrequency}; final double factor = numberOfBands / (Math.log(highFrequency / (double) lowFrequency) / LOG2); final float scale[] = new float[numberOfBands+1]; scale[0] = lowFrequency; for (int i=1; i<numberOfBands+1; i++) { scale[i] = lowFrequency * (float)Math.pow(2, i/factor); } return scale; } /** * Creates and array of frequency boundaries exactly +-50 cents to the given MIDI * notes. * * @param lowMidi low MIDI note * @param highMidi high MIDI note * @return frequency boundaries */ public static float[] createMidiBands(final int lowMidi, final int highMidi) { return createMidiBands(lowMidi, highMidi, 1, 0); } /** * Creates an array of frequency boundaries by dividing each note into the given number of bins. * * @param lowMidi low MIDI note * @param highMidi high MIDI note * @param binsPerSemitone bins/semitone * @return frequency boundaries */ public static float[] createMidiBands(final int lowMidi, final int highMidi, final int binsPerSemitone) { return createMidiBands(lowMidi, highMidi, binsPerSemitone, 0); } /** * Creates an array of frequency boundaries by dividing each note into the given number of bins * and allowing for a different then the standard 440Hz tuning specified in cents. * * @param binsPerSemitone bins/semitone * @param lowMidi low MIDI note * @param highMidi high MIDI note * @param centDeviation deviation in cent from concert pitch (A4=440Hz) * @return frequency boundaries */ public static float[] createMidiBands(final int lowMidi, final int highMidi, final int binsPerSemitone, final float centDeviation) { final int semitones = highMidi - lowMidi; final float[] bands = new float[semitones*binsPerSemitone+1]; for (int i=0; i<semitones; i++) { for (int bin = 0; bin<binsPerSemitone; bin++) { // subtract x cents final double cents = 100.0/binsPerSemitone*bin - 50.0 + centDeviation; bands[i*binsPerSemitone+bin] = midiToFrequency(lowMidi+i, cents); } } bands[bands.length-1] = midiToFrequency(highMidi, 50.0); return bands; } private static float midiToFrequency(final int midiNote, final double cents) { final double freq = (Math.pow(2.0, (midiNote -69.0)/12.0) * 440.0); return (float) (freq*Math.pow(2.0, cents /1200.0)); } private float[] computeBins(final float[] frequencies, final float[] values) { final int[] valuesPerBin = new int[numberOfBands+2]; int currentEntry = 0; int bin = 0; for (final float freq : frequencies) { while (bin < bandBoundariesInHz.length && freq >= bandBoundariesInHz[bin]) { valuesPerBin[bin] = currentEntry; currentEntry = 0; bin++; } currentEntry++; } valuesPerBin[bin] = currentEntry; final float[] bins = new float[numberOfBands+2]; int binIndex = 0; int offset = 0; for (final int length : valuesPerBin) { for (int i = 0; i < length; i++) { bins[binIndex] += values[i+offset]; } offset += length; binIndex++; } // remove outOfBand bins final float[] inBandBins = new float[numberOfBands]; System.arraycopy(bins, 1, inBandBins, 0, inBandBins.length); return inBandBins; } public MultiBandSpectrum derive(final float[] real, final float[] imaginary) { return new MultiBandSpectrum(getFrameNumber(), real, imaginary, getAudioFormat(), bandBoundariesInHz); } /** * Array with frequency values in Hz corresponding to the band boundaries. * * @return array of length numberOfBands+1 * @see #getNumberOfBands() */ public float[] getBandBoundaries() { return bandBoundariesInHz; } /** * Number of bands. * * @return number of bands * @see #getBandBoundaries() */ public int getNumberOfBands() { return numberOfBands; } /** * Computes a bin for the given frequency. Returns -1, if the bin is not found. * * @param frequency frequency * @return bin */ public int getBin(final float frequency) { float lastFreq = 0; for (int bin=0; bin<bandBoundariesInHz.length; bin++) { final float freq = bandBoundariesInHz[bin]; if (frequency > lastFreq && frequency < freq) return bin; } return -1; } public float[] getFrequencies() { final float[] frequencies = new float[numberOfBands]; for (int i=0; i<frequencies.length; i++) { frequencies[i] = (bandBoundariesInHz[i]+bandBoundariesInHz[i+1]) / 2f; } return frequencies; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultiBandSpectrum that = (MultiBandSpectrum) o; if (!Arrays.equals(bandBoundariesInHz, that.bandBoundariesInHz)) return false; if (!Arrays.equals(imaginaryData, that.imaginaryData)) return false; if (!Arrays.equals(realData, that.realData)) return false; return true; } @Override public int hashCode() { int result = realData != null ? Arrays.hashCode(realData) : 0; result = 31 * result + (imaginaryData != null ? Arrays.hashCode(imaginaryData) : 0); result = 31 * result + (bandBoundariesInHz != null ? Arrays.hashCode(bandBoundariesInHz) : 0); return result; } @Override public String toString() { return "MultiBandSpectrum{" + "timestamp=" + getTimestamp() + ", frameNumber=" + getFrameNumber() + ", bandBoundariesInHz=" + bandBoundariesInHz + ", numberOfBands=" + numberOfBands + '}'; } @Override public Object clone() throws CloneNotSupportedException { final MultiBandSpectrum clone = (MultiBandSpectrum)super.clone(); clone.numberOfBands = numberOfBands; clone.bandBoundariesInHz = bandBoundariesInHz.clone(); return clone; } }
package org.lucene.analysis.vi; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.TypeAttribute; import org.elasticsearch.common.collect.Lists; import vn.hus.nlp.sd.IConstants; import vn.hus.nlp.sd.SentenceDetector; import vn.hus.nlp.sd.SentenceDetectorFactory; import vn.hus.nlp.tokenizer.TokenizerProvider; import vn.hus.nlp.tokenizer.tokens.TaggedWord; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Iterator; import java.util.List; /** * Vietnamese Tokenizer. * * @author duydo */ public class VietnameseTokenizer extends Tokenizer { private Iterator<TaggedWord> taggedWords; private int offset = 0; private final CharTermAttribute termAtt; private final OffsetAttribute offsetAtt; private final TypeAttribute type; public VietnameseTokenizer(Reader input) { super(input); termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); type = addAttribute(TypeAttribute.class); } private final void tokenize(Reader input) { final List<TaggedWord> words = Lists.newArrayList(); try { final vn.hus.nlp.tokenizer.Tokenizer tokenizer = TokenizerProvider.getInstance() .getTokenizer(); final SentenceDetector sentenceDetector = SentenceDetectorFactory.create(IConstants.LANG_VIETNAMESE); String[] sentences = sentenceDetector.detectSentences(input); for (String s : sentences) { tokenizer.tokenize(new StringReader(s)); for (TaggedWord taggedWord : tokenizer.getResult()) { words.add(taggedWord); } } tokenizer.tokenize(input); for (TaggedWord taggedWord : tokenizer.getResult()) { words.add(taggedWord); } } catch (IOException e) { } taggedWords = words.iterator(); } @Override public final boolean incrementToken() throws IOException { clearAttributes(); if (taggedWords.hasNext()) { final TaggedWord word = taggedWords.next(); termAtt.append(word.getText()); type.setType(word.getRule().getName()); final int wordLength = word.getText().length(); offsetAtt.setOffset(offset, offset + wordLength); offset += wordLength; return true; } return false; } @Override public final void end() throws IOException { super.end(); final int finalOffset = correctOffset(offset); offsetAtt.setOffset(finalOffset, finalOffset); } @Override public void reset() throws IOException { super.reset(); offset = 0; tokenize(input); } }
package org.onedatashare.server.module; import com.box.sdk.*; import org.onedatashare.server.model.core.Stat; import org.onedatashare.server.model.credential.EndpointCredential; import org.onedatashare.server.model.credential.OAuthEndpointCredential; import org.onedatashare.server.model.error.ODSAccessDeniedException; import org.onedatashare.server.model.filesystem.operations.DeleteOperation; import org.onedatashare.server.model.filesystem.operations.DownloadOperation; import org.onedatashare.server.model.filesystem.operations.ListOperation; import org.onedatashare.server.model.filesystem.operations.MkdirOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import reactor.core.publisher.Mono; import java.util.ArrayList; public class BoxResource extends Resource { private BoxAPIConnection client; Logger logger = LoggerFactory.getLogger(BoxResource.class); @Value("${box.clientId}") private String clientId; @Value("${box.clientSecret}") private String clientSecret; public BoxResource(EndpointCredential credential) { super(credential); OAuthEndpointCredential oAuthEndpointCredential = (OAuthEndpointCredential) credential; this.client = new BoxAPIConnection(clientId, clientSecret, oAuthEndpointCredential.getToken(), oAuthEndpointCredential.getRefreshToken()); } public static Mono<? extends Resource> initialize(EndpointCredential credential) { return Mono.create(s -> { try { BoxResource boxResource = new BoxResource(credential); s.success(boxResource); } catch (Exception e) { s.error(e); } }); } @Override public Mono<Void> delete(DeleteOperation operation) { return Mono.create(s -> { BoxTrash boxTrash = new BoxTrash(this.client); try{ boxTrash.deleteFile(operation.getToDelete()); s.success(); }catch (BoxAPIException boxAPIException){} try{ boxTrash.deleteFolder(operation.getToDelete()); s.success(); }catch (BoxAPIException boxAPIResponseException){ logger.error("Failed to delete the box id specified in the toDelete field"); boxAPIResponseException.printStackTrace(); } }); } @Override public Mono<Stat> list(ListOperation operation) { return Mono.create(s -> { try { Stat betterStat = new Stat(); if (operation.getId().isEmpty() || operation.getId() == null) { operation.setId("0"); betterStat.setName("Root"); } betterStat.setFilesList(new ArrayList<>()); BoxFolder folder = new BoxFolder(this.client, operation.getId()); //generally speaking u would only ever list a directory betterStat.setDir(true).setFile(false); betterStat.setId(folder.getID()); logger.info(folder.getInfo().toString()); betterStat.setName(folder.getInfo().getName()); betterStat.setSize(folder.getInfo().getSize()); ArrayList<Stat> childList = new ArrayList<>(); for (BoxItem.Info itemInfo : folder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; childList.add(boxFileToStat(fileInfo)); // Do something with the file. } else if (itemInfo instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; childList.add(boxFolderToStat(folderInfo)); } } betterStat.setFilesList(childList); s.success(betterStat); } catch (Exception e) { s.error(e); } }); } @Override public Mono<Void> mkdir(MkdirOperation operation) { return Mono.create(s -> { String[] pathToMake = operation.getFolderToCreate().split("/"); BoxFolder parentFolder = null; String operationId = operation.getId(); if (operation.getId() == null || operation.getId().isEmpty()) { parentFolder = BoxFolder.getRootFolder(this.client); } else { parentFolder = new BoxFolder(this.client, operationId); } for (String partOfPath : pathToMake) { BoxFolder.Info folder = parentFolder.createFolder(partOfPath); operationId = folder.getID(); parentFolder = new BoxFolder(this.client, operationId); } s.success(); }); } /** * this is not needed as we do not offer downloading over browser anymore. * The reason is there is no optimization applied to the download then. * Leaving this incase we decide to change this * * @param operation * @return */ @Override public Mono download(DownloadOperation operation) { return Mono.create(s -> { String url = ""; try { BoxFile file = new BoxFile(this.client, operation.getId()); url = file.getDownloadURL().toString(); s.success(url); } catch (BoxAPIResponseException be) { if (be.getResponseCode() == 403) { s.error(new ODSAccessDeniedException(403)); } } catch (Exception e) { s.error(e); } }); } public Stat boxFileToStat(BoxItem.Info fileInfo) { Stat stat = new Stat(); stat.setId(fileInfo.getID()); stat.setName(fileInfo.getName()); stat.setSize(fileInfo.getSize()); stat.setFile(true); stat.setDir(false); try { stat.setTime(fileInfo.getCreatedAt().getTime()); } catch (NullPointerException ignored) { } return stat; } public Stat boxFolderToStat(BoxFolder.Info folderInfo) { Stat stat = new Stat(); stat.setFiles(new ArrayList<>()); stat.setId(folderInfo.getID()); stat.setName(folderInfo.getName()); stat.setDir(true); try { stat.setTime(folderInfo.getCreatedAt().getTime()); } catch (NullPointerException ignored) { } stat.setFile(false); if (folderInfo.getCreatedAt() != null) { stat.setTime(folderInfo.getCreatedAt().getTime()); } return stat; } }
package org.owasp.esapi.reference; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Encoder; import org.owasp.esapi.ValidationErrorList; import org.owasp.esapi.ValidationRule; import org.owasp.esapi.Validator; import org.owasp.esapi.errors.IntrusionException; import org.owasp.esapi.errors.ValidationAvailabilityException; import org.owasp.esapi.errors.ValidationException; import org.owasp.esapi.reference.validation.CreditCardValidationRule; import org.owasp.esapi.reference.validation.DateValidationRule; import org.owasp.esapi.reference.validation.HTMLValidationRule; import org.owasp.esapi.reference.validation.IntegerValidationRule; import org.owasp.esapi.reference.validation.NumberValidationRule; import org.owasp.esapi.reference.validation.StringValidationRule; public class DefaultValidator implements org.owasp.esapi.Validator { private static volatile Validator instance = null; public static Validator getInstance() { if ( instance == null ) { synchronized ( Validator.class ) { if ( instance == null ) { instance = new DefaultValidator(); } } } return instance; } /** A map of validation rules */ private Map<String, ValidationRule> rules = new HashMap<String, ValidationRule>(); /** The encoder to use for canonicalization */ private Encoder encoder = null; /** The encoder to use for file system */ private static Validator fileValidator = null; /** Initialize file validator with an appropriate set of codecs */ static { List<String> list = new ArrayList<String>(); list.add( "HTMLEntityCodec" ); list.add( "PercentCodec" ); Encoder fileEncoder = new DefaultEncoder( list ); fileValidator = new DefaultValidator( fileEncoder ); } /** * Default constructor uses the ESAPI standard encoder for canonicalization. */ public DefaultValidator() { this.encoder = ESAPI.encoder(); } /** * Construct a new DefaultValidator that will use the specified * Encoder for canonicalization. * * @param encoder */ public DefaultValidator( Encoder encoder ) { this.encoder = encoder; } /** * Add a validation rule to the registry using the "type name" of the rule as the key. */ public void addRule( ValidationRule rule ) { rules.put( rule.getTypeName(), rule ); } /** * Get a validation rule from the registry with the "type name" of the rule as the key. */ public ValidationRule getRule( String name ) { return rules.get( name ); } public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException { try { getValidInput( context, input, type, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException { StringValidationRule rvr = new StringValidationRule( type, encoder ); Pattern p = ESAPI.securityConfiguration().getValidationPattern( type ); if ( p != null ) { rvr.addWhitelistPattern( p ); } else { rvr.addWhitelistPattern( type ); } rvr.setMaximumLength(maxLength); rvr.setAllowNull(allowNull); return rvr.getValid(context, input); } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInput(context, input, type, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException { try { getValidDate( context, input, format, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException { DateValidationRule dvr = new DateValidationRule( "SimpleDate", encoder, format); dvr.setAllowNull(allowNull); return dvr.getValid(context, input); } /** * {@inheritDoc} */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDate(context, input, format, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return null return null; } /** * {@inheritDoc} */ public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidSafeHTML( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} * * This implementation relies on the OWASP AntiSamy project. */ public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException { HTMLValidationRule hvr = new HTMLValidationRule( "safehtml", encoder ); hvr.setMaximumLength(maxLength); hvr.setAllowNull(allowNull); return hvr.getValid(context, input); } /** * {@inheritDoc} */ public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidSafeHTML(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException { try { getValidCreditCard( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { CreditCardValidationRule ccvr = new CreditCardValidationRule( "creditcard", encoder ); ccvr.setAllowNull(allowNull); return ccvr.getValid(context, input); } /** * {@inheritDoc} */ public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidCreditCard(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws IntrusionException { try { getValidDirectoryPath( context, input, parent, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context ); } File dir = new File( input ); // check dir exists and parent exists and dir is inside parent if ( !dir.exists() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, does not exist: context=" + context + ", input=" + input ); } if ( !dir.isDirectory() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not a directory: context=" + context + ", input=" + input ); } if ( !parent.exists() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent does not exist: context=" + context + ", input=" + input + ", parent=" + parent ); } if ( !parent.isDirectory() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent is not a directory: context=" + context + ", input=" + input + ", parent=" + parent ); } if ( !dir.getCanonicalPath().startsWith(parent.getCanonicalPath() ) ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not inside specified parent: context=" + context + ", input=" + input + ", parent=" + parent ); } // check canonical form matches input String canonicalPath = dir.getCanonicalPath(); String canonical = fileValidator.getValidInput( context, canonicalPath, "DirectoryName", 255, false); if ( !canonical.equals( input ) ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } return canonical; } catch (Exception e) { throw new ValidationException( context + ": Invalid directory name", "Failure to validate directory path: context=" + context + ", input=" + input, e, context ); } } /** * {@inheritDoc} */ public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDirectoryPath(context, input, parent, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException { return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull ); } /** * {@inheritDoc} */ public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws IntrusionException { try { getValidFileName( context, input, allowedExtensions, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException { if ((allowedExtensions == null) || (allowedExtensions.isEmpty())) { throw new ValidationException( "Internal Error", "getValidFileName called with an empty or null list of allowed Extensions, therefore no files can be uploaded" ); } String canonical = ""; // detect path manipulation try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context ); } // do basic validation canonical = new File(input).getCanonicalFile().getName(); getValidInput( context, input, "FileName", 255, true ); File f = new File(canonical); String c = f.getCanonicalPath(); String cpath = c.substring(c.lastIndexOf(File.separator) + 1); // the path is valid if the input matches the canonical path if (!input.equals(cpath)) { throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } } catch (IOException e) { throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context ); } // verify extensions Iterator<String> i = allowedExtensions.iterator(); while (i.hasNext()) { String ext = i.next(); if (input.toLowerCase().endsWith(ext.toLowerCase())) { return canonical; } } throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+allowedExtensions+")", "Invalid file name does not have valid extension ( "+allowedExtensions+"): context=" + context+", input=" + input, context ); } /** * {@inheritDoc} */ public String getValidFileName(String context, String input, List<String> allowedParameters, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileName(context, input, allowedParameters, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException { try { getValidNumber(context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException { Double minDoubleValue = new Double(minValue); Double maxDoubleValue = new Double(maxValue); return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull); } /** * {@inheritDoc} */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidNumber(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return null; } /** * {@inheritDoc} */ public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException { try { getValidDouble( context, input, minValue, maxValue, allowNull ); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException { NumberValidationRule nvr = new NumberValidationRule( "number", encoder, minValue, maxValue ); nvr.setAllowNull(allowNull); return nvr.getValid(context, input); } /** * {@inheritDoc} */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDouble(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return new Double(Double.NaN); } /** * {@inheritDoc} */ public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException { try { getValidInteger( context, input, minValue, maxValue, allowNull); return true; } catch( ValidationException e ) { return false; } } /** * {@inheritDoc} */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException { IntegerValidationRule ivr = new IntegerValidationRule( "number", encoder, minValue, maxValue ); ivr.setAllowNull(allowNull); return ivr.getValid(context, input); } /** * {@inheritDoc} */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInteger(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return null; } /** * {@inheritDoc} */ public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException { try { getValidFileContent( context, input, maxBytes, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize(); if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context ); if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context ); return input; } /** * {@inheritDoc} */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileContent(context, input, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // return empty byte array on error return new byte[0]; } /** * {@inheritDoc} * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException { return( isValidFileName( context, filename, allowNull ) && isValidDirectoryPath( context, directorypath, parent, allowNull ) && isValidFileContent( context, content, maxBytes, allowNull ) ); } /** * {@inheritDoc} */ public void assertValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException { getValidFileName( context, filename, allowedExtensions, allowNull ); getValidDirectoryPath( context, directorypath, parent, allowNull ); getValidFileContent( context, content, maxBytes, allowNull ); } /** * {@inheritDoc} */ public void assertValidFileUpload(String context, String filepath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { assertValidFileUpload(context, filepath, filename, parent, content, maxBytes, allowedExtensions, allowNull); } catch (ValidationException e) { errors.addError(context, e); } } /** * {@inheritDoc} * * Returns true if input is a valid list item. */ public boolean isValidListItem(String context, String input, List<String> list) { try { getValidListItem( context, input, list); return true; } catch( Exception e ) { return false; } } /** * Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidListItem(String context, String input, List<String> list) throws ValidationException, IntrusionException { if (list.contains(input)) return input; throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context ); } /** * ValidationErrorList variant of getValidListItem * * @param errors */ public String getValidListItem(String context, String input, List<String> list, ValidationErrorList errors) throws IntrusionException { try { return getValidListItem(context, input, list); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} */ public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames) { try { assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames); return true; } catch( Exception e ) { return false; } } /** * Validates that the parameters in the current request contain all required parameters and only optional ones in * addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest */ public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional) throws ValidationException, IntrusionException { Set<String> actualNames = request.getParameterMap().keySet(); // verify ALL required parameters are present Set<String> missing = new HashSet<String>(required); missing.removeAll(actualNames); if (missing.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context ); } // verify ONLY optional + required parameters are present Set<String> extra = new HashSet<String>(actualNames); extra.removeAll(required); extra.removeAll(optional); if (extra.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context ); } } /** * ValidationErrorList variant of assertIsValidHTTPRequestParameterSet * * Uses current HTTPRequest saved in ESAPI Authenticator * @param errors */ public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional, ValidationErrorList errors) throws IntrusionException { try { assertValidHTTPRequestParameterSet(context, request, required, optional); } catch (ValidationException e) { errors.addError(context, e); } } public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * @throws IntrusionException */ public char[] getValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context ); } if (input.length > maxLength) { throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + new String( input ), context); } for (int i = 0; i < input.length; i++) { if (input[i] <= 0x20 || input[i] >= 0x7E ) { throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + new String( input ), context); } } return input; } /** * ValidationErrorList variant of getValidPrintable * * @param errors */ public char[] getValidPrintable(String context, char[] input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * Returns true if input is valid printable ASCII characters (32-126). */ public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * @throws IntrusionException */ public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { try { String canonical = encoder.canonicalize(input); return new String( getValidPrintable( context, canonical.toCharArray(), maxLength, allowNull) ); //TODO - changed this to base Exception since we no longer need EncodingException //TODO - this is a bit lame: we need to re-think this function. } catch (Exception e) { throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context); } } /** * ValidationErrorList variant of getValidPrintable * * @param errors */ public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * Returns true if input is a valid redirect location. */ public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException { return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull); } /** * Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull); } /** * ValidationErrorList variant of getValidRedirectLocation * * @param errors */ public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidRedirectLocation(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * This implementation reads until a newline or the specified number of * characters. * * @param in * @param max */ public String safeReadLine(InputStream in, int max) throws ValidationException { if (max <= 0) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream"); } StringBuilder sb = new StringBuilder(); int count = 0; int c; try { while (true) { c = in.read(); if ( c == -1 ) { if (sb.length() == 0) { return null; } break; } if (c == '\n' || c == '\r') { break; } count++; if (count > max) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")"); } sb.append((char) c); } return sb.toString(); } catch (IOException e) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e); } } /** * Helper function to check if a String is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(String input) { return (input==null || input.trim().length() == 0); } /** * Helper function to check if a byte array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(byte[] input) { return (input==null || input.length == 0); } /** * Helper function to check if a char array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(char[] input) { return (input==null || input.length == 0); } }
package org.appwork.swing.exttable.columns; import java.awt.Rectangle; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JProgressBar; import javax.swing.border.CompoundBorder; import org.appwork.swing.exttable.ExtColumn; import org.appwork.swing.exttable.ExtDefaultRowSorter; import org.appwork.swing.exttable.ExtTableModel; import org.appwork.swing.exttable.renderercomponents.RendererProgressBar; abstract public class ExtProgressColumn<E> extends ExtColumn<E> { private static final long serialVersionUID = -2473320164484034664L; protected JProgressBar determinatedRenderer; protected CompoundBorder defaultBorder; private JProgressBar indeterminatedRenderer; private JProgressBar renderer; private HashMap<E, Long> map; private int columnIndex = -1; public ExtProgressColumn(final String title) { this(title, null); } public ExtProgressColumn(final String name, final ExtTableModel<E> extModel) { super(name, extModel); this.map = new HashMap<E, Long>(); this.determinatedRenderer = new RendererProgressBar() { }; this.indeterminatedRenderer = new RendererProgressBar() { private static final long serialVersionUID = 1L; private long cleanupTimer = 0; private volatile boolean indeterminate = false; private volatile long timer = 0; @Override public boolean isDisplayable() { return true; } @Override public boolean isIndeterminate() { return this.indeterminate; } @Override public boolean isVisible() { return false; } @Override public void repaint() { if (ExtProgressColumn.this.isModifying()) { return; } final ExtTableModel<E> mod = ExtProgressColumn.this.getModel(); if (mod != null && mod.getTable() != null && ExtProgressColumn.this.indeterminatedRenderer.isIndeterminate() && mod.getTable().isShowing()) { // cleanup map in case we removed a indeterminated value if (System.currentTimeMillis() - this.cleanupTimer > 30000) { Entry<E, Long> next; for (final Iterator<Entry<E, Long>> it = ExtProgressColumn.this.map.entrySet().iterator(); it.hasNext();) { next = it.next(); final long lastUpdate = System.currentTimeMillis() - next.getValue(); if (lastUpdate > 5000) { it.remove(); } } this.cleanupTimer = System.currentTimeMillis(); if (ExtProgressColumn.this.map.size() == 0 && ExtProgressColumn.this.indeterminatedRenderer.isIndeterminate()) { ExtProgressColumn.this.indeterminatedRenderer.setIndeterminate(false); return; } } if (ExtProgressColumn.this.columnIndex >= 0) { if (System.currentTimeMillis() - this.timer > 1000 / ExtProgressColumn.this.getFps()) { mod._fireTableStructureChanged(mod.getTableData(), false); this.timer = System.currentTimeMillis(); } } } } @Override public void repaint(final Rectangle r) { this.repaint(); } @Override public void setIndeterminate(final boolean newValue) { if (newValue == this.indeterminate) { return; } this.indeterminate = newValue; super.setIndeterminate(newValue); } }; // this.getModel().addTableModelListener(new TableModelListener() { // @Override // public void tableChanged(final TableModelEvent e) { // switch (e.getType()) { // case TableModelEvent.DELETE: // System.out.println(e); // if (ExtProgressColumn.this.map.size() == 0) { // ExtProgressColumn.this.indeterminatedRenderer.setIndeterminate(false); this.renderer = this.determinatedRenderer; this.defaultBorder = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, 2, 1), this.determinatedRenderer.getBorder()); this.setRowSorter(new ExtDefaultRowSorter<E>() { @Override public int compare(final E o1, final E o2) { final double v1 = (double) ExtProgressColumn.this.getValue(o1) / ExtProgressColumn.this.getMax(o1); final double v2 = (double) ExtProgressColumn.this.getValue(o2) / ExtProgressColumn.this.getMax(o2); if (v1 == v2) { return 0; } if (this.getSortOrderIdentifier() != ExtColumn.SORT_ASC) { return v1 > v2 ? -1 : 1; } else { return v2 > v1 ? -1 : 1; } } }); } @Override public void configureEditorComponent(final E value, final boolean isSelected, final int row, final int column) { // TODO Auto-generated method stub } @Override public void configureRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { this.prepareGetter(value); if (this.renderer == this.determinatedRenderer) { // Normalize value and maxvalue to fit in the integer range long m = this.getMax(value); long v = 0; if (m >= 0) { v = this.getValue(value); final double factor = Math.max(v / (double) Integer.MAX_VALUE, m / (double) Integer.MAX_VALUE); if (factor >= 1.0) { v /= factor; m /= factor; } } // take care to set the maximum before the value!! this.renderer.setMaximum((int) m); this.renderer.setValue((int) v); this.renderer.setString(this.getString(value, v, m)); } else { this.renderer.setString(this.getString(value, -1, -1)); if (!this.renderer.isIndeterminate()) { this.renderer.setIndeterminate(true); } } } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#getCellEditorValue * () */ @Override public Object getCellEditorValue() { return null; } /** * @return */ @Override public JComponent getEditorComponent(final E value, final boolean isSelected, final int row, final int column) { return null; } /** * @return */ protected int getFps() { return 15; } protected long getMax(final E value) { return 100; } public static double getPercentString(final long current, final long total) { if (total <= 0) { return 0.00d; } return current * 10000 / total / 100.0d; } /** * @return */ @Override public JComponent getRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { this.columnIndex = column; if (this.isIndeterminated(value, isSelected, hasFocus, row, column)) { this.renderer = this.indeterminatedRenderer; if (this.map.size() == 0) { if (!this.indeterminatedRenderer.isIndeterminate()) { this.map.put(value, System.currentTimeMillis()); this.indeterminatedRenderer.setIndeterminate(true); } } this.map.put(value, System.currentTimeMillis()); } else { this.renderer = this.determinatedRenderer; this.map.remove(value); if (this.map.size() == 0) { if (this.indeterminatedRenderer.isIndeterminate()) { this.indeterminatedRenderer.setIndeterminate(false); } } } return this.renderer; } abstract protected String getString(E value, long current, long total); @Override protected String getTooltipText(final E value) { long v = this.getValue(value); long m = this.getMax(value); final double factor = Math.max(v / (double) Integer.MAX_VALUE, m / (double) Integer.MAX_VALUE); if (factor >= 1.0) { v /= factor; m /= factor; } return this.getString(value, v, m); } abstract protected long getValue(E value); /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#isEditable(java * .lang.Object) */ @Override public boolean isEditable(final E obj) { return false; } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#isEnabled(java * .lang.Object) */ @Override public boolean isEnabled(final E obj) { return true; } /** * @param column * @param row * @param hasFocus * @param isSelected * @param value * @return */ protected boolean isIndeterminated(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#isSortable(java * .lang.Object) */ @Override public boolean isSortable(final E obj) { return true; } /** * @param value */ protected void prepareGetter(final E value) { } @Override public void resetEditor() { // TODO Auto-generated method stub } @Override public void resetRenderer() { this.renderer.setOpaque(false); this.renderer.setStringPainted(true); this.renderer.setBorder(this.defaultBorder); } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#setValue(java * .lang.Object, java.lang.Object) */ @Override public void setValue(final Object value, final E object) { } }
package org.pentaho.agilebi.pdi.modeler; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.swt.widgets.Display; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.tableoutput.TableOutputMeta; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.metadata.model.Category; import org.pentaho.metadata.model.Domain; import org.pentaho.metadata.model.LogicalColumn; import org.pentaho.metadata.model.LogicalModel; import org.pentaho.metadata.model.LogicalTable; import org.pentaho.metadata.model.concept.types.AggregationType; import org.pentaho.metadata.model.concept.types.DataType; import org.pentaho.metadata.model.concept.types.LocalizedString; import org.pentaho.metadata.model.olap.OlapCube; import org.pentaho.metadata.model.olap.OlapDimension; import org.pentaho.metadata.model.olap.OlapDimensionUsage; import org.pentaho.metadata.model.olap.OlapHierarchy; import org.pentaho.metadata.model.olap.OlapHierarchyLevel; import org.pentaho.metadata.model.olap.OlapMeasure; import org.pentaho.metadata.util.XmiParser; /** * Utility class for generating ModelerModels for the User Interface. * * @author nbaker * */ public class ModelerWorkspaceUtil { private static final List<AggregationType> DEFAULT_AGGREGATION_LIST = new ArrayList<AggregationType>(); private static Log logger = LogFactory.getLog(ModelerWorkspaceUtil.class); static { DEFAULT_AGGREGATION_LIST.add(AggregationType.NONE); DEFAULT_AGGREGATION_LIST.add(AggregationType.SUM); DEFAULT_AGGREGATION_LIST.add(AggregationType.AVERAGE); DEFAULT_AGGREGATION_LIST.add(AggregationType.MINIMUM); DEFAULT_AGGREGATION_LIST.add(AggregationType.MAXIMUM); } public static ModelerWorkspace populateModelFromSource( ModelerWorkspace model, IModelerSource source ) throws ModelerException { Domain d = source.generateDomain(); model.setModelSource(source); model.setModelName(source.getTableName()); model.setDomain(d); return model; } public static ModelerWorkspace populateModelFromOutputStep(ModelerWorkspace model) throws ModelerException { String MODELER_NAME = "OutputStepModeler"; //$NON-NLS-1$ Spoon spoon = ((Spoon)SpoonFactory.getInstance()); TransMeta transMeta = spoon.getActiveTransformation(); if( transMeta == null ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.TransNotOpen" ), MODELER_NAME, false, Const.ERROR); //$NON-NLS-1$ throw new IllegalStateException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.TransNotOpen")); //$NON-NLS-1$ } List<StepMeta> steps = transMeta.getSelectedSteps(); if( steps == null || steps.size() > 1 ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.OneStepNeeded"), MODELER_NAME, false, Const.ERROR); //$NON-NLS-1$ throw new IllegalStateException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.OneStepNeeded")); //$NON-NLS-1$ } // assume only one selected StepMeta stepMeta = steps.get(0); if( !(stepMeta.getStepMetaInterface() instanceof TableOutputMeta) ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.OutputStepNeeded"), MODELER_NAME, false, Const.ERROR); //$NON-NLS-1$ throw new IllegalStateException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.OutputStepNeeded")); //$NON-NLS-1$ } TableOutputMeta tableOutputMeta = (TableOutputMeta) stepMeta.getStepMetaInterface(); DatabaseMeta databaseMeta = tableOutputMeta.getDatabaseMeta(); RowMetaInterface rowMeta = null; try { rowMeta = transMeta.getStepFields(stepMeta); } catch (KettleException e) { logger.info(e); Throwable e1 = e; while (e1.getCause() != null && e1 != e1.getCause()) { e1 = e1.getCause(); } throw new ModelerException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.NoStepMeta"), e1); //$NON-NLS-1$ } if(rowMeta == null){ throw new ModelerException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.FromOutputStep.NoStepMeta")); //$NON-NLS-1$ } OutputStepModelerSource source = new OutputStepModelerSource(tableOutputMeta, databaseMeta, rowMeta); source.setFileName(transMeta.getFilename()); source.setStepId(stepMeta.getStepID()); Repository repository = transMeta.getRepository(); if(repository != null) { source.setRepositoryName(repository.getName()); } Domain d = source.generateDomain(); model.setModelSource(source); model.setModelName(tableOutputMeta.getTablename()); model.setDomain(d); return model; } /** * Builds an OLAP model that is attribute based. * @param modelId * @param rowMeta * @param locale * @param user * @param tableName */ public static void autoModelFlat( ModelerWorkspace workspace ) throws ModelerException { if(workspace.isAutoModel()) { workspace.setModel(new MainModelNode()); workspace.setModelIsChanging(true); List<AvailableField> fields = workspace.getAvailableFields(); for( AvailableField field : fields ) { DataType dataType = field.getLogicalColumn().getDataType(); if( dataType == DataType.NUMERIC) { // create a measure MeasureMetaData measure = workspace.createMeasureForNode(field); workspace.getModel().getMeasures().add(measure); } // create a dimension workspace.addDimensionFromNode(field); } workspace.setModelIsChanging(false); } } /** * Builds an OLAP model that is attribute based. * @param modelId * @param rowMeta * @param locale * @param user * @param tableName */ public static void autoModelFlatInBackground( final ModelerWorkspace workspace ) throws ModelerException { if(workspace.isAutoModel()) { final Display display = Display.findDisplay(Thread.currentThread()); Runnable worker = new Runnable(){ public void run() { workspace.setModel(new MainModelNode()); final boolean prevChangeState = workspace.isModelChanging(); workspace.setModelIsChanging(true); List<AvailableField> fields = workspace.getAvailableFields(); for( AvailableField field : fields ) { DataType dataType = field.getLogicalColumn().getDataType(); if( dataType == DataType.NUMERIC) { // create a measure MeasureMetaData measure = workspace.createMeasureForNode(field); workspace.getModel().getMeasures().add(measure); } // create a dimension workspace.addDimensionFromNode(field); } display.syncExec(new Runnable(){ public void run() { workspace.setModelIsChanging(prevChangeState); } }); } }; new Thread(worker).start(); } } public static void populateDomain(ModelerWorkspace model) throws ModelerException { Domain domain = model.getDomain(); domain.setId( model.getModelName() ); List<Category> cats = domain.getLogicalModels().get(0).getCategories(); LogicalTable logicalTable = domain.getLogicalModels().get(0).getLogicalTables().get(0); if (model.getModelSource() != null) { model.getModelSource().serializeIntoDomain(domain); } LogicalModel logicalModel = domain.getLogicalModels().get(0); logicalModel.setName( new LocalizedString( Locale.getDefault().toString(), model.getModelName() ) ); Category cat; // Find existing category or create new one if (cats.size() > 0) { cat = cats.get(0); } else { cat = new Category(); logicalModel.addCategory(cat); } cat.setId(model.getModelName()); cat.getLogicalColumns().clear(); // Add all measures for (MeasureMetaData f : model.getModel().getMeasures()) { LogicalColumn lCol = logicalModel.findLogicalColumn(f.getLogicalColumn().getId()); lCol.setName(new LocalizedString(Locale.getDefault().toString(), f.getName())); AggregationType type = AggregationType.valueOf(f.getAggTypeDesc()); if (type != AggregationType.NONE) { lCol.setAggregationType(type); } // set the format mask String formatMask = f.getFormat(); if( MeasureMetaData.FORMAT_NONE.equals(formatMask) || StringUtils.isBlank(formatMask)) { formatMask = null; } if (formatMask != null) { lCol.setProperty("mask", formatMask); //$NON-NLS-1$ } else { // remove old mask that might have been set if (lCol.getChildProperty("mask") != null) { //$NON-NLS-1$ lCol.removeChildProperty("mask"); //$NON-NLS-1$ } } lCol.setAggregationList(DEFAULT_AGGREGATION_LIST); AggregationType selectedAgg = AggregationType.NONE; try{ selectedAgg = AggregationType.valueOf(f.getAggTypeDesc()); } catch(IllegalArgumentException e){ logger.info(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.Populate.BadAggType", f.getAggTypeDesc() ), e); //$NON-NLS-1$ throw new ModelerException(e); } lCol.setAggregationType(selectedAgg); cat.addLogicalColumn(lCol); } // Add levels for (DimensionMetaData dim : model.getModel().getDimensions()) { for (HierarchyMetaData hier : dim) { for (int j = 0; j < hier.size(); j++) { LevelMetaData level = hier.get(j); LogicalColumn lCol = logicalModel.findLogicalColumn(level.getLogicalColumn().getId()); lCol.setName(new LocalizedString(Locale.getDefault().toString(), level.getName())); if (cat.findLogicalColumn(lCol.getId()) == null) { cat.addLogicalColumn(lCol); } } } } List<OlapDimensionUsage> usages = new ArrayList<OlapDimensionUsage>(); List<OlapDimension> olapDimensions = new ArrayList<OlapDimension>(); List<OlapMeasure> measures = new ArrayList<OlapMeasure>(); for (DimensionMetaData dim : model.getModel().getDimensions()) { OlapDimension dimension = new OlapDimension(); String dimTitle = dim.getName(); dimension.setName(dimTitle); dimension.setTimeDimension(dim.isTime()); List<OlapHierarchy> hierarchies = new ArrayList<OlapHierarchy>(); for (HierarchyMetaData hier : dim) { OlapHierarchy hierarchy = new OlapHierarchy(dimension); hierarchy.setName(hier.getName()); hierarchy.setLogicalTable(logicalTable); List<OlapHierarchyLevel> levels = new ArrayList<OlapHierarchyLevel>(); for (LevelMetaData lvl : hier) { OlapHierarchyLevel level = new OlapHierarchyLevel(hierarchy); level.setName(lvl.getName()); LogicalColumn lvlColumn = logicalModel.findLogicalColumn(lvl.getLogicalColumn().getId()); level.setReferenceColumn(lvlColumn); level.setHavingUniqueMembers(lvl.isUniqueMembers()); levels.add(level); } hierarchy.setHierarchyLevels(levels); hierarchies.add(hierarchy); } if(hierarchies.isEmpty()) { // create a default hierarchy OlapHierarchy defaultHierarchy = new OlapHierarchy(dimension); defaultHierarchy.setLogicalTable(logicalTable); hierarchies.add(defaultHierarchy); } dimension.setHierarchies(hierarchies); olapDimensions.add(dimension); OlapDimensionUsage usage = new OlapDimensionUsage(dimension.getName(), dimension); usages.add(usage); } OlapCube cube = new OlapCube(); cube.setLogicalTable(logicalTable); // TODO find a better way to generate default names cube.setName( BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.Populate.CubeName", model.getModelName() ) ); //$NON-NLS-1$ cube.setOlapDimensionUsages(usages); for (MeasureMetaData f : model.getModel().getMeasures()) { OlapMeasure measure = new OlapMeasure(); String n = f.getName(); measure.setName(n); f.getLogicalColumn().setAggregationType(AggregationType.valueOf(f.getAggTypeDesc())); measure.setLogicalColumn(f.getLogicalColumn()); measures.add(measure); } cube.setOlapMeasures(measures); LogicalModel lModel = domain.getLogicalModels().get(0); if (olapDimensions.size() > 0) { // Metadata OLAP generator doesn't like empty lists. lModel.setProperty("olap_dimensions", olapDimensions); //$NON-NLS-1$ } List<OlapCube> cubes = new ArrayList<OlapCube>(); cubes.add(cube); lModel.setProperty("olap_cubes", cubes); //$NON-NLS-1$ } public static void saveWorkspace(ModelerWorkspace aModel, String fileName) throws ModelerException { try { String xmi = getMetadataXML(aModel); // write the XMI to a tmp file // models was created earlier. try{ File file = new File(fileName); PrintWriter pw = new PrintWriter(new FileWriter(file)); pw.print(xmi); pw.close(); } catch(IOException e){ logger.info(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.Populate.BadGenerateMetadata"),e); //$NON-NLS-1$ throw new ModelerException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.Populate.BadGenerateMetadata"),e); //$NON-NLS-1$ } } catch (Exception e) { logger.info(e.getLocalizedMessage()); throw new ModelerException(e); } } public static String getMetadataXML(ModelerWorkspace aModel) throws ModelerException { populateDomain(aModel); XmiParser parser = new XmiParser(); return parser.generateXmi(aModel.getDomain()); } public static void loadWorkspace(String fileName, String aXml, ModelerWorkspace aModel) throws ModelerException { try{ XmiParser parser = new XmiParser(); Domain domain = parser.parseXmi(new ByteArrayInputStream(aXml.getBytes())); // re-hydrate the source LogicalModel logical = domain.getLogicalModels().get(0); Object property = logical.getProperty("source_type"); //$NON-NLS-1$ if( property != null ) { IModelerSource theSource = ModelerSourceFactory.generateSource(property.toString()); theSource.initialize(domain); aModel.setModelSource(theSource); } aModel.setDomain(domain); aModel.setFileName(fileName); aModel.resolveConnectionFromDomain(); aModel.refresh(); aModel.setDirty(false); } catch (Exception e){ logger.info(e); e.printStackTrace(); throw new ModelerException(BaseMessages.getString(ModelerWorkspaceUtil.class, "ModelerWorkspaceUtil.LoadWorkspace.Failed"),e); //$NON-NLS-1$ } } }
package org.picocontainer; import org.jetbrains.annotations.NotNull; import java.io.PrintStream; import java.io.PrintWriter; /** * Superclass for all Exceptions in PicoContainer. You can use this if you want to catch all exceptions thrown by * PicoContainer. Be aware that some parts of the PicoContainer API will also throw {@link NullPointerException} when * <code>null</code> values are provided for method arguments, and this is not allowed. * * @author Paul Hammant * @author Aslak Helles&oslash;y * @version $Revision: 1812 $ * @since 1.0 */ public class PicoException extends RuntimeException { /** * The exception that caused this one. */ private Throwable cause; /** * Construct a new exception with no cause and no detail message. Note modern JVMs may still track the exception * that caused this one. */ public PicoException() { } /** * Construct a new exception with no cause and the specified detail message. Note modern JVMs may still track the * exception that caused this one. * * @param message the message detailing the exception. */ public PicoException(@NotNull String message) { super(message); } /** * Construct a new exception with the specified cause and no detail message. * * @param cause the exception that caused this one. */ public PicoException(final Throwable cause) { this.cause = cause; } /** * Construct a new exception with the specified cause and the specified detail message. * * @param message the message detailing the exception. * @param cause the exception that caused this one. */ public PicoException(final String message, final Throwable cause) { super(message); this.cause = cause; } /** * Retrieve the exception that caused this one. * * @return the exception that caused this one, or null if it was not set. * @see Throwable#getCause() the method available since JDK 1.4 that is overridden by this method. */ @Override public Throwable getCause() { return cause; } /** * Overridden to provide 1.4 style stack traces on pre-1.4. */ @Override public void printStackTrace() { printStackTrace(System.err); } /** * Overridden to provide 1.4 style stack traces on pre-1.4. */ @Override public void printStackTrace(PrintStream s) { super.printStackTrace(s); if (cause != null) { s.println("Caused by:\n"); cause.printStackTrace(s); } } /** * Overridden to provide 1.4 style stack traces on pre-1.4. * * @param s the {@link PrintWriter} used to print the stack trace */ @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if (cause != null) { s.println("Caused by:\n"); cause.printStackTrace(s); } } }
package com.jaguarlandrover.pki; import android.content.Context; import android.security.KeyPairGeneratorSpec; import android.util.Log; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.spongycastle.asn1.x500.X500Name; import org.spongycastle.asn1.x509.AlgorithmIdentifier; import org.spongycastle.asn1.x509.BasicConstraints; import org.spongycastle.asn1.x509.Certificate; import org.spongycastle.asn1.x509.Extension; import org.spongycastle.asn1.x509.ExtensionsGenerator; import org.spongycastle.operator.ContentSigner; import org.spongycastle.operator.OperatorCreationException; import org.spongycastle.pkcs.PKCS10CertificationRequest; import org.spongycastle.pkcs.PKCS10CertificationRequestBuilder; import org.spongycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import javax.security.auth.x500.X500Principal; public class KeyManager { private final static String TAG = "UnlockDemo:KeyManager"; private final static String KEYSTORE_ALIAS = "RVI_KEYPAIR_4096_6"; private final static String DEFAULT_SIGNATURE_ALGORITHM = "SHA256withRSA"; private final static String CN_PATTERN = "CN=%s, O=Genivi, OU=OrgUnit, EMAILADDRESS=pdxostc.android@gmail.com"; private final static Integer KEY_SIZE = 4096; static byte [] getCSR(Context context, String commonName) { String principal = String.format(CN_PATTERN, commonName); KeyStore keyStore = null; KeyPair keyPair = null; java.security.cert.Certificate cert = null; try { keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); if (!keyStore.containsAlias(KEYSTORE_ALIAS)) { Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 1); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context) .setAlias(KEYSTORE_ALIAS) .setKeySize(KEY_SIZE) .setSubject(new X500Principal(principal)) .setSerialNumber(BigInteger.ONE) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(spec); keyPair = generator.generateKeyPair(); cert = keyStore.getCertificate(KEYSTORE_ALIAS); } else { Key key = keyStore.getKey(KEYSTORE_ALIAS, null); cert = keyStore.getCertificate(KEYSTORE_ALIAS); PublicKey publicKey = cert.getPublicKey(); keyPair = new KeyPair(publicKey, (PrivateKey) key); } return cert.getEncoded(); } catch (Exception e) { e.printStackTrace(); } return null; } }
package com.intellij.util.io; import com.intellij.openapi.util.io.FileUtil; import gnu.trove.TIntIntHashMap; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; class IntToIntBtree { static final int VERSION = 2; static final boolean doSanityCheck = false; static final boolean doDump = false; final int pageSize; private final short maxInteriorNodes; private final short maxLeafNodes; private final short maxLeafNodesInHash; final BtreeIndexNodeView root; private int height; private int maxStepsSearchedInHash; private int totalHashStepsSearched; private int hashSearchRequests; private int pagesCount; private int hashedPagesCount; private int count; private int movedMembersCount; private boolean isLarge = true; private final ResizeableMappedFile storage; private final boolean offloadToSiblingsBeforeSplit = false; private boolean indexNodeIsHashTable = true; final int metaDataLeafPageLength; final int hashPageCapacity; private static final boolean hasCachedMappings = false; private TIntIntHashMap myCachedMappings; private final int myCachedMappingsSize; public IntToIntBtree(int _pageSize, File file, boolean initial) throws IOException { pageSize = _pageSize; if (initial) { FileUtil.delete(file); } storage = new ResizeableMappedFile(file, pageSize, PersistentEnumeratorBase.ourLock, 1024 * 1024, true); root = new BtreeIndexNodeView(this); if (initial) { nextPage(); // allocate root root.setAddress(0); root.setIndexLeaf(true); } int i = (pageSize - BtreePage.RESERVED_META_PAGE_LEN) / BtreeIndexNodeView.INTERIOR_SIZE - 1; assert i < Short.MAX_VALUE && i % 2 == 0; maxInteriorNodes = (short)i; maxLeafNodes = (short)i; int metaPageLen = BtreePage.RESERVED_META_PAGE_LEN; if (indexNodeIsHashTable) { ++i; final double bitsPerState = BtreeIndexNodeView.haveDeleteState? 2d:1d; while(Math.ceil(bitsPerState * i / 8) + i * BtreeIndexNodeView.INTERIOR_SIZE + BtreePage.RESERVED_META_PAGE_LEN > pageSize || !isPrime(i) ) { i -= 2; } hashPageCapacity = i; metaPageLen = BtreePage.RESERVED_META_PAGE_LEN + (int)Math.ceil(bitsPerState * hashPageCapacity / 8); i = (int)(hashPageCapacity * 0.8); if ((i & 1) == 1) ++i; } else { hashPageCapacity = -1; } metaDataLeafPageLength = metaPageLen; assert i > 0 && i % 2 == 0; maxLeafNodesInHash = (short) i; if (hasCachedMappings) { myCachedMappings = new TIntIntHashMap(myCachedMappingsSize = 4 * maxLeafNodes); } else { myCachedMappings = null; myCachedMappingsSize = -1; } } public void persistVars(BtreeDataStorage storage, boolean toDisk) { height = storage.persistInt(0, height, toDisk); pagesCount = storage.persistInt(4, pagesCount, toDisk); movedMembersCount = storage.persistInt(8, movedMembersCount, toDisk); maxStepsSearchedInHash = storage.persistInt(12, maxStepsSearchedInHash, toDisk); count = storage.persistInt(16, count, toDisk); hashSearchRequests = storage.persistInt(20, hashSearchRequests, toDisk); totalHashStepsSearched = storage.persistInt(24, totalHashStepsSearched, toDisk); hashedPagesCount = storage.persistInt(28, hashedPagesCount, toDisk); root.setAddress(storage.persistInt(32, root.address, toDisk)); } interface BtreeDataStorage { int persistInt(int offset, int value, boolean toDisk); } private static boolean isPrime(int val) { if (val % 2 == 0) return false; int maxDivisor = (int)Math.sqrt(val); for(int i = 3; i <= maxDivisor; i+=2) { if (val % i == 0) return false; } return true; } private int nextPage() { int pageStart = (int)storage.length(); storage.putInt(pageStart + pageSize - 4, 0); ++pagesCount; return pageStart; } public @Nullable Integer get(int key) { if (hasCachedMappings) { if (myCachedMappings.containsKey(key)) { return myCachedMappings.get(key); } } BtreeIndexNodeView currentIndexNode = new BtreeIndexNodeView(this); currentIndexNode.setAddress(root.address); int index = currentIndexNode.locate(key, false); if (index < 0) return null; return currentIndexNode.addressAt(index); } public void put(int key, int value) { if (hasCachedMappings) { myCachedMappings.put(key, value); if (myCachedMappings.size() == myCachedMappingsSize) flushCachedMappings(); } else { doPut(key, value); } } private void doPut(int key, int value) { BtreeIndexNodeView currentIndexNode = new BtreeIndexNodeView(this); currentIndexNode.setAddress(root.address); int index = currentIndexNode.locate(key, true); if (index < 0) { ++count; currentIndexNode.insert(key, value); } else { currentIndexNode.setAddressAt(index, value); } } //public int remove(int key) { // // TODO // BtreeIndexNodeView currentIndexNode = new BtreeIndexNodeView(this); // currentIndexNode.setAddress(root.address); // int index = currentIndexNode.locate(key, false); // myAssert(BtreeIndexNodeView.haveDeleteState); // throw new UnsupportedOperationException("Remove does not work yet "+key); void dumpStatistics() { int leafPages = height == 3 ? pagesCount - (1 + root.getChildrenCount() + 1):height == 2 ? pagesCount - 1:1; long leafNodesCapacity = hashedPagesCount * maxLeafNodesInHash + (leafPages - hashedPagesCount)* maxLeafNodes; long leafNodesCapacity2 = leafPages * maxLeafNodes; int usedPercent = (int)((count * 100L) / leafNodesCapacity); int usedPercent2 = (int)((count * 100L) / leafNodesCapacity2); IOStatistics.dump("pagecount:" + pagesCount + ", height:" + height + ", movedMembers:"+movedMembersCount + ", hash steps:" + maxStepsSearchedInHash + ", avg search in hash:" + (hashSearchRequests != 0 ? totalHashStepsSearched / hashSearchRequests:0) + ", leaf pages used:" + usedPercent + "%, leaf pages used if sorted: " + usedPercent2 + "%, size:"+storage.length() ); } private void flushCachedMappings() { if (hasCachedMappings) { int[] keys = myCachedMappings.keys(); Arrays.sort(keys); for(int key:keys) doPut(key, myCachedMappings.get(key)); myCachedMappings.clear(); } } void doClose() throws IOException { myCachedMappings = null; storage.close(); } void doFlush() { flushCachedMappings(); storage.force(); } static void myAssert(boolean b) { if (!b) { myAssert("breakpoint place" != "do not remove"); } assert b; } static class BtreePage { static final int RESERVED_META_PAGE_LEN = 8; protected final IntToIntBtree btree; protected int address = -1; private short myChildrenCount; protected int myAddressInBuffer; protected ByteBuffer myBuffer; public BtreePage(IntToIntBtree btree) { this.btree = btree; myChildrenCount = -1; } void setAddress(int _address) { if (doSanityCheck) myAssert(_address % btree.pageSize == 0); address = _address; syncWithStore(); } protected void syncWithStore() { myChildrenCount = -1; PagedFileStorage pagedFileStorage = btree.storage.getPagedFileStorage(); myAddressInBuffer = pagedFileStorage.getOffsetInPage(address); myBuffer = pagedFileStorage.getByteBuffer(address); } protected final void setFlag(int mask, boolean flag) { byte b = myBuffer.get(myAddressInBuffer); if (flag) b |= mask; else b &= ~mask; myBuffer.put(myAddressInBuffer, b); } protected final short getChildrenCount() { if (myChildrenCount == -1) { myChildrenCount = myBuffer.getShort(myAddressInBuffer + 1); } return myChildrenCount; } protected final void setChildrenCount(short value) { myChildrenCount = value; myBuffer.putShort(myAddressInBuffer + 1, value); } protected final void setNextPage(int nextPage) { putInt(3, nextPage); } // TODO: use it protected final int getNextPage() { return getInt(3); } protected final int getInt(int address) { return myBuffer.getInt(myAddressInBuffer + address); } protected final void putInt(int offset, int value) { myBuffer.putInt(myAddressInBuffer + offset, value); } protected final ByteBuffer getBytes(int address, int length) { ByteBuffer duplicate = myBuffer.duplicate(); int newPosition = address + myAddressInBuffer; duplicate.position(newPosition); duplicate.limit(newPosition + length); return duplicate; } protected final void putBytes(int address, ByteBuffer buffer) { myBuffer.position(address + myAddressInBuffer); myBuffer.put(buffer); } } // Leaf index node // (value_address {<0 if address in duplicates segment}, hash key) {getChildrenCount()} // (|next_node {<0} , hash key|) {getChildrenCount()} , next_node {<0} // next_node[i] is pointer to all less than hash_key[i] except for the last static class BtreeIndexNodeView extends BtreePage { static final int INTERIOR_SIZE = 8; static final int KEY_OFFSET = 4; static final int MIN_ITEMS_TO_SHARE = 20; private boolean isIndexLeaf; private boolean flagsSet; private boolean isHashedLeaf; private static final int LARGE_MOVE_THRESHOLD = 5; BtreeIndexNodeView(IntToIntBtree btree) { super(btree); } @Override protected void syncWithStore() { super.syncWithStore(); flagsSet = false; } static final int HASH_FREE = 0; static final int HASH_FULL = 1; static final int HASH_REMOVED = 2; int search(int value) { if (isIndexLeaf() && isHashedLeaf()) { return hashIndex(value); } else { int hi = getChildrenCount() - 1; int lo = 0; while(lo <= hi) { int mid = lo + (hi - lo) / 2; int keyAtMid = keyAt(mid); if (value > keyAtMid) { lo = mid + 1; } else if (value < keyAtMid) { hi = mid - 1; } else { return mid; } } return -(lo + 1); } } final int addressAt(int i) { if (doSanityCheck) { short childrenCount = getChildrenCount(); if (isHashedLeaf()) myAssert(i < btree.hashPageCapacity); else myAssert(i < childrenCount || (!isIndexLeaf() && i == childrenCount)); } return getInt(indexToOffset(i)); } private void setAddressAt(int i, int value) { int offset = indexToOffset(i); if (doSanityCheck) { short childrenCount = getChildrenCount(); final int metaPageLen; if (isHashedLeaf()) { myAssert(i < btree.hashPageCapacity); metaPageLen = btree.metaDataLeafPageLength; } else { myAssert(i < childrenCount || (!isIndexLeaf() && i == childrenCount)); metaPageLen = RESERVED_META_PAGE_LEN; } myAssert(offset + 4 <= btree.pageSize); myAssert(offset >= metaPageLen); } putInt(offset, value); } private final int indexToOffset(int i) { return i * INTERIOR_SIZE + (isHashedLeaf() ? btree.metaDataLeafPageLength:RESERVED_META_PAGE_LEN); } private final int keyAt(int i) { if (doSanityCheck) { if (isHashedLeaf()) myAssert(i < btree.hashPageCapacity); else myAssert(i < getChildrenCount()); } return getInt(indexToOffset(i) + KEY_OFFSET); } private void setKeyAt(int i, int value) { final int offset = indexToOffset(i) + KEY_OFFSET; if (doSanityCheck) { final int metaPageLen; if (isHashedLeaf()) { myAssert(i < btree.hashPageCapacity); metaPageLen = btree.metaDataLeafPageLength; } else { myAssert(i < getChildrenCount()); metaPageLen = RESERVED_META_PAGE_LEN; } myAssert(offset + 4 <= btree.pageSize); myAssert(offset >= metaPageLen); } putInt(offset, value); } static final int INDEX_LEAF_MASK = 0x1; static final int HASHED_LEAF_MASK = 0x2; final boolean isIndexLeaf() { if (!flagsSet) initFlags(); return isIndexLeaf; } private void initFlags() { byte flags = myBuffer.get(myAddressInBuffer); isHashedLeaf = (flags & HASHED_LEAF_MASK) == HASHED_LEAF_MASK; isIndexLeaf = (flags & INDEX_LEAF_MASK) == INDEX_LEAF_MASK; } void setIndexLeaf(boolean value) { isIndexLeaf = value; setFlag(INDEX_LEAF_MASK, value); } private final boolean isHashedLeaf() { if (!flagsSet) initFlags(); return isHashedLeaf; } void setHashedLeaf(boolean value) { isHashedLeaf = value; setFlag(HASHED_LEAF_MASK, value); } final short getMaxChildrenCount() { return isIndexLeaf() ? isHashedLeaf() ? btree.maxLeafNodesInHash:btree.maxLeafNodes:btree.maxInteriorNodes; } final boolean isFull() { short childrenCount = getChildrenCount(); if (!isIndexLeaf()) { ++childrenCount; } return childrenCount == getMaxChildrenCount(); } int[] exportKeys() { assert isIndexLeaf(); short childrenCount = getChildrenCount(); int[] keys = new int[childrenCount]; if (isHashedLeaf()) { final int offset = myAddressInBuffer + indexToOffset(0) + KEY_OFFSET; int keyNumber = 0; for(int i = 0; i < btree.hashPageCapacity; ++i) { if (hashGetState(i) == HASH_FULL) { int key = myBuffer.getInt(offset + i * INTERIOR_SIZE); keys[keyNumber++] = key; } } } else { for(int i = 0; i < childrenCount; ++i) { keys[i] = keyAt(i); } } return keys; } static class HashLeafData { final BtreeIndexNodeView nodeView; final int[] keys; final TIntIntHashMap values; HashLeafData(BtreeIndexNodeView _nodeView, int recordCount) { nodeView = _nodeView; final IntToIntBtree btree = _nodeView.btree; final int offset = nodeView.myAddressInBuffer + nodeView.indexToOffset(0); final ByteBuffer buffer = nodeView.myBuffer; keys = new int[recordCount]; values = new TIntIntHashMap(recordCount); int keyNumber = 0; for(int i = 0; i < btree.hashPageCapacity; ++i) { if (nodeView.hashGetState(i) == HASH_FULL) { int key = buffer.getInt(offset + i * INTERIOR_SIZE + KEY_OFFSET); keys[keyNumber++] = key; int value = buffer.getInt(offset + i * INTERIOR_SIZE); values.put(key, value); } } Arrays.sort(keys); } void clean() { final IntToIntBtree btree = nodeView.btree; for(int i = 0; i < btree.hashPageCapacity; ++i) { nodeView.hashSetState(i, HASH_FREE); } } } private int splitNode(int parentAddress) { final boolean indexLeaf = isIndexLeaf(); if (doSanityCheck) { myAssert(isFull()); dump("before split:"+indexLeaf); } final boolean hashedLeaf = isHashedLeaf(); final short recordCount = getChildrenCount(); BtreeIndexNodeView parent = null; HashLeafData hashLeafData = null; if (parentAddress != 0) { parent = new BtreeIndexNodeView(btree); parent.setAddress(parentAddress); if (btree.offloadToSiblingsBeforeSplit) { if (hashedLeaf) { hashLeafData = new HashLeafData(this, recordCount); if (doOffloadToSiblingsWhenHashed(parent, hashLeafData)) return parentAddress; } else { if (doOffloadToSiblingsSorted(parent)) return parentAddress; } } } short maxIndex = (short)(getMaxChildrenCount() / 2); BtreeIndexNodeView newIndexNode = new BtreeIndexNodeView(btree); newIndexNode.setAddress(btree.nextPage()); syncWithStore(); // next page can cause ByteBuffer to be invalidated! if (parent != null) parent.syncWithStore(); btree.root.syncWithStore(); newIndexNode.setIndexLeaf(indexLeaf); int nextPage = getNextPage(); setNextPage(newIndexNode.address); newIndexNode.setNextPage(nextPage); int medianKey = -1; if (indexLeaf && hashedLeaf) { if (hashLeafData == null) hashLeafData = new HashLeafData(this, recordCount); final int[] keys = hashLeafData.keys; boolean defaultSplit = true; //if (keys[keys.length - 1] < newValue && btree.height <= 3) { // optimization for adding element to last block // btree.root.syncWithStore(); // if (btree.height == 2 && btree.root.search(keys[0]) == btree.root.getChildrenCount() - 1) { // defaultSplit = false; // } else if (btree.height == 3 && // btree.root.search(keys[0]) == -btree.root.getChildrenCount() - 1 && // parent.search(keys[0]) == parent.getChildrenCount() - 1 // defaultSplit = false; // if (!defaultSplit) { // newIndexNode.setChildrenCount((short)0); // newIndexNode.insert(newValue, 0); // ++btree.count; // medianKey = newValue; if (defaultSplit) { hashLeafData.clean(); final TIntIntHashMap map = hashLeafData.values; final int avg = keys.length / 2; medianKey = keys[avg]; --btree.hashedPagesCount; setChildrenCount((short)0); newIndexNode.setChildrenCount((short)0); for(int i = 0; i < avg; ++i) { int key = keys[i]; insert(key, map.get(key)); key = keys[avg + i]; newIndexNode.insert(key, map.get(key)); } /*setHashedLeaf(false); setChildrenCount((short)keys.length); --btree.hashedPagesCount; btree.movedMembersCount += keys.length; for(int i = 0; i < keys.length; ++i) { int key = keys[i]; setKeyAt(i, key); setAddressAt(i, map.get(key)); } return parentAddress;*/ } } else { short recordCountInNewNode = (short)(recordCount - maxIndex); newIndexNode.setChildrenCount(recordCountInNewNode); if (btree.isLarge) { ByteBuffer buffer = getBytes(indexToOffset(maxIndex), recordCountInNewNode * INTERIOR_SIZE); newIndexNode.putBytes(newIndexNode.indexToOffset(0), buffer); } else { for(int i = 0; i < recordCountInNewNode; ++i) { newIndexNode.setAddressAt(i, addressAt(i + maxIndex)); newIndexNode.setKeyAt(i, keyAt(i + maxIndex)); } } if (indexLeaf) { medianKey = newIndexNode.keyAt(0); } else { newIndexNode.setAddressAt(recordCountInNewNode, addressAt(recordCount)); --maxIndex; medianKey = keyAt(maxIndex); // key count is odd (since children count is even) and middle key goes to parent } setChildrenCount(maxIndex); } if (parent != null) { if (doSanityCheck) { int medianKeyInParent = parent.search(medianKey); int ourKey = keyAt(0); int ourKeyInParent = parent.search(ourKey); parent.dump("About to insert "+medianKey + "," + newIndexNode.address+"," + medianKeyInParent + " our key " + ourKey + ", " + ourKeyInParent); myAssert(medianKeyInParent < 0); myAssert(!parent.isFull()); } parent.insert(medianKey, -newIndexNode.address); if (doSanityCheck) { parent.dump("After modifying parent"); int search = parent.search(medianKey); myAssert(search >= 0); myAssert(parent.addressAt(search + 1) == -newIndexNode.address); dump("old node after split:"); newIndexNode.dump("new node after split:"); } } else { if (doSanityCheck) { btree.root.dump("Splitting root:"+medianKey); } int newRootAddress = btree.nextPage(); newIndexNode.syncWithStore(); syncWithStore(); if (doSanityCheck) { System.out.println("Pages:"+btree.pagesCount+", elements:"+btree.count + ", average:" + (btree.height + 1)); } btree.root.setAddress(newRootAddress); parentAddress = newRootAddress; btree.root.setChildrenCount((short)1); btree.root.setKeyAt(0, medianKey); btree.root.setAddressAt(0, -address); btree.root.setAddressAt(1, -newIndexNode.address); if (doSanityCheck) { btree.root.dump("New root"); dump("First child"); newIndexNode.dump("Second child"); } } return parentAddress; } private boolean doOffloadToSiblingsWhenHashed(BtreeIndexNodeView parent, final HashLeafData hashLeafData) { int indexInParent = parent.search(hashLeafData.keys[0]); if (indexInParent >= 0) { BtreeIndexNodeView sibling = new BtreeIndexNodeView(btree); sibling.setAddress(-parent.addressAt(indexInParent)); int numberOfKeysToMove = (sibling.getMaxChildrenCount() - sibling.getChildrenCount()) / 2; if (!sibling.isFull() && numberOfKeysToMove > MIN_ITEMS_TO_SHARE) { if (doSanityCheck) { sibling.dump("Offloading to left sibling"); parent.dump("parent before"); } final int childrenCount = getChildrenCount(); final int[] keys = hashLeafData.keys; final TIntIntHashMap map = hashLeafData.values; for(int i = 0; i < numberOfKeysToMove; ++i) { final int key = keys[i]; sibling.insert(key, map.get(key)); } if (doSanityCheck) { sibling.dump("Left sibling after"); } parent.setKeyAt(indexInParent, keys[numberOfKeysToMove]); setChildrenCount((short)0); --btree.hashedPagesCount; hashLeafData.clean(); for(int i = numberOfKeysToMove; i < childrenCount; ++i) { final int key = keys[i]; insert(key, map.get(key)); } } else if (indexInParent + 1 < parent.getChildrenCount()) { insertToRightSiblingWhenHashed(parent, hashLeafData, indexInParent, sibling); } } else if (indexInParent == -1) { insertToRightSiblingWhenHashed(parent, hashLeafData, 0, new BtreeIndexNodeView(btree)); } if (!isFull()) { if (doSanityCheck) { dump("old node after split:"); parent.dump("Parent node after split"); } return true; } return false; } private void insertToRightSiblingWhenHashed(BtreeIndexNodeView parent, HashLeafData hashLeafData, int indexInParent, BtreeIndexNodeView sibling) { sibling.setAddress(-parent.addressAt(indexInParent + 1)); int numberOfKeysToMove = (sibling.getMaxChildrenCount() - sibling.getChildrenCount()) / 2; if (!sibling.isFull() && numberOfKeysToMove > MIN_ITEMS_TO_SHARE) { if (doSanityCheck) { sibling.dump("Offloading to right sibling"); parent.dump("parent before"); } final int[] keys = hashLeafData.keys; final TIntIntHashMap map = hashLeafData.values; final int childrenCount = getChildrenCount(); final int lastChildIndex = childrenCount - numberOfKeysToMove; for(int i = lastChildIndex; i < childrenCount; ++i) { final int key = keys[i]; sibling.insert(key, map.get(key)); } if (doSanityCheck) { sibling.dump("Right sibling after"); } parent.setKeyAt(indexInParent, keys[lastChildIndex]); setChildrenCount((short)0); --btree.hashedPagesCount; hashLeafData.clean(); for(int i = 0; i < lastChildIndex; ++i) { final int key = keys[i]; insert(key, map.get(key)); } } } private boolean doOffloadToSiblingsSorted(BtreeIndexNodeView parent) { boolean indexLeaf = isIndexLeaf(); if (!indexLeaf) return false; // TODO int indexInParent = parent.search(keyAt(0)); if (indexInParent >= 0) { if (doSanityCheck) { myAssert(parent.keyAt(indexInParent) == keyAt(0)); myAssert(parent.addressAt(indexInParent + 1) == -address); } BtreeIndexNodeView sibling = new BtreeIndexNodeView(btree); sibling.setAddress(-parent.addressAt(indexInParent)); final int toMove = (sibling.getMaxChildrenCount() - sibling.getChildrenCount()) / 2; if (toMove > 0) { if (doSanityCheck) { sibling.dump("Offloading to left sibling"); parent.dump("parent before"); } for(int i = 0; i < toMove; ++i) sibling.insert(keyAt(i), addressAt(i)); if (doSanityCheck) { sibling.dump("Left sibling after"); } parent.setKeyAt(indexInParent, keyAt(toMove)); int indexOfLastChildToMove = (int)getChildrenCount() - toMove; btree.movedMembersCount += indexOfLastChildToMove; if (btree.isLarge) { ByteBuffer buffer = getBytes(indexToOffset(toMove), indexOfLastChildToMove * INTERIOR_SIZE); putBytes(indexToOffset(0), buffer); } else { for (int i = 0; i < indexOfLastChildToMove; ++i) { setAddressAt(i, addressAt(i + toMove)); setKeyAt(i, keyAt(i + toMove)); } } setChildrenCount((short)indexOfLastChildToMove); } else if (indexInParent + 1 < parent.getChildrenCount()) { insertToRightSiblingWhenSorted(parent, indexInParent + 1, sibling); } } else if (indexInParent == -1) { insertToRightSiblingWhenSorted(parent, 0, new BtreeIndexNodeView(btree)); } if (!isFull()) { if (doSanityCheck) { dump("old node after split:"); parent.dump("Parent node after split"); } return true; } return false; } private void insertToRightSiblingWhenSorted(BtreeIndexNodeView parent, int indexInParent, BtreeIndexNodeView sibling) { sibling.setAddress(-parent.addressAt(indexInParent + 1)); int toMove = (sibling.getMaxChildrenCount() - sibling.getChildrenCount()) / 2; if (toMove > 0) { if (doSanityCheck) { sibling.dump("Offloading to right sibling"); parent.dump("parent before"); } int childrenCount = getChildrenCount(); int lastChildIndex = childrenCount - toMove; for(int i = lastChildIndex; i < childrenCount; ++i) sibling.insert(keyAt(i), addressAt(i)); if (doSanityCheck) { sibling.dump("Right sibling after"); } parent.setKeyAt(indexInParent, keyAt(lastChildIndex)); setChildrenCount((short)lastChildIndex); } } private void dump(String s) { if (doDump) { immediateDump(s); } } private void immediateDump(String s) { short maxIndex = getChildrenCount(); System.out.println(s + " @" + address); for(int i = 0; i < maxIndex; ++i) { System.out.print(addressAt(i) + " " + keyAt(i) + " "); } if (!isIndexLeaf()) { System.out.println(addressAt(maxIndex)); } else { System.out.println(); } } private int locate(int valueHC, boolean split) { int searched = 0; int parentAddress = 0; while(true) { if (split && isFull()) { parentAddress = splitNode(parentAddress); if (parentAddress != 0) setAddress(parentAddress); --searched; } int i = search(valueHC); ++searched; if (isIndexLeaf()) { btree.height = Math.max(btree.height, searched); return i; } int address = i < 0 ? addressAt(-i - 1):addressAt(i + 1); parentAddress = this.address; setAddress(-address); } } private void insert(int valueHC, int newValueId) { if (doSanityCheck) myAssert(!isFull()); short recordCount = getChildrenCount(); if (doSanityCheck) myAssert(recordCount < getMaxChildrenCount()); final boolean indexLeaf = isIndexLeaf(); if (indexLeaf) { if (recordCount == 0 && btree.indexNodeIsHashTable) { setHashedLeaf(true); ++btree.hashedPagesCount; } if (isHashedLeaf()) { int index = hashInsertionIndex(valueHC); if (index < 0) { index = -index - 1; } setKeyAt(index, valueHC); hashSetState(index, HASH_FULL); setAddressAt(index, newValueId); setChildrenCount((short)(recordCount + 1)); return; } } int medianKeyInParent = search(valueHC); if (doSanityCheck) myAssert(medianKeyInParent < 0); int index = -medianKeyInParent - 1; setChildrenCount((short)(recordCount + 1)); final int itemsToMove = recordCount - index; btree.movedMembersCount += itemsToMove; if (indexLeaf) { if (btree.isLarge && itemsToMove > LARGE_MOVE_THRESHOLD) { ByteBuffer buffer = getBytes(indexToOffset(index), itemsToMove * INTERIOR_SIZE); putBytes(indexToOffset(index + 1), buffer); } else { for(int i = recordCount - 1; i >= index; --i) { setKeyAt(i + 1, keyAt(i)); setAddressAt(i + 1, addressAt(i)); } } setKeyAt(index, valueHC); setAddressAt(index, newValueId); } else { // <address> (<key><address>) {record_count - 1} setAddressAt(recordCount + 1, addressAt(recordCount)); if (btree.isLarge && itemsToMove > LARGE_MOVE_THRESHOLD) { int elementsAfterIndex = recordCount - index - 1; if (elementsAfterIndex > 0) { ByteBuffer buffer = getBytes(indexToOffset(index + 1), elementsAfterIndex * INTERIOR_SIZE); putBytes(indexToOffset(index + 2), buffer); } } else { for(int i = recordCount - 1; i > index; --i) { setKeyAt(i + 1, keyAt(i)); setAddressAt(i + 1, addressAt(i)); } } if (index < recordCount) setKeyAt(index + 1, keyAt(index)); setKeyAt(index, valueHC); setAddressAt(index + 1, newValueId); } if (doSanityCheck) { if (index > 0) myAssert(keyAt(index - 1) < keyAt(index)); if (index < recordCount) myAssert(keyAt(index) < keyAt(index + 1)); } } private int hashIndex(int value) { int hash, probe, index; final int length = btree.hashPageCapacity; hash = hash(value) & 0x7fffffff; index = hash % length; int state = hashGetState(index); int total = 0; btree.hashSearchRequests++; if (state != HASH_FREE && (state == HASH_REMOVED || keyAt(index) != value)) { // see Knuth, p. 529 probe = 1 + (hash % (length - 2)); do { index -= probe; if (index < 0) { index += length; } state = hashGetState(index); ++total; if (total > length) { // violation of Euler's theorem throw new IllegalStateException("Index corrupted"); } } while (state != HASH_FREE && (state == HASH_REMOVED || keyAt(index) != value)); } btree.maxStepsSearchedInHash = Math.max(btree.maxStepsSearchedInHash, total); btree.totalHashStepsSearched += total; return state == HASH_FREE ? -1 : index; } protected int hashInsertionIndex(int val) { int hash, probe, index; final int length = btree.hashPageCapacity; hash = hash(val) & 0x7fffffff; index = hash % length; btree.hashSearchRequests++; int state = hashGetState(index); if (state == HASH_FREE) { return index; // empty, all done } else if (state == HASH_FULL && keyAt(index) == val) { return -index - 1; // already stored } else { // already FULL or REMOVED, must probe // compute the double hash probe = 1 + (hash % (length - 2)); int total = 0; // starting at the natural offset, probe until we find an // offset that isn't full. do { index -= probe; if (index < 0) { index += length; } ++total; state = hashGetState(index); } while (state == HASH_FULL && keyAt(index) != val); // if the index we found was removed: continue probing until we // locate a free location or an element which equal()s the // one we have. if (state == HASH_REMOVED) { int firstRemoved = index; while (state != HASH_FREE && (state == HASH_REMOVED || keyAt(index) != val)) { index -= probe; if (index < 0) { index += length; } state = hashGetState(index); ++total; } return state == HASH_FULL ? -index - 1 : firstRemoved; } btree.maxStepsSearchedInHash = Math.max(btree.maxStepsSearchedInHash, total); btree.totalHashStepsSearched += total; // if it's full, the key is already stored return state == HASH_FULL ? -index - 1 : index; } } private final int hash(int val) { //return val * 0x278DDE6D; return val; } static final int STATE_MASK = 0x3; static final int STATE_MASK_WITHOUT_DELETE = 0x1; private final int hashGetState(int index) { byte b = myBuffer.get(hashOccupiedStatusByteOffset(index)); if (haveDeleteState) { return ((b & 0xFF) >> hashOccupiedStatusShift(index)) & STATE_MASK; } else { return ((b & 0xFF) >> hashOccupiedStatusShift(index)) & STATE_MASK_WITHOUT_DELETE; } } private final int hashOccupiedStatusShift(int index) { if (haveDeleteState) { return 6 - ((index & 0x3) << 1); } else { return 7 - (index & 0x7); } } private final int hashOccupiedStatusByteOffset(int index) { if (haveDeleteState) { return myAddressInBuffer + BtreePage.RESERVED_META_PAGE_LEN + (index >> 2); } else { return myAddressInBuffer + BtreePage.RESERVED_META_PAGE_LEN + (index >> 3); } } private static final boolean haveDeleteState = false; private void hashSetState(int index, int value) { if (doSanityCheck) { if (haveDeleteState) myAssert(value >= HASH_FREE && value <= HASH_REMOVED); else myAssert(value >= HASH_FREE && value < HASH_REMOVED); } int hashOccupiedStatusOffset = hashOccupiedStatusByteOffset(index); byte b = myBuffer.get(hashOccupiedStatusOffset); int shift = hashOccupiedStatusShift(index); if (haveDeleteState) { b = (byte)(((b & 0xFF) & ~(STATE_MASK << shift)) | (value << shift)); } else { b = (byte)(((b & 0xFF) & ~(STATE_MASK_WITHOUT_DELETE << shift)) | (value << shift)); } myBuffer.put(hashOccupiedStatusOffset, b); if (doSanityCheck) myAssert(hashGetState(index) == value); } } }
package com.alibaba.json.bvt.parser; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.util.TypeUtils; public class TypeUtilsTest3 extends TestCase { public void test_enum() throws Exception { Assert.assertEquals(Type.A, JSON.parseObject("\"A\"", Type.class)); Assert.assertEquals(Type.A, JSON.parseObject("" + Type.A.ordinal(), Type.class)); Assert.assertEquals(Type.B, JSON.parseObject("" + Type.B.ordinal(), Type.class)); Assert.assertEquals(Type.C, JSON.parseObject("" + Type.C.ordinal(), Type.class)); } public void test_enum_2() throws Exception { Assert.assertEquals(Type.A, TypeUtils.cast("A", Type.class, null)); Assert.assertEquals(Type.A, TypeUtils.cast(Type.A.ordinal(), Type.class, null)); Assert.assertEquals(Type.B, TypeUtils.cast(Type.B.ordinal(), Type.class, null)); } public void test_error() throws Exception { assertNull(TypeUtils.castToEnum("\"A1\"", Type.class, null)); } public void test_error_1() throws Exception { Exception error = null; try { TypeUtils.castToEnum(Boolean.TRUE, Type.class, null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { Exception error = null; try { TypeUtils.castToEnum(1000, Type.class, null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_null() throws Exception { Assert.assertEquals(null, TypeUtils.cast(null, new TypeReference<Object>() { }.getType(), null)); } public void test_null_1() throws Exception { Assert.assertEquals(null, TypeUtils.cast("", new TypeReference<List<Object>>() { }.getType(), null)); } public void test_null_2() throws Exception { Assert.assertEquals(null, TypeUtils.cast("", new TypeReference<Object[]>() { }.getType(), null)); } public void test_error_3() throws Exception { Exception error = null; try { TypeUtils.cast("xxx", new TypeReference<Object[]>() { }.getType(), null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_ex() throws Exception { RuntimeException ex = new RuntimeException(); JSONObject object = (JSONObject) JSON.toJSON(ex); JSONArray array = object.getJSONArray("stackTrace"); array.getJSONObject(0).put("lineNumber", null); JSON.parseObject(object.toJSONString(), Exception.class); } public static enum Type { A, B, C } }
package com.emc.mongoose.system; import com.emc.mongoose.config.TimeUtil; import com.emc.mongoose.item.op.OpType; import com.emc.mongoose.params.Concurrency; import com.emc.mongoose.params.EnvParams; import com.emc.mongoose.params.ItemSize; import com.emc.mongoose.params.RunMode; import com.emc.mongoose.params.StorageType; import com.emc.mongoose.util.DirWithManyFilesDeleter; import com.emc.mongoose.util.docker.HttpStorageMockContainer; import com.emc.mongoose.util.docker.MongooseEntryNodeContainer; import com.emc.mongoose.util.docker.MongooseAdditionalNodeContainer; import static com.emc.mongoose.util.LogValidationUtil.getMetricsLogRecords; import static com.emc.mongoose.util.LogValidationUtil.getMetricsTotalLogRecords; import static com.emc.mongoose.util.LogValidationUtil.testFinalMetricsStdout; import static com.emc.mongoose.util.LogValidationUtil.testOpTraceLogRecords; import static com.emc.mongoose.util.LogValidationUtil.testOpTraceRecord; import static com.emc.mongoose.util.LogValidationUtil.testMetricsLogRecords; import static com.emc.mongoose.util.LogValidationUtil.testTotalMetricsLogRecord; import static com.emc.mongoose.util.TestCaseUtil.snakeCaseName; import static com.emc.mongoose.util.TestCaseUtil.stepId; import static com.emc.mongoose.util.docker.MongooseEntryNodeContainer.BUNDLED_DEFAULTS; import static com.emc.mongoose.util.docker.MongooseContainer.CONTAINER_SHARE_PATH; import static com.emc.mongoose.util.docker.MongooseContainer.HOST_SHARE_PATH; import static com.emc.mongoose.util.docker.MongooseEntryNodeContainer.systemTestContainerScenarioPath; import com.github.akurilov.commons.concurrent.AsyncRunnableBase; import com.github.akurilov.commons.reflection.TypeUtil; import com.github.akurilov.commons.system.SizeInBytes; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.FileUtils; import org.apache.commons.math3.stat.Frequency; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; import java.util.function.Consumer; import java.util.stream.Collectors; @RunWith(Parameterized.class) public final class CircularAppendTest { @Parameterized.Parameters(name = "{0}, {1}, {2}, {3}") public static List<Object[]> envParams() { return EnvParams.PARAMS; } private final String SCENARIO_PATH = systemTestContainerScenarioPath(getClass()); private final int EXPECTED_APPEND_COUNT = 50; private final long EXPECTED_COUNT = 200; private final int TIMEOUT_IN_MILLIS = 1_000_000; private final String ITEM_LIST_FILE_0 = snakeCaseName(getClass()) + "_0.csv"; private final String ITEM_LIST_FILE_1 = snakeCaseName(getClass()) + "_1.csv"; private final String HOST_ITEM_LIST_FILE_1 = HOST_SHARE_PATH + "/" + ITEM_LIST_FILE_1; private final String CONTAINER_ITEM_LIST_FILE_0 = CONTAINER_SHARE_PATH + "/" + ITEM_LIST_FILE_0; private final String CONTAINER_ITEM_LIST_FILE_1 = CONTAINER_SHARE_PATH + "/" + ITEM_LIST_FILE_1; private final Map<String, HttpStorageMockContainer> storageMocks = new HashMap<>(); private final Map<String, MongooseAdditionalNodeContainer> additionalNodes = new HashMap<>(); private final MongooseEntryNodeContainer testContainer; private final String stepId; private final StorageType storageType; private final RunMode runMode; private final Concurrency concurrency; private final ItemSize itemSize; public CircularAppendTest( final StorageType storageType, final RunMode runMode, final Concurrency concurrency, final ItemSize itemSize ) throws Exception { stepId = stepId(getClass(), storageType, runMode, concurrency, itemSize); try { FileUtils.deleteDirectory(Paths.get(MongooseEntryNodeContainer.HOST_LOG_PATH.toString(), stepId).toFile()); } catch(final IOException ignored) { } this.storageType = storageType; this.runMode = runMode; this.concurrency = concurrency; this.itemSize = itemSize; final List<String> env = System .getenv() .entrySet() .stream() .map(e -> e.getKey() + "=" + e.getValue()) .collect(Collectors.toList()); env.add("BASE_ITEMS_COUNT=" + EXPECTED_COUNT); env.add("APPEND_COUNT=" + EXPECTED_APPEND_COUNT); env.add("ITEM_LIST_FILE_0=" + CONTAINER_ITEM_LIST_FILE_0); env.add("ITEM_LIST_FILE_1=" + CONTAINER_ITEM_LIST_FILE_1); env.add("ITEM_DATA_SIZE=" + itemSize.getValue()); final List<String> args = new ArrayList<>(); switch(storageType) { case ATMOS: case S3: case SWIFT: final HttpStorageMockContainer storageMock = new HttpStorageMockContainer( HttpStorageMockContainer.DEFAULT_PORT, false, null, null, Character.MAX_RADIX, HttpStorageMockContainer.DEFAULT_CAPACITY, HttpStorageMockContainer.DEFAULT_CONTAINER_CAPACITY, HttpStorageMockContainer.DEFAULT_CONTAINER_COUNT_LIMIT, HttpStorageMockContainer.DEFAULT_FAIL_CONNECT_EVERY, HttpStorageMockContainer.DEFAULT_FAIL_RESPONSES_EVERY, 0 ); final String addr = "127.0.0.1:" + HttpStorageMockContainer.DEFAULT_PORT; storageMocks.put(addr, storageMock); args.add("--storage-net-node-addrs=" + storageMocks.keySet().stream().collect(Collectors.joining(","))); break; case FS: try { DirWithManyFilesDeleter.deleteExternal(MongooseEntryNodeContainer.getHostItemOutputPath(stepId)); } catch(final Throwable t) { Assert.fail(t.toString()); } break; } switch(runMode) { case DISTRIBUTED: for(int i = 1; i < runMode.getNodeCount(); i++) { final int port = MongooseAdditionalNodeContainer.DEFAULT_PORT + i; final MongooseAdditionalNodeContainer nodeSvc = new MongooseAdditionalNodeContainer(port); final String addr = "127.0.0.1:" + port; additionalNodes.put(addr, nodeSvc); } args.add( "--load-step-node-addrs=" + additionalNodes.keySet().stream().collect(Collectors.joining(",")) ); break; } testContainer = new MongooseEntryNodeContainer( stepId, storageType, runMode, concurrency, itemSize.getValue(), SCENARIO_PATH, env, args ); } @Before public final void setUp() throws Exception { storageMocks.values().forEach(AsyncRunnableBase::start); additionalNodes.values().forEach(AsyncRunnableBase::start); testContainer.start(); testContainer.await(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS); } @After public final void tearDown() throws Exception { testContainer.close(); additionalNodes .values() .parallelStream() .forEach( node -> { try { node.close(); } catch(final Throwable t) { t.printStackTrace(System.err); } } ); storageMocks .values() .parallelStream() .forEach( storageMock -> { try { storageMock.close(); } catch(final Throwable t) { t.printStackTrace(System.err); } } ); try { DirWithManyFilesDeleter.deleteExternal(MongooseEntryNodeContainer.getHostItemOutputPath(stepId)); } catch(final Throwable t) { Assert.fail(t.toString()); } } @Test public final void test() throws Exception { try { final List<CSVRecord> metricsLogRecords = getMetricsLogRecords(stepId); assertTrue("There should be more than 0 metrics records in the log file", metricsLogRecords.size() > 0); final int outputMetricsAveragePeriod; final Object outputMetricsAveragePeriodRaw = BUNDLED_DEFAULTS.val("output-metrics-average-period"); final long expectedMaxCount = (long) (1.2 * (EXPECTED_APPEND_COUNT * EXPECTED_COUNT)); if(outputMetricsAveragePeriodRaw instanceof String) { outputMetricsAveragePeriod = (int) TimeUtil.getTimeInSeconds((String) outputMetricsAveragePeriodRaw); } else { outputMetricsAveragePeriod = TypeUtil.typeConvert(outputMetricsAveragePeriodRaw, int.class); } testMetricsLogRecords( metricsLogRecords, OpType.UPDATE, concurrency.getValue(), runMode.getNodeCount(), itemSize.getValue(), expectedMaxCount, 0, outputMetricsAveragePeriod ); } catch(final FileNotFoundException ignored) { //there may be no metrics file if append step duration is less than 10s } final List<CSVRecord> totalMetrcisLogRecords = getMetricsTotalLogRecords(stepId); assertEquals("There should be 1 total metrics records in the log file", 1, totalMetrcisLogRecords.size()); testTotalMetricsLogRecord( totalMetrcisLogRecords.get(0), OpType.UPDATE, concurrency.getValue(), runMode.getNodeCount(), itemSize.getValue(), 0, 0 ); final String stdOutContent = testContainer.stdOutContent(); testFinalMetricsStdout( stdOutContent, OpType.UPDATE, concurrency.getValue(), runMode.getNodeCount(), itemSize.getValue(), stepId ); final LongAdder opTraceRecCount = new LongAdder(); final Consumer<CSVRecord> opTraceRecTestFunc = ioTraceRec -> { testOpTraceRecord(ioTraceRec, OpType.UPDATE.ordinal(), itemSize.getValue()); opTraceRecCount.increment(); }; testOpTraceLogRecords(stepId, opTraceRecTestFunc); assertTrue( "There should be more than " + EXPECTED_COUNT + " records in the I/O trace log file, but got: " + opTraceRecCount.sum(), EXPECTED_COUNT < opTraceRecCount.sum() ); final List<CSVRecord> items = new ArrayList<>(); try(final BufferedReader br = new BufferedReader(new FileReader(HOST_ITEM_LIST_FILE_1))) { final CSVParser csvParser = CSVFormat.RFC4180.parse(br); for(final CSVRecord csvRecord : csvParser) { items.add(csvRecord); } } final int itemIdRadix = BUNDLED_DEFAULTS.intVal("item-naming-radix"); final Frequency freq = new Frequency(); String itemPath, itemId; long itemOffset; long size; final SizeInBytes expectedFinalSize = new SizeInBytes( (EXPECTED_APPEND_COUNT + 1) * itemSize.getValue().get() / 3, (EXPECTED_APPEND_COUNT + 1) * itemSize.getValue().get() * 3, 1 ); final int n = items.size(); CSVRecord itemRec; for(int i = 0; i < n; i ++) { itemRec = items.get(i); itemPath = itemRec.get(0); for(int j = i; j < n; j ++) { if(i != j) { assertNotEquals(itemPath, items.get(j).get(0)); } } itemId = itemPath.substring(itemPath.lastIndexOf('/') + 1); if(!storageType.equals(StorageType.ATMOS)) { itemOffset = Long.parseLong(itemRec.get(1), 0x10); assertEquals(Long.parseLong(itemId, itemIdRadix), itemOffset); freq.addValue(itemOffset); } size = Long.parseLong(itemRec.get(2)); assertTrue( "Expected size: " + expectedFinalSize.toString() + ", actual: " + size, expectedFinalSize.getMin() <= size && size <= expectedFinalSize.getMax() ); assertEquals("0/0", itemRec.get(3)); } if(!storageType.equals(StorageType.ATMOS)) { assertEquals(EXPECTED_COUNT, freq.getUniqueCount(), EXPECTED_COUNT / 10); } } }
package de.fhg.ids.comm; import de.fhg.ids.comm.client.ClientConfiguration; import de.fhg.ids.comm.client.IdscpClient; import org.asynchttpclient.ws.WebSocket; import javax.xml.bind.DatatypeConverter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; public class Client { public static void main(String[] args) throws Exception { // Configure and start client (blocks until IDSCP has finished) IdscpClient client = new IdscpClient().config( new ClientConfiguration.Builder() .setSha256CertificateHashes(Arrays.asList( DatatypeConverter.parseHexBinary( "A3374C859BD5E819B5B50486040FB2DCEA5EC4E3F04DDBC3D059E162B8B7AB37"), DatatypeConverter.parseHexBinary( "4439DA49F320E3786319A5CF8D69F3A0831C4801B5CE3A14570EA84E0ECD82B0"))) .build()); WebSocket wsClient = client.connect("consumer-core", 9292); try (ServerSocket listener = new ServerSocket(4441)) { System.out.println("Waiting for data connections on port 4441..."); try (Socket socket = listener.accept()) { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); while(true) { if (in.ready()) { String msg = in.readLine(); if (msg.equals("exit")) { System.out.println("Exiting..."); System.exit(0); } wsClient.sendTextFrame(msg); } } } } } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; public class WrapLayout extends FlowLayout { private static final long serialVersionUID = 1L; /** * Constructs a new <code>WrapLayout</code> with a left alignment and a default 5-unit * horizontal and vertical gap. */ public WrapLayout() { super(); } /** * Constructs a new <code>FlowLayout</code> with the specified alignment and a default 5-unit * horizontal and vertical gap. The value of the alignment argument must be one of * <code>WrapLayout</code>, <code>WrapLayout</code>, or <code>WrapLayout</code>. * * @param align * the alignment value */ public WrapLayout(int align) { super(align); } /** * Creates a new flow layout manager with the indicated alignment and the indicated horizontal * and vertical gaps. * <p> * The value of the alignment argument must be one of <code>WrapLayout</code>, * <code>WrapLayout</code>, or <code>WrapLayout</code>. * * @param align * the alignment value * @param hgap * the horizontal gap between components * @param vgap * the vertical gap between components */ public WrapLayout(int align, int hgap, int vgap) { super(align, hgap, vgap); } /** * Returns the preferred dimensions for this layout given the <i>visible</i> components in the * specified target container. * * @param target * the component which needs to be laid out * @return the preferred dimensions to lay out the subcomponents of the specified container */ @Override public Dimension preferredLayoutSize(Container target) { return layoutSize(target, true); } /** * Returns the minimum dimensions needed to layout the <i>visible</i> components contained in * the specified target container. * * @param target * the component which needs to be laid out * @return the minimum dimensions to lay out the subcomponents of the specified container */ @Override public Dimension minimumLayoutSize(Container target) { Dimension minimum = layoutSize(target, false); minimum.width -= (getHgap() + 1); return minimum; } /** * Returns the minimum or preferred dimension needed to layout the target container. * * @param target * target to get layout size for * @param preferred * should preferred size be calculated * @return the dimension to layout the target container */ private Dimension layoutSize(Container target, boolean preferred) { synchronized (target.getTreeLock()) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container // has not yet been calculated so lets ask for the maximum. int targetWidth = target.getSize().width; if (targetWidth == 0) targetWidth = Integer.MAX_VALUE; int hgap = getHgap(); int vgap = getVgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; // Fit components into the allowed width Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; int nmembers = target.getComponentCount(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); // Can't add the component to current row. Start a new row. if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } // Add a horizontal gap for all components after the first if (rowWidth != 0) { rowWidth += hgap; } rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); if (scrollPane != null) { dim.width -= (hgap + 1); } return dim; } } /* * A new row has been completed. Use the dimensions of this row to update the preferred size for * the container. * * @param dim update the width and height when appropriate * * @param rowWidth the width of the row to add * * @param rowHeight the height of the row to add */ private void addRow(Dimension dim, int rowWidth, int rowHeight) { dim.width = Math.max(dim.width, rowWidth); if (dim.height > 0) { dim.height += getVgap(); } dim.height += rowHeight; } }
package com.lamfire.chimaera.test.server; import com.lamfire.chimaera.ChimaeraOpts; import com.lamfire.chimaera.ChimaeraServer; import com.lamfire.chimaera.bootstrap.ChimaeraBootstrap; import com.lamfire.logger.Logger; public class TestChimaeraServer { private static final Logger LOGGER = Logger.getLogger(TestChimaeraServer.class); public static void main(String[] args) { ChimaeraBootstrap.startup(); } }
package semanticMarkup.ling.learn.knowledge; import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import semanticMarkup.know.lib.WordNetPOSKnowledgeBase; import semanticMarkup.ling.learn.Configuration; import semanticMarkup.ling.learn.Learner; import semanticMarkup.ling.learn.dataholder.DataHolder; import semanticMarkup.ling.learn.utility.LearnerUtility; import semanticMarkup.ling.learn.utility.WordFormUtility; import semanticMarkup.ling.transform.ITokenizer; import semanticMarkup.ling.transform.lib.OpenNLPSentencesTokenizer; import semanticMarkup.ling.transform.lib.OpenNLPTokenizer; public class MarkupByPOSTest { @Test public void testCaseHandler() { List<String> words = new ArrayList<String>(); words.addAll(Arrays .asList("large interlocking <N>plates</N> <B>with</B> pronounced crescentic <N>margins</N>" .split(" "))); String ptn = "qqnbqqn"; MarkupByPOS myTester = this.markupByPOSFactory(); DataHolder myDataHolder = this.dataHolderFactory(); myTester.CaseHandler(myDataHolder, null, words, ptn); } private MarkupByPOS markupByPOSFactory() { Configuration myConfiguration = new Configuration(); ITokenizer sentenceDetector = new OpenNLPSentencesTokenizer( myConfiguration.getOpenNLPSentenceDetectorDir()); ITokenizer tokenizer = new OpenNLPTokenizer(myConfiguration.getOpenNLPTokenizerDir()); WordNetPOSKnowledgeBase wordNetPOSKnowledgeBase = null; try { wordNetPOSKnowledgeBase = new WordNetPOSKnowledgeBase(myConfiguration.getWordNetDictDir(), false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } LearnerUtility myLearnerUtility = new LearnerUtility(sentenceDetector, tokenizer, wordNetPOSKnowledgeBase); MarkupByPOS myMarkupByPOS = new MarkupByPOS(myLearnerUtility); return myMarkupByPOS; } private DataHolder dataHolderFactory() { DataHolder tester; Configuration myConfiguration = new Configuration(); WordNetPOSKnowledgeBase wordNetPOSKnowledgeBase = null; try { wordNetPOSKnowledgeBase = new WordNetPOSKnowledgeBase(myConfiguration.getWordNetDictDir(), false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } WordFormUtility wordFormUtility = new WordFormUtility(wordNetPOSKnowledgeBase); tester = new DataHolder(myConfiguration, wordFormUtility); return tester; } }
import com.sun.star.beans.*; import com.sun.star.container.*; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Exception; import com.sun.star.uno.UnoRuntime; import com.sun.star.lang.Locale; import com.sun.star.util.XChangesBatch; /** * This class gives access to the OO configuration api. * It contains 4 get and 4 set convenience methods for getting and settings properties * in the configuration. <br/> * For the get methods, two parameters must be given: name and parent, where name is the * name of the property, parent is a HierarchyElement (::com::sun::star::configuration::HierarchyElement)<br/> * The get and set methods support hieryrchical property names like "options/gridX". <br/> * NOTE: not yet supported, but sometime later, * If you will ommit the "parent" parameter, then the "name" parameter must be in hierarchy form from * the root of the registry. * @author rpiterman */ public abstract class Configuration { public static int getInt(String name, Object parent) throws Exception { Object o = getNode(name, parent); if (AnyConverter.isVoid(o)) return 0; return AnyConverter.toInt(o); } public static short getShort(String name, Object parent) throws Exception { Object o = getNode(name, parent); if (AnyConverter.isVoid(o)) return (short) 0; return AnyConverter.toShort(o); } public static float getFloat(String name, Object parent) throws Exception { Object o = getNode(name, parent); if (AnyConverter.isVoid(o)) return (float) 0; return AnyConverter.toFloat(o); } public static double getDouble(String name, Object parent) throws Exception { Object o = getNode(name, parent); if (AnyConverter.isVoid(o)) return (double) 0; return AnyConverter.toDouble(o); } public static String getString(String name, Object parent) throws Exception { Object o = getNode(name, parent); if (AnyConverter.isVoid(o)) return ""; return (String) o; } public static boolean getBoolean(String name, Object parent) throws Exception { Object o = getNode(name, parent); if (AnyConverter.isVoid(o)) return false; return AnyConverter.toBoolean(o); } public static Object getNode(String name, Object parent) throws Exception { return ((XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, parent)).getByName(name); } public static void set(int value, String name, Object parent) throws Exception { set(new Integer(value), name, parent); } public static void set(short value, String name, Object parent) throws Exception { set(new Short(value), name, parent); } public static void set(String value, String name, Object parent) throws Exception { set((Object) value, name, parent); } public static void set(boolean value, String name, Object parent) throws Exception { if (value = true) set(Boolean.TRUE, name, parent); else set(Boolean.FALSE, name, parent); } public static void set(Object value, String name, Object parent) throws com.sun.star.lang.IllegalArgumentException, PropertyVetoException, UnknownPropertyException, WrappedTargetException { ((XHierarchicalPropertySet) UnoRuntime.queryInterface(XHierarchicalPropertySet.class, parent)).setHierarchicalPropertyValue(name, value); } /** Creates a new instance of RegistryEntry */ public static Object getConfigurationNode(String name, Object parent) throws Exception { return ((XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, parent)).getByName(name); } public static Object getConfigurationRoot(XMultiServiceFactory xmsf, String sPath, boolean updateable) throws com.sun.star.uno.Exception { Object oConfigProvider; oConfigProvider = xmsf.createInstance("com.sun.star.configuration.ConfigurationProvider"); XMultiServiceFactory confMsf = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, oConfigProvider); final String sView = updateable ? "com.sun.star.configuration.ConfigurationUpdateAccess" : "com.sun.star.configuration.ConfigurationAccess"; Object args[] = new Object[updateable ? 2 : 1]; PropertyValue aPathArgument = new PropertyValue(); aPathArgument.Name = "nodepath"; aPathArgument.Value = sPath; args[0] = aPathArgument; if (updateable) { PropertyValue aModeArgument = new PropertyValue(); aModeArgument.Name = "lazywrite"; aModeArgument.Value = Boolean.FALSE; args[1] = aModeArgument; } return confMsf.createInstanceWithArguments(sView, args); } public static String[] getChildrenNames(Object configView) { XNameAccess nameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, configView); return nameAccess.getElementNames(); } public static String getProductName(XMultiServiceFactory xMSF) { try { Object oProdNameAccess = getConfigurationRoot(xMSF, "org.openoffice.Setup/Product", false); String ProductName = (String) Helper.getUnoObjectbyName(oProdNameAccess, "ooName"); return ProductName; } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } public static Locale getOfficeLocale(XMultiServiceFactory xMSF) { try { Locale aLocLocale = new Locale(); Object oMasterKey = getConfigurationRoot(xMSF, "org.openoffice.Setup/L10N/", false); String sLocale = (String) Helper.getUnoObjectbyName(oMasterKey, "ooLocale"); String[] sLocaleList = JavaTools.ArrayoutofString(sLocale, "-"); aLocLocale.Language = sLocaleList[0]; if (sLocaleList.length > 1) aLocLocale.Country = sLocaleList[1]; return aLocLocale; } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } public static String getOfficeLinguistic(XMultiServiceFactory xMSF) { try { Object oMasterKey = getConfigurationRoot(xMSF, "org.openoffice.Setup/L10N/", false); String sLinguistic = (String) Helper.getUnoObjectbyName(oMasterKey, "ooLocale"); return sLinguistic; } catch (Exception exception) { exception.printStackTrace(); return null; } } /** * This method creates a new configuration node and adds it * to the given view. Note that if a node with the given name * already exists it will be completely removed from * the configuration. * @param configView * @param name * @return the new created configuration node. * @throws com.sun.star.lang.WrappedTargetException * @throws ElementExistException * @throws NoSuchElementException * @throws com.sun.star.uno.Exception */ public static Object addConfigNode(Object configView, String name) throws com.sun.star.lang.WrappedTargetException, ElementExistException, NoSuchElementException, com.sun.star.uno.Exception { XNameContainer xNameContainer = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, configView); if (xNameContainer == null) { XNameReplace xNameReplace = (XNameReplace) UnoRuntime.queryInterface(XNameReplace.class, configView); return xNameReplace.getByName(name); } else { /*if (xNameContainer.hasByName(name)) xNameContainer.removeByName(name);*/ // create a new detached set element (instance of DataSourceDescription) XSingleServiceFactory xElementFactory = (XSingleServiceFactory) UnoRuntime.queryInterface(XSingleServiceFactory.class, configView); // the new element is the result ! Object newNode = xElementFactory.createInstance(); // insert it - this also names the element xNameContainer.insertByName(name, newNode); return newNode; } } public static void removeNode(Object configView, String name) throws NoSuchElementException, WrappedTargetException { XNameContainer xNameContainer = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, configView); if (xNameContainer.hasByName(name)) xNameContainer.removeByName(name); } public static void commit(Object configView) throws WrappedTargetException { XChangesBatch xUpdateControl = (XChangesBatch) UnoRuntime.queryInterface(XChangesBatch.class, configView); xUpdateControl.commitChanges(); } public static void updateConfiguration(XMultiServiceFactory xmsf, String path, String name, ConfigNode node, Object param) throws com.sun.star.uno.Exception, com.sun.star.container.ElementExistException, NoSuchElementException, WrappedTargetException { Object view = Configuration.getConfigurationRoot(xmsf, path, true); addConfigNode(path, name); node.writeConfiguration(view, param); XChangesBatch xUpdateControl = (XChangesBatch) UnoRuntime.queryInterface(XChangesBatch.class, view); xUpdateControl.commitChanges(); } public static void removeNode(XMultiServiceFactory xmsf, String path, String name) throws com.sun.star.uno.Exception, com.sun.star.container.ElementExistException, NoSuchElementException, WrappedTargetException { Object view = Configuration.getConfigurationRoot(xmsf, path, true); removeNode(view, name); XChangesBatch xUpdateControl = (XChangesBatch) UnoRuntime.queryInterface(XChangesBatch.class, view); xUpdateControl.commitChanges(); } public static String[] getNodeDisplayNames(XNameAccess _xNameAccessNode){ String[] snames = null; return getNodeChildNames(_xNameAccessNode, "Name"); } public static String[] getNodeChildNames(XNameAccess xNameAccessNode, String _schildname){ String[] snames = null; try { snames = xNameAccessNode.getElementNames(); String[] sdisplaynames = new String[snames.length]; for (int i = 0; i < snames.length; i++){ Object oContent = Helper.getUnoPropertyValue(xNameAccessNode.getByName(snames[i]), _schildname); if (!AnyConverter.isVoid(oContent)) sdisplaynames[i] = (String) Helper.getUnoPropertyValue(xNameAccessNode.getByName(snames[i]), _schildname); else sdisplaynames[i] = snames[i]; } return sdisplaynames; } catch (Exception e) { e.printStackTrace(System.out); return snames; }} public static XNameAccess getChildNodebyIndex(Object _oNode, int _index){ XNameAccess xNameAccessNode = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, _oNode); return getChildNodebyIndex(xNameAccessNode, _index); } public static XNameAccess getChildNodebyIndex(XNameAccess _xNameAccess, int _index){ try { String[] snames = _xNameAccess.getElementNames(); Object oNode = _xNameAccess.getByName(snames[_index]); XNameAccess xNameAccessNode = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, oNode); return xNameAccessNode; } catch (Exception e) { e.printStackTrace(System.out); return null; }} public static XNameAccess getChildNodebyName(XNameAccess _xNameAccessNode, String _SubNodeName){ try { if (_xNameAccessNode.hasByName(_SubNodeName)) return (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, _xNameAccessNode.getByName(_SubNodeName)); } catch (Exception e) { e.printStackTrace(System.out); } return null; } public static XNameAccess getChildNodebyDisplayName(XNameAccess _xNameAccessNode, String _displayname){ String[] snames = null; return getChildNodebyDisplayName(_xNameAccessNode, _displayname, "Name"); } public static XNameAccess getChildNodebyDisplayName(XNameAccess _xNameAccessNode, String _displayname, String _nodename){ String[] snames = null; try { snames = _xNameAccessNode.getElementNames(); String[] sdisplaynames = new String[snames.length]; for (int i = 0; i < snames.length; i++){ String curdisplayname = (String) Helper.getUnoPropertyValue(_xNameAccessNode.getByName(snames[i]), _nodename); if (curdisplayname.equals(_displayname)) return (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, _xNameAccessNode.getByName(snames[i])); } } catch (Exception e) { e.printStackTrace(System.out); } return null; } public static XNameAccess getChildNodebyDisplayName(XMultiServiceFactory _xMSF, Locale _aLocale, XNameAccess _xNameAccessNode, String _displayname, String _nodename, int _nmaxcharcount){ String[] snames = null; try { snames = _xNameAccessNode.getElementNames(); String[] sdisplaynames = new String[snames.length]; for (int i = 0; i < snames.length; i++){ String curdisplayname = (String) Helper.getUnoPropertyValue(_xNameAccessNode.getByName(snames[i]), _nodename); if ((_nmaxcharcount > 0) && (_nmaxcharcount < curdisplayname.length())){ curdisplayname = curdisplayname.substring(0, _nmaxcharcount); } curdisplayname = Desktop.removeSpecialCharacters(_xMSF, _aLocale, curdisplayname); if (curdisplayname.equals(_displayname)) return (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, _xNameAccessNode.getByName(snames[i])); } } catch (Exception e) { e.printStackTrace(System.out); } return null; } }
package com.jetbrains.python.psi.impl; import com.intellij.codeInsight.completion.CompletionUtil; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.*; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.python.*; import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.resolve.PyResolveUtil; import com.jetbrains.python.psi.resolve.QualifiedNameFinder; import com.jetbrains.python.psi.stubs.PropertyStubStorage; import com.jetbrains.python.psi.stubs.PyClassStub; import com.jetbrains.python.psi.stubs.PyFunctionStub; import com.jetbrains.python.psi.stubs.PyTargetExpressionStub; import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyClassTypeImpl; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.toolbox.Maybe; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; /** * @author yole */ public class PyClassImpl extends PyPresentableElementImpl<PyClassStub> implements PyClass { public static final PyClass[] EMPTY_ARRAY = new PyClassImpl[0]; private List<PyTargetExpression> myInstanceAttributes; private final NotNullLazyValue<CachedValue<Boolean>> myNewStyle = new NotNullLazyValue<CachedValue<Boolean>>() { @NotNull @Override protected CachedValue<Boolean> compute() { return CachedValuesManager.getManager(getProject()).createCachedValue(new NewStyleCachedValueProvider(), false); } }; private volatile Map<String, Property> myPropertyCache; @Override public PyType getType(@NotNull TypeEvalContext context) { return new PyClassTypeImpl(this, true); } private class NewStyleCachedValueProvider implements CachedValueProvider<Boolean> { @Override public Result<Boolean> compute() { return new Result<Boolean>(calculateNewStyleClass(), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT); } } public PyClassImpl(@NotNull ASTNode astNode) { super(astNode); } public PyClassImpl(@NotNull final PyClassStub stub) { this(stub, PyElementTypes.CLASS_DECLARATION); } public PyClassImpl(@NotNull final PyClassStub stub, @NotNull IStubElementType nodeType) { super(stub, nodeType); } public PsiElement setName(@NotNull String name) throws IncorrectOperationException { final ASTNode nameElement = PyElementGenerator.getInstance(getProject()).createNameIdentifier(name); final ASTNode node = getNameNode(); if (node != null) { getNode().replaceChild(node, nameElement); } return this; } @Nullable @Override public String getName() { final PyClassStub stub = getStub(); if (stub != null) { return stub.getName(); } else { ASTNode node = getNameNode(); return node != null ? node.getText() : null; } } public PsiElement getNameIdentifier() { final ASTNode nameNode = getNameNode(); return nameNode != null ? nameNode.getPsi() : null; } public ASTNode getNameNode() { return getNode().findChildByType(PyTokenTypes.IDENTIFIER); } @Override public Icon getIcon(int flags) { return PlatformIcons.CLASS_ICON; } @Override protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyClass(this); } @NotNull public PyStatementList getStatementList() { final PyStatementList statementList = childToPsi(PyElementTypes.STATEMENT_LIST); assert statementList != null : "Statement list missing for class " + getText(); return statementList; } @Override public PyArgumentList getSuperClassExpressionList() { final PyArgumentList argList = PsiTreeUtil.getChildOfType(this, PyArgumentList.class); if (argList != null && argList.getFirstChild() != null) { return argList; } return null; } @NotNull public PyExpression[] getSuperClassExpressions() { final PyArgumentList argList = getSuperClassExpressionList(); if (argList != null) { return argList.getArguments(); } return PyExpression.EMPTY_ARRAY; } @NotNull public PsiElement[] getSuperClassElements() { final PyExpression[] superExpressions = getSuperClassExpressions(); List<PsiElement> superClasses = new ArrayList<PsiElement>(); for (PyExpression expr : superExpressions) { superClasses.add(classElementFromExpression(expr)); } return PsiUtilCore.toPsiElementArray(superClasses); } @Nullable public static PsiElement classElementFromExpression(@NotNull PyExpression expression) { expression = unfoldClass(expression); if (expression instanceof PyReferenceExpression) { final PsiPolyVariantReference ref = ((PyReferenceExpression)expression).getReference(PyResolveContext.noProperties()); return ref.resolve(); } return null; } public static PyExpression unfoldClass(PyExpression expression) { if (expression instanceof PyCallExpression) { PyCallExpression call = (PyCallExpression)expression; //noinspection ConstantConditions if (call.getCallee() != null && "with_metaclass".equals(call.getCallee().getName()) && call.getArguments().length > 1) { expression = call.getArguments()[1]; } } return expression; } public Iterable<PyClassRef> iterateAncestors() { // The implementation is manifestly lazy wrt psi scanning and uses stack rather sparingly. // It must be more efficient on deep and wide hierarchies, but it was more fun than efficiency that produced it. return new AncestorsIterable(this); } @Override public Iterable<PyClass> iterateAncestorClasses() { return new AncestorClassesIterable(this); } public boolean isSubclass(PyClass parent) { if (this == parent) { return true; } for (PyClass superclass : iterateAncestorClasses()) { if (parent == superclass) return true; } return false; } @Override public boolean isSubclass(@NotNull String superClassQName) { if (superClassQName.equals(getQualifiedName())) { return true; } for (PyClassRef superclass : iterateAncestors()) { if (superClassQName.equals(superclass.getQualifiedName())) return true; } return false; } public PyDecoratorList getDecoratorList() { return getStubOrPsiChild(PyElementTypes.DECORATOR_LIST); } @Nullable public String getQualifiedName() { String name = getName(); final PyClassStub stub = getStub(); PsiElement ancestor = stub != null ? stub.getParentStub().getPsi() : getParent(); while (!(ancestor instanceof PsiFile)) { if (ancestor == null) return name; // can this happen? if (ancestor instanceof PyClass) { name = ((PyClass)ancestor).getName() + "." + name; } ancestor = stub != null ? ((StubBasedPsiElement)ancestor).getStub().getParentStub().getPsi() : ancestor.getParent(); } PsiFile psiFile = ((PsiFile)ancestor).getOriginalFile(); final PyFile builtins = PyBuiltinCache.getInstance(this).getBuiltinsFile(); if (!psiFile.equals(builtins)) { VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { final String packageName = QualifiedNameFinder.findShortestImportableName(this, vFile); return packageName + "." + name; } } return name; } @Override public List<String> getSlots() { List<String> slots = getOwnSlots(); if (slots != null) { return slots; } for (PyClass cls : iterateAncestorClasses()) { slots = ((PyClassImpl)cls).getOwnSlots(); if (slots != null) { return slots; } } return null; } @Nullable public List<String> getOwnSlots() { final PyClassStub stub = getStub(); if (stub != null) { return stub.getSlots(); } return PyFileImpl.getStringListFromTargetExpression(PyNames.SLOTS, getClassAttributes()); } protected List<PyClassRef> getSuperClassesList() { if (PyNames.FAKE_OLD_BASE.equals(getName())) { return Collections.emptyList(); } List<PyClassRef> result = resolveSuperClassesFromStub(); if (result == null) { result = new ArrayList<PyClassRef>(); final TypeEvalContext context = TypeEvalContext.fastStubOnly(null); final PyExpression[] superClassExpressions = getSuperClassExpressions(); for (PyExpression expression : superClassExpressions) { final PsiElement element = classElementFromExpression(expression); if (element != null) { result.add(new PyClassRef(element)); } else { final PyType type = expression.getType(context); if (type instanceof PyClassType) { result.add(new PyClassRef((PyClassType)type)); } else { result.add(new PyClassRef((PsiElement)null)); } } } } if (result.size() == 0 && isValid() && !PyBuiltinCache.getInstance(this).hasInBuiltins(this)) { String implicitSuperclassName = LanguageLevel.forElement(this).isPy3K() ? PyNames.OBJECT : PyNames.FAKE_OLD_BASE; PyClass implicitSuperclass = PyBuiltinCache.getInstance(this).getClass(implicitSuperclassName); if (implicitSuperclass != null) { result.add(new PyClassRef(implicitSuperclass)); } } return result; } @Nullable private List<PyClassRef> resolveSuperClassesFromStub() { final PyClassStub stub = getStub(); if (stub == null) { return null; } // stub-based resolve currently works correctly only with classes in file level final PsiElement parent = stub.getParentStub().getPsi(); if (!(parent instanceof PyFile)) { // TODO[yole] handle this case return null; } List<PyClassRef> result = new ArrayList<PyClassRef>(); for (PyQualifiedName qualifiedName : stub.getSuperClasses()) { result.add(classRefFromQName((NameDefiner)parent, qualifiedName)); } return result; } private static PyClassRef classRefFromQName(NameDefiner parent, PyQualifiedName qualifiedName) { if (qualifiedName == null) { return new PyClassRef((String)null); } NameDefiner currentParent = parent; for (String component : qualifiedName.getComponents()) { PsiElement element = currentParent.getElementNamed(component); element = PyUtil.turnDirIntoInit(element); if (element instanceof PyImportElement) { element = ((PyImportElement)element).resolve(); } if (!(element instanceof NameDefiner)) { currentParent = null; break; } currentParent = (NameDefiner)element; } if (currentParent != null) { return new PyClassRef(currentParent); } if (qualifiedName.getComponentCount() == 1) { final PyClass builtinClass = PyBuiltinCache.getInstance(parent).getClass(qualifiedName.getComponents().get(0)); if (builtinClass != null) { return new PyClassRef(builtinClass); } } return new PyClassRef(qualifiedName.toString()); } @NotNull public PyClass[] getSuperClasses() { final PyClassStub stub = getStub(); if (stub != null) { final List<PyClassRef> pyClasses = resolveSuperClassesFromStub(); if (pyClasses == null) { return EMPTY_ARRAY; } List<PyClass> result = new ArrayList<PyClass>(); for (PyClassRef clsRef : pyClasses) { PyClass pyClass = clsRef.getPyClass(); if (pyClass != null) { result.add(pyClass); } } return result.toArray(new PyClass[result.size()]); } PsiElement[] superClassElements = getSuperClassElements(); if (superClassElements.length > 0) { List<PyClass> result = new ArrayList<PyClass>(); for (PsiElement element : superClassElements) { if (element instanceof PyClass) { result.add((PyClass)element); } } return result.toArray(new PyClass[result.size()]); } return EMPTY_ARRAY; } public @NotNull List<PyClass> getMRO() { // see http://hackage.haskell.org/packages/archive/MetaObject/latest/doc/html/src/MO-Util-C3.html#linearize for code to port from. return mroLinearize(this, Collections.<PyClass>emptyList()); } private static List<PyClass> mroMerge(List<List<PyClass>> sequences) { List<PyClass> result = new LinkedList<PyClass>(); // need to insert to 0th position on linearize while (true) { // filter blank sequences List<List<PyClass>> nonBlankSequences = new ArrayList<List<PyClass>>(sequences.size()); for (List<PyClass> item : sequences) { if (item.size() > 0) nonBlankSequences.add(item); } if (nonBlankSequences.isEmpty()) return result; // find a clean head PyClass head = null; // to keep compiler happy; really head is assigned in the loop at least once. for (List<PyClass> seq : nonBlankSequences) { head = seq.get(0); boolean head_in_tails = false; for (List<PyClass> tail_seq : nonBlankSequences) { if (tail_seq.indexOf(head) > 0) { // -1 is not found, 0 is head, >0 is tail. head_in_tails = true; break; } } if (!head_in_tails) { break; } else { head = null; // as a signal } } assert head != null : "Inconsistent hierarchy!"; // TODO: better diagnostics? // our head is clean; result.add(head); // remove it from heads of other sequences for (List<PyClass> seq : nonBlankSequences) { if (seq.get(0) == head) seq.remove(0); } } // we either return inside the loop or die by assertion } private static List<PyClass> mroLinearize(PyClass cls, List<PyClass> seen) { assert (seen.indexOf(cls) < 0) : "Circular import structure on " + PyUtil.nvl(cls); PyClass[] bases = cls.getSuperClasses(); List<List<PyClass>> lins = new ArrayList<List<PyClass>>(bases.length * 2); ArrayList<PyClass> new_seen = new ArrayList<PyClass>(seen.size() + 1); new_seen.add(cls); for (PyClass base : bases) { List<PyClass> lin = mroLinearize(base, new_seen); if (!lin.isEmpty()) lins.add(lin); } for (PyClass base : bases) { lins.add(new SmartList<PyClass>(base)); } List<PyClass> result = mroMerge(lins); result.add(0, cls); return result; } @NotNull public PyFunction[] getMethods() { return getClassChildren(PythonDialectsTokenSetProvider.INSTANCE.getFunctionDeclarationTokens(), PyFunction.ARRAY_FACTORY); } @Override public PyClass[] getNestedClasses() { return getClassChildren(TokenSet.create(PyElementTypes.CLASS_DECLARATION), PyClass.ARRAY_FACTORY); } protected <T extends PsiElement> T[] getClassChildren(TokenSet elementTypes, ArrayFactory<T> factory) { // TODO: gather all top-level functions, maybe within control statements final PyClassStub classStub = getStub(); if (classStub != null) { return classStub.getChildrenByType(elementTypes, factory); } List<T> result = new ArrayList<T>(); final PyStatementList statementList = getStatementList(); for (PsiElement element : statementList.getChildren()) { if (elementTypes.contains(element.getNode().getElementType())) { //noinspection unchecked result.add((T)element); } } return result.toArray(factory.create(result.size())); } private static class NameFinder<T extends PyElement> implements Processor<T> { private T myResult; private final String[] myNames; public NameFinder(String... names) { myNames = names; myResult = null; } public T getResult() { return myResult; } public boolean process(T target) { final String targetName = target.getName(); for (String name : myNames) { if (name.equals(targetName)) { myResult = target; return false; } } return true; } } public PyFunction findMethodByName(@Nullable final String name, boolean inherited) { if (name == null) return null; NameFinder<PyFunction> proc = new NameFinder<PyFunction>(name); visitMethods(proc, inherited); return proc.getResult(); } @Nullable @Override public PyClass findNestedClass(String name, boolean inherited) { if (name == null) return null; NameFinder<PyClass> proc = new NameFinder<PyClass>(name); visitNestedClasses(proc, inherited); return proc.getResult(); } @Nullable public PyFunction findInitOrNew(boolean inherited) { NameFinder<PyFunction> proc; if (isNewStyleClass()) { proc = new NameFinder<PyFunction>(PyNames.INIT, PyNames.NEW); } else { proc = new NameFinder<PyFunction>(PyNames.INIT); } visitMethods(proc, inherited, true); return proc.getResult(); } private final static Maybe<Callable> UNKNOWN_CALL = new Maybe<Callable>(); // denotes _not_ a PyFunction, actually private final static Maybe<Callable> NONE = new Maybe<Callable>(null); // denotes an explicit None /** * @param name name of the property * @param property_filter returns true if the property is acceptable * @param advanced is @foo.setter syntax allowed * @return the first property that both filters accepted. */ @Nullable private Property processPropertiesInClass(@Nullable String name, @Nullable Processor<Property> property_filter, boolean advanced) { // NOTE: fast enough to be rerun every time Property prop = processDecoratedProperties(name, property_filter, advanced); if (prop != null) return prop; if (getStub() != null) { prop = processStubProperties(name, property_filter); if (prop != null) return prop; } else { // name = property(...) assignments from PSI for (PyTargetExpression target : getClassAttributes()) { if (name == null || name.equals(target.getName())) { prop = PropertyImpl.fromTarget(target); if (prop != null) { if (property_filter == null || property_filter.process(prop)) return prop; } } } } return null; } @Nullable private Property processDecoratedProperties(@Nullable String name, @Nullable Processor<Property> filter, boolean useAdvancedSyntax) { // look at @property decorators Map<String, List<PyFunction>> grouped = new HashMap<String, List<PyFunction>>(); // group suitable same-named methods, each group defines a property for (PyFunction method : getMethods()) { final String methodName = method.getName(); if (name == null || name.equals(methodName)) { List<PyFunction> bucket = grouped.get(methodName); if (bucket == null) { bucket = new SmartList<PyFunction>(); grouped.put(methodName, bucket); } bucket.add(method); } } for (Map.Entry<String, List<PyFunction>> entry : grouped.entrySet()) { Maybe<Callable> getter = NONE; Maybe<Callable> setter = NONE; Maybe<Callable> deleter = NONE; String doc = null; final String decoratorName = entry.getKey(); for (PyFunction method : entry.getValue()) { final PyDecoratorList decoratorList = method.getDecoratorList(); if (decoratorList != null) { for (PyDecorator deco : decoratorList.getDecorators()) { final PyQualifiedName qname = deco.getQualifiedName(); if (qname != null) { if (qname.matches(PyNames.PROPERTY)) { getter = new Maybe<Callable>(method); } else if (useAdvancedSyntax && qname.matches(decoratorName, PyNames.SETTER)) { setter = new Maybe<Callable>(method); } else if (useAdvancedSyntax && qname.matches(decoratorName, PyNames.DELETER)) { deleter = new Maybe<Callable>(method); } } } } if (getter != NONE && setter != NONE && deleter != NONE) break; // can't improve } if (getter != NONE || setter != NONE || deleter != NONE) { final PropertyImpl prop = new PropertyImpl(decoratorName, getter, setter, deleter, doc, null); if (filter == null || filter.process(prop)) return prop; } } return null; } private Maybe<Callable> fromPacked(Maybe<String> maybeName) { if (maybeName.isDefined()) { final String value = maybeName.value(); if (value == null || PyNames.NONE.equals(value)) { return NONE; } PyFunction method = findMethodByName(value, true); if (method != null) return new Maybe<Callable>(method); } return UNKNOWN_CALL; } @Nullable private Property processStubProperties(@Nullable String name, @Nullable Processor<Property> propertyProcessor) { final PyClassStub stub = getStub(); if (stub != null) { for (StubElement subStub : stub.getChildrenStubs()) { if (subStub.getStubType() == PyElementTypes.TARGET_EXPRESSION) { final PyTargetExpressionStub targetStub = (PyTargetExpressionStub)subStub; PropertyStubStorage prop = targetStub.getCustomStub(PropertyStubStorage.class); if (prop != null && (name == null || name.equals(targetStub.getName()))) { Maybe<Callable> getter = fromPacked(prop.getGetter()); Maybe<Callable> setter = fromPacked(prop.getSetter()); Maybe<Callable> deleter = fromPacked(prop.getDeleter()); String doc = prop.getDoc(); if (getter != NONE || setter != NONE || deleter != NONE) { final PropertyImpl property = new PropertyImpl(targetStub.getName(), getter, setter, deleter, doc, targetStub.getPsi()); if (propertyProcessor == null || propertyProcessor.process(property)) return property; } } } } } return null; } @Nullable @Override public Property findProperty(@NotNull final String name) { Property property = findLocalProperty(name); if (property != null) { return property; } if (findMethodByName(name, false) != null || findClassAttribute(name, false) != null) { return null; } for (PyClass aClass : iterateAncestorClasses()) { final Property ancestorProperty = ((PyClassImpl)aClass).findLocalProperty(name); if (ancestorProperty != null) { return ancestorProperty; } } return null; } @Override public Property findPropertyByFunction(PyFunction function) { if (myPropertyCache == null) { myPropertyCache = initializePropertyCache(); } for (Property property : myPropertyCache.values()) { if (property.getGetter().valueOrNull() == function || property.getSetter().valueOrNull() == function || property.getDeleter().valueOrNull() == function) { return property; } } return null; } private Property findLocalProperty(String name) { if (myPropertyCache == null) { myPropertyCache = initializePropertyCache(); } return myPropertyCache.get(name); } private Map<String, Property> initializePropertyCache() { final Map<String, Property> result = new HashMap<String, Property>(); processProperties(null, new Processor<Property>() { @Override public boolean process(Property property) { result.put(property.getName(), property); return false; } }, false); return result; } @Nullable @Override public Property scanProperties(@Nullable Processor<Property> filter, boolean inherited) { return processProperties(null, filter, inherited); } @Nullable private Property processProperties(@Nullable String name, @Nullable Processor<Property> filter, boolean inherited) { if (!isValid()) { return null; } LanguageLevel level = LanguageLevel.getDefault(); // EA-32381: A tree-based instance may not have a parent element somehow, so getContainingFile() may be not appropriate final PsiFile file = getParentByStub() != null ? getContainingFile() : null; if (file != null) { final VirtualFile vfile = file.getVirtualFile(); if (vfile != null) { level = LanguageLevel.forFile(vfile); } } final boolean useAdvancedSyntax = level.isAtLeast(LanguageLevel.PYTHON26); final Property local = processPropertiesInClass(name, filter, useAdvancedSyntax); if (local != null) { return local; } if (inherited) { if (name != null && (findMethodByName(name, false) != null || findClassAttribute(name, false) != null)) { return null; } for (PyClass cls : iterateAncestorClasses()) { final Property property = ((PyClassImpl)cls).processPropertiesInClass(name, filter, useAdvancedSyntax); if (property != null) { return property; } } } return null; } private static class PropertyImpl extends PropertyBunch<Callable> implements Property { private final String myName; private PropertyImpl(String name, Maybe<Callable> getter, Maybe<Callable> setter, Maybe<Callable> deleter, String doc, PyTargetExpression site) { myName = name; myDeleter = deleter; myGetter = getter; mySetter = setter; myDoc = doc; mySite = site; } public String getName() { return myName; } public PyTargetExpression getDefinitionSite() { return mySite; } @NotNull @Override public Maybe<Callable> getByDirection(@NotNull AccessDirection direction) { switch (direction) { case READ: return myGetter; case WRITE: return mySetter; case DELETE: return myDeleter; } throw new IllegalArgumentException("Unknown direction " + PyUtil.nvl(direction)); } @NotNull @Override protected Maybe<Callable> translate(@Nullable PyExpression expr) { if (expr == null) { return NONE; } if (PyNames.NONE.equals(expr.getName())) return NONE; // short-circuit a common case if (expr instanceof Callable) { return new Maybe<Callable>((Callable)expr); } final PsiReference ref = expr.getReference(); if (ref != null) { PsiElement something = ref.resolve(); if (something instanceof Callable) { return new Maybe<Callable>((Callable)something); } } return NONE; } public String toString() { return "property(" + myGetter + ", " + mySetter + ", " + myDeleter + ", " + myDoc + ")"; } @Nullable public static PropertyImpl fromTarget(PyTargetExpression target) { PyExpression expr = target.findAssignedValue(); final PropertyImpl prop = new PropertyImpl(target.getName(), null, null, null, null, target); final boolean success = fillFromCall(expr, prop); return success ? prop : null; } } public boolean visitMethods(Processor<PyFunction> processor, boolean inherited) { return visitMethods(processor, inherited, false); } public boolean visitMethods(Processor<PyFunction> processor, boolean inherited, boolean skipClassObj) { PyFunction[] methods = getMethods(); if (!ContainerUtil.process(methods, processor)) return false; if (inherited) { for (PyClass ancestor : iterateAncestorClasses()) { if (skipClassObj && PyNames.FAKE_OLD_BASE.equals(ancestor.getName())) { continue; } if (!ancestor.visitMethods(processor, false)) { return false; } } } return true; } public boolean visitNestedClasses(Processor<PyClass> processor, boolean inherited) { PyClass[] nestedClasses = getNestedClasses(); if (!ContainerUtil.process(nestedClasses, processor)) return false; if (inherited) { for (PyClass ancestor : iterateAncestorClasses()) { if (!((PyClassImpl)ancestor).visitNestedClasses(processor, false)) { return false; } } } return true; } public boolean visitClassAttributes(Processor<PyTargetExpression> processor, boolean inherited) { List<PyTargetExpression> methods = getClassAttributes(); if (!ContainerUtil.process(methods, processor)) return false; if (inherited) { for (PyClass ancestor : iterateAncestorClasses()) { if (!ancestor.visitClassAttributes(processor, false)) { return false; } } } return true; // NOTE: sorry, not enough metaprogramming to generalize visitMethods and visitClassAttributes } public List<PyTargetExpression> getClassAttributes() { PyClassStub stub = getStub(); if (stub != null) { final PyTargetExpression[] children = stub.getChildrenByType(PyElementTypes.TARGET_EXPRESSION, PyTargetExpression.EMPTY_ARRAY); return Arrays.asList(children); } List<PyTargetExpression> result = new ArrayList<PyTargetExpression>(); for (PsiElement psiElement : getStatementList().getChildren()) { if (psiElement instanceof PyAssignmentStatement) { final PyAssignmentStatement assignmentStatement = (PyAssignmentStatement)psiElement; final PyExpression[] targets = assignmentStatement.getTargets(); for (PyExpression target : targets) { if (target instanceof PyTargetExpression) { result.add((PyTargetExpression)target); } } } } return result; } @Override public PyTargetExpression findClassAttribute(@NotNull String name, boolean inherited) { final NameFinder<PyTargetExpression> processor = new NameFinder<PyTargetExpression>(name); visitClassAttributes(processor, inherited); return processor.getResult(); } public List<PyTargetExpression> getInstanceAttributes() { if (myInstanceAttributes == null) { myInstanceAttributes = collectInstanceAttributes(); } return myInstanceAttributes; } @Nullable @Override public PyTargetExpression findInstanceAttribute(String name, boolean inherited) { final List<PyTargetExpression> instanceAttributes = getInstanceAttributes(); for (PyTargetExpression instanceAttribute : instanceAttributes) { if (name.equals(instanceAttribute.getReferencedName())) { return instanceAttribute; } } if (inherited) { for (PyClass ancestor : iterateAncestorClasses()) { final PyTargetExpression attribute = ancestor.findInstanceAttribute(name, false); if (attribute != null) { return attribute; } } } return null; } private List<PyTargetExpression> collectInstanceAttributes() { Map<String, PyTargetExpression> result = new HashMap<String, PyTargetExpression>(); // __init__ takes priority over all other methods PyFunctionImpl initMethod = (PyFunctionImpl)findMethodByName(PyNames.INIT, false); if (initMethod != null) { collectInstanceAttributes(initMethod, result); } final PyFunction[] methods = getMethods(); for (PyFunction method : methods) { if (!PyNames.INIT.equals(method.getName())) { collectInstanceAttributes(method, result); } } final Collection<PyTargetExpression> expressions = result.values(); return new ArrayList<PyTargetExpression>(expressions); } private static void collectInstanceAttributes(@NotNull PyFunction method, @NotNull final Map<String, PyTargetExpression> result) { final PyParameter[] params = method.getParameterList().getParameters(); if (params.length == 0) { return; } final PyFunctionStub methodStub = method.getStub(); if (methodStub != null) { final PyTargetExpression[] targets = methodStub.getChildrenByType(PyElementTypes.TARGET_EXPRESSION, PyTargetExpression.EMPTY_ARRAY); for (PyTargetExpression target : targets) { if (!result.containsKey(target.getName())) { result.put(target.getName(), target); } } } else { final PyStatementList statementList = method.getStatementList(); if (statementList != null) { statementList.accept(new PyRecursiveElementVisitor() { public void visitPyAssignmentStatement(final PyAssignmentStatement node) { super.visitPyAssignmentStatement(node); collectNewTargets(result, node); } }); } } } private static void collectNewTargets(Map<String, PyTargetExpression> collected, PyAssignmentStatement node) { final PyExpression[] targets = node.getTargets(); for (PyExpression target : targets) { if (target instanceof PyTargetExpression && PyUtil.isInstanceAttribute(target)) { collected.put(target.getName(), (PyTargetExpression)target); } } } public boolean isNewStyleClass() { return myNewStyle.getValue().getValue(); } private boolean calculateNewStyleClass() { final PsiFile containingFile = getContainingFile(); if (containingFile instanceof PyFile && ((PyFile)containingFile).getLanguageLevel().isPy3K()) { return true; } final PyClass objClass = PyBuiltinCache.getInstance(this).getClass("object"); if (this == objClass) return true; // a rare but possible case if (hasNewStyleMetaClass(this)) return true; for (PyClassRef ancestor : iterateAncestors()) { final PyClass pyClass = ancestor.getPyClass(); if (pyClass == null) { // unknown, assume new-style class return true; } if (pyClass == objClass) return true; if (hasNewStyleMetaClass(pyClass)) { return true; } } return false; } private static boolean hasNewStyleMetaClass(PyClass pyClass) { final PsiFile containingFile = pyClass.getContainingFile(); if (containingFile instanceof PyFile) { final PsiElement element = ((PyFile)containingFile).getElementNamed(PyNames.DUNDER_METACLASS); if (element instanceof PyTargetExpression) { final PyQualifiedName qName = ((PyTargetExpression)element).getAssignedQName(); if (qName != null && qName.matches("type")) { return true; } } } if (pyClass.findClassAttribute(PyNames.DUNDER_METACLASS, false) != null) { return true; } return false; } @Override public boolean processClassLevelDeclarations(@NotNull PsiScopeProcessor processor) { final PyClassStub stub = getStub(); if (stub != null) { final List<StubElement> children = stub.getChildrenStubs(); for (StubElement child : children) { if (!processor.execute(child.getPsi(), ResolveState.initial())) { return false; } } } else { PyResolveUtil.scopeCrawlUp(processor, this, null, this); } return true; } @Override public boolean processInstanceLevelDeclarations(@NotNull PsiScopeProcessor processor, @Nullable PyExpression location) { Map<String, PyTargetExpression> declarationsInMethod = new HashMap<String, PyTargetExpression>(); PyFunction instanceMethod = PsiTreeUtil.getParentOfType(location, PyFunction.class); final PyClass containingClass = instanceMethod != null ? instanceMethod.getContainingClass() : null; if (instanceMethod != null && containingClass != null && CompletionUtil.getOriginalElement(containingClass) == this) { collectInstanceAttributes(instanceMethod, declarationsInMethod); for (PyTargetExpression targetExpression : declarationsInMethod.values()) { if (!processor.execute(targetExpression, ResolveState.initial())) { return false; } } } for (PyTargetExpression expr : getInstanceAttributes()) { if (declarationsInMethod.containsKey(expr.getName())) { continue; } if (!processor.execute(expr, ResolveState.initial())) return false; } return true; } public int getTextOffset() { final ASTNode name = getNameNode(); return name != null ? name.getStartOffset() : super.getTextOffset(); } public PyStringLiteralExpression getDocStringExpression() { return PythonDocStringFinder.find(getStatementList()); } @Override public String getDocStringValue() { final PyClassStub stub = getStub(); if (stub != null) { return stub.getDocString(); } return PyPsiUtils.strValue(getDocStringExpression()); } public String toString() { return "PyClass: " + getName(); } @NotNull public Iterable<PyElement> iterateNames() { return Collections.<PyElement>singleton(this); } public PyElement getElementNamed(final String the_name) { return the_name.equals(getName()) ? this : null; } public boolean mustResolveOutside() { return false; } public void subtreeChanged() { super.subtreeChanged(); ControlFlowCache.clear(this); if (myInstanceAttributes != null) { myInstanceAttributes = null; } myPropertyCache = null; } @NotNull @Override public SearchScope getUseScope() { final ScopeOwner scopeOwner = ScopeUtil.getScopeOwner(this); if (scopeOwner instanceof PyFunction) { return new LocalSearchScope(scopeOwner); } return super.getUseScope(); } private static class AncestorsIterable implements Iterable<PyClassRef> { private final PyClassImpl myClass; public AncestorsIterable(final PyClassImpl pyClass) { myClass = pyClass; } public Iterator<PyClassRef> iterator() { return new AncestorsIterator(myClass); } } private static class AncestorsIterator implements Iterator<PyClassRef> { List<PyClassRef> pending = new LinkedList<PyClassRef>(); private final Set<PyClassRef> seen; Iterator<PyClassRef> percolator; PyClassRef prefetch = null; private final PyClassImpl myAClass; public AncestorsIterator(PyClassImpl aClass) { myAClass = aClass; percolator = myAClass.getSuperClassesList().iterator(); seen = new HashSet<PyClassRef>(); } private AncestorsIterator(PyClassImpl AClass, Set<PyClassRef> seen) { myAClass = AClass; this.seen = seen; percolator = myAClass.getSuperClassesList().iterator(); } public boolean hasNext() { // due to already-seen filtering, there's no way but to try and see. if (prefetch != null) return true; prefetch = getNext(); return prefetch != null; } public PyClassRef next() { final PyClassRef nextClass = getNext(); if (nextClass == null) throw new NoSuchElementException(); return nextClass; } @Nullable private PyClassRef getNext() { iterations: while (true) { if (prefetch != null) { PyClassRef ret = prefetch; prefetch = null; return ret; } if (percolator.hasNext()) { PyClassRef it = percolator.next(); if (seen.contains(it)) { continue iterations; // loop back is equivalent to return next(); } pending.add(it); seen.add(it); return it; } else { while (pending.size() > 0) { PyClassRef it = pending.get(0); pending.remove(0); PyClass pyClass = it.getPyClass(); if (pyClass != null) { percolator = new AncestorsIterator((PyClassImpl)pyClass, new HashSet<PyClassRef>(seen)); continue iterations; } } return null; } } } public void remove() { throw new UnsupportedOperationException(); } } private static class AncestorClassesIterable implements Iterable<PyClass> { private final PyClassImpl myClass; public AncestorClassesIterable(final PyClassImpl pyClass) { myClass = pyClass; } public Iterator<PyClass> iterator() { return new AncestorClassesIterator(new AncestorsIterator(myClass)); } } private static class AncestorClassesIterator implements Iterator<PyClass> { private final AncestorsIterator myAncestorsIterator; private PyClass myNext; public AncestorClassesIterator(AncestorsIterator ancestorsIterator) { myAncestorsIterator = ancestorsIterator; } @Override public boolean hasNext() { if (myNext != null) { return true; } while (myAncestorsIterator.hasNext()) { PyClassRef clsRef = myAncestorsIterator.getNext(); if (clsRef == null) { return false; } myNext = clsRef.getPyClass(); if (myNext != null) { return true; } } return false; } @Nullable @Override public PyClass next() { if (myNext == null) { if (!hasNext()) return null; } PyClass next = myNext; myNext = null; return next; } @Override public void remove() { throw new UnsupportedOperationException(); } } }
package org.rabix.tests; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.rabix.common.helper.JSONHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { private static String testDirPath; private static String cmd_prefix; private static String resultPath = "./rabix-backend-local/target/result.yaml"; private static String workingdir = "./rabix-backend-local/target/"; private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); public static void main(String[] commandLineArguments) { try { testDirPath = getConfig("testDirPath"); cmd_prefix = getConfig("cmd_prefix"); } catch (IOException e) { e.printStackTrace(); } startTestExecution(); } private static void startTestExecution() { boolean success = true; boolean testPassed = false; File dir = new File(testDirPath); File[] directoryListing = dir.listFiles(); ArrayList<Object> failedTests = new ArrayList<Object>(); if (!dir.isDirectory()) { logger.error("Problem with test directory path: Test directory path is not valid directory path."); } else { if (directoryListing == null) { logger.error("Problem with provided test directory: Test directory is empty."); } else { logger.info("Extracting jar file"); executeCommand("sudo tar -zxvf " + System.getProperty("user.dir") + "/rabix-backend-local/target/rabix-backend-local-0.0.1-SNAPSHOT-id3.tar.gz"); executeCommand("cp -a " + System.getProperty("user.dir") + "/rabix-tests/testbacklog ."); for (File child : directoryListing) { if (!child.toString().endsWith(".test.yaml")) continue; try { String currentTest = readFile(child.getAbsolutePath(), Charset.defaultCharset()); Map<String, Object> inputSuite = JSONHelper.readMap(JSONHelper.transformToJSON(currentTest)); Iterator entries = inputSuite.entrySet().iterator(); while (entries.hasNext()) { Entry thisEntry = (Entry) entries.next(); Object test_name = thisEntry.getKey(); Object test = thisEntry.getValue(); logger .info(" logger.info("Running test: " + test_name + " with given parameters:"); Map<String, Map<String, LinkedHashMap>> mapTest = (Map<String, Map<String, LinkedHashMap>>) test; logger.info(" app: " + mapTest.get("app")); logger.info(" inputs: " + mapTest.get("inputs")); logger.info(" expected: " + mapTest.get("expected")); String cmd = cmd_prefix + " " + mapTest.get("app") + " " + mapTest.get("inputs") + " > result.yaml"; logger.info("->Running cmd: " + cmd + "\n"); executeCommand(cmd); File resultFile = new File(resultPath); String resultText = readFile(resultFile.getAbsolutePath(), Charset.defaultCharset()); Map<String, Object> resultData = JSONHelper.readMap(JSONHelper.transformToJSON(resultText)); logger.info("\nGenerated result file:"); logger.info(resultText); testPassed = validateTestCase(mapTest, resultData); logger.info("\nTest result: "); if (testPassed) { logger.info(test_name + " PASSED"); } else { logger.info(test_name + " FAILED"); failedTests.add(test_name); success = false; } } } catch (IOException e) { e.printStackTrace(); } } if (success) { logger .info(" logger.info("Test suite passed successfully."); logger .info(" } else { logger .info(" logger.info("Test suite failed."); logger.info("Failed test number: " + failedTests.size()); logger.info("Failed tests:"); for (Object test : failedTests) { logger.info(test.toString()); } logger .info(" } } } } private static boolean validateTestCase(Map<String, Map<String, LinkedHashMap>> mapTest, Map<String, Object> resultData) { String resultFileName; int resultFileSize; String resultFileClass; Map<String, Object> resultValues = ((Map<String, Object>) resultData.get("outfile")); resultFileName = resultValues.get("path").toString(); resultFileName = resultFileName.split("/")[resultFileName.split("/").length - 1]; resultFileSize = (int) resultValues.get("size"); resultFileClass = resultValues.get("class").toString(); logger.info("Test validation:"); logger.info("result file name: " + resultFileName + ", expected file name: " + mapTest.get("expected").get("outfile").get("name")); logger.info("result file size: " + resultFileSize + ", expected file size: " + mapTest.get("expected").get("outfile").get("size")); logger.info("result file class: " + resultFileClass + ", expected file class: " + mapTest.get("expected").get("outfile").get("class")); boolean fileNamesEqual = resultFileName.equals(mapTest.get("expected").get("outfile").get("name")); boolean fileSizesEqual = resultFileSize == (int) mapTest.get("expected").get("outfile").get("size"); boolean fileClassesEqual = resultFileClass.equals(mapTest.get("expected").get("outfile").get("class")); if (!fileNamesEqual) { logger.info("result and expected file name are not equal!"); } else { if (!fileSizesEqual) { logger.info("result and expected file size are not equal!"); } else { if (!fileClassesEqual) { logger.info("result and expected file class are not equal!"); } else { return true; } } } return false; } public static ArrayList<String> command(final String cmdline, final String directory) { try { Process process = new ProcessBuilder(new String[] { "bash", "-c", cmdline }).redirectErrorStream(true) .directory(new File(directory)).start(); ArrayList<String> output = new ArrayList<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = br.readLine()) != null) output.add(line); if (0 != process.waitFor()) { return null; } return output; } catch (Exception e) { return null; } } static void executeCommand(String cmdline) { ArrayList<String> output = command(cmdline, workingdir); if (null == output) logger.info("COMMAND FAILED: " + cmdline + "\n"); else for (String line : output) { logger.info(line); } } /** * Reads content from a file */ static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } private static String getConfig(String key) throws IOException { File configFile = new File(System.getProperty("user.dir") + "/rabix-tests/config/core.properties"); String config = readFile(configFile.getAbsolutePath(), Charset.defaultCharset()); String[] splitedRows = config.split("\n"); Map<String, String> cmap = new HashMap<String, String>(); for (String row : splitedRows) { String[] elems = row.split("="); cmap.put(elems[0], elems[1]); } return cmap.get(key); } }
package outbackcdx; import org.apache.commons.lang.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import outbackcdx.auth.Permit; import java.io.*; import java.nio.charset.Charset; import java.util.*; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static outbackcdx.Json.GSON; import static outbackcdx.NanoHTTPD.Method.*; import static outbackcdx.NanoHTTPD.Response.Status.BAD_REQUEST; import static outbackcdx.NanoHTTPD.Response.Status.CREATED; import static outbackcdx.NanoHTTPD.Response.Status.OK; public class WebappTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); private Webapp webapp; @Before public void setUp() throws IOException { FeatureFlags.setExperimentalAccessControl(true); File root = folder.newFolder(); DataStore manager = new DataStore(root, 0); webapp = new Webapp(manager, false, Collections.emptyMap()); } @After public void tearDown() { FeatureFlags.setExperimentalAccessControl(false); } @Test public void test() throws Exception { POST("/test", "- 20050614070159 http: POST("/test", "- 20060614070159 http: { String response = GET("/test", "url", "nla.gov.au"); assertTrue(response.indexOf("au,gov,nla)/ 20050614070159") != -1); assertTrue(response.indexOf("example") == -1); } { String response = GET("/test", "q", "type:urlquery url:http%3A%2F%2Fnla.gov.au%2F"); assertTrue(response.indexOf("20050614070159") != -1); assertTrue(response.indexOf("20060614070159") != -1); } POST("/test", "@alias http: { String response = GET("/test", "q", "type:urlquery url:http%3A%2F%2Fnla.gov.au%2F"); assertTrue(response.indexOf("20050614070159") != -1); assertTrue(response.indexOf("20060614070159") != -1); assertTrue(response.indexOf("20100614070159") != -1); assertTrue(response.indexOf("20030614070159") != -1); } { String response = GET("/test", "q", "type:urlquery url:http%3A%2F%2Fnla.gov.au%2F limit:2 offset:0"); assertEquals(2, StringUtils.countMatches(response, "<result>")); } } @Test public void testDelete() throws Exception { POST("/test", "- 20050614070159 http: POST("/test", "- 20060614070159 http: { String response = GET("/test", "q", "type:urlquery url:http%3A%2F%2Fnla.gov.au%2F"); assertTrue(response.contains("20050614070159")); assertTrue(response.contains("20060614070159")); } POST("/test/delete", "- 20060614070159 http: { String response = GET("/test", "q", "type:urlquery url:http%3A%2F%2Fnla.gov.au%2F"); assertTrue(response.contains("20050614070159")); assertTrue(!response.contains("20060614070159")); } } @Test public void testAccessPoint() throws Exception { POST("/testap", "- 20050614070159 http://a.ex.org/ text/html 200 - - 42 wrc\n" + "- 20030614070159 http://a.ex.org/ text/html 200 - - - - 42 wrc\n" + "- 20030614070159 http://b.ex.org/ text/html 200 - - - - 42 wrc\n"); long publicPolicyId = createPolicy("Normal", "public", "staff"); long staffPolicyId = createPolicy("Restricted", "staff"); assertEquals(5, GSON.fromJson(GET("/testap/access/policies"), AccessPolicy[].class).length); createRule(publicPolicyId, "*"); long ruleIdC = createRule(staffPolicyId, "*.c.ex.org"); long ruleIdA = createRule(staffPolicyId, "*.a.ex.org"); // default sort should be rule id { AccessRule[] actualRules = GSON.fromJson(GET("/testap/access/rules"), AccessRule[].class); assertEquals(3, actualRules.length); assertEquals(ruleIdC, (long) actualRules[1].id); assertEquals(ruleIdA, (long) actualRules[2].id); } // check sorting by SURT { AccessRule[] actualRules = GSON.fromJson(GET("/testap/access/rules", "sort", "surt"), AccessRule[].class); assertEquals(3, actualRules.length); assertEquals(ruleIdA, (long) actualRules[1].id); assertEquals(ruleIdC, (long) actualRules[2].id); } assertEquals(asList("http: cdxUrls(GET("/testap", "url", "*.ex.org"))); assertEquals(asList("http: cdxUrls(GET("/testap/ap/staff", "url", "*.ex.org"))); assertEquals(asList("http://b.ex.org/"), cdxUrls(GET("/testap/ap/public", "url", "*.ex.org"))); // try modifying a policy AccessPolicy policy = GSON.fromJson(GET("/testap/access/policies/" + staffPolicyId), AccessPolicy.class); policy.accessPoints.remove("staff"); POST("/testap/access/policies", GSON.toJson(policy)); assertEquals(asList("http://b.ex.org/"), cdxUrls(GET("/testap/ap/staff", "url", "*.ex.org"))); // try modifying a rule AccessRule rule = GSON.fromJson(GET("/testap/access/rules/" + ruleIdA), AccessRule.class); rule.urlPatterns.clear(); rule.urlPatterns.add("*.b.ex.org"); POST("/testap/access/rules", GSON.toJson(rule)); assertEquals(asList("http: cdxUrls(GET("/testap/ap/public", "url", "*.ex.org"))); // try deleting a rule DELETE("/testap/access/rules/" + ruleIdA); assertEquals(asList("http: cdxUrls(GET("/testap/ap/public", "url", "*.ex.org"))); // invalid rules should be rejected AccessRule badRule = new AccessRule(); badRule.policyId = staffPolicyId; badRule.urlPatterns.add("*.example.org/with/a/path"); POST("/testap/access/rules", GSON.toJson(badRule), BAD_REQUEST); AccessRule badRule2 = new AccessRule(); badRule2.policyId = staffPolicyId; badRule2.urlPatterns.add(""); POST("/testap/access/rules", GSON.toJson(badRule2), BAD_REQUEST); AccessRule badRule3 = new AccessRule(); badRule3.policyId = staffPolicyId; POST("/testap/access/rules", GSON.toJson(badRule3), BAD_REQUEST); } List<String> cdxUrls(String cdx) { List<String> urls = new ArrayList<>(); for (String line: cdx.trim().split("\n")) { urls.add(line.split(" ")[2]); } return urls; } private long createRule(long policyId, String... surts) throws Exception { AccessRule rule = new AccessRule(); rule.policyId = policyId; rule.urlPatterns.addAll(asList(surts)); String response = POST("/testap/access/rules", GSON.toJson(rule), CREATED); return GSON.fromJson(response, Id.class).id; } private long createPolicy(String name, String... accessPoints) throws Exception { AccessPolicy publicPolicy = new AccessPolicy(); publicPolicy.name = name; publicPolicy.accessPoints.addAll(asList(accessPoints)); String response = POST("/testap/access/policies", GSON.toJson(publicPolicy), CREATED); return GSON.fromJson(response, Id.class).id; } public static class Id { public long id; } private String POST(String url, String data) throws Exception { return POST(url, data, OK); } private String POST(String url, String data, NanoHTTPD.Response.Status expectedStatus) throws Exception { DummySession session = new DummySession(POST, url); session.data(data); NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full())); assertEquals(expectedStatus, response.getStatus()); return slurp(response); } private String GET(String url, String... parmKeysAndValues) throws Exception { DummySession session = new DummySession(GET, url); for (int i = 0; i < parmKeysAndValues.length; i += 2) { session.parm(parmKeysAndValues[i], parmKeysAndValues[i + 1]); } NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full())); assertEquals(OK, response.getStatus()); return slurp(response); } private String DELETE(String url) throws Exception { DummySession session = new DummySession(DELETE, url); NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full())); assertEquals(OK, response.getStatus()); return slurp(response); } private String slurp(NanoHTTPD.Response response) throws IOException { NanoHTTPD.IStreamer streamer = response.getStreamer(); if (streamer != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); streamer.stream(out); return out.toString("UTF-8"); } InputStream data = response.getData(); if (data != null) { Scanner scanner = new Scanner(response.getData(), "UTF-8").useDelimiter("\\Z"); if (scanner.hasNext()) { return scanner.next(); } } return ""; } private static class DummySession implements NanoHTTPD.IHTTPSession { private final NanoHTTPD.Method method; InputStream stream = new ByteArrayInputStream(new byte[0]); Map<String, String> parms = new HashMap<String, String>(); String url; public DummySession(NanoHTTPD.Method method, String url) { this.url = url; this.method = method; } public DummySession data(String data) { stream = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8"))); return this; } public DummySession parm(String key, String value) { parms.put(key, value); return this; } @Override public void execute() throws IOException { // nothing } @Override public Map<String, String> getParms() { return parms; } @Override public Map<String, String> getHeaders() { return Collections.emptyMap(); } @Override public String getUri() { return url; } @Override public String getQueryParameterString() { return ""; } @Override public NanoHTTPD.Method getMethod() { return method; } @Override public InputStream getInputStream() { return stream; } } }
package resources; import java.util.List; import resources.objects.creature.CreatureObject; import services.galaxy.TravelService.TravelInfo; public final class TravelPoint { private final String name; private final Location location; private final List<TravelInfo> allowedRoutesForPoint; private final int additionalCost; // Additional cost. Perhaps based on distance from source to destination? private final boolean reachable; private CreatureObject shuttle; public TravelPoint(String name, Location location, List<TravelInfo> allowedRoutesForPoint, int additionalCost) { this.name = name; this.location = location; this.allowedRoutesForPoint = allowedRoutesForPoint; this.additionalCost = additionalCost; reachable = true; // Not sure which effect this has on the client. } public String getName() { return name; } public Location getLocation() { return location; } public int ticketPrice(Terrain arrivalPlanet) { int foundPrice = 0; for(TravelInfo travelInfo : allowedRoutesForPoint) { if(travelInfo.getTerrain() == arrivalPlanet) { foundPrice = travelInfo.getPrice(); break; } } return foundPrice; } public int getAdditionalCost() { return additionalCost; } public int totalTicketPrice(Terrain arrivalPlanet) { return ticketPrice(arrivalPlanet) + getAdditionalCost(); } public boolean isReachable() { return reachable; } public CreatureObject getShuttle() { return shuttle; } public void setShuttle(CreatureObject shuttle) { this.shuttle = shuttle; } public String suiFormat() { return String.format("@planet_n:%s -- %s", location.getTerrain().getName(), name); } }
package fr.obeo.tools.stuart.jira; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import com.atlassian.jira.rest.client.api.JiraRestClient; import com.atlassian.jira.rest.client.api.JiraRestClientFactory; import com.atlassian.jira.rest.client.api.domain.Comment; import com.atlassian.jira.rest.client.api.domain.Issue; import com.atlassian.jira.rest.client.api.domain.SearchResult; import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import fr.obeo.tools.stuart.Post; public class JiraLogger { private static final String BUG_ICON = "https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/bug.png"; private String baseURL = "https://support.jira.obeo.fr/"; private String username; private String password; public JiraLogger() { } public JiraLogger(String baseURL) { this.baseURL = baseURL; } public void setAuth(String username, String password) { this.username = username; this.password = password; } public Collection<Post> jiraLog(int nbDaysAgo, Collection<String> projects) throws MalformedURLException { List<Post> posts = new ArrayList<Post>(); JiraRestClient jira = null; try { JiraRestClientFactory restClientFactory = new AsynchronousJiraRestClientFactory(); URI uri = new URI(baseURL); if (username != null && password != null) { jira = restClientFactory.createWithBasicHttpAuthentication(uri, username, password); } else { jira = restClientFactory.createWithBasicHttpAuthentication(uri, "anonymous", "nopass"); } String projectsQL = "(" + Joiner.on(" OR ").join(Iterables.transform(projects, new Function<String, String>() { @Override public String apply(String input) { return "project=" + input; } })) + " )"; String jql = projectsQL + " AND updated>=-" + nbDaysAgo + "d ORDER BY updated DESC"; SearchResult r = jira.getSearchClient().searchJql(jql).get(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -nbDaysAgo); Date daysAgo = cal.getTime(); for (Issue lightIssue : r.getIssues()) { /* * for some reasons I don't get comments when using the search * API and has to retrieve each issue explicitely. */ Issue i = jira.getIssueClient().getIssue(lightIssue.getKey()).get(); String issueURL = baseURL + "browse/" + i.getKey(); if (!i.getComments().iterator().hasNext()) { if (i.getCreationDate().toDate().after(daysAgo)) { posts.add(Post.createPostWithSubject(issueURL, "[[" + i.getKey() + "](" + i.getSelf() + ")] " + i.getSummary(), "Has been created", i.getReporter().getName(), BUG_ICON, i.getCreationDate().toDate()).addURLs(issueURL)); } } else { for (Comment c : i.getComments()) { if (c.getCreationDate().toDate().after(daysAgo)) { String commentURL = issueURL + "?focusedCommentId=" + c.getId(); posts.add(Post .createPostWithSubject(commentURL, "[[" + i.getKey() + "](" + commentURL + ")] " + i.getSummary(), c.getBody(), c.getAuthor().getName(), BUG_ICON, c.getCreationDate().toDate()) .addURLs(commentURL)); } } } } } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (jira != null) { try { jira.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return posts; } }
package com.stripe.functional; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertNull; import static junit.framework.TestCase.assertTrue; import com.stripe.BaseStripeTest; import com.stripe.Stripe; import com.stripe.exception.StripeException; import com.stripe.model.Balance; import com.stripe.net.ApiResource; import com.stripe.net.ClientTelemetryPayload; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.Test; public class TelemetryTest extends BaseStripeTest { @Test public void testTelemetryEnabled() throws StripeException, IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("{}").addHeader("Request-Id", "req_1") .setBodyDelay(30, TimeUnit.MILLISECONDS)); server.enqueue(new MockResponse().setBody("{}").addHeader("Request-Id", "req_2") .setBodyDelay(120, TimeUnit.MILLISECONDS)); server.enqueue(new MockResponse().setBody("{}").addHeader("Request-Id", "req_3")); server.start(); Stripe.overrideApiBase(server.url("").toString()); Stripe.enableTelemetry = true; Balance b1 = Balance.retrieve(); RecordedRequest request1 = server.takeRequest(); assertNull(request1.getHeader("X-Stripe-Client-Telemetry")); Balance b2 = Balance.retrieve(); RecordedRequest request2 = server.takeRequest(); String telemetry1 = request2.getHeader("X-Stripe-Client-Telemetry"); ClientTelemetryPayload payload1 = ApiResource.GSON.fromJson( telemetry1, ClientTelemetryPayload.class); assertEquals(payload1.lastRequestMetrics.requestId, "req_1"); assertTrue(payload1.lastRequestMetrics.requestDurationMs > 30); Balance b3 = Balance.retrieve(); RecordedRequest request3 = server.takeRequest(); String telemetry2 = request3.getHeader("X-Stripe-Client-Telemetry"); ClientTelemetryPayload payload2 = ApiResource.GSON.fromJson( telemetry2, ClientTelemetryPayload.class); assertEquals(payload2.lastRequestMetrics.requestId, "req_2"); assertTrue(payload2.lastRequestMetrics.requestDurationMs > 120); server.shutdown(); } @Test public void testTelemetryDisabled() throws StripeException, IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("{}").addHeader("Request-Id", "req_1")); server.enqueue(new MockResponse().setBody("{}").addHeader("Request-Id", "req_2")); server.enqueue(new MockResponse().setBody("{}").addHeader("Request-Id", "req_3")); server.start(); Stripe.overrideApiBase(server.url("").toString()); Stripe.enableTelemetry = false; Balance b1 = Balance.retrieve(); RecordedRequest request1 = server.takeRequest(); assertNull(request1.getHeader("X-Stripe-Client-Telemetry")); Balance b2 = Balance.retrieve(); RecordedRequest request2 = server.takeRequest(); assertNull(request2.getHeader("X-Stripe-Client-Telemetry")); server.shutdown(); } @Test public void testTelemetryWorksWithConcurrentRequests() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); for (int i = 0; i < 20; i++) { server.enqueue(new MockResponse().setBody("{}") .addHeader("Request-Id", "req_" + i) .setBodyDelay(50, TimeUnit.MILLISECONDS)); } server.start(); Stripe.overrideApiBase(server.url("").toString()); Stripe.enableTelemetry = true; Runnable work = new Runnable() { @Override public void run() { try { Balance.retrieve(); } catch (StripeException e) { assertNull(e); } } }; // the first 10 requests will not contain telemetry ArrayList<Thread> threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { threads.add(new Thread(work)); } for (int i = 0; i < 10; i++) { threads.get(i).start(); } for (int i = 0; i < 10; i++) { threads.get(i).join(); } threads.clear(); // the following 10 requests will contain telemetry for (int i = 0; i < 10; i++) { threads.add(new Thread(work)); } for (int i = 0; i < 10; i++) { threads.get(i).start(); } for (int i = 0; i < 10; i++) { threads.get(i).join(); } threads.clear(); Set<String> seenRequestIds = new HashSet<>(); for (int i = 0; i < 10; i++) { RecordedRequest request = server.takeRequest(); assertNull(request.getHeader("X-Stripe-Client-Telemetry")); } for (int i = 0; i < 10; i++) { RecordedRequest request = server.takeRequest(); String telemetry2 = request.getHeader("X-Stripe-Client-Telemetry"); ClientTelemetryPayload payload = ApiResource.GSON.fromJson( telemetry2, ClientTelemetryPayload.class); seenRequestIds.add(payload.lastRequestMetrics.requestId); } // check that each telemetry payload corresponds to a unique request id assertEquals(10, seenRequestIds.size()); server.shutdown(); } }
package com.vryba.selenium; import com.vryba.selenium.pageObjects.HomePage; import com.vryba.selenium.pageObjects.NavigationBar; import com.vryba.selenium.pageObjects.QuestionsPage; import com.vryba.selenium.utilities.TestBase; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.Assert; import org.testng.annotations.Test; public class NavigationBar_TC extends TestBase{ private Logger LOG = LogManager.getLogger(NavigationBar_TC.class); @Test public void checkActiveNavBarListItem() { LOG.info("Start Test: checkActiveNavBarListItem"); NavigationBar navbar = new NavigationBar(); navbar.questionsNavBarListItem.click(); Assert.assertEquals(navbar.questionsNavBarListItem.getAttribute("class"), "-item _current"); LOG.info("Questions tab is active"); } }
package de.ganskef.test; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import java.io.File; import java.io.RandomAccessFile; import java.net.URI; import java.nio.channels.FileChannel; import org.apache.commons.io.IOUtils; public class NettyClient_NoHttps { public File get(String url, IProxy proxy, String target) throws Exception { return get(new URI(url), url, "127.0.0.1", proxy.getProxyPort(), target); } public File get(String url, IProxy proxy) throws Exception { return get(new URI(url), url, "127.0.0.1", proxy.getProxyPort(), "proxy.out"); } public File get(String url) throws Exception { return get(url, "client.out"); } public File get(String url, String target) throws Exception { URI uri = new URI(url); String host = uri.getHost(); int port = uri.getPort(); if (port == -1) { if (isSecured(uri)) { port = 443; } else { port = 80; } } return get(uri, uri.getRawPath(), host, port, target); } private boolean isSecured(URI uri) { // XXX https via offline proxy won't work with this client. I mean, this // was my experience while debugging it. I had no success with Apache // HC, too. Only URLConnection works like expected for me. // It seems to me we have to wait for a proper solution - see: // https://github.com/netty/netty/issues/1133#event-299614098 // normanmaurer modified the milestone: 4.1.0.Beta5, 4.1.0.Beta6 // return uri.getScheme().equalsIgnoreCase("https"); return false; } private File get(URI uri, String url, String proxyHost, int proxyPort, final String target) throws Exception { final SslContext sslCtx; if (isSecured(uri)) { sslCtx = SslContext .newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } final NettyClientHandler handler = new NettyClientHandler(target); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .handler(new NettyClientInitializer(sslCtx, handler)); // .handler(new HttpSnoopClientInitializer(sslCtx)); Channel ch = b.connect(proxyHost, proxyPort).sync().channel(); HttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, url); request.headers().set(HttpHeaders.Names.HOST, uri.getHost()); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); ch.writeAndFlush(request); ch.closeFuture().sync(); } finally { group.shutdownGracefully(); } return handler.getFile(); } } class NettyClientHandler extends SimpleChannelInboundHandler<HttpObject> { private File file; public NettyClientHandler(String target) { File dir = new File("src/test/resources/tmp"); dir.mkdirs(); file = new File(dir, target); file.delete(); } @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; RandomAccessFile output = null; FileChannel oc = null; try { output = new RandomAccessFile(file, "rw"); oc = output.getChannel(); oc.position(oc.size()); ByteBuf buffer = content.content(); for (int i = 0, len = buffer.nioBufferCount(); i < len; i++) { oc.write(buffer.nioBuffers()[i]); } } finally { IOUtils.closeQuietly(oc); IOUtils.closeQuietly(output); } if (content instanceof LastHttpContent) { ctx.close(); } } } public File getFile() { return file; } } class NettyClientInitializer extends ChannelInitializer<SocketChannel> { private ChannelHandler handler; private SslContext sslCtx; public NettyClientInitializer(SslContext sslCtx, ChannelHandler handler) { this.sslCtx = sslCtx; this.handler = handler; } @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast("log", new LoggingHandler(LogLevel.TRACE)); p.addLast("codec", new HttpClientCodec()); p.addLast("inflater", new HttpContentDecompressor()); // p.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024)); p.addLast("handler", handler); } }
package de.railroad.rasproc.tools; import static org.junit.Assert.fail; import java.io.EOFException; import java.io.IOException; import org.junit.Before; import org.junit.Test; public class ToolsTest { @Before public void setUp() throws Exception { } @Test public void testGetUInt32() throws EOFException, IOException { byte[] b = new byte[] { 0x00, 0x30, 0x00, 0x00 }; long value = Tools.getUInt32(b); System.out.println(value); } @Test public void testToByteArray() { //fail("Not yet implemented"); } }
package junitparams; import static junitparams.JUnitParamsRunner.*; import static org.junit.Assert.*; import java.lang.reflect.*; import org.junit.*; import org.junit.internal.matchers.*; import org.junit.rules.*; import org.junit.runner.*; import org.junit.runners.model.*; @RunWith(JUnitParamsRunner.class) public class ParametersProvidersTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test @Parameters(source = SingleParamSetProvider.class) public void oneParamSetFromClass(String a, String b) { } static class SingleParamSetProvider { public static Object[] provideOneParamSetSameTypes() { return $($("a", "b")); } } @Test public void shouldPutProviderClassNameInExceptionMessageForProviderWithNoValidMethods() { ParameterisedTestMethodRunner runner = new ParameterisedTestMethodRunner(getTestMethodWithInvalidProvider()); exception.expect(RuntimeException.class); exception.expectMessage(new StringContains(ProviderClassWithNoValidMethods.class.getName())); runner.paramsFromAnnotation(); } private TestMethod getTestMethodWithInvalidProvider() { Method testMethod = TestClassWithProviderClassWithNoValidMethods.class.getMethods()[0]; return new TestMethod(new FrameworkMethod(testMethod), new TestClass(TestClassWithProviderClassWithNoValidMethods.class)); } @RunWith(JUnitParamsRunner.class) static class TestClassWithProviderClassWithNoValidMethods { @Test @Parameters(source = ProviderClassWithNoValidMethods.class) public void shouldDoNothingItsJustToConnectTestClassWithProvider() { } } static class ProviderClassWithNoValidMethods { } @Test @Parameters(source = OneIntegerProvider.class) public void providedPrimitiveParams(int integer) { assertTrue(integer < 4); } public static class OneIntegerProvider { public static Object[] provideTwoNumbers() { return $($(1), $(2)); } public static Object[] provideOneNumber() { return new Object[] { $(3) }; } } @Test @Parameters(source = DomainObjectProvider.class) public void providedDomainParams(DomainClass object1, DomainClass object2) { assertEquals("dupa1", object1.toString()); assertEquals("dupa2", object2.toString()); } public static class DomainObjectProvider { public static Object[] provideDomainObject() { return new Object[] { new Object[] { new DomainClass("dupa1"), new DomainClass("dupa2") } }; } } public static class DomainClass { private final String name; public DomainClass(String name) { this.name = name; } @Override public String toString() { return name; } } }
package mho.wheels.math; import mho.wheels.iterables.ExhaustiveProvider; import mho.wheels.iterables.IterableProvider; import mho.wheels.iterables.IterableUtils; import mho.wheels.iterables.RandomProvider; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigInteger; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.iterables.IterableUtils.tail; import static mho.wheels.math.MathUtils.*; import static mho.wheels.ordering.Ordering.*; import static org.junit.Assert.*; public class MathUtilsProperties { private static boolean USE_RANDOM; private static int LIMIT; private static IterableProvider P; private static void initialize() { if (USE_RANDOM) { P = new RandomProvider(new Random(0x6af477d9a7e54fcaL)); LIMIT = 1000; } else { P = ExhaustiveProvider.INSTANCE; LIMIT = 10000; } } @Test public void testAllProperties() { System.out.println("MathUtils properties"); for (boolean useRandom : Arrays.asList(false, true)) { System.out.println("\ttesting " + (useRandom ? "randomly" : "exhaustively")); USE_RANDOM = useRandom; propertiesGcd_int_int(); compareImplementationsGcd_int_int(); propertiesGcd_long_long(); compareImplementationsGcd_long_long(); propertiesBits_int(); compareImplementationsBits_int(); propertiesBits_BigInteger(); compareImplementationsBits_BigInteger(); propertiesBitsPadded_int_int(); compareImplementationsBitsPadded_int_int(); propertiesBitsPadded_int_BigInteger(); propertiesBigEndianBits_int(); compareImplementationsBigEndianBits_int(); propertiesBigEndianBits_BigInteger(); propertiesBigEndianBitsPadded_int_int(); compareImplementationsBigEndianBitsPadded_int_int(); propertiesBigEndianBitsPadded_int_BigInteger(); propertiesFromBigEndianBits(); propertiesFromBits(); propertiesDigits_int_int(); compareImplementationsDigits_int_int(); propertiesDigits_BigInteger_BigInteger(); propertiesDigitsPadded_int_int_int(); compareImplementationsDigitsPadded_int_int_int(); propertiesDigitsPadded_int_BigInteger_BigInteger(); propertiesBigEndianDigits_int_int(); compareImplementationsBigEndianDigits_int_int(); propertiesBigEndianDigits_BigInteger_BigInteger(); propertiesBigEndianDigitsPadded_int_int_int(); compareImplementationsBigEndianDigitsPadded_int_int_int(); propertiesBigEndianDigitsPadded_int_BigInteger_BigInteger(); propertiesFromDigits_int_Iterable_Integer(); compareImplementationsFromDigits_int_Iterable_Integer(); propertiesFromDigits_int_Iterable_BigInteger(); propertiesFromBigEndianDigits_int_Iterable_Integer(); compareImplementationsFromBigEndianDigits_int_Iterable_Integer(); propertiesFromBigEndianDigits_int_Iterable_BigInteger(); propertiesToDigit(); propertiesFromDigit(); propertiesToStringBase_int_int(); compareImplementationsToStringBase_int_int(); propertiesToStringBase_BigInteger_BigInteger(); propertiesFromStringBase_int_String(); compareImplementationsFromStringBase_int_String(); propertiesFromStringBase_BigInteger_String(); propertiesLogarithmicMux(); propertiesLogarithmicDemux(); propertiesSquareRootMux(); propertiesSquareRootDemux(); } System.out.println("Done"); } private static int gcd_int_int_simplest(int x, int y) { return BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue(); } private static int gcd_int_int_explicit(int x, int y) { x = Math.abs(x); y = Math.abs(y); if (x == 0) return y; if (y == 0) return x; return maximum(intersect(factors(x), factors(y))); } private static void propertiesGcd_int_int() { initialize(); System.out.println("\t\ttesting gcd(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; int gcd = gcd(p.a, p.b); assertEquals(p.toString(), gcd, gcd_int_int_simplest(p.a, p.b)); assertEquals(p.toString(), gcd, gcd_int_int_explicit(p.a, p.b)); assertTrue(p.toString(), gcd >= 0); assertEquals(p.toString(), gcd, gcd(Math.abs(p.a), Math.abs(p.b))); } } private static void compareImplementationsGcd_int_int() { initialize(); System.out.println("\t\tcomparing gcd(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_int_int_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_int_int_explicit(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\texplicit: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static long gcd_long_long_simplest(long x, long y) { return BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).longValue(); } private static long gcd_long_long_explicit(long x, long y) { x = Math.abs(x); y = Math.abs(y); if (x == 0) return y; if (y == 0) return x; return maximum(intersect(factors(BigInteger.valueOf(x)), factors(BigInteger.valueOf(y)))).longValue(); } private static void propertiesGcd_long_long() { initialize(); System.out.println("\t\ttesting gcd(long, long) properties..."); Iterable<Pair<Long, Long>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.longs())); for (Pair<Long, Long> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; long gcd = gcd(p.a, p.b); assertEquals(p.toString(), gcd, gcd_long_long_simplest(p.a, p.b)); if (Math.abs(p.a) <= Integer.MAX_VALUE && Math.abs(p.b) <= Integer.MAX_VALUE) { assertEquals(p.toString(), gcd, gcd_long_long_explicit(p.a, p.b)); } assertTrue(p.toString(), gcd >= 0); assertEquals(p.toString(), gcd, gcd(Math.abs(p.a), Math.abs(p.b))); } } private static void compareImplementationsGcd_long_long() { initialize(); System.out.println("\t\tcomparing gcd(long, long) implementations..."); long totalTime = 0; Iterable<Pair<Long, Long>> ps = filter(p -> p.a != 0 || p.b != 0, P.pairs(P.longs())); for (Pair<Long, Long> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_long_long_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); if (P instanceof ExhaustiveProvider) { for (Pair<Long, Long> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd_long_long_explicit(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\texplicit: " + ((double) totalTime) / 1e9 + " s"); } else { System.out.println("\t\t\texplicit: too long"); } totalTime = 0; for (Pair<Long, Long> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; gcd(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static @NotNull Iterable<Boolean> bits_int_simplest(int n) { return bits(BigInteger.valueOf(n)); } private static void propertiesBits_int() { initialize(); System.out.println("\t\ttesting bits(int) properties..."); for (int i : take(LIMIT, P.naturalIntegers())) { List<Boolean> bits = toList(bits(i)); aeq(Integer.toString(i), bits, bits_int_simplest(i)); aeq(Integer.toString(i), bits, reverse(bigEndianBits(i))); assertTrue(Integer.toString(i), all(b -> b != null, bits)); assertEquals(Integer.toString(i), fromBits(bits).intValueExact(), i); assertEquals(Integer.toString(i), bits.size(), BigInteger.valueOf(i).bitLength()); } for (int i : take(LIMIT, P.positiveIntegers())) { List<Boolean> bits = toList(bits(i)); assertFalse(Integer.toString(i), bits.isEmpty()); assertEquals(Integer.toString(i), last(bits), true); } for (int i : take(LIMIT, P.negativeIntegers())) { try { bits(i); fail(Integer.toString(i)); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBits_int() { initialize(); System.out.println("\t\tcomparing bits(int) implementations..."); long totalTime = 0; for (int i : take(LIMIT, P.naturalIntegers())) { long time = System.nanoTime(); toList(bits_int_simplest(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (int i : take(LIMIT, P.naturalIntegers())) { long time = System.nanoTime(); toList(bits(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static @NotNull Iterable<Boolean> bits_BigInteger_alt(@NotNull BigInteger n) { return () -> new Iterator<Boolean>() { private BigInteger remaining = n; @Override public boolean hasNext() { return !remaining.equals(BigInteger.ZERO); } @Override public Boolean next() { boolean bit = remaining.testBit(0); remaining = remaining.shiftRight(1); return bit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } private static void propertiesBits_BigInteger() { initialize(); System.out.println("\t\ttesting bits(BigInteger) properties..."); for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { List<Boolean> bits = toList(bits(i)); aeq(i.toString(), bits, bits_BigInteger_alt(i)); aeq(i.toString(), bits, reverse(bigEndianBits(i))); assertTrue(i.toString(), all(b -> b != null, bits)); assertEquals(i.toString(), fromBits(bits), i); assertEquals(i.toString(), bits.size(), i.bitLength()); } for (BigInteger i : take(LIMIT, P.positiveBigIntegers())) { List<Boolean> bits = toList(bits(i)); assertFalse(i.toString(), bits.isEmpty()); assertEquals(i.toString(), last(bits), true); } for (BigInteger i : take(LIMIT, P.negativeBigIntegers())) { try { bits(i); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBits_BigInteger() { initialize(); System.out.println("\t\tcomparing bits(BigInteger) implementations..."); long totalTime = 0; for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { long time = System.nanoTime(); toList(bits_BigInteger_alt(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\talt: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { long time = System.nanoTime(); toList(bits(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static @NotNull Iterable<Boolean> bitsPadded_int_int_simplest(int length, int n) { return bitsPadded(length, BigInteger.valueOf(n)); } private static void propertiesBitsPadded_int_int() { initialize(); System.out.println("\t\ttesting bitsPadded(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers()); } else { ps = P.pairs(P.naturalIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bitsPadded(p.b, p.a)); aeq(p.toString(), bits, bitsPadded_int_int_simplest(p.b, p.a)); aeq(p.toString(), bits, reverse(bigEndianBitsPadded(p.b, p.a))); assertTrue(p.toString(), all(b -> b != null, bits)); assertEquals(p.toString(), Integer.valueOf(bits.size()), p.b); } ps = P.dependentPairsLogarithmic(P.naturalIntegers(), i -> range(BigInteger.valueOf(i).bitLength())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bitsPadded(p.b, p.a)); assertEquals(p.toString(), Integer.valueOf(fromBits(bits).intValueExact()), p.a); } Iterable<Pair<Integer, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.negativeIntegers()); } else { psFail = P.pairs(P.naturalIntegers(), ((RandomProvider) P).negativeIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.negativeIntegers(), P.naturalIntegers()); } else { psFail = P.pairs(P.negativeIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBitsPadded_int_int() { initialize(); System.out.println("\t\tcomparing bitsPadded(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers()); } else { ps = P.pairs(P.naturalIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; toList(bitsPadded_int_int_simplest(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; toList(bitsPadded(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesBitsPadded_int_BigInteger() { initialize(); System.out.println("\t\ttesting bitsPadded(int, BigInteger) properties..."); Iterable<Pair<BigInteger, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalBigIntegers(), P.naturalIntegers()); } else { ps = P.pairs(P.naturalBigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bitsPadded(p.b, p.a)); aeq(p.toString(), bits, reverse(bigEndianBitsPadded(p.b, p.a))); assertTrue(p.toString(), all(b -> b != null, bits)); assertEquals(p.toString(), Integer.valueOf(bits.size()), p.b); } ps = P.dependentPairsLogarithmic(P.naturalBigIntegers(), i -> range(i.bitLength())); for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bitsPadded(p.b, p.a)); assertEquals(p.toString(), fromBits(bits), p.a); } Iterable<Pair<BigInteger, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalBigIntegers(), P.negativeIntegers()); } else { psFail = P.pairs(P.naturalBigIntegers(), ((RandomProvider) P).negativeIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.negativeBigIntegers(), P.naturalIntegers()); } else { psFail = P.pairs(P.negativeBigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static @NotNull Iterable<Boolean> bigEndianBits_int_simplest(int n) { return bigEndianBits(BigInteger.valueOf(n)); } private static void propertiesBigEndianBits_int() { initialize(); System.out.println("\t\ttesting bigEndianBits(int) properties..."); for (int i : take(LIMIT, P.naturalIntegers())) { List<Boolean> bits = toList(bigEndianBits(i)); aeq(Integer.toString(i), bits, bigEndianBits_int_simplest(i)); aeq(Integer.toString(i), bits, reverse(bits(i))); assertTrue(Integer.toString(i), all(b -> b != null, bits)); assertEquals(Integer.toString(i), fromBigEndianBits(bits).intValueExact(), i); assertEquals(Integer.toString(i), bits.size(), BigInteger.valueOf(i).bitLength()); } for (int i : take(LIMIT, P.positiveIntegers())) { List<Boolean> bits = toList(bigEndianBits(i)); assertFalse(Integer.toString(i), bits.isEmpty()); assertEquals(Integer.toString(i), head(bits), true); } for (int i : take(LIMIT, P.negativeIntegers())) { try { bigEndianBits(i); fail(Integer.toString(i)); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBigEndianBits_int() { initialize(); System.out.println("\t\tcomparing bigEndianBits(int) implementations..."); long totalTime = 0; for (int i : take(LIMIT, P.naturalIntegers())) { long time = System.nanoTime(); toList(bigEndianBits_int_simplest(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (int i : take(LIMIT, P.naturalIntegers())) { long time = System.nanoTime(); toList(bigEndianBits(i)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesBigEndianBits_BigInteger() { initialize(); System.out.println("\t\ttesting bigEndianBits(BigInteger) properties..."); for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { List<Boolean> bits = toList(bigEndianBits(i)); aeq(i.toString(), bits, reverse(bits(i))); assertTrue(i.toString(), all(b -> b != null, bits)); assertEquals(i.toString(), fromBigEndianBits(bits), i); assertEquals(i.toString(), bits.size(), i.bitLength()); } for (BigInteger i : take(LIMIT, P.positiveBigIntegers())) { List<Boolean> bits = toList(bigEndianBits(i)); assertFalse(i.toString(), bits.isEmpty()); assertEquals(i.toString(), head(bits), true); } for (BigInteger i : take(LIMIT, P.negativeBigIntegers())) { try { bigEndianBits(i); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static @NotNull Iterable<Boolean> bigEndianBitsPadded_int_int_simplest(int length, int n) { return bigEndianBitsPadded(length, BigInteger.valueOf(n)); } private static void propertiesBigEndianBitsPadded_int_int() { initialize(); System.out.println("\t\ttesting bigEndianBitsPadded(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers()); } else { ps = P.pairs(P.naturalIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bigEndianBitsPadded(p.b, p.a)); aeq(p.toString(), bits, bigEndianBitsPadded_int_int_simplest(p.b, p.a)); aeq(p.toString(), bits, reverse(bitsPadded(p.b, p.a))); assertTrue(p.toString(), all(b -> b != null, bits)); assertEquals(p.toString(), Integer.valueOf(bits.size()), p.b); } ps = P.dependentPairsLogarithmic(P.naturalIntegers(), i -> range(BigInteger.valueOf(i).bitLength())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bigEndianBitsPadded(p.b, p.a)); assertEquals(p.toString(), Integer.valueOf(fromBigEndianBits(bits).intValueExact()), p.a); } Iterable<Pair<Integer, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.negativeIntegers()); } else { psFail = P.pairs(P.naturalIntegers(), ((RandomProvider) P).negativeIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianBitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.negativeIntegers(), P.naturalIntegers()); } else { psFail = P.pairs(P.negativeIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianBitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBigEndianBitsPadded_int_int() { initialize(); System.out.println("\t\tcomparing bigEndianBitsPadded(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers()); } else { ps = P.pairs(P.naturalIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; toList(bigEndianBitsPadded_int_int_simplest(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; toList(bigEndianBitsPadded(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesBigEndianBitsPadded_int_BigInteger() { initialize(); System.out.println("\t\ttesting bigEndianBitsPadded(int, BigInteger) properties..."); Iterable<Pair<BigInteger, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalBigIntegers(), P.naturalIntegers()); } else { ps = P.pairs(P.naturalBigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bigEndianBitsPadded(p.b, p.a)); aeq(p.toString(), bits, reverse(bitsPadded(p.b, p.a))); assertTrue(p.toString(), all(b -> b != null, bits)); assertEquals(p.toString(), Integer.valueOf(bits.size()), p.b); } ps = P.dependentPairsLogarithmic(P.naturalBigIntegers(), i -> range(i.bitLength())); for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Boolean> bits = toList(bigEndianBitsPadded(p.b, p.a)); assertEquals(p.toString(), fromBigEndianBits(bits), p.a); } Iterable<Pair<BigInteger, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalBigIntegers(), P.negativeIntegers()); } else { psFail = P.pairs(P.naturalBigIntegers(), ((RandomProvider) P).negativeIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianBitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.negativeBigIntegers(), P.naturalIntegers()); } else { psFail = P.pairs(P.negativeBigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianBitsPadded(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesFromBits() { initialize(); System.out.println("\t\ttesting fromBits(Iterable<Boolean>) properties..."); for (List<Boolean> bs : take(LIMIT, P.lists(P.booleans()))) { BigInteger i = fromBits(bs); assertTrue(bs.toString(), i.signum() != -1); assertEquals(bs.toString(), i, fromBigEndianBits(reverse(bs))); } Iterable<List<Boolean>> bss = map(xs -> toList(concat(xs, Arrays.asList(true))), P.lists(P.booleans())); for (List<Boolean> bs : take(LIMIT, bss)) { BigInteger i = fromBits(bs); aeq(bs.toString(), bs, bits(i)); } Iterable<List<Boolean>> failBss = map(p -> { assert p.a != null; assert p.b != null; return toList(insert(p.a, p.b, null)); }, (Iterable<Pair<List<Boolean>, Integer>>) P.dependentPairsLogarithmic( P.lists(P.booleans()), bs -> range(0, bs.size()) )); for (List<Boolean> bs : take(LIMIT, failBss)) { try { fromBits(bs); fail(bs.toString()); } catch (NullPointerException ignored) {} } } private static void propertiesFromBigEndianBits() { initialize(); System.out.println("\t\ttesting fromBigEndianBits(Iterable<Boolean>) properties..."); for (List<Boolean> bs : take(LIMIT, P.lists(P.booleans()))) { BigInteger i = fromBigEndianBits(bs); assertTrue(bs.toString(), i.signum() != -1); assertEquals(bs.toString(), i, fromBits(reverse(bs))); } for (List<Boolean> bs : take(LIMIT, map(xs -> toList(cons(true, xs)), P.lists(P.booleans())))) { BigInteger i = fromBigEndianBits(bs); aeq(bs.toString(), bs, bigEndianBits(i)); } Iterable<List<Boolean>> failBss = map(p -> { assert p.a != null; assert p.b != null; return toList(insert(p.a, p.b, null)); }, (Iterable<Pair<List<Boolean>, Integer>>) P.dependentPairsLogarithmic( P.lists(P.booleans()), bs -> range(0, bs.size()) )); for (List<Boolean> bs : take(LIMIT, failBss)) { try { fromBigEndianBits(bs); fail(bs.toString()); } catch (NullPointerException ignored) {} } } private static @NotNull Iterable<Integer> digits_int_int_simplest(int base, int n) { return map(BigInteger::intValue, digits(BigInteger.valueOf(base), BigInteger.valueOf(n))); } private static void propertiesDigits_int_int() { initialize(); System.out.println("\t\ttesting digits(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.rangeUp(2)); } else { ps = P.pairs(P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Integer> digits = toList(digits(p.b, p.a)); aeq(p.toString(), digits, digits_int_int_simplest(p.b, p.a)); aeq(p.toString(), digits, reverse(bigEndianDigits(p.b, p.a))); assertTrue(p.toString(), all(i -> i != null && i >= 0 && i < p.b, digits)); assertEquals(p.toString(), Integer.valueOf(fromDigits(p.b, digits).intValueExact()), p.a); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.positiveIntegers(), P.rangeUp(2)); } else { ps = P.pairs(P.positiveIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Integer> digits = toList(digits(p.b, p.a)); assertFalse(p.toString(), digits.isEmpty()); assertNotEquals(p.toString(), last(digits), Integer.valueOf(0)); int targetDigitCount = ceilingLog(BigInteger.valueOf(p.b), BigInteger.valueOf(p.a)).intValueExact(); if (BigInteger.valueOf(p.b).pow(targetDigitCount).equals(BigInteger.valueOf(p.a))) { targetDigitCount++; } assertEquals(p.toString(), digits.size(), targetDigitCount); } Function<Integer, Boolean> digitsToBits = i -> { switch (i) { case 0: return false; case 1: return true; default: throw new IllegalArgumentException(); } }; for (int i : take(LIMIT, P.naturalIntegers())) { List<Integer> digits = toList(digits(2, i)); aeq(Integer.toString(i), map(digitsToBits, digits), bits(i)); } for (int i : take(LIMIT, P.rangeUp(2))) { assertTrue(Integer.toString(i), isEmpty(digits(i, 0))); } Iterable<Pair<Integer, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.rangeDown(1)); } else { psFail = P.pairs(P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { digits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.negativeIntegers(), P.rangeUp(2)); } else { psFail = P.pairs(P.negativeIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { digits(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsDigits_int_int() { initialize(); System.out.println("\t\tcomparing digits(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.rangeUp(2)); } else { ps = P.pairs(P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; long time = System.nanoTime(); toList(digits_int_int_simplest(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; long time = System.nanoTime(); toList(digits(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesDigits_BigInteger_BigInteger() { initialize(); System.out.println("\t\ttesting digits(BigInteger, BigInteger) properties..."); Iterable<Pair<BigInteger, BigInteger>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.naturalBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ); } else { ps = P.pairs( P.naturalBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<BigInteger> digits = toList(digits(p.b, p.a)); aeq(p.toString(), digits, reverse(bigEndianDigits(p.b, p.a))); assertTrue(p.toString(), all(i -> i != null && i.signum() != -1 && lt(i, p.b), digits)); assertEquals(p.toString(), fromDigits(p.b, digits), p.a); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.positiveBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ); } else { ps = P.pairs( P.positiveBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<BigInteger> digits = toList(digits(p.b, p.a)); assertFalse(p.toString(), digits.isEmpty()); assertNotEquals(p.toString(), last(digits), BigInteger.ZERO); int targetDigitCount = ceilingLog(p.b, p.a).intValueExact(); if (p.b.pow(targetDigitCount).equals(p.a)) { targetDigitCount++; } assertEquals(p.toString(), digits.size(), targetDigitCount); } Function<BigInteger, Boolean> digitsToBits = i -> { if (i.equals(BigInteger.ZERO)) return false; if (i.equals(BigInteger.ONE)) return true; throw new IllegalArgumentException(); }; for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { List<BigInteger> digits = toList(digits(BigInteger.valueOf(2), i)); aeq(i.toString(), map(digitsToBits, digits), bits(i)); } for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(2)))) { assertTrue(i.toString(), isEmpty(digits(i, BigInteger.ZERO))); } Iterable<Pair<BigInteger, BigInteger>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.naturalBigIntegers(), P.rangeDown(BigInteger.ONE) ); } else { psFail = P.pairs( P.naturalBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { digits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.negativeBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ); } else { psFail = P.pairs( P.negativeBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { digits(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static @NotNull Iterable<Integer> digitsPadded_int_int_int_simplest(int length, int base, int n) { return map(BigInteger::intValue, digitsPadded(length, BigInteger.valueOf(base), BigInteger.valueOf(n))); } private static void propertiesDigitsPadded_int_int_int() { initialize(); System.out.println("\t\ttesting digitsPadded(int, int, int) properties..."); Iterable<Triple<Integer, Integer, Integer>> ts; if (P instanceof ExhaustiveProvider) { ts = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.naturalIntegers())), P.naturalIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); ts = P.triples(is, map(i -> i + 2, is), P.naturalIntegers()); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<Integer> digits = toList(digitsPadded(t.a, t.b, t.c)); aeq(t.toString(), digits, digitsPadded_int_int_int_simplest(t.a, t.b, t.c)); aeq(t.toString(), digits, reverse(bigEndianDigitsPadded(t.a, t.b, t.c))); assertTrue(t.toString(), all(i -> i != null && i >= 0 && i < t.b, digits)); assertEquals(t.toString(), Integer.valueOf(digits.size()), t.a); } if (P instanceof ExhaustiveProvider) { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<Integer, Integer>>) ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.naturalIntegers(), P.rangeUp(2) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a > 0) { targetDigitCount = ceilingLog( BigInteger.valueOf(p.b), BigInteger.valueOf(p.a) ).intValueExact(); BigInteger x = BigInteger.valueOf(p.b).pow(targetDigitCount); BigInteger y = BigInteger.valueOf(p.a); //noinspection SuspiciousNameCombination if (x.equals(y)) { targetDigitCount++; } } return P.rangeUp(targetDigitCount); } ) ); } else { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<Integer, Integer>>) P.pairs( P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a > 0) { targetDigitCount = ceilingLog( BigInteger.valueOf(p.b), BigInteger.valueOf(p.a) ).intValueExact(); BigInteger x = BigInteger.valueOf(p.b).pow(targetDigitCount); BigInteger y = BigInteger.valueOf(p.a); //noinspection SuspiciousNameCombination if (x.equals(y)) { targetDigitCount++; } } final int c = targetDigitCount; return (Iterable<Integer>) map( i -> i + c, ((RandomProvider) P).naturalIntegersGeometric(20) ); } ) ); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<Integer> digits = toList(digitsPadded(t.a, t.b, t.c)); assertEquals(t.toString(), Integer.valueOf(fromDigits(t.b, digits).intValueExact()), t.c); } Function<Integer, Boolean> digitsToBits = i -> { switch (i) { case 0: return false; case 1: return true; default: throw new IllegalArgumentException(); } }; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers()); } else { ps = P.pairs(P.naturalIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Integer> digits = toList(digitsPadded(p.b, 2, p.a)); aeq(p.toString(), map(digitsToBits, digits), bitsPadded(p.b, p.a)); } Iterable<Triple<Integer, Integer, Integer>> tsFail; if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.naturalIntegers())), P.negativeIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); tsFail = P.triples(is, map(i -> i + 2, is), P.negativeIntegers()); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { digitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.negativeIntegers(), map(i -> i + 2, P.naturalIntegers())), P.naturalIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).negativeIntegersGeometric(20), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)), P.naturalIntegers() ); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { digitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.negativeIntegers())), P.negativeIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).naturalIntegersGeometric(20), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20)), P.negativeIntegers() ); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { digitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } } private static void compareImplementationsDigitsPadded_int_int_int() { initialize(); System.out.println("\t\tcomparing digitsPadded(int, int, int) implementations..."); long totalTime = 0; Iterable<Triple<Integer, Integer, Integer>> ts; if (P instanceof ExhaustiveProvider) { ts = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.naturalIntegers())), P.naturalIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); ts = P.triples(is, map(i -> i + 2, is), P.naturalIntegers()); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { long time = System.nanoTime(); assert t.a != null; assert t.b != null; assert t.c != null; toList(digitsPadded_int_int_int_simplest(t.a, t.b, t.c)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { long time = System.nanoTime(); assert t.a != null; assert t.b != null; assert t.c != null; toList(digitsPadded(t.a, t.b, t.c)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesDigitsPadded_int_BigInteger_BigInteger() { initialize(); System.out.println("\t\ttesting digitsPadded(int, BigInteger, BigInteger) properties..."); Iterable<Triple<Integer, BigInteger, BigInteger>> ts; if (P instanceof ExhaustiveProvider) { ts = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> BigInteger.valueOf(i + 2), P.naturalIntegers())), P.naturalBigIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); ts = P.triples(is, map(i -> BigInteger.valueOf(i + 2), is), P.naturalBigIntegers()); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<BigInteger> digits = toList(digitsPadded(t.a, t.b, t.c)); aeq(t.toString(), digits, reverse(bigEndianDigitsPadded(t.a, t.b, t.c))); assertTrue(t.toString(), all(i -> i != null && i.signum() != -1 && lt(i, t.b), digits)); assertEquals(t.toString(), Integer.valueOf(digits.size()), t.a); } if (P instanceof ExhaustiveProvider) { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<BigInteger, BigInteger>>) ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.naturalBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a.signum() == 1) { targetDigitCount = ceilingLog(p.b, p.a).intValueExact(); //noinspection SuspiciousNameCombination if (p.b.pow(targetDigitCount).equals(p.a)) { targetDigitCount++; } } return P.rangeUp(targetDigitCount); } ) ); } else { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<BigInteger, BigInteger>>) P.pairs( P.naturalBigIntegers(), map( i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20) ) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a.signum() == 1) { targetDigitCount = ceilingLog(p.b, p.a).intValueExact(); //noinspection SuspiciousNameCombination if (p.b.pow(targetDigitCount).equals(p.a)) { targetDigitCount++; } } final int c = targetDigitCount; return (Iterable<Integer>) map( i -> i + c, ((RandomProvider) P).naturalIntegersGeometric(20) ); } ) ); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<BigInteger> digits = toList(digitsPadded(t.a, t.b, t.c)); assertEquals(t.toString(), fromDigits(t.b, digits), t.c); } Function<BigInteger, Boolean> digitsToBits = i -> { if (i.equals(BigInteger.ZERO)) return false; if (i.equals(BigInteger.ONE)) return true; throw new IllegalArgumentException(); }; Iterable<Pair<BigInteger, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalBigIntegers(), P.naturalIntegers()); } else { ps = P.pairs(P.naturalBigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<BigInteger> digits = toList(digitsPadded(p.b, BigInteger.valueOf(2), p.a)); aeq(p.toString(), map(digitsToBits, digits), bitsPadded(p.b, p.a)); } Iterable<Triple<Integer, BigInteger, BigInteger>> tsFail; if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs( P.naturalIntegers(), map(i -> i.add(BigInteger.valueOf(2)), P.naturalBigIntegers()) ), P.negativeBigIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); tsFail = P.triples(is, map(i -> BigInteger.valueOf(i + 2), is), P.negativeBigIntegers()); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { digitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs( P.negativeIntegers(), map(i -> i.add(BigInteger.valueOf(2)), P.naturalBigIntegers()) ), P.naturalBigIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).negativeIntegersGeometric(20), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)), P.naturalBigIntegers() ); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { digitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> BigInteger.valueOf(i + 2), P.negativeIntegers())), P.negativeBigIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).naturalIntegersGeometric(20), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)), P.negativeBigIntegers() ); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { digitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } } private static @NotNull Iterable<Integer> bigEndianDigits_int_int_simplest(int base, int n) { return map(BigInteger::intValue, bigEndianDigits(BigInteger.valueOf(base), BigInteger.valueOf(n))); } private static void propertiesBigEndianDigits_int_int() { initialize(); System.out.println("\t\ttesting bigEndianDigits(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.rangeUp(2)); } else { ps = P.pairs(P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Integer> digits = toList(bigEndianDigits(p.b, p.a)); aeq(p.toString(), digits, bigEndianDigits_int_int_simplest(p.b, p.a)); aeq(p.toString(), digits, reverse(digits(p.b, p.a))); assertTrue(p.toString(), all(i -> i != null && i >= 0 && i < p.b, digits)); assertEquals(p.toString(), Integer.valueOf(fromBigEndianDigits(p.b, digits).intValueExact()), p.a); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.positiveIntegers(), P.rangeUp(2)); } else { ps = P.pairs(P.positiveIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Integer> digits = toList(bigEndianDigits(p.b, p.a)); assertFalse(p.toString(), digits.isEmpty()); assertNotEquals(p.toString(), head(digits), Integer.valueOf(0)); int targetDigitCount = ceilingLog(BigInteger.valueOf(p.b), BigInteger.valueOf(p.a)).intValueExact(); if (BigInteger.valueOf(p.b).pow(targetDigitCount).equals(BigInteger.valueOf(p.a))) { targetDigitCount++; } assertEquals(p.toString(), digits.size(), targetDigitCount); } Function<Integer, Boolean> digitsToBits = i -> { switch (i) { case 0: return false; case 1: return true; default: throw new IllegalArgumentException(); } }; for (int i : take(LIMIT, P.naturalIntegers())) { List<Integer> digits = toList(bigEndianDigits(2, i)); aeq(Integer.toString(i), map(digitsToBits, digits), bigEndianBits(i)); } for (int i : take(LIMIT, P.rangeUp(2))) { assertTrue(Integer.toString(i), isEmpty(bigEndianDigits(i, 0))); } Iterable<Pair<Integer, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.rangeDown(1)); } else { psFail = P.pairs(P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.negativeIntegers(), P.rangeUp(2)); } else { psFail = P.pairs(P.negativeIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianDigits(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void compareImplementationsBigEndianDigits_int_int() { initialize(); System.out.println("\t\tcomparing bigEndianDigits(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers(), P.rangeUp(2)); } else { ps = P.pairs(P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; long time = System.nanoTime(); toList(bigEndianDigits_int_int_simplest(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; long time = System.nanoTime(); toList(bigEndianDigits(p.b, p.a)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesBigEndianDigits_BigInteger_BigInteger() { initialize(); System.out.println("\t\ttesting bigEndianDigits(BigInteger, BigInteger) properties..."); Iterable<Pair<BigInteger, BigInteger>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.naturalBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ); } else { ps = P.pairs( P.naturalBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<BigInteger> digits = toList(bigEndianDigits(p.b, p.a)); aeq(p.toString(), digits, reverse(digits(p.b, p.a))); assertTrue(p.toString(), all(i -> i != null && i.signum() != -1 && lt(i, p.b), digits)); assertEquals(p.toString(), fromBigEndianDigits(p.b, digits), p.a); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.positiveBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ); } else { ps = P.pairs( P.positiveBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<BigInteger> digits = toList(bigEndianDigits(p.b, p.a)); assertFalse(p.toString(), digits.isEmpty()); assertNotEquals(p.toString(), head(digits), BigInteger.ZERO); int targetDigitCount = ceilingLog(p.b, p.a).intValueExact(); if (p.b.pow(targetDigitCount).equals(p.a)) { targetDigitCount++; } assertEquals(p.toString(), digits.size(), targetDigitCount); } Function<BigInteger, Boolean> digitsToBits = i -> { if (i.equals(BigInteger.ZERO)) return false; if (i.equals(BigInteger.ONE)) return true; throw new IllegalArgumentException(); }; for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { List<BigInteger> digits = toList(bigEndianDigits(BigInteger.valueOf(2), i)); aeq(i.toString(), map(digitsToBits, digits), bigEndianBits(i)); } for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(2)))) { assertTrue(i.toString(), isEmpty(bigEndianDigits(i, BigInteger.ZERO))); } Iterable<Pair<BigInteger, BigInteger>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.naturalBigIntegers(), P.rangeDown(BigInteger.ONE) ); } else { psFail = P.pairs( P.naturalBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.negativeBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ); } else { psFail = P.pairs( P.negativeBigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { bigEndianDigits(p.b, p.a); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static @NotNull Iterable<Integer> bigEndianDigitsPadded_int_int_int_simplest(int length, int base, int n) { return map( BigInteger::intValue, bigEndianDigitsPadded(length, BigInteger.valueOf(base), BigInteger.valueOf(n)) ); } private static void propertiesBigEndianDigitsPadded_int_int_int() { initialize(); System.out.println("\t\ttesting bigEndianDigitsPadded(int, int, int) properties..."); Iterable<Triple<Integer, Integer, Integer>> ts; if (P instanceof ExhaustiveProvider) { ts = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.naturalIntegers())), P.naturalIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); ts = P.triples(is, map(i -> i + 2, is), P.naturalIntegers()); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<Integer> digits = toList(bigEndianDigitsPadded(t.a, t.b, t.c)); aeq(t.toString(), digits, bigEndianDigitsPadded_int_int_int_simplest(t.a, t.b, t.c)); aeq(t.toString(), digits, reverse(digitsPadded(t.a, t.b, t.c))); assertTrue(t.toString(), all(i -> i != null && i >= 0 && i < t.b, digits)); assertEquals(t.toString(), Integer.valueOf(digits.size()), t.a); } if (P instanceof ExhaustiveProvider) { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<Integer, Integer>>) ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.naturalIntegers(), P.rangeUp(2) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a > 0) { targetDigitCount = ceilingLog( BigInteger.valueOf(p.b), BigInteger.valueOf(p.a) ).intValueExact(); BigInteger x = BigInteger.valueOf(p.b).pow(targetDigitCount); BigInteger y = BigInteger.valueOf(p.a); //noinspection SuspiciousNameCombination if (x.equals(y)) { targetDigitCount++; } } return P.rangeUp(targetDigitCount); } ) ); } else { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<Integer, Integer>>) P.pairs( P.naturalIntegers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a > 0) { targetDigitCount = ceilingLog( BigInteger.valueOf(p.b), BigInteger.valueOf(p.a) ).intValueExact(); BigInteger x = BigInteger.valueOf(p.b).pow(targetDigitCount); BigInteger y = BigInteger.valueOf(p.a); //noinspection SuspiciousNameCombination if (x.equals(y)) { targetDigitCount++; } } final int c = targetDigitCount; return (Iterable<Integer>) map( i -> i + c, ((RandomProvider) P).naturalIntegersGeometric(20) ); } ) ); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<Integer> digits = toList(bigEndianDigitsPadded(t.a, t.b, t.c)); assertEquals(t.toString(), Integer.valueOf(fromBigEndianDigits(t.b, digits).intValueExact()), t.c); } Function<Integer, Boolean> digitsToBits = i -> { switch (i) { case 0: return false; case 1: return true; default: throw new IllegalArgumentException(); } }; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalIntegers()); } else { ps = P.pairs(P.naturalIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<Integer> digits = toList(bigEndianDigitsPadded(p.b, 2, p.a)); aeq(p.toString(), map(digitsToBits, digits), bigEndianBitsPadded(p.b, p.a)); } Iterable<Triple<Integer, Integer, Integer>> tsFail; if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.naturalIntegers())), P.negativeIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); tsFail = P.triples(is, map(i -> i + 2, is), P.negativeIntegers()); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { bigEndianDigitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.negativeIntegers(), map(i -> i + 2, P.naturalIntegers())), P.naturalIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).negativeIntegersGeometric(20), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)), P.naturalIntegers() ); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { bigEndianDigitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.negativeIntegers())), P.negativeIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).naturalIntegersGeometric(20), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20)), P.negativeIntegers() ); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { bigEndianDigitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } } private static void compareImplementationsBigEndianDigitsPadded_int_int_int() { initialize(); System.out.println("\t\tcomparing bigEndianDigitsPadded(int, int, int) implementations..."); long totalTime = 0; Iterable<Triple<Integer, Integer, Integer>> ts; if (P instanceof ExhaustiveProvider) { ts = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, Integer>, Integer>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> i + 2, P.naturalIntegers())), P.naturalIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); ts = P.triples(is, map(i -> i + 2, is), P.naturalIntegers()); } for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { long time = System.nanoTime(); assert t.a != null; assert t.b != null; assert t.c != null; toList(bigEndianDigitsPadded_int_int_int_simplest(t.a, t.b, t.c)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) { long time = System.nanoTime(); assert t.a != null; assert t.b != null; assert t.c != null; toList(bigEndianDigitsPadded(t.a, t.b, t.c)); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesBigEndianDigitsPadded_int_BigInteger_BigInteger() { initialize(); System.out.println("\t\ttesting bigEndianDigitsPadded(int, BigInteger, BigInteger) properties..."); Iterable<Triple<Integer, BigInteger, BigInteger>> ts; if (P instanceof ExhaustiveProvider) { ts = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> BigInteger.valueOf(i + 2), P.naturalIntegers())), P.naturalBigIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); ts = P.triples(is, map(i -> BigInteger.valueOf(i + 2), is), P.naturalBigIntegers()); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<BigInteger> digits = toList(bigEndianDigitsPadded(t.a, t.b, t.c)); aeq(t.toString(), digits, reverse(digitsPadded(t.a, t.b, t.c))); assertTrue(t.toString(), all(i -> i != null && i.signum() != -1 && lt(i, t.b), digits)); assertEquals(t.toString(), Integer.valueOf(digits.size()), t.a); } if (P instanceof ExhaustiveProvider) { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<BigInteger, BigInteger>>) ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.naturalBigIntegers(), P.rangeUp(BigInteger.valueOf(2)) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a.signum() == 1) { targetDigitCount = ceilingLog(p.b, p.a).intValueExact(); //noinspection SuspiciousNameCombination if (p.b.pow(targetDigitCount).equals(p.a)) { targetDigitCount++; } } return P.rangeUp(targetDigitCount); } ) ); } else { ts = map( q -> { assert q.a != null; return new Triple<>(q.b, q.a.b, q.a.a); }, P.dependentPairsLogarithmic( (Iterable<Pair<BigInteger, BigInteger>>) P.pairs( P.naturalBigIntegers(), map( i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20) ) ), p -> { assert p.a != null; assert p.b != null; int targetDigitCount = 0; if (p.a.signum() == 1) { targetDigitCount = ceilingLog(p.b, p.a).intValueExact(); //noinspection SuspiciousNameCombination if (p.b.pow(targetDigitCount).equals(p.a)) { targetDigitCount++; } } final int c = targetDigitCount; return (Iterable<Integer>) map( i -> i + c, ((RandomProvider) P).naturalIntegersGeometric(20) ); } ) ); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; List<BigInteger> digits = toList(bigEndianDigitsPadded(t.a, t.b, t.c)); assertEquals(t.toString(), fromBigEndianDigits(t.b, digits), t.c); } Function<BigInteger, Boolean> digitsToBits = i -> { if (i.equals(BigInteger.ZERO)) return false; if (i.equals(BigInteger.ONE)) return true; throw new IllegalArgumentException(); }; Iterable<Pair<BigInteger, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.naturalBigIntegers(), P.naturalIntegers()); } else { ps = P.pairs(P.naturalBigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; List<BigInteger> digits = toList(bigEndianDigitsPadded(p.b, BigInteger.valueOf(2), p.a)); aeq(p.toString(), map(digitsToBits, digits), bigEndianBitsPadded(p.b, p.a)); } Iterable<Triple<Integer, BigInteger, BigInteger>> tsFail; if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs( P.naturalIntegers(), map(i -> i.add(BigInteger.valueOf(2)), P.naturalBigIntegers()) ), P.negativeBigIntegers() ) ); } else { Iterable<Integer> is = ((RandomProvider) P).naturalIntegersGeometric(20); tsFail = P.triples(is, map(i -> BigInteger.valueOf(i + 2), is), P.negativeBigIntegers()); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { bigEndianDigitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs( P.negativeIntegers(), map(i -> i.add(BigInteger.valueOf(2)), P.naturalBigIntegers()) ), P.naturalBigIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).negativeIntegersGeometric(20), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)), P.naturalBigIntegers() ); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { bigEndianDigitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { tsFail = map( p -> { assert p.a != null; return new Triple<>(p.a.a, p.a.b, p.b); }, (Iterable<Pair<Pair<Integer, BigInteger>, BigInteger>>) P.pairs( P.pairs(P.naturalIntegers(), map(i -> BigInteger.valueOf(i + 2), P.negativeIntegers())), P.negativeBigIntegers() ) ); } else { tsFail = P.triples( ((RandomProvider) P).naturalIntegersGeometric(20), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)), P.negativeBigIntegers() ); } for (Triple<Integer, BigInteger, BigInteger> t : take(LIMIT, tsFail)) { assert t.a != null; assert t.b != null; assert t.c != null; try { bigEndianDigitsPadded(t.a, t.b, t.c); fail(t.toString()); } catch (IllegalArgumentException ignored) {} } } private static @NotNull BigInteger fromDigits_int_Iterable_Integer_simplest( int base, @NotNull Iterable<Integer> digits ) { //noinspection Convert2MethodRef return fromDigits(BigInteger.valueOf(base), map(i -> BigInteger.valueOf(i), digits)); } private static void propertiesFromDigits_int_Iterable_Integer() { initialize(); System.out.println("\t\ttesting fromDigits(int, Iterable<Integer>) properties..."); Iterable<Pair<List<Integer>, Integer>> unfilteredPs; if (P instanceof ExhaustiveProvider) { unfilteredPs = ((ExhaustiveProvider) P).pairsLogarithmicOrder(P.lists(P.naturalIntegers()), P.rangeUp(2)); } else { unfilteredPs = P.pairs( P.lists(((RandomProvider) P).naturalIntegersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ); } Iterable<Pair<List<Integer>, Integer>> ps = filter(p -> { assert p.a != null; return all(i -> i < p.b, p.a); }, unfilteredPs); for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromDigits(p.b, p.a); assertEquals(p.toString(), n, fromDigits_int_Iterable_Integer_simplest(p.b, p.a)); assertEquals(p.toString(), n, fromBigEndianDigits(p.b, reverse(p.a))); assertNotEquals(p.toString(), n.signum(), -1); } ps = filter(p -> { assert p.a != null; return p.a.isEmpty() || last(p.a) != 0; }, ps); for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromDigits(p.b, p.a); aeq(p.toString(), p.a, map(BigInteger::intValueExact, digits(BigInteger.valueOf(p.b), n))); } Function<Integer, Boolean> digitsToBits = i -> { switch (i) { case 0: return false; case 1: return true; default: throw new IllegalArgumentException(); } }; for (List<Integer> is : take(LIMIT, P.lists(P.range(0, 1)))) { assertEquals(is.toString(), fromDigits(2, is), fromBits(map(digitsToBits, is))); } Iterable<Pair<List<Integer>, Integer>> unfilteredPsFail; if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.integers()), P.rangeDown(1) ); } else { unfilteredPsFail = P.pairs( P.lists(((RandomProvider) P).integersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20)) ); } Iterable<Pair<List<Integer>, Integer>> psFail = filter(p -> { assert p.a != null; return all(i -> i < p.b, p.a); }, unfilteredPsFail); for (Pair<List<Integer>, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.integers()), P.rangeUp(2) ); } else { unfilteredPsFail = P.pairs( P.lists(((RandomProvider) P).integersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ); } psFail = filter(p -> { assert p.a != null; return any(i -> i < 0, p.a); }, unfilteredPsFail); for (Pair<List<Integer>, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } psFail = filter(p -> any(i -> i >= p.b, p.a), unfilteredPsFail); for (Pair<List<Integer>, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static void compareImplementationsFromDigits_int_Iterable_Integer() { initialize(); System.out.println("\t\tcomparing fromDigits(int, Iterable<Integer>) implementations..."); long totalTime = 0; Iterable<Pair<List<Integer>, Integer>> unfilteredPs; if (P instanceof ExhaustiveProvider) { unfilteredPs = ((ExhaustiveProvider) P).pairsLogarithmicOrder(P.lists(P.naturalIntegers()), P.rangeUp(2)); } else { unfilteredPs = P.pairs( P.lists(((RandomProvider) P).naturalIntegersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ); } Iterable<Pair<List<Integer>, Integer>> ps = filter(p -> all(i -> i < p.b, p.a), unfilteredPs); for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; fromDigits_int_Iterable_Integer_simplest(p.b, p.a); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; fromDigits(p.b, p.a); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesFromDigits_int_Iterable_BigInteger() { initialize(); System.out.println("\t\ttesting fromDigits(int, Iterable<BigInteger>) properties..."); Iterable<Pair<List<BigInteger>, BigInteger>> unfilteredPs; if (P instanceof ExhaustiveProvider) { unfilteredPs = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.naturalBigIntegers()), P.rangeUp(BigInteger.valueOf(2)) ); } else { unfilteredPs = P.pairs( P.lists(map(i -> BigInteger.valueOf(i), ((RandomProvider) P).naturalIntegersGeometric(10))), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } Iterable<Pair<List<BigInteger>, BigInteger>> ps = filter(p -> { assert p.a != null; return all(i -> lt(i, p.b), p.a); }, unfilteredPs); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromDigits(p.b, p.a); assertEquals(p.toString(), n, fromBigEndianDigits(p.b, reverse(p.a))); assertNotEquals(p.toString(), n.signum(), -1); } ps = filter(p -> { assert p.a != null; return p.a.isEmpty() || !last(p.a).equals(BigInteger.ZERO); }, ps); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromDigits(p.b, p.a); aeq(p.toString(), p.a, digits(p.b, n)); } Function<BigInteger, Boolean> digitsToBits = i -> { if (i.equals(BigInteger.ZERO)) return false; if (i.equals(BigInteger.ONE)) return true; throw new IllegalArgumentException(); }; for (List<BigInteger> is : take(LIMIT, P.lists(P.range(BigInteger.ZERO, BigInteger.ONE)))) { assertEquals(is.toString(), fromDigits(BigInteger.valueOf(2), is), fromBits(map(digitsToBits, is))); } Iterable<Pair<List<BigInteger>, BigInteger>> unfilteredPsFail; if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.bigIntegers()), P.rangeDown(BigInteger.ONE) ); } else { unfilteredPsFail = P.pairs( P.lists(map(i -> BigInteger.valueOf(i), ((RandomProvider) P).integersGeometric(10))), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)) ); } Iterable<Pair<List<BigInteger>, BigInteger>> psFail = filter(p -> { assert p.a != null; return all(i -> lt(i, p.b), p.a); }, unfilteredPsFail); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.bigIntegers()), P.rangeUp(BigInteger.valueOf(2)) ); } else { unfilteredPsFail = P.pairs( P.lists(map(i -> BigInteger.valueOf(i), ((RandomProvider) P).integersGeometric(10))), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } psFail = filter(p -> { assert p.a != null; return any(i -> i.signum() == -1, p.a); }, unfilteredPsFail); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } psFail = filter(p -> { assert p.a != null; return any(i -> ge(i, p.b), p.a); }, unfilteredPsFail); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static @NotNull BigInteger fromBigEndianDigits_int_Iterable_Integer_simplest( int base, @NotNull Iterable<Integer> digits ) { //noinspection Convert2MethodRef return fromBigEndianDigits(BigInteger.valueOf(base), map(i -> BigInteger.valueOf(i), digits)); } private static void propertiesFromBigEndianDigits_int_Iterable_Integer() { initialize(); System.out.println("\t\ttesting fromBigEndianDigits(int, Iterable<Integer>) properties..."); Iterable<Pair<List<Integer>, Integer>> unfilteredPs; if (P instanceof ExhaustiveProvider) { unfilteredPs = ((ExhaustiveProvider) P).pairsLogarithmicOrder(P.lists(P.naturalIntegers()), P.rangeUp(2)); } else { unfilteredPs = P.pairs( P.lists(((RandomProvider) P).naturalIntegersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ); } Iterable<Pair<List<Integer>, Integer>> ps = filter(p -> { assert p.a != null; return all(i -> i < p.b, p.a); }, unfilteredPs); for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromBigEndianDigits(p.b, p.a); assertEquals(p.toString(), n, fromBigEndianDigits_int_Iterable_Integer_simplest(p.b, p.a)); assertEquals(p.toString(), n, fromDigits(p.b, reverse(p.a))); assertNotEquals(p.toString(), n.signum(), -1); } ps = filter(p -> { assert p.a != null; return p.a.isEmpty() || head(p.a) != 0; }, ps); for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromBigEndianDigits(p.b, p.a); aeq(p.toString(), p.a, map(BigInteger::intValueExact, bigEndianDigits(BigInteger.valueOf(p.b), n))); } Function<Integer, Boolean> digitsToBits = i -> { switch (i) { case 0: return false; case 1: return true; default: throw new IllegalArgumentException(); } }; for (List<Integer> is : take(LIMIT, P.lists(P.range(0, 1)))) { assertEquals(is.toString(), fromBigEndianDigits(2, is), fromBigEndianBits(map(digitsToBits, is))); } Iterable<Pair<List<Integer>, Integer>> unfilteredPsFail; if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.integers()), P.rangeDown(1) ); } else { unfilteredPsFail = P.pairs( P.lists(((RandomProvider) P).integersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20)) ); } Iterable<Pair<List<Integer>, Integer>> psFail = filter(p -> { assert p.a != null; return all(i -> i < p.b, p.a); }, unfilteredPsFail); for (Pair<List<Integer>, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromBigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.integers()), P.rangeUp(2) ); } else { unfilteredPsFail = P.pairs( P.lists(((RandomProvider) P).integersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ); } psFail = filter(p -> { assert p.a != null; return any(i -> i < 0, p.a); }, unfilteredPsFail); for (Pair<List<Integer>, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromBigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } psFail = filter(p -> any(i -> i >= p.b, p.a), unfilteredPsFail); for (Pair<List<Integer>, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromBigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static void compareImplementationsFromBigEndianDigits_int_Iterable_Integer() { initialize(); System.out.println("\t\tcomparing fromBigEndianDigits(int, Iterable<Integer>) implementations..."); long totalTime = 0; Iterable<Pair<List<Integer>, Integer>> unfilteredPs; if (P instanceof ExhaustiveProvider) { unfilteredPs = ((ExhaustiveProvider) P).pairsLogarithmicOrder(P.lists(P.naturalIntegers()), P.rangeUp(2)); } else { unfilteredPs = P.pairs( P.lists(((RandomProvider) P).naturalIntegersGeometric(10)), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20)) ); } Iterable<Pair<List<Integer>, Integer>> ps = filter(p -> all(i -> i < p.b, p.a), unfilteredPs); for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; fromBigEndianDigits_int_Iterable_Integer_simplest(p.b, p.a); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<List<Integer>, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; fromBigEndianDigits(p.b, p.a); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesFromBigEndianDigits_int_Iterable_BigInteger() { initialize(); System.out.println("\t\ttesting fromBigEndianDigits(int, Iterable<BigInteger>) properties..."); Iterable<Pair<List<BigInteger>, BigInteger>> unfilteredPs; if (P instanceof ExhaustiveProvider) { unfilteredPs = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.naturalBigIntegers()), P.rangeUp(BigInteger.valueOf(2)) ); } else { unfilteredPs = P.pairs( P.lists(map(i -> BigInteger.valueOf(i), ((RandomProvider) P).naturalIntegersGeometric(10))), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } Iterable<Pair<List<BigInteger>, BigInteger>> ps = filter(p -> { assert p.a != null; return all(i -> lt(i, p.b), p.a); }, unfilteredPs); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromBigEndianDigits(p.b, p.a); assertEquals(p.toString(), n, fromDigits(p.b, reverse(p.a))); assertNotEquals(p.toString(), n.signum(), -1); } ps = filter(p -> { assert p.a != null; return p.a.isEmpty() || !head(p.a).equals(BigInteger.ZERO); }, ps); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger n = fromBigEndianDigits(p.b, p.a); aeq(p.toString(), p.a, bigEndianDigits(p.b, n)); } Function<BigInteger, Boolean> digitsToBits = i -> { if (i.equals(BigInteger.ZERO)) return false; if (i.equals(BigInteger.ONE)) return true; throw new IllegalArgumentException(); }; for (List<BigInteger> is : take(LIMIT, P.lists(P.range(BigInteger.ZERO, BigInteger.ONE)))) { assertEquals( is.toString(), fromBigEndianDigits(BigInteger.valueOf(2), is), fromBigEndianBits(map(digitsToBits, is)) ); } Iterable<Pair<List<BigInteger>, BigInteger>> unfilteredPsFail; if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.bigIntegers()), P.rangeDown(BigInteger.ONE) ); } else { unfilteredPsFail = P.pairs( P.lists(map(i -> BigInteger.valueOf(i), ((RandomProvider) P).integersGeometric(10))), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)) ); } Iterable<Pair<List<BigInteger>, BigInteger>> psFail = filter(p -> { assert p.a != null; return all(i -> lt(i, p.b), p.a); }, unfilteredPsFail); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromBigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } if (P instanceof ExhaustiveProvider) { unfilteredPsFail = ((ExhaustiveProvider) P).pairsLogarithmicOrder( P.lists(P.bigIntegers()), P.rangeUp(BigInteger.valueOf(2)) ); } else { unfilteredPsFail = P.pairs( P.lists(map(i -> BigInteger.valueOf(i), ((RandomProvider) P).integersGeometric(10))), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } psFail = filter(p -> { assert p.a != null; return any(i -> i.signum() == -1, p.a); }, unfilteredPsFail); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromBigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } psFail = filter(p -> { assert p.a != null; return any(i -> ge(i, p.b), p.a); }, unfilteredPsFail); for (Pair<List<BigInteger>, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { fromBigEndianDigits(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static void propertiesToDigit() { initialize(); System.out.println("\t\ttesting toDigit(int) properties..."); for (int i : take(LIMIT, P.range(0, 35))) { char digit = toDigit(i); assertTrue(Integer.toString(i), elem(digit, range('0', '9')) || elem(digit, range('A', 'Z'))); assertEquals(Integer.toString(i), i, fromDigit(digit)); } for (int i : take(LIMIT, P.negativeIntegers())) { try { toDigit(i); fail(Integer.toString(i)); } catch (IllegalArgumentException ignored) {} } for (int i : take(LIMIT, P.rangeUp(36))) { try { toDigit(i); fail(Integer.toString(i)); } catch (IllegalArgumentException ignored) {} } } private static void propertiesFromDigit() { initialize(); System.out.println("\t\ttesting fromDigit(char) properties..."); for (char c : take(LIMIT, IterableUtils.mux(Arrays.asList(P.range('0', '9'), P.range('A', 'Z'))))) { int i = fromDigit(c); assertTrue(Character.toString(c), i >= 0 && i < 36); assertEquals(Character.toString(c), c, toDigit(i)); } Iterable<Character> csFail = filter( d -> !elem(d, range('0', '9')) && !elem(d, range('A', 'Z')), P.characters() ); for (char c : take(LIMIT, csFail)) { try { fromDigit(c); fail(Character.toString(c)); } catch (IllegalArgumentException ignored) {} } } private static @NotNull String toStringBase_int_int_simplest(int base, int n) { return toStringBase(BigInteger.valueOf(base), BigInteger.valueOf(n)); } private static void propertiesToStringBase_int_int() { initialize(); System.out.println("\t\ttesting toStringBase(int, int) properties..."); Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.integers(), P.rangeUp(2)); } else { ps = P.pairs(P.integers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; String s = toStringBase(p.b, p.a); assertEquals(p.toString(), toStringBase_int_int_simplest(p.b, p.a), s); assertEquals(p.toString(), fromStringBase(p.b, s), BigInteger.valueOf(p.a)); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.integers(), P.range(2, 36)); } else { ps = P.pairs(P.range(2, 36)); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; String s = toStringBase(p.b, p.a); if (head(s) == '-') s = tail(s); assertTrue(p.toString(), all(c -> elem(c, charsToString(concat(range('0', '9'), range('A', 'Z')))), s)); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.integers(), P.rangeUp(37)); } else { ps = P.pairs(P.integers(), map(i -> i + 37, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; String s = toStringBase(p.b, p.a); if (head(s) == '-') s = tail(s); assertEquals(p.toString(), head(s), '('); assertEquals(p.toString(), last(s), ')'); s = tail(init(s)); Iterable<Integer> digits = map(Integer::parseInt, Arrays.asList(s.split("\\)\\("))); assertFalse(p.toString(), isEmpty(digits)); assertTrue(p.toString(), p.a == 0 || head(digits) != 0); assertTrue(p.toString(), all(d -> d >= 0 && d < p.b, digits)); } Iterable<Pair<Integer, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.integers(), P.rangeDown(1)); } else { psFail = P.pairs(P.integers(), map(i -> i + 2, ((RandomProvider) P).negativeIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { toStringBase(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static void compareImplementationsToStringBase_int_int() { initialize(); System.out.println("\t\tcomparing toStringBase(int, int) implementations..."); long totalTime = 0; Iterable<Pair<Integer, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.integers(), P.rangeUp(2)); } else { ps = P.pairs(P.integers(), map(i -> i + 2, ((RandomProvider) P).naturalIntegersGeometric(20))); } for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; toStringBase_int_int_simplest(p.b, p.a); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, Integer> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; toStringBase(p.b, p.a); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesToStringBase_BigInteger_BigInteger() { initialize(); System.out.println("\t\ttesting toStringBase(BigInteger, BigInteger) properties..."); Iterable<Pair<BigInteger, BigInteger>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigIntegers(), P.rangeUp(BigInteger.valueOf(2))); } else { ps = P.pairs( P.bigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; String s = toStringBase(p.b, p.a); assertEquals(p.toString(), fromStringBase(p.b, s), p.a); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder( P.bigIntegers(), P.range(BigInteger.valueOf(2), BigInteger.valueOf(36)) ); } else { ps = P.pairs(P.range(BigInteger.valueOf(2), BigInteger.valueOf(36))); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; String s = toStringBase(p.b, p.a); if (head(s) == '-') s = tail(s); assertTrue(p.toString(), all(c -> elem(c, charsToString(concat(range('0', '9'), range('A', 'Z')))), s)); } if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigIntegers(), P.rangeUp(BigInteger.valueOf(37))); } else { ps = P.pairs( P.bigIntegers(), map(i -> BigInteger.valueOf(i + 37), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; String s = toStringBase(p.b, p.a); if (head(s) == '-') s = tail(s); assertEquals(p.toString(), head(s), '('); assertEquals(p.toString(), last(s), ')'); s = tail(init(s)); Iterable<BigInteger> digits = map(BigInteger::new, Arrays.asList(s.split("\\)\\("))); assertFalse(p.toString(), isEmpty(digits)); assertTrue(p.toString(), p.a.equals(BigInteger.ZERO) || !head(digits).equals(BigInteger.ZERO)); assertTrue(p.toString(), all(d -> d.signum() != -1 && lt(d, p.b), digits)); } Iterable<Pair<BigInteger, BigInteger>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigIntegers(), P.rangeDown(BigInteger.ONE)); } else { psFail = P.pairs( P.bigIntegers(), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).negativeIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { toStringBase(p.b, p.a); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static @NotNull BigInteger fromStringBase_int_String_simplest(int base, @NotNull String s) { return fromStringBase(BigInteger.valueOf(base), s); } private static void propertiesFromStringBase_int_String() { initialize(); System.out.println("\t\ttesting fromString(int, String) properties..."); Iterable<Pair<Integer, String>> ps = P.dependentPairs( P.rangeUp(2), b -> { Iterable<String> positiveStrings; if (b <= 36) { positiveStrings = P.strings(map(MathUtils::toDigit, P.range(0, b - 1))); } else { positiveStrings = map( is -> concatMapStrings(i -> "(" + i + ")", is), P.lists(P.range(0, b - 1)) ); } return mux( (List<Iterable<String>>) Arrays.asList( positiveStrings, map((String s) -> cons('-', s), filter(t -> !t.isEmpty(), positiveStrings)) ) ); } ); for (Pair<Integer, String> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger i = fromStringBase(p.a, p.b); assertEquals(p.toString(), fromStringBase_int_String_simplest(p.a, p.b), i); } ps = P.dependentPairs( P.rangeUp(2), b -> { Iterable<String> positiveStrings; if (b <= 36) { positiveStrings = filter( s -> !s.isEmpty() && head(s) != '0', P.strings(map(MathUtils::toDigit, P.range(0, b - 1))) ); } else { positiveStrings = map( is -> concatMapStrings(i -> "(" + i + ")", is), filter( is -> !is.isEmpty() && head(is) != 0, (Iterable<List<Integer>>) P.lists(P.range(0, b - 1)) ) ); } return mux( (List<Iterable<String>>) Arrays.asList( positiveStrings, map((String s) -> cons('-', s), filter(t -> !t.isEmpty(), positiveStrings)) ) ); } ); for (Pair<Integer, String> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger i = fromStringBase(p.a, p.b); assertEquals(p.toString(), toStringBase(BigInteger.valueOf(p.a), i), p.b); } for (Pair<Integer, String> p : take(LIMIT, P.pairs(P.rangeDown(1), P.strings()))) { assert p.a != null; assert p.b != null; try { fromStringBase(p.a, p.b); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } //improper String left untested } private static void compareImplementationsFromStringBase_int_String() { initialize(); System.out.println("\t\tcomparing fromStringBase(int, String) implementations..."); long totalTime = 0; Iterable<Pair<Integer, String>> ps = P.dependentPairs( P.rangeUp(2), b -> { Iterable<String> positiveStrings; if (b <= 36) { positiveStrings = P.strings(map(MathUtils::toDigit, P.range(0, b - 1))); } else { positiveStrings = map( is -> concatMapStrings(i -> "(" + i + ")", is), P.lists(P.range(0, b - 1)) ); } return mux( (List<Iterable<String>>) Arrays.asList( positiveStrings, map((String s) -> cons('-', s), filter(t -> !t.isEmpty(), positiveStrings)) ) ); } ); for (Pair<Integer, String> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; fromStringBase_int_String_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Integer, String> p : take(LIMIT, ps)) { long time = System.nanoTime(); assert p.a != null; assert p.b != null; fromStringBase(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private static void propertiesFromStringBase_BigInteger_String() { initialize(); System.out.println("\t\ttesting fromStringBase(BigInteger, String) properties..."); Iterable<Pair<BigInteger, String>> ps = P.dependentPairs( P.rangeUp(BigInteger.valueOf(2)), b -> { Iterable<String> positiveStrings; if (le(b, BigInteger.valueOf(36))) { positiveStrings = P.strings(map(MathUtils::toDigit, P.range(0, b.intValueExact() - 1))); } else { positiveStrings = map( is -> concatMapStrings(i -> "(" + i + ")", is), P.lists(P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE))) ); } return mux( (List<Iterable<String>>) Arrays.asList( positiveStrings, map((String s) -> cons('-', s), filter(t -> !t.isEmpty(), positiveStrings)) ) ); } ); for (Pair<BigInteger, String> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; fromStringBase(p.a, p.b); } ps = P.dependentPairs( P.rangeUp(BigInteger.valueOf(2)), b -> { Iterable<String> positiveStrings; if (le(b, BigInteger.valueOf(36))) { positiveStrings = filter( s -> !s.isEmpty() && head(s) != '0', P.strings(map(MathUtils::toDigit, P.range(0, b.intValueExact() - 1))) ); } else { positiveStrings = map( is -> concatMapStrings(i -> "(" + i + ")", is), filter( is -> !is.isEmpty() && !head(is).equals(BigInteger.ZERO), (Iterable<List<BigInteger>>) P.lists( P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE)) ) ) ); } return mux( (List<Iterable<String>>) Arrays.asList( positiveStrings, map((String s) -> cons('-', s), filter(t -> !t.isEmpty(), positiveStrings)) ) ); } ); for (Pair<BigInteger, String> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger i = fromStringBase(p.a, p.b); assertEquals(p.toString(), toStringBase(p.a, i), p.b); } for (Pair<BigInteger, String> p : take(LIMIT, P.pairs(P.rangeDown(BigInteger.ONE), P.strings()))) { assert p.a != null; assert p.b != null; try { fromStringBase(p.a, p.b); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } //improper String left untested } private static void propertiesLogarithmicMux() { initialize(); System.out.println("\t\ttesting logarithmicMux(BigInteger, BigInteger) properties..."); Iterable<Pair<BigInteger, BigInteger>> ps; if (P instanceof ExhaustiveProvider) { ps = P.pairs(P.naturalBigIntegers()); } else { //noinspection Convert2MethodRef ps = P.pairs( P.naturalBigIntegers(), map(i -> BigInteger.valueOf(i), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger i = logarithmicMux(p.a, p.b); assertNotEquals(p.toString(), i.signum(), -1); assertEquals(p.toString(), logarithmicDemux(i), p); } Iterable<Pair<BigInteger, BigInteger>> psFail; if (P instanceof ExhaustiveProvider) { psFail = P.pairs(P.naturalBigIntegers(), P.negativeBigIntegers()); } else { //noinspection Convert2MethodRef psFail = P.pairs( P.naturalBigIntegers(), map(i -> BigInteger.valueOf(i), ((RandomProvider) P).negativeIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { logarithmicMux(p.a, p.b); fail(p.toString()); } catch (ArithmeticException ignored) {} } if (P instanceof ExhaustiveProvider) { psFail = P.pairs(P.negativeBigIntegers(), P.naturalBigIntegers()); } else { //noinspection Convert2MethodRef psFail = P.pairs( P.negativeBigIntegers(), map(i -> BigInteger.valueOf(i), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { logarithmicMux(p.a, p.b); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesLogarithmicDemux() { initialize(); System.out.println("\t\ttesting logarithmicDemux(BigInteger) properties..."); for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { Pair<BigInteger, BigInteger> p = logarithmicDemux(i); assert p.a != null; assert p.b != null; assertNotEquals(p.toString(), p.a.signum(), -1); assertNotEquals(p.toString(), p.b.signum(), -1); assertEquals(p.toString(), logarithmicMux(p.a, p.b), i); } for (BigInteger i : take(LIMIT, P.negativeBigIntegers())) { try { logarithmicDemux(i); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesSquareRootMux() { initialize(); System.out.println("\t\ttesting squareRootMux(BigInteger, BigInteger) properties..."); for (Pair<BigInteger, BigInteger> p : take(LIMIT, P.pairs(P.naturalBigIntegers()))) { assert p.a != null; assert p.b != null; BigInteger i = squareRootMux(p.a, p.b); assertNotEquals(p.toString(), i.signum(), -1); assertEquals(p.toString(), squareRootDemux(i), p); } for (Pair<BigInteger, BigInteger> p : take(LIMIT, P.pairs(P.naturalBigIntegers(), P.negativeBigIntegers()))) { assert p.a != null; assert p.b != null; try { squareRootMux(p.a, p.b); fail(p.toString()); } catch (ArithmeticException ignored) {} } for (Pair<BigInteger, BigInteger> p : take(LIMIT, P.pairs(P.negativeBigIntegers(), P.naturalBigIntegers()))) { assert p.a != null; assert p.b != null; try { squareRootMux(p.a, p.b); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesSquareRootDemux() { initialize(); System.out.println("\t\ttesting squareRootDemux(BigInteger) properties..."); for (BigInteger i : take(LIMIT, P.naturalBigIntegers())) { Pair<BigInteger, BigInteger> p = squareRootDemux(i); assert p.a != null; assert p.b != null; assertNotEquals(p.toString(), p.a.signum(), -1); assertNotEquals(p.toString(), p.b.signum(), -1); assertEquals(p.toString(), squareRootMux(p.a, p.b), i); } for (BigInteger i : take(LIMIT, P.negativeBigIntegers())) { try { squareRootDemux(i); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static <T> void aeq(String message, Iterable<T> xs, Iterable<T> ys) { assertTrue(message, equal(xs, ys)); } }
package net.bramp.ffmpeg; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; import com.google.common.io.CountingOutputStream; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.fixtures.Samples; import net.bramp.ffmpeg.job.FFmpegJob; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import net.bramp.ffmpeg.progress.Progress; import net.bramp.ffmpeg.progress.RecordingProgressListener; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests actually shelling out ffmpeg and ffprobe. Could be flakey if ffmpeg or ffprobe change. */ public class FFmpegExecutorTest { @Rule public Timeout timeout = new Timeout(30, TimeUnit.SECONDS); final FFmpeg ffmpeg = new FFmpeg(); final FFprobe ffprobe = new FFprobe(); final FFmpegExecutor ffExecutor = new FFmpegExecutor(ffmpeg, ffprobe); final ExecutorService executor = Executors.newSingleThreadExecutor(); public FFmpegExecutorTest() throws IOException {} @Test public void testTwoPass() throws InterruptedException, ExecutionException, IOException { FFmpegProbeResult in = ffprobe.probe(Samples.big_buck_bunny_720p_1mb); assertFalse(in.hasError()); FFmpegBuilder builder = new FFmpegBuilder().setInput(in).overrideOutputFiles(true).addOutput(Samples.output_mp4) .setFormat("mp4").disableAudio().setVideoCodec("mpeg4") .setVideoFrameRate(FFmpeg.FPS_30).setVideoResolution(320, 240) .setTargetSize(1024 * 1024).done(); FFmpegJob job = ffExecutor.createTwoPassJob(builder); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); } @Test public void testFilter() throws InterruptedException, ExecutionException, IOException { FFmpegBuilder builder = new FFmpegBuilder().setInput(Samples.big_buck_bunny_720p_1mb).overrideOutputFiles(true) .addOutput(Samples.output_mp4).setFormat("mp4").disableAudio().setVideoCodec("mpeg4") .setVideoFilter("scale=320:trunc(ow/a/2)*2").done(); FFmpegJob job = ffExecutor.createJob(builder); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); } @Test public void testMetaTags() throws InterruptedException, ExecutionException, IOException { FFmpegBuilder builder = new FFmpegBuilder().setInput(Samples.big_buck_bunny_720p_1mb).overrideOutputFiles(true) .addOutput(Samples.output_mp4).setFormat("mp4").disableAudio().setVideoCodec("mpeg4") .addMetaTag("comment", "This=Nice!").addMetaTag("title", "Big Buck Bunny").done(); FFmpegJob job = ffExecutor.createJob(builder); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); } /** * Test if addStdoutOutput() actually works, and the output can be correctly captured. * * @throws InterruptedException * @throws ExecutionException * @throws IOException */ @Test public void testStdout() throws InterruptedException, ExecutionException, IOException { // @formatter:off FFmpegBuilder builder = new FFmpegBuilder() .setInput(Samples.big_buck_bunny_720p_1mb) .addStdoutOutput() .setFormat("s8") .setAudioChannels(1) .done(); List<String> newArgs = ImmutableList.<String>builder() .add(ffmpeg.getPath()) .addAll(builder.build()) .build(); // @formatter:on // TODO Add support to the FFmpegJob to export the stream Process p = new ProcessBuilder(newArgs).start(); CountingOutputStream out = new CountingOutputStream(ByteStreams.nullOutputStream()); ByteStreams.copy(p.getInputStream(), out); assertEquals(0, p.waitFor()); // This is perhaps fragile, but one byte per audio sample assertEquals(254976, out.getCount()); } @Test public void testProgress() throws InterruptedException, ExecutionException, IOException { FFmpegProbeResult in = ffprobe.probe(Samples.big_buck_bunny_720p_1mb); assertFalse(in.hasError()); FFmpegBuilder builder = new FFmpegBuilder().readAtNativeFrameRate() // Slows the test down .setInput(in).overrideOutputFiles(true).addOutput(Samples.output_mp4).done(); RecordingProgressListener listener = new RecordingProgressListener(); FFmpegJob job = ffExecutor.createJob(builder, listener); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); List<Progress> progesses = listener.progesses; // Since the results of ffmpeg are not predictable, test for the bare minimum. assertThat(progesses, hasSize(greaterThanOrEqualTo(2))); assertThat(progesses.get(0).progress, is("continue")); assertThat(progesses.get(progesses.size() - 1).progress, is("end")); } protected void runAndWait(FFmpegJob job) throws ExecutionException, InterruptedException { executor.submit(job).get(); } }
package no.cantara.process.worker; import org.hyperic.sigar.ProcCpu; import org.hyperic.sigar.ProcCred; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; public class SigarTest { private static final Logger log = LoggerFactory.getLogger(SigarTest.class); private long getCurrentUid() { try { String userName = System.getProperty("user.name"); String command = "id -u "+userName; Process child = Runtime.getRuntime().exec(command); // Get the input stream and read from it InputStream in = child.getInputStream(); java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A"); String val = ""; if (s.hasNext()) { val = s.next(); } else { val = ""; } return Long.valueOf(val.replaceAll("\n", "")); } catch (IOException e) { } return -1; } @Test public void testSigar() throws Exception { long currentUid = getCurrentUid(); log.trace("Current UID: {}", currentUid); long[] procList = null; Sigar sigar = null; try { sigar = new Sigar(); procList = sigar.getProcList(); } catch (UnsatisfiedLinkError e) { log.warn("Unable to use sigar native API", e); return; } for(long pid : procList) { try { ProcCred cred = sigar.getProcCred(pid); if (currentUid != cred.getUid()) { log.trace("pid: {} - skipped - not owned by you", pid); continue; } log.trace("pid: {}", pid); ProcCpu cpu = sigar.getProcCpu(pid); log.trace("---> cpu: {}", cpu.toString()); String[] args = sigar.getProcArgs(pid); StringBuffer buf = new StringBuffer(); for(String arg : args) { buf.append(arg).append(" "); } log.trace("---> args: {}", buf.toString()); } catch (SigarException e) { log.error("<--- pid: {} - {}", pid, e.getMessage()); } } } }
package no.priv.garshol.duke.integration; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import org.junit.Rule; import org.junit.Test; import org.junit.Before; import org.junit.rules.TemporaryFolder; import static org.junit.Assert.fail; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; /** * Duke integration tests, testing the command-line tools. */ public class IT { @Test public void testFailWithNoArguments() throws IOException { Result r = run(""); assertEquals("didn't fail with error code", 1, r.code); assertTrue("Duke gave no error message: " + r.out, r.out.contains("ERROR:")); } @Test public void testShowMatches() throws IOException { Result r = run("--showmatches doc/example-data/countries.xml"); assertEquals("failed with error code: " + r.out, 0, r.code); assertTrue("not enough matches", r.countOccurrences("MATCH 0.") > 50); } private Result run(String args) throws IOException { Process p = Runtime.getRuntime().exec("java -cp target/duke*.jar no.priv.garshol.duke.Duke " + args); StringBuilder tmp = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = r.readLine()) != null) tmp.append(line); r.close(); r = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = r.readLine()) != null) tmp.append(line); r.close(); p.waitFor(); // we wait for process to exit return new Result(tmp.toString(), p.exitValue()); } private static class Result { public String out; public int code; public Result(String out, int code) { this.out = out; this.code = code; } public int countOccurrences(String sub) { int pos = 0; int count = 0; while (true) { pos = out.indexOf(sub, pos); if (pos == -1) return count; count++; pos += sub.length(); } } } }
package org.graphwalker.core.model; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import static org.hamcrest.core.Is.is; /** * @author Nils Olsson */ public class EdgeTest { @Test public void create() { Edge edge = new Edge() .setGuard(new Guard("script")) .setName("name") .setSourceVertex(new Vertex()) .setTargetVertex(new Vertex()) .setBlocked(true) .addAction(new Action("action1")) .addActions(Arrays.asList(new Action("action2"), new Action("action3"))); Assert.assertNotNull(edge); Assert.assertTrue(edge.isBlocked()); Assert.assertTrue(edge.build().isBlocked()); Assert.assertEquals("name", edge.getName()); Assert.assertEquals("name", edge.build().getName()); Assert.assertNotNull(edge.getSourceVertex()); Assert.assertNotNull(edge.build().getTargetVertex()); Assert.assertNotNull(edge.getTargetVertex()); Assert.assertNotNull(edge.build().getTargetVertex()); Assert.assertNotNull(edge.getGuard()); Assert.assertNotNull(edge.build().getGuard()); Assert.assertEquals(edge.getGuard(), edge.build().getGuard()); Assert.assertNotNull(edge.getActions()); Assert.assertThat(edge.getActions().size(), is(3)); Assert.assertNotNull(edge.build().getActions()); Assert.assertThat(edge.build().getActions().size(), is(3)); } }
package org.jenkins; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JenkinsApplication.class) @WebAppConfiguration public class JenkinsApplicationTests { @Test public void contextLoads() { Assert.assertEquals("Mario", "Mario"); } }
package org.tendiwa.lexeme; import com.google.common.collect.ImmutableSet; import java.util.stream.IntStream; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.tendiwa.lexeme.implementations.English; /** * @since 0.1 */ public final class ParsedLexemeTest { @Test public void hasBaseForm() throws Exception { MatcherAssert.assertThat( this .firstWordOfBundle("characters.en_US.words") .baseForm(), CoreMatchers.equalTo("bear") ); } @Test public void worksWithZeroPersistentGrammemes() throws Exception { MatcherAssert.assertThat( this .firstWordOfBundle("characters.en_US.words") .persistentGrammemes(), CoreMatchers.equalTo(ImmutableSet.of()) ); } @Test public void canAssumeCorrectForm() throws Exception { MatcherAssert.assertThat( this .firstWordOfBundle("characters.en_US.words") .form(ImmutableSet.of(English.Grammemes.Plur)), CoreMatchers.equalTo("bears") ); } @Test public void canBeUsedMultipleTimes() throws Exception { final ParsedLexeme lexeme = this.firstWordOfBundle("characters.en_US.words"); IntStream.range(0, 1).forEach( i-> MatcherAssert.assertThat( lexeme.baseForm(), CoreMatchers.equalTo("bear") ) ); } private ParsedLexeme firstWordOfBundle( String resourceName ) { return new ParsedLexeme( new English().grammar(), new BasicWordBundleParser( ParsedLexemeTest.class.getResourceAsStream( resourceName ) ) .word_bundle() .word() .get(0) ); } }
package utils; import java.io.File; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Test for missing localizations of feature toggles */ public class FeatureSwitchLocalizationTest { private static ResourceBundle bundle; @BeforeClass public static void setUp() throws Exception { bundle = fetchBundle(); } @Test public void testCorrectCode() throws Exception { String result = fetchTranslation(CorrectFeatureSwitch.class); Assert.assertTrue(result != null); } @Test(expected = MissingResourceException.class) public void testIncorrectCode() throws Exception { fetchTranslation(IncorrectFeatureSwitch.class); } private String fetchTranslation(Class<?> testedClass) throws MalformedURLException, IllegalAccessException { Field[] fields = testedClass.getDeclaredFields(); for (Field field : fields) { if (java.lang.reflect.Modifier.isPublic(field.getModifiers()) && field.get(null).getClass().equals(testedClass)) { @SuppressWarnings("unchecked") NamedType<String> property = (NamedType<String>) field.get(field); return bundle.getString(property.getId()); } } return null; } private static ResourceBundle fetchBundle() throws MalformedURLException { File localizationsDirectory = new File("src/test/resources/localizations"); URL[] urls = { localizationsDirectory.toURI().toURL() }; ClassLoader loader = new URLClassLoader(urls); ResourceBundle bundle = ResourceBundle.getBundle("myResource", Locale.ENGLISH, loader); return bundle; } }
package tk.wurst_client.features.mods; import net.minecraft.block.Block; import net.minecraft.block.BlockCocoa; import net.minecraft.block.BlockCrops; import net.minecraft.block.BlockGrass; import net.minecraft.block.BlockSapling; import net.minecraft.block.BlockStem; import net.minecraft.block.IGrowable; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import tk.wurst_client.events.listeners.UpdateListener; import tk.wurst_client.features.special_features.YesCheatSpf.BypassLevel; import tk.wurst_client.settings.CheckboxSetting; import tk.wurst_client.settings.SliderSetting; import tk.wurst_client.settings.SliderSetting.ValueDisplay; import tk.wurst_client.utils.BlockUtils; import tk.wurst_client.utils.InventoryUtils; @Mod.Info( description = "Automatically uses bone meal on specific types of plants.\n" + "Use the checkboxes to specify the types of plants.", name = "BonemealAura", tags = "bonemeal aura, bone meal aura, AutoBone, auto bone", help = "Mods/BonemealAura") @Mod.Bypasses(ghostMode = false) public class BonemealAuraMod extends Mod implements UpdateListener { public final SliderSetting range = new SliderSetting("Range", 4.25, 1, 6, 0.05, ValueDisplay.DECIMAL); private final CheckboxSetting saplings = new CheckboxSetting("Saplings", true); private final CheckboxSetting crops = new CheckboxSetting("Crops", true); private final CheckboxSetting stems = new CheckboxSetting("Stems", true); private final CheckboxSetting cocoa = new CheckboxSetting("Cocoa", true); private final CheckboxSetting other = new CheckboxSetting("Other", false); @Override public void initSettings() { settings.add(range); settings.add(saplings); settings.add(crops); settings.add(stems); settings.add(cocoa); settings.add(other); } @Override public void onEnable() { wurst.events.add(UpdateListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); } @Override public void onUpdate() { // check held item ItemStack stack = mc.player.inventory.getCurrentItem(); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemDye) || stack.getMetadata() != 15) return; BlockPos playerPos = new BlockPos(mc.player); for(int y = -range.getValueI() + 1; y < range.getValueI() + 2; y++) for(int x = -range.getValueI(); x < range.getValueI() + 1; x++) for(int z = -range.getValueI(); z < range.getValueI() + 1; z++) { BlockPos pos = playerPos.add(x, y, z); if(BlockUtils.getPlayerBlockDistance(pos) > range .getValueF() || !isCorrectBlock(pos)) continue; BlockUtils.faceBlockPacket(pos); mc.player.connection .sendPacket(new CPacketPlayerTryUseItemOnBlock(pos, EnumFacing.UP, EnumHand.MAIN_HAND, 0.5F, 1F, 0.5F)); } } @Override public void onYesCheatUpdate(BypassLevel bypassLevel) { switch(bypassLevel) { default: case OFF: case MINEPLEX: range.unlock(); break; case ANTICHEAT: case OLDER_NCP: case LATEST_NCP: case GHOST_MODE: range.lockToMax(4.25); break; } } private boolean isCorrectBlock(BlockPos pos) { Block block = BlockUtils.getBlock(pos); if(!(block instanceof IGrowable) || block instanceof BlockGrass || !((IGrowable)block).canGrow(mc.world, pos, BlockUtils.getState(pos), false)) return false; if(block instanceof BlockSapling) return saplings.isChecked(); else if(block instanceof BlockCrops) return crops.isChecked(); else if(block instanceof BlockStem) return stems.isChecked(); else if(block instanceof BlockCocoa) return cocoa.isChecked(); else return other.isChecked(); } }
package spms.controls; import java.util.HashMap; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import spms.dao.MemberDao; import spms.vo.Member; @Controller @RequestMapping("/auth") @SessionAttributes("loginUser") // loginUser . public class AuthControl { @Autowired(required=false) MemberDao memberDao; @Autowired(required=false) ExcelControl excelControl; @RequestMapping(value="/login",method=RequestMethod.GET) public String form(@CookieValue(required=false) String id, Model model) { if (id != null) { model.addAttribute("id", id); model.addAttribute("checkSaveId", "checked"); } return "redirect:/index.jsp"; } @RequestMapping(value="/login",method=RequestMethod.POST) public String login(String id, String password, String saveId, HttpServletResponse response, Model model) throws Exception { Cookie cookie = null; if (saveId != null) { cookie = new Cookie("id", id); cookie.setMaxAge(60 * 60 * 24 * 3); } else { cookie = new Cookie("id", null); cookie.setMaxAge(0); } response.addCookie(cookie); HashMap<String,String> sqlparamMap = new HashMap<String,String>(); sqlparamMap.put("id", id); sqlparamMap.put("password", password); Member member = memberDao.selectByIdPassword(sqlparamMap); if(member == null) { return "redirect:/failLogin.jsp"; } System.err.println("dddd : " + member.getNo()); { excelControl.staticId = member.getNo(); model.addAttribute("loginUser", member); if (member.getNo()==1){ return "redirect:/main.do"; } else{ return "redirect:../delivery/deliveryMember.html"; } } } @RequestMapping("/logout") public String logout(SessionStatus status) throws Exception { status.setComplete(); return "redirect:/index.jsp"; } @RequestMapping("/loginUser") public String loginUser() throws Exception { return "auth/loginUser"; } }
package org.terasology.math; import com.google.common.collect.Maps; import org.joml.Math; import org.joml.Vector3fc; import org.joml.Vector3ic; import org.terasology.math.geom.Vector3f; import org.terasology.math.geom.Vector3i; import java.util.EnumMap; /** * An enumeration of the axis of the world from the player perspective. There is also * */ public enum Direction { UP(Vector3i.up(), new Vector3f(0, 1, 0)), RIGHT(new Vector3i(-1, 0, 0), new Vector3f(-1, 0, 0)), LEFT(new Vector3i(1, 0, 0), new Vector3f(1, 0, 0)), BACKWARD(new Vector3i(0, 0, -1), new Vector3f(0, 0, -1)), FORWARD(new Vector3i(0, 0, 1), new Vector3f(0, 0, 1)), DOWN(Vector3i.down(), new Vector3f(0, -1, 0)); private static final EnumMap<Direction, Direction> REVERSE_MAP; private static final EnumMap<Direction, Side> CONVERSION_MAP; private final Vector3i vector3iDir; private final Vector3f vector3fDir; static { REVERSE_MAP = new EnumMap<>(Direction.class); REVERSE_MAP.put(UP, DOWN); REVERSE_MAP.put(LEFT, RIGHT); REVERSE_MAP.put(RIGHT, LEFT); REVERSE_MAP.put(FORWARD, BACKWARD); REVERSE_MAP.put(BACKWARD, FORWARD); REVERSE_MAP.put(DOWN, UP); CONVERSION_MAP = Maps.newEnumMap(Direction.class); CONVERSION_MAP.put(UP, Side.TOP); CONVERSION_MAP.put(DOWN, Side.BOTTOM); CONVERSION_MAP.put(FORWARD, Side.BACK); CONVERSION_MAP.put(BACKWARD, Side.FRONT); CONVERSION_MAP.put(LEFT, Side.RIGHT); CONVERSION_MAP.put(RIGHT, Side.LEFT); } Direction(Vector3i vector3i, Vector3f vector3f) { this.vector3iDir = vector3i; this.vector3fDir = vector3f; } public static Direction inDirection(int x, int y, int z) { if (Math.abs(x) > Math.abs(y)) { if (Math.abs(x) > Math.abs(z)) { return (x > 0) ? LEFT : RIGHT; } } else if (Math.abs(y) > Math.abs(z)) { return (y > 0) ? UP : DOWN; } return (z > 0) ? FORWARD : BACKWARD; } /** * @param dir * @return * @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation * {@link #inDirection(Vector3fc)}. */ @Deprecated public static Direction inDirection(Vector3f dir) { return inDirection(dir.x, dir.y, dir.z); } public static Direction inDirection(Vector3fc dir) { return inDirection(dir.x(), dir.y(), dir.z()); } public Side toSide() { return CONVERSION_MAP.get(this); } /** * Determines which direction the player is facing * * @param x right/left * @param y top/bottom * @param z back/front * @return Side enum with the appropriate direction */ public static Direction inDirection(float x, float y, float z) { if (Math.abs(x) > Math.abs(y)) { if (Math.abs(x) > Math.abs(z)) { return (x > 0) ? LEFT : RIGHT; } } else if (Math.abs(y) > Math.abs(z)) { return (y > 0) ? UP : DOWN; } return (z > 0) ? FORWARD : BACKWARD; } /** * Determines which horizontal direction the player is facing * * @param x right/left * @param z back/front * @return Side enum with the appropriate direction */ public static Direction inHorizontalDirection(float x, float z) { if (Math.abs(x) > Math.abs(z)) { return (x > 0) ? LEFT : RIGHT; } return (z > 0) ? FORWARD : BACKWARD; } /** * readonly normalized {@link Vector3ic} in the given {@link Direction} * * @return vector pointing in the direction */ public Vector3ic asVector3i() { return JomlUtil.from(vector3iDir); } /** * readonly normalized {@link Vector3fc} in the given {@link Direction} * * @return vector pointing in the direction */ public Vector3fc asVector3f() { return JomlUtil.from(vector3fDir); } /** * @return The vector3i in the direction of the side. Do not modify. * @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation * {@link #asVector3i()}. */ @Deprecated public Vector3i getVector3i() { return new Vector3i(vector3iDir); } /** * @return * @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation * {@link #asVector3f()} */ @Deprecated public Vector3f getVector3f() { return new Vector3f(vector3fDir); } /** * @return The opposite side to this side. */ public Direction reverse() { return REVERSE_MAP.get(this); } }
package org.apache.pig.spark; import static org.apache.pig.builtin.mock.Storage.bag; import static org.apache.pig.builtin.mock.Storage.tuple; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Level; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.executionengine.ExecJob; import org.apache.pig.builtin.mock.Storage; import org.apache.pig.builtin.mock.Storage.Data; import org.apache.pig.data.Tuple; import org.junit.Assert; import org.junit.Test; public class TestSpark { private static final ExecType MODE = ExecType.SPARK; private static final Log LOG = LogFactory.getLog(TestSpark.class); static { org.apache.log4j.Logger.getLogger("org.apache.pig.backend.hadoop.executionengine.spark").setLevel(Level.DEBUG); } private PigServer newPigServer() throws ExecException { PigServer pigServer = new PigServer(MODE); return pigServer; } @Test public void testLoadStore() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("test1"), tuple("test2")); pigServer.setBatchOn(); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("STORE A INTO 'output' using mock.Storage;"); List<ExecJob> executeBatch = pigServer.executeBatch(); // TODO: good stats // assertEquals(1, executeBatch.size()); // assertTrue(executeBatch.get(0).hasCompleted()); assertEquals( Arrays.asList(tuple("test1"), tuple("test2")), data.get("output")); } @Test public void testGroupBy() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("foo", "key1", "test1"), tuple("bar", "key1", "test2"), tuple("baz", "key2", "test3")); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = GROUP A BY $1;"); pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList( tuple("key1", bag(tuple("foo", "key1", "test1"), tuple("bar", "key1", "test2"))), tuple("key2", bag(tuple("baz", "key2", "test3")))), sortByIndex(data.get("output"), 0)); } private List<Tuple> sortByIndex(List<Tuple> out, final int i) { List<Tuple> result = new ArrayList<Tuple>(out); Collections.sort(result, new Comparator<Tuple>() { @Override public int compare(Tuple o1, Tuple o2) { try { Comparable c1 = (Comparable)o1.get(i); Comparable c2 = (Comparable)o2.get(i); return c1.compareTo(c2); } catch (ExecException e) { throw new RuntimeException(e); } } }); return result; } @Test public void testGroupByFlatten() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("test1"), tuple("test1"), tuple("test2")); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = GROUP A BY $0;"); pigServer.registerQuery("C = FOREACH B GENERATE FLATTEN(A);"); pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(tuple("test1"), tuple("test1"), tuple("test2")), data.get("output")); } @Test public void testCount() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("test1"), tuple("test1"), tuple("test2")); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = GROUP A BY $0;"); pigServer.registerQuery("C = FOREACH B GENERATE COUNT(A);"); pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(tuple(2l), tuple(1l)), data.get("output")); } @Test public void testCountWithNoData() throws Exception { PigServer pigServer = new PigServer(ExecType.SPARK); Data data = Storage.resetData(pigServer); data.set("input"); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = GROUP A BY $0;"); pigServer.registerQuery("C = FOREACH B GENERATE COUNT(A);"); pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(), data.get("output")); } @Test public void testForEach() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("1"), tuple("12"), tuple("123")); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = FOREACH A GENERATE StringSize($0);"); pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(tuple(1l), tuple(2l), tuple(3l)), data.get("output")); } @Test public void testForEachFlatten() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple(bag(tuple("1"), tuple("2"), tuple("3"))), tuple(bag(tuple("4"), tuple("5"), tuple("6")))); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = FOREACH A GENERATE FLATTEN($0);"); pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(tuple("1"), tuple("2"), tuple("3"), tuple("4"), tuple("5"), tuple("6")), data.get("output")); } @Test public void testSimpleUDF() throws Exception { PigServer pigServer = new PigServer(ExecType.SPARK); Data data = Storage.resetData(pigServer); data.set("input", tuple("Foo"), tuple("BAR"), tuple("baT")); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = FOREACH A GENERATE org.apache.pig.spark.LowercaseUDF($0);"); pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(tuple("foo"), tuple("bar"), tuple("bat")), data.get("output")); } @Test public void testFilter() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("1"), tuple("2"), tuple("3"), tuple("1")); pigServer.registerQuery("A = LOAD 'input' using mock.Storage;"); pigServer.registerQuery("B = FILTER A BY $0 == '1';"); pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList(tuple("1"), tuple("1")), data.get("output")); } @Test public void testCoGroup() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input1", tuple("foo", 1, "a"), tuple("foo", 2, "b"), tuple("foo", 3, "c"), tuple("foo", 1, "d")); data.set("input2", tuple("bar", 1, "e"), tuple("bar", 2, "f"), tuple("bar", 1, "g")); pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;"); pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;"); pigServer.registerQuery("C = COGROUP A BY $1, B BY $1;"); pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList( tuple(1,bag(tuple("foo", 1,"a"),tuple("foo", 1,"d")),bag(tuple("bar", 1,"e"),tuple("bar", 1,"g"))), tuple(2,bag(tuple("foo", 2,"b")),bag(tuple("bar", 2,"f"))), tuple(3,bag(tuple("foo", 3,"c")),bag()) ), sortByIndex(data.get("output"), 0)); } @Test public void testJoin() throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input1", tuple(1, "a"), tuple(2, "b"), tuple(3, "c"), tuple(1, "d")); data.set("input2", tuple(1, "e"), tuple(2, "f"), tuple(1, "g")); pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;"); pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;"); pigServer.registerQuery("C = JOIN A BY $0, B BY $0;"); pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;"); assertEquals( Arrays.asList( tuple(1, "a", 1, "e"), tuple(1, "a", 1, "g"), tuple(1, "d", 1, "e"), tuple(1, "d", 1, "g"), tuple(2, "b", 2, "f") ), data.get("output")); } @Test public void testCachingLoad() throws Exception { testCaching("A = LOAD 'input' using mock.Storage;" + "CACHE A;" + "STORE A INTO 'output' using mock.Storage;"); } @Test public void testCachingLoadCast() throws Exception { testCaching("A = LOAD 'input' using mock.Storage as (foo:chararray);" + "CACHE A;" + "STORE A INTO 'output' using mock.Storage;"); } @Test public void testCachingWithFilter() throws Exception { testCaching("A = LOAD 'input' using mock.Storage; " + "B = FILTER A by $0 == $0;" + // useless filter "A = FOREACH B GENERATE (chararray) $0;" + "CACHE A;" + "STORE A INTO 'output' using mock.Storage;"); } @Test public void testCachingJoin() throws Exception { testCaching("A = LOAD 'input' using mock.Storage; " + "B = LOAD 'input' using mock.Storage; " + "A = JOIN A by $0, B by LOWER($0); " + "CACHE A; " + "STORE A INTO 'output' using mock.Storage;"); } @Test public void testIgnoreWrongUDFCache() throws Exception { testIgnoreCache( "A = LOAD 'input' using mock.Storage; " + "B = LOAD 'input' using mock.Storage; " + "A = JOIN A by $0, B by LOWER($0); " + "CACHE A; " + "STORE A INTO 'output' using mock.Storage;", "A = LOAD 'input' using mock.Storage; " + "B = LOAD 'input' using mock.Storage; " + "A = JOIN A by $0, B by UPPER($0); " + "CACHE A; " + "STORE A INTO 'output' using mock.Storage;"); } @Test public void testIgnoreDiffFilterCache() throws Exception { testIgnoreCache("A = LOAD 'input' using mock.Storage;" + "A = FILTER A by $0 == 'test1';" + "CACHE A;" + "STORE A INTO 'output' using mock.Storage;", "A = LOAD 'input' using mock.Storage;" + "A = FILTER A by $0 == 'test2';" + "CACHE A;" + "STORE A INTO 'output' using mock.Storage;"); } public void testIgnoreCache(String query1, String query2) throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("test1"), tuple("test2")); pigServer.setBatchOn(); pigServer.registerQuery(query1); pigServer.executeBatch(); List<Tuple> originalOutput = data.get("output"); LOG.debug("After first query: " + originalOutput); data = Storage.resetData(pigServer); data.set("input", tuple("test3"), tuple("test4")); pigServer.registerQuery(query2); pigServer.executeBatch(); LOG.debug("After second query: " + data.get("output")); Assert.assertFalse( originalOutput.equals( data.get("output"))); } /** * Kind of a hack: To test whether caching is happening, we modify a file on disk after caching * it in Spark. */ private void testCaching(String query) throws Exception { PigServer pigServer = newPigServer(); Data data = Storage.resetData(pigServer); data.set("input", tuple("test1"), tuple("test2")); pigServer.setBatchOn(); pigServer.registerQuery(query); pigServer.executeBatch(); LOG.debug("After first query: " + data.get("output")); List<Tuple> originalOutput = data.get("output"); data = Storage.resetData(pigServer); data.set("input", tuple("test3"), tuple("test4")); pigServer.registerQuery("STORE A INTO 'output' using mock.Storage;"); pigServer.executeBatch(); LOG.debug("After second query: " + data.get("output")); assertEquals( originalOutput, data.get("output")); } }
package net.sf.farrago.fennel; import java.util.Arrays; /** * FennelPseudoUuid represents universal unique identifiers (UUIDs). UUIDs * are generated via Fennel (via {@link FennelPseudoUuidGenerator}) in a way * that abstracts away OS and hardware dependencies. * * <p>Depends on Fennel's libfarrago. * * @author Stephan Zuercher * @version $Id$ */ public class FennelPseudoUuid { public static final int UUID_LENGTH = 16; private final byte[] uuid; /** * Creates a FennelPseudoUuid with the given bytes. Use * {@link FennelPseudoUuidGenerator#validUuid()} or * {@link FennelPseudoUuidGenerator#invalidUuid()} to create a UUID. */ public FennelPseudoUuid(byte[] bytes) { this.uuid = (byte[])bytes.clone(); validate(); } public FennelPseudoUuid(String uuidStr) { this.uuid = parse(uuidStr); validate(); } /** * @return a copy of the byte array that backs this FennelPseudoUuid. */ public byte[] getBytes() { byte[] copy = new byte[UUID_LENGTH]; for(int i = 0; i < UUID_LENGTH; i++) { copy[i] = uuid[i]; } return copy; } /** * Returns the byte value at a particular position within the UUID * represented by this instance. * * @param index must be greater than or equal to 0 and less than * {@link #UUID_LENGTH}. * @return the byte value at a particular possition * @throws ArrayIndexOutOfBoundsException * if index is less than 0 or greater than or equal to * {@link #UUID_LENGTH}. */ public byte getByte(int index) { return uuid[index]; } private byte[] parse(String uuid) { if (uuid.length() != 36) { throw new IllegalArgumentException("invalid uuid format"); } byte[] bytes = new byte[UUID_LENGTH]; try { // one 4 byte int for(int i = 0; i < 4; i++) { int b = Integer.parseInt(uuid.substring(i * 2, i * 2 + 2), 16); bytes[i] = (byte)b; } if (uuid.charAt(8) != '-') { throw new IllegalArgumentException("invalid uuid format"); } // three 2 byte ints for(int i = 0; i < 3; i++) { int start = 9 + i * 5; for(int j = 0; j < 2; j++) { int b = Integer.parseInt( uuid.substring( start + j * 2, start + j * 2 + 2), 16); bytes[4 + i * 2 + j] = (byte)b; } if (uuid.charAt(start + 4) != '-') { throw new IllegalArgumentException("invalid uuid format"); } } // one 6-byte int for(int i = 0; i < 6; i++) { int b = Integer.parseInt( uuid.substring(24 + i * 2, 24 + i * 2 + 2), 16); bytes[10 + i] = (byte)b; } } catch(NumberFormatException e) { IllegalArgumentException iae = new IllegalArgumentException("invalid uuid format"); iae.initCause(e); throw iae; } return bytes; } /** * @return UUID in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format */ public String toString() { StringBuffer buffer = new StringBuffer(36); for(int i = 0; i < uuid.length; i++) { if (i == 4 || i == 6 || i == 8 || i == 10) { buffer.append('-'); } String digits = Integer.toHexString((int)uuid[i] & 0xFF); if (digits.length() == 1) { buffer.append('0'); } buffer.append(digits); } return buffer.toString(); } /** * Compares two UUID objects for equality by value. * * @param obj another FennelPseudoUuid object * @return true if the UUIDs are the same, false otherwise * @throws ClassCastException if <code>obj</code> is not a FennelPseudoUuid */ public boolean equals(Object obj) { FennelPseudoUuid other = (FennelPseudoUuid)obj; return Arrays.equals(this.uuid, other.uuid); } public int hashCode() { // REVIEW: SWZ 12/1/2004: This may want a better algorithm. As long // as Fennel's UUIDs are random numbers, this provides a nearly random // distribution of hash code values -- if the UUIDs aren't random (for // instance if they're based on time, MAC address, etc.), that may not // be the case. return ((int)(uuid[0] ^ uuid[4] ^ uuid[8] ^ uuid[12]) & 0xFF) << 24 | ((int)(uuid[1] ^ uuid[5] ^ uuid[9] ^ uuid[13]) & 0xFF) << 16 | ((int)(uuid[2] ^ uuid[6] ^ uuid[10] ^ uuid[14]) & 0xFF) << 8 | ((int)(uuid[3] ^ uuid[7] ^ uuid[11] ^ uuid[15]) & 0xFF); } private void validate() { assert(uuid != null); assert(uuid.length == UUID_LENGTH); } }
package com.valkryst.VTerminal.samples; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.builder.PanelBuilder; import com.valkryst.VTerminal.builder.component.LabelBuilder; import com.valkryst.VTerminal.component.Label; import com.valkryst.VTerminal.component.Screen; import com.valkryst.VTerminal.font.Font; import com.valkryst.VTerminal.font.FontLoader; import com.valkryst.VTerminal.shader.*; import com.valkryst.VTerminal.shader.blur.FastMotionBlurShader; import com.valkryst.VTerminal.shader.blur.GaussianBlurShader; import com.valkryst.VTerminal.shader.blur.MotionBlurShader; import java.io.IOException; import java.net.URISyntaxException; public class SampleShaders { public static void main(final String[] args) throws IOException, URISyntaxException, InterruptedException { final Font font = FontLoader.loadFontFromJar("Fonts/DejaVu Sans Mono/18pt/bitmap.png", "Fonts/DejaVu Sans Mono/18pt/data.fnt", 1); final PanelBuilder builder = new PanelBuilder(); builder.setFont(font); builder.setWidthInCharacters(90); final Panel panel = builder.build(); final Screen screen = panel.getScreen(); Thread.sleep(50); final LabelBuilder labelBuilder = new LabelBuilder(); labelBuilder.setColumnIndex(0); labelBuilder.setRowIndex(0); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using No Shader."); Label label = labelBuilder.build(); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using FastMotionBlurShader (Angle 90, Distance 5)."); label = labelBuilder.build(); final FastMotionBlurShader fastMotionBlurShader = new FastMotionBlurShader(); fastMotionBlurShader.setAngle(90); fastMotionBlurShader.setDistance(5); label.addShaders(fastMotionBlurShader); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using GaussianBlurShader."); label = labelBuilder.build(); label.addShaders(new GaussianBlurShader()); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using MotionBlurShader (Angle 90, Distance 5)."); label = labelBuilder.build(); final MotionBlurShader motionBlurShader = new MotionBlurShader(); motionBlurShader.setAngle(90); motionBlurShader.setDistance(5); label.addShaders(motionBlurShader); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using GlowShader."); label = labelBuilder.build(); label.addShaders(new GlowShader()); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using RayShader."); label = labelBuilder.build(); label.addShaders(new RayShader()); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using SharpenShader."); label = labelBuilder.build(); label.addShaders(new SharpenShader()); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using TextShadowShader."); label = labelBuilder.build(); label.addShaders(new TextShadowShader()); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using TextGlowShader."); label = labelBuilder.build(); label.addShaders(new TextGlowShader()); screen.addComponent(label); labelBuilder.setRowIndex(labelBuilder.getRowIndex() + 1); labelBuilder.setText("Sample text 123456789!@#$%^&*()_+-=. Using TextBoldShader."); label = labelBuilder.build(); label.addShaders(new TextBoldShader()); screen.addComponent(label); panel.draw(); } }
package org.opencms.search.solr; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.CmsResource; import org.opencms.file.collectors.CmsSolrCollector; import org.opencms.file.collectors.I_CmsResourceCollector; import org.opencms.main.OpenCms; import org.opencms.search.CmsSearchIndex; import org.opencms.search.fields.CmsSearchField; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import java.util.List; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the priority resource collectors.<p> */ public class TestCmsSolrCollector extends OpenCmsTestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestCmsSolrCollector(String arg0) { super(arg0); } /** * Test suite for this test class.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); TestSuite suite = new TestSuite(); suite.setName(TestCmsSolrCollector.class.getName()); suite.addTest(new TestCmsSolrCollector("testByQuery")); suite.addTest(new TestCmsSolrCollector("testByContext")); suite.addTest(new TestCmsSolrCollector("testByContextWithQuery")); TestSetup wrapper = new TestSetup(suite) { @Override protected void setUp() { setupOpenCms("solrtest", "/", "/../org/opencms/search/solr"); // disable all lucene indexes for (String indexName : OpenCms.getSearchManager().getIndexNames()) { if (!indexName.equalsIgnoreCase(AllTests.SOLR_ONLINE)) { CmsSearchIndex index = OpenCms.getSearchManager().getIndex(indexName); if (index != null) { index.setEnabled(false); } } } } @Override protected void tearDown() { removeOpenCms(); } }; return wrapper; } /** * Tests the "allInFolderPriorityDesc" resource collector.<p> * * @throws Throwable if something goes wrong */ public void testByQuery() throws Throwable { echo("Testing if Solr is able to do the same as: allInFolderPriorityDateDesc resource collector"); CmsObject cms = getCmsObject(); cms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID)); I_CmsResourceCollector collector = new CmsSolrCollector(); StringBuffer q = new StringBuffer(128); q.append("&fq=parent-folders:\"/sites/default/xmlcontent/\""); q.append("&fq=type:article"); q.append("&rows=" + 3); q.append("&sort=" + CmsSearchField.FIELD_DATE_LASTMODIFIED + " desc"); List<CmsResource> resources = collector.getResults(cms, "byQuery", q.toString()); // assert that 3 files are returned assertEquals(3, resources.size()); CmsResource res; res = resources.get(0); assertEquals("/sites/default/xmlcontent/article_0004.html", res.getRootPath()); res = resources.get(1); assertEquals("/sites/default/xmlcontent/article_0003.html", res.getRootPath()); res = resources.get(2); assertEquals("/sites/default/xmlcontent/article_0002.html", res.getRootPath()); } /** * Tests the "allInFolderPriorityDesc" resource collector.<p> * * @throws Throwable if something goes wrong */ public void testByContext() throws Throwable { echo("Testing testByContext resource collector"); CmsObject cms = getCmsObject(); cms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID)); I_CmsResourceCollector collector = new CmsSolrCollector(); List<CmsResource> resources = collector.getResults(cms, "byContext", null); // assert that 10 files are returned assertEquals(10, resources.size()); } /** * Tests the "allInFolderPriorityDesc" resource collector.<p> * * @throws Throwable if something goes wrong */ public void testByContextWithQuery() throws Throwable { echo("Testing testByContextWithQuery resource collector"); CmsObject cms = getCmsObject(); cms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID)); I_CmsResourceCollector collector = new CmsSolrCollector(); StringBuffer q = new StringBuffer(128); q.append("q="); q.append("+type:article"); q.append("&rows=" + 3); q.append("&sort=" + CmsSearchField.FIELD_DATE_LASTMODIFIED + " desc"); List<CmsResource> resources = collector.getResults(cms, "byContext", q.toString()); // assert that 3 files are returned assertEquals(3, resources.size()); CmsResource res; res = resources.get(0); assertEquals("/sites/default/xmlcontent/article_0004.html", res.getRootPath()); res = resources.get(1); assertEquals("/sites/default/xmlcontent/article_0003.html", res.getRootPath()); res = resources.get(2); assertEquals("/sites/default/xmlcontent/article_0002.html", res.getRootPath()); } }
package com.gani.lib.http; import android.content.Context; import com.gani.lib.json.GJsonObject; import com.gani.lib.logging.GLog; import com.gani.lib.ui.alert.ToastUtils; import org.json.JSONException; import java.io.IOException; import java.io.Serializable; public abstract class GHttpError<HR extends GHttpResponse> implements Serializable { private static final long serialVersionUID = 1L; public enum ErrorType { NETWORK, CODE, JSON, AUTH } private HR response; private String message; private ErrorType type; private Integer code; public GHttpError(HR response) { this.type = null; this.response = response; } String getUrl() { return response.getUrl(); } public HR getResponse() { return response; } public String getMessage() { return message; } public boolean hasError() { return type != null; } private GHttpError setError(ErrorType type, String reportMessage, String logMessage) { GLog.e(getClass(), logMessage); this.type = type; this.message = reportMessage; return this; } private GHttpError setError(ErrorType type, String message) { return setError(type, message, message); } public ErrorType getType() { return type; } public Integer getCode() { return code; } public GHttpError markForJson(JSONException e) { return setError(ErrorType.JSON, GHttp.instance().alertHelper().messageForJsonError(getUrl(), e)); } GHttpError markForCode(int code) { this.code = code; return setError(ErrorType.CODE, GHttp.instance().networkErrorMessage() + " Code: " + code, "HTTP error code: " + code); } GHttpError markForNetwork(IOException e) { return setError(ErrorType.NETWORK, GHttp.instance().networkErrorMessage(), "HTTP exception: " + e); } // The logout part relies on handleDefault() which means that this only applies for foreground network operation (when activity is involved). public GHttpError markForAuth(String logMessagePrefix) { return setError(ErrorType.AUTH, ErrorType.AUTH.name(), logMessagePrefix + " -- logging out (" + getUrl() + ") ..."); } // // TODO: Review. This seems to handle multiple types of error, the distinction is unclear. // public void handleDefault(Context context) { // GLog.t(getClass(), "handleDefault1 " + getClass()); // // To be overidden protected abstract void handle(Context context); public static class Default extends GHttpError<GHttpResponse> { public Default(GHttpResponse response) { super(response); } @Override protected void handle(Context context) { try { GJsonObject restData = getResponse().asRestResponse().getResult(); String message = restData.getNullableString("message"); if (message != null) { ToastUtils.showNormal(message); return; } } catch (JSONException e) { // Will be handled later. } ToastUtils.showNormal(getMessage()); } } }
package hex.schemas; import hex.deeplearning.DeepLearning; import hex.deeplearning.DeepLearningModel.DeepLearningParameters; import water.api.API; import water.api.KeyV1.ModelKeyV1; import water.api.SupervisedModelParametersSchema; import water.fvec.Frame; import java.util.Random; public class DeepLearningV2 extends SupervisedModelBuilderSchema<DeepLearning,DeepLearningV2,DeepLearningV2.DeepLearningParametersV2> { public static final class DeepLearningParametersV2 extends SupervisedModelParametersSchema<DeepLearningParameters, DeepLearningParametersV2> { // Determines the order of parameters in the GUI static public String[] own_fields = new String[] { "n_folds", "keep_cross_validation_splits", "checkpoint", "override_with_best_model", "use_all_factor_levels", "activation", "hidden", "epochs", "train_samples_per_iteration", "target_ratio_comm_to_comp", "seed", "adaptive_rate", "rho", "epsilon", "rate", "rate_annealing", "rate_decay", "momentum_start", "momentum_ramp", "momentum_stable", "nesterov_accelerated_gradient", "input_dropout_ratio", "hidden_dropout_ratios", "l1", "l2", "max_w2", "initial_weight_distribution", "initial_weight_scale", "loss", "score_interval", "score_training_samples", "score_validation_samples", "score_duty_cycle", "classification_stop", "regression_stop", "max_hit_ratio_k", "score_validation_sampling", "diagnostics", "fast_mode", "ignore_const_cols", "force_load_balance", "variable_importances", "replicate_training_data", "single_node_mode", "shuffle_training_data", "missing_values_handling", "quiet_mode", "max_confusion_matrix_size", "autoencoder", "sparse", "col_major", "average_activation", "sparsity_beta", "max_categorical_features", "reproducible", "export_weights_and_biases" }; @API(help="Number of folds for n-fold cross-validation (0 to n)", level = API.Level.critical, direction= API.Direction.INOUT) public int n_folds; @API(help="Keep cross-validation Frames", level = API.Level.expert, direction=API.Direction.INOUT) public boolean keep_cross_validation_splits; /** * A model key associated with a previously trained Deep Learning * model. This option allows users to build a new model as a * continuation of a previously generated model (e.g., by a grid search). */ @API(help = "Model checkpoint to resume training with", level = API.Level.secondary, direction=API.Direction.INOUT) public ModelKeyV1 checkpoint; /** * If enabled, store the best model under the destination key of this model at the end of training. * Only applicable if training is not cancelled. */ @API(help = "If enabled, override the final model with the best model found during training", level = API.Level.expert, direction=API.Direction.INOUT) public boolean override_with_best_model; @API(help = "Auto-Encoder (Experimental)", level = API.Level.secondary, direction=API.Direction.INOUT) public boolean autoencoder; @API(help="Use all factor levels of categorical variables. Otherwise, the first factor level is omitted (without loss of accuracy). Useful for variable importances and auto-enabled for autoencoder.", level = API.Level.secondary, direction=API.Direction.INOUT) public boolean use_all_factor_levels; /*Neural Net Topology*/ /** * The activation function (non-linearity) to be used the neurons in the hidden layers. * Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid). * Rectifier: Chooses the maximum of (0, x) where x is the input value. * Maxout: Choose the maximum coordinate of the input vector. * With Dropout: Zero out a random user-given fraction of the * incoming weights to each hidden layer during training, for each * training row. This effectively trains exponentially many models at * once, and can improve generalization. */ @API(help = "Activation function", values = { "Tanh", "TanhWithDropout", "Rectifier", "RectifierWithDropout", "Maxout", "MaxoutWithDropout" }, level=API.Level.critical, direction=API.Direction.INOUT) public DeepLearningParameters.Activation activation; /** * The number and size of each hidden layer in the model. * For example, if a user specifies "100,200,100" a model with 3 hidden * layers will be produced, and the middle hidden layer will have 200 * neurons. */ @API(help = "Hidden layer sizes (e.g. 100,100).", level = API.Level.critical, direction=API.Direction.INOUT) public int[] hidden; /** * The number of passes over the training dataset to be carried out. * It is recommended to start with lower values for initial grid searches. * This value can be modified during checkpoint restarts and allows continuation * of selected models. */ @API(help = "How many times the dataset should be iterated (streamed), can be fractional", /* dmin = 1e-3, */ level = API.Level.critical, direction=API.Direction.INOUT) public double epochs; /** * The number of training data rows to be processed per iteration. Note that * independent of this parameter, each row is used immediately to update the model * with (online) stochastic gradient descent. This parameter controls the * synchronization period between nodes in a distributed environment and the * frequency at which scoring and model cancellation can happen. For example, if * it is set to 10,000 on H2O running on 4 nodes, then each node will * process 2,500 rows per iteration, sampling randomly from their local data. * Then, model averaging between the nodes takes place, and scoring can happen * (dependent on scoring interval and duty factor). Special values are 0 for * one epoch per iteration, -1 for processing the maximum amount of data * per iteration (if **replicate training data** is enabled, N epochs * will be trained per iteration on N nodes, otherwise one epoch). Special value * of -2 turns on automatic mode (auto-tuning). */ @API(help = "Number of training samples (globally) per MapReduce iteration. Special values are 0: one epoch, -1: all available data (e.g., replicated training data), -2: automatic", /* lmin = -2, */ level = API.Level.secondary, direction=API.Direction.INOUT) public long train_samples_per_iteration; @API(help = "Target ratio of communication overhead to computation. Only for multi-node operation and train_samples_per_iteration=-2 (auto-tuning)", /* dmin = 1e-3, dmax=0.999, */ level = API.Level.expert, direction=API.Direction.INOUT) public double target_ratio_comm_to_comp; /** * The random seed controls sampling and initialization. Reproducible * results are only expected with single-threaded operation (i.e., * when running on one node, turning off load balancing and providing * a small dataset that fits in one chunk). In general, the * multi-threaded asynchronous updates to the model parameters will * result in (intentional) race conditions and non-reproducible * results. Note that deterministic sampling and initialization might * still lead to some weak sense of determinism in the model. */ @API(help = "Seed for random numbers (affects sampling) - Note: only reproducible when running single threaded", level = API.Level.expert, direction=API.Direction.INOUT) public long seed; /*Adaptive Learning Rate*/ /** * The implemented adaptive learning rate algorithm (ADADELTA) automatically * combines the benefits of learning rate annealing and momentum * training to avoid slow convergence. Specification of only two * parameters (rho and epsilon) simplifies hyper parameter search. * In some cases, manually controlled (non-adaptive) learning rate and * momentum specifications can lead to better results, but require the * specification (and hyper parameter search) of up to 7 parameters. * If the model is built on a topology with many local minima or * long plateaus, it is possible for a constant learning rate to produce * sub-optimal results. Learning rate annealing allows digging deeper into * local minima, while rate decay allows specification of different * learning rates per layer. When the gradient is being estimated in * a long valley in the optimization landscape, a large learning rate * can cause the gradient to oscillate and move in the wrong * direction. When the gradient is computed on a relatively flat * surface with small learning rates, the model can converge far * slower than necessary. */ @API(help = "Adaptive learning rate (ADADELTA)", level = API.Level.secondary, direction=API.Direction.INOUT) public boolean adaptive_rate; /** * The first of two hyper parameters for adaptive learning rate (ADADELTA). * It is similar to momentum and relates to the memory to prior weight updates. * Typical values are between 0.9 and 0.999. * This parameter is only active if adaptive learning rate is enabled. */ @API(help = "Adaptive learning rate time decay factor (similarity to prior updates)", /* dmin = 0.01, dmax = 1, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double rho; /** * The second of two hyper parameters for adaptive learning rate (ADADELTA). * It is similar to learning rate annealing during initial training * and momentum at later stages where it allows forward progress. * Typical values are between 1e-10 and 1e-4. * This parameter is only active if adaptive learning rate is enabled. */ @API(help = "Adaptive learning rate smoothing factor (to avoid divisions by zero and allow progress)", /* dmin = 1e-15, dmax = 1, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double epsilon; /*Learning Rate*/ /** * When adaptive learning rate is disabled, the magnitude of the weight * updates are determined by the user specified learning rate * (potentially annealed), and are a function of the difference * between the predicted value and the target value. That difference, * generally called delta, is only available at the output layer. To * correct the output at each hidden layer, back propagation is * used. Momentum modifies back propagation by allowing prior * iterations to influence the current update. Using the momentum * parameter can aid in avoiding local minima and the associated * instability. Too much momentum can lead to instabilities, that's * why the momentum is best ramped up slowly. * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Learning rate (higher => less stable, lower => slower convergence)", /* dmin = 1e-10, dmax = 1, */ level = API.Level.expert, direction=API.Direction.INOUT) public double rate; /** * Learning rate annealing reduces the learning rate to "freeze" into * local minima in the optimization landscape. The annealing rate is the * inverse of the number of training samples it takes to cut the learning rate in half * (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate). * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Learning rate annealing: rate / (1 + rate_annealing * samples)", /* dmin = 0, dmax = 1, */ level = API.Level.expert, direction=API.Direction.INOUT) public double rate_annealing; /** * The learning rate decay parameter controls the change of learning rate across layers. * For example, assume the rate parameter is set to 0.01, and the rate_decay parameter is set to 0.5. * Then the learning rate for the weights connecting the input and first hidden layer will be 0.01, * the learning rate for the weights connecting the first and the second hidden layer will be 0.005, * and the learning rate for the weights connecting the second and third hidden layer will be 0.0025, etc. * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Learning rate decay factor between layers (N-th layer: rate*alpha^(N-1))", /* dmin = 0, */ level = API.Level.expert, direction=API.Direction.INOUT) public double rate_decay; /*Momentum*/ /** * The momentum_start parameter controls the amount of momentum at the beginning of training. * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Initial momentum at the beginning of training (try 0.5)", /* dmin = 0, dmax = 0.9999999999, */ level = API.Level.expert, direction=API.Direction.INOUT) public double momentum_start; /** * The momentum_ramp parameter controls the amount of learning for which momentum increases * (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number * of training samples. * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Number of training samples for which momentum increases", /* dmin = 1, */ level = API.Level.expert, direction=API.Direction.INOUT) public double momentum_ramp; /** * The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples. * The momentum used for training will remain the same for training beyond reaching that point. * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Final momentum after the ramp is over (try 0.99)", /* dmin = 0, dmax = 0.9999999999, */ level = API.Level.expert, direction=API.Direction.INOUT) public double momentum_stable; /** * The Nesterov accelerated gradient descent method is a modification to * traditional gradient descent for convex functions. The method relies on * gradient information at various points to build a polynomial approximation that * minimizes the residuals in fewer iterations of the descent. * This parameter is only active if adaptive learning rate is disabled. */ @API(help = "Use Nesterov accelerated gradient (recommended)", level = API.Level.expert, direction=API.Direction.INOUT) public boolean nesterov_accelerated_gradient; /*Regularization*/ /** * A fraction of the features for each training row to be omitted from training in order * to improve generalization (dimension sampling). */ @API(help = "Input layer dropout ratio (can improve generalization, try 0.1 or 0.2)", /* dmin = 0, dmax = 1, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double input_dropout_ratio; /** * A fraction of the inputs for each hidden layer to be omitted from training in order * to improve generalization. Defaults to 0.5 for each hidden layer if omitted. */ @API(help = "Hidden layer dropout ratios (can improve generalization), specify one value per hidden layer, defaults to 0.5", /* dmin = 0, dmax = 1, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double[] hidden_dropout_ratios; /** * A regularization method that constrains the absolute value of the weights and * has the net effect of dropping some weights (setting them to zero) from a model * to reduce complexity and avoid overfitting. */ @API(help = "L1 regularization (can add stability and improve generalization, causes many weights to become 0)", /* dmin = 0, dmax = 1, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double l1; /** * A regularization method that constrdains the sum of the squared * weights. This method introduces bias into parameter estimates, but * frequently produces substantial gains in modeling as estimate variance is * reduced. */ @API(help = "L2 regularization (can add stability and improve generalization, causes many weights to be small", /* dmin = 0, dmax = 1, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double l2; /** * A maximum on the sum of the squared incoming weights into * any one neuron. This tuning parameter is especially useful for unbound * activation functions such as Maxout or Rectifier. */ @API(help = "Constraint for squared sum of incoming weights per unit (e.g. for Rectifier)", /* dmin = 1e-10, */ level = API.Level.expert, direction=API.Direction.INOUT) public float max_w2; /*Initialization*/ /** * The distribution from which initial weights are to be drawn. The default * option is an optimized initialization that considers the size of the network. * The "uniform" option uses a uniform distribution with a mean of 0 and a given * interval. The "normal" option draws weights from the standard normal * distribution with a mean of 0 and given standard deviation. */ @API(help = "Initial Weight Distribution", values = { "UniformAdaptive", "Uniform", "Normal" }, level = API.Level.expert, direction=API.Direction.INOUT) public DeepLearningParameters.InitialWeightDistribution initial_weight_distribution; /** * The scale of the distribution function for Uniform or Normal distributions. * For Uniform, the values are drawn uniformly from -initial_weight_scale...initial_weight_scale. * For Normal, the values are drawn from a Normal distribution with a standard deviation of initial_weight_scale. */ @API(help = "Uniform: -value...value, Normal: stddev)", /* dmin = 0, */ level = API.Level.expert, direction=API.Direction.INOUT) public double initial_weight_scale; /** * The loss (error) function to be minimized by the model. * CrossEntropy loss is used when the model output consists of independent * hypotheses, and the outputs can be interpreted as the probability that each * hypothesis is true. Cross entropy is the recommended loss function when the * target values are class labels, and especially for imbalanced data. * It strongly penalizes error in the prediction of the actual class label. * MeanSquare loss is used when the model output are continuous real values, but can * be used for classification as well (where it emphasizes the error on all * output classes, not just for the actual class). */ @API(help = "Loss function", values = { "Automatic", "CrossEntropy", "MeanSquare", "Huber", "Absolute" }, required = false, level = API.Level.expert, direction=API.Direction.INOUT) public DeepLearningParameters.Loss loss; /*Scoring*/ /** * The minimum time (in seconds) to elapse between model scoring. The actual * interval is determined by the number of training samples per iteration and the scoring duty cycle. */ @API(help = "Shortest time interval (in secs) between model scoring", /* dmin = 0, */ level = API.Level.secondary, direction=API.Direction.INOUT) public double score_interval; /** * The number of training dataset points to be used for scoring. Will be * randomly sampled. Use 0 for selecting the entire training dataset. */ @API(help = "Number of training set samples for scoring (0 for all)", /* lmin = 0, */ level = API.Level.secondary, direction=API.Direction.INOUT) public long score_training_samples; /** * The number of validation dataset points to be used for scoring. Can be * randomly sampled or stratified (if "balance classes" is set and "score * validation sampling" is set to stratify). Use 0 for selecting the entire * training dataset. */ @API(help = "Number of validation set samples for scoring (0 for all)", /* lmin = 0, */ level = API.Level.secondary, direction=API.Direction.INOUT) public long score_validation_samples; /** * Maximum fraction of wall clock time spent on model scoring on training and validation samples, * and on diagnostics such as computation of feature importances (i.e., not on training). */ @API(help = "Maximum duty cycle fraction for scoring (lower: more training, higher: more scoring).", /* dmin = 0, dmax = 1, */ level = API.Level.expert, direction=API.Direction.INOUT) public double score_duty_cycle; /** * The stopping criteria in terms of classification error (1-accuracy) on the * training data scoring dataset. When the error is at or below this threshold, * training stops. */ @API(help = "Stopping criterion for classification error fraction on training data (-1 to disable)", /* dmin=-1, dmax=1, */ level = API.Level.expert, direction=API.Direction.INOUT) public double classification_stop; /** * The stopping criteria in terms of regression error (MSE) on the training * data scoring dataset. When the error is at or below this threshold, training * stops. */ @API(help = "Stopping criterion for regression error (MSE) on training data (-1 to disable)", /* dmin=-1, */ level = API.Level.expert, direction=API.Direction.INOUT) public double regression_stop; /** * Enable quiet mode for less output to standard output. */ @API(help = "Enable quiet mode for less output to standard output", level = API.Level.expert, direction=API.Direction.INOUT) public boolean quiet_mode; /** * For classification models, the maximum size (in terms of classes) of the * confusion matrix for it to be printed. This option is meant to avoid printing * extremely large confusion matrices. */ @API(help = "Max. size (number of classes) for confusion matrices to be shown", level = API.Level.expert, direction=API.Direction.INOUT) public int max_confusion_matrix_size; /** * The maximum number (top K) of predictions to use for hit ratio computation (for multi-class only, 0 to disable) */ @API(help = "Max. number (top K) of predictions to use for hit ratio computation (for multi-class only, 0 to disable)", /* lmin=0, */ level = API.Level.expert, direction=API.Direction.INOUT) public int max_hit_ratio_k; /** * Method used to sample the validation dataset for scoring, see Score Validation Samples above. */ @API(help = "Method used to sample validation dataset for scoring", values = { "Uniform", "Stratified" }, level = API.Level.expert, direction=API.Direction.INOUT) public DeepLearningParameters.ClassSamplingMethod score_validation_sampling; /*Misc*/ /** * Gather diagnostics for hidden layers, such as mean and RMS values of learning * rate, momentum, weights and biases. */ @API(help = "Enable diagnostics for hidden layers", level = API.Level.expert, direction=API.Direction.INOUT) public boolean diagnostics; /** * Whether to compute variable importances for input features. * The implemented method (by Gedeon) considers the weights connecting the * input features to the first two hidden layers. */ @API(help = "Compute variable importances for input features (Gedeon method) - can be slow for large networks", direction=API.Direction.INOUT) public boolean variable_importances; /** * Enable fast mode (minor approximation in back-propagation), should not affect results significantly. */ @API(help = "Enable fast mode (minor approximation in back-propagation)", level = API.Level.expert, direction=API.Direction.INOUT) public boolean fast_mode; /** * Ignore constant training columns (no information can be gained anyway). */ @API(help = "Ignore constant training columns (no information can be gained anyway)", level = API.Level.expert, direction=API.Direction.INOUT) public boolean ignore_const_cols; /** * Increase training speed on small datasets by splitting it into many chunks * to allow utilization of all cores. */ @API(help = "Force extra load balancing to increase training speed for small datasets (to keep all cores busy)", level = API.Level.expert, direction=API.Direction.INOUT) public boolean force_load_balance; /** * Replicate the entire training dataset onto every node for faster training on small datasets. */ @API(help = "Replicate the entire training dataset onto every node for faster training on small datasets", level = API.Level.critical, direction=API.Direction.INOUT) public boolean replicate_training_data; /** * Run on a single node for fine-tuning of model parameters. Can be useful for * checkpoint resumes after training on multiple nodes for fast initial * convergence. */ @API(help = "Run on a single node for fine-tuning of model parameters", level = API.Level.expert, direction=API.Direction.INOUT) public boolean single_node_mode; /** * Enable shuffling of training data (on each node). This option is * recommended if training data is replicated on N nodes, and the number of training samples per iteration * is close to N times the dataset size, where all nodes train will (almost) all * the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N * times the dataset size or larger). */ @API(help = "Enable shuffling of training data (recommended if training data is replicated and train_samples_per_iteration is close to #nodes x #rows)", level = API.Level.expert, direction=API.Direction.INOUT) public boolean shuffle_training_data; @API(help = "Handling of missing values. Either Skip or MeanImputation.", values = { "Skip", "MeanImputation" }, level = API.Level.expert, direction=API.Direction.INOUT) public DeepLearningParameters.MissingValuesHandling missing_values_handling; @API(help = "Sparse data handling (Experimental).", level = API.Level.expert, direction=API.Direction.INOUT) public boolean sparse; @API(help = "Use a column major weight matrix for input layer. Can speed up forward propagation, but might slow down backpropagation (Experimental).", level = API.Level.expert, direction=API.Direction.INOUT) public boolean col_major; @API(help = "Average activation for sparse auto-encoder (Experimental)", level = API.Level.expert, direction=API.Direction.INOUT) public double average_activation; @API(help = "Sparsity regularization (Experimental)", level = API.Level.expert, direction=API.Direction.INOUT) public double sparsity_beta; @API(help = "Max. number of categorical features, enforced via hashing (Experimental)", level = API.Level.expert, direction=API.Direction.INOUT) public int max_categorical_features; @API(help = "Force reproducibility on small data (will be slow - only uses 1 thread)", level = API.Level.expert, direction=API.Direction.INOUT) public boolean reproducible; @API(help = "Whether to export Neural Network weights and biases to H2O Frames", level = API.Level.expert, direction=API.Direction.INOUT) public boolean export_weights_and_biases; } }
package ai.h2o.automl; import hex.*; import water.*; import water.api.schemas3.KeyV3; import water.exceptions.H2OIllegalArgumentException; import water.util.Log; import water.util.TwoDimTable; import java.text.SimpleDateFormat; import java.util.*; import static water.DKV.getGet; import static water.Key.make; /** * Utility to track all the models built for a given dataset type. * <p> * Note that if a new Leaderboard is made for the same project it'll * keep using the old model list, which allows us to run AutoML multiple * times and keep adding to the leaderboard. * <p> * The models are returned sorted by either an appropriate default metric * for the model category (auc, mean per class error, or mean residual deviance), * or by a metric that's set via #setMetricAndDirection. * <p> * TODO: make this robust against removal of models from the DKV. */ public class Leaderboard extends Keyed<Leaderboard> { /** * Identifier for models that should be grouped together in the leaderboard * (e.g., "airlines" and "iris"). */ private final String project; /** * List of models for this leaderboard, sorted by metric so that the best is first, * according to the standard metric for the given model type. NOTE: callers should * access this through #models() to make sure they don't get a stale copy. */ private Key<Model>[] models; /** * Sort metrics for the models in this leaderboard, in the same order as the models. */ public double[] sort_metrics; /** * Metric used to sort this leaderboard. */ private String sort_metric; /** * Metric direction used in the sort. */ private boolean sort_decreasing; /** * UserFeedback object used to send, um, feedback to the, ah, user. :-) * Right now this is a "new leader" message. */ private UserFeedback userFeedback; /** HIDEME! */ private Leaderboard() { throw new UnsupportedOperationException("Do not call the default constructor Leaderboard()."); } public Leaderboard(String project, UserFeedback userFeedback) { this._key = make(idForProject(project)); this.project = project; this.userFeedback = userFeedback; Leaderboard old = DKV.getGet(this._key); if (null == old) { this.models = new Key[0]; DKV.put(this); } } // satisfy typing for job return type... public static class LeaderboardKeyV3 extends KeyV3<Iced, LeaderboardKeyV3, Leaderboard> { public LeaderboardKeyV3() { } public LeaderboardKeyV3(Key<Leaderboard> key) { super(key); } } public static String idForProject(String project) { return "AutoML_Leaderboard_" + project; } public String getProject() { return project; } public void setMetricAndDirection(String metric, boolean sortDecreasing){ this.sort_metric = metric; this.sort_decreasing = sortDecreasing; } public void setDefaultMetricAndDirection(Model m) { if (m._output.isBinomialClassifier()) setMetricAndDirection("auc", true); else if (m._output.isClassifier()) setMetricAndDirection("mean_per_class_error", false); else if (m._output.isSupervised()) setMetricAndDirection("residual_deviance", false); } /** * Add the given models to the leaderboard. Note that to make this easier to use from * Grid, which returns its models in random order, we allow the caller to add the same * model multiple times and we eliminate the duplicates here. * @param newModels */ final public void addModels(final Key<Model>[] newModels) { if (null == this._key) throw new H2OIllegalArgumentException("Can't add models to a Leaderboard which isn't in the DKV."); if (this.sort_metric == null) { // lazily set to default for this model category setDefaultMetricAndDirection(newModels[0].get()); } final Key<Model> newLeader[] = new Key[1]; // only set if there's a new leader new TAtomic<Leaderboard>() { @Override final public Leaderboard atomic(Leaderboard old) { if (old == null) old = new Leaderboard(); final Key<Model>[] oldModels = old.models; final Key<Model> oldLeader = (oldModels == null || 0 == oldModels.length) ? null : oldModels[0]; // eliminate duplicates Set<Key<Model>> uniques = new HashSet(oldModels.length + newModels.length); uniques.addAll(Arrays.asList(oldModels)); uniques.addAll(Arrays.asList(newModels)); old.models = uniques.toArray(new Key[0]); // Sort by metric. // TODO: If we want to train on different frames and then compare we need to score all the models and sort on the new metrics. try { List<Key<Model>> newModelsSorted = ModelMetrics.sortModelsByMetric(sort_metric, sort_decreasing, Arrays.asList(old.models)); old.models = newModelsSorted.toArray(new Key[0]); } catch (H2OIllegalArgumentException e) { Log.warn("ModelMetrics.sortModelsByMetric failed: " + e); throw e; } Model[] models = new Model[old.models.length]; old.sort_metrics = old.sortMetrics(modelsForModelKeys(old.models, models)); // NOTE: we've now written over old.models // TODO: should take out of the tatomic if (oldLeader == null || ! oldLeader.equals(old.models[0])) newLeader[0] = old.models[0]; return old; } // atomic }.invoke(this._key); // We've updated the DKV but not this instance, so: this.models = this.modelKeys(); this.sort_metrics = sortMetrics(this.models()); // always EckoClient.updateLeaderboard(this); if (null != newLeader[0]) { userFeedback.info(UserFeedbackEvent.Stage.ModelTraining, "New leader: " + newLeader[0]); } } public void addModel(final Key<Model> key) { Key<Model>keys[] = new Key[1]; keys[0] = key; addModels(keys); } public void addModel(final Model model) { Key<Model>keys[] = new Key[1]; keys[0] = model._key; addModels(keys); } private static Model[] modelsForModelKeys(Key<Model>[] modelKeys, Model[] models) { assert models.length >= modelKeys.length; int i = 0; for (Key<Model> modelKey : modelKeys) models[i++] = getGet(modelKey); return models; } /** * @return list of keys of models sorted by the default metric for the model category, fetched from the DKV */ public Key<Model>[] modelKeys() { return ((Leaderboard)DKV.getGet(this._key)).models; } /** * @return list of keys of models sorted by the given metric , fetched from the DKV */ public Key<Model>[] modelKeys(String metric, boolean sortDecreasing) { Key<Model>[] models = modelKeys(); List<Key<Model>> newModelsSorted = ModelMetrics.sortModelsByMetric(metric, sortDecreasing, Arrays.asList(models)); return newModelsSorted.toArray(new Key[0]); } /** * @return list of models sorted by the default metric for the model category */ public Model[] models() { Key<Model>[] modelKeys = modelKeys(); if (modelKeys == null || 0 == modelKeys.length) return new Model[0]; Model[] models = new Model[modelKeys.length]; return modelsForModelKeys(modelKeys, models); } /** * @return list of models sorted by the given metric */ public Model[] models(String metric, boolean sortDecreasing) { Key<Model>[] modelKeys = modelKeys(metric, sortDecreasing); if (modelKeys == null || 0 == modelKeys.length) return new Model[0]; Model[] models = new Model[modelKeys.length]; return modelsForModelKeys(modelKeys, models); } public Model leader() { Key<Model>[] modelKeys = modelKeys(); if (modelKeys == null || 0 == modelKeys.length) return null; return modelKeys[0].get(); } public long[] timestamps(Model[] models) { long[] timestamps = new long[models.length]; int i = 0; for (Model m : models) timestamps[i++] = m._output._end_time; return timestamps; } public double[] sortMetrics(Model[] models) { double[] sort_metrics = new double[models.length]; int i = 0; for (Model m : models) sort_metrics[i++] = defaultMetricForModel(m); return sort_metrics; } /** * Delete everything in the DKV that this points to. We currently need to be able to call this after deleteWithChildren(). */ public void delete() { remove(); } public void deleteWithChildren() { for (Model m : models()) m.delete(); delete(); } public static double defaultMetricForModel(Model m) { ModelMetrics mm = m._output._cross_validation_metrics != null ? m._output._cross_validation_metrics : m._output._validation_metrics != null ? m._output._validation_metrics : m._output._training_metrics; if (m._output.isBinomialClassifier()) { return(((ModelMetricsBinomial)mm).auc()); } else if (m._output.isClassifier()) { return(((ModelMetricsMultinomial)mm).mean_per_class_error()); } else if (m._output.isSupervised()) { return(((ModelMetricsRegression)mm).residual_deviance()); } Log.warn("Failed to find metric for model: " + m); return Double.NaN; } public static String defaultMetricNameForModel(Model m) { if (m._output.isBinomialClassifier()) { return "auc"; } else if (m._output.isClassifier()) { return "mean per-class error"; } else if (m._output.isSupervised()) { return "residual deviance"; } return "unknown"; } public String rankTsv() { String fieldSeparator = "\\t"; String lineSeparator = "\\n"; StringBuffer sb = new StringBuffer(); // sb.append("Rank").append(fieldSeparator).append("Error").append(lineSeparator); sb.append("Error").append(lineSeparator); Model[] models = models(); for (int i = models.length - 1; i >= 0; i // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. Model m = models[i]; sb.append(defaultMetricForModel(m)); sb.append(lineSeparator); } return sb.toString(); } public String timeTsv() { String fieldSeparator = "\\t"; String lineSeparator = "\\n"; StringBuffer sb = new StringBuffer(); sb.append("Time").append(fieldSeparator).append("Error").append(lineSeparator); Model[] models = models(); for (int i = models.length - 1; i >= 0; i // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. Model m = models[i]; sb.append(timestampFormat.format(m._output._end_time)); sb.append(fieldSeparator); sb.append(defaultMetricForModel(m)); sb.append(lineSeparator); } return sb.toString(); } protected static final String[] colHeaders = { "model ID", "timestamp", "metric" }; protected static final String[] colTypes= { "string", "string", "double" }; protected static final String[] colFormats= { "%s", "%s", "%1.6d" }; public static final TwoDimTable makeTwoDimTable(String tableHeader, int length) { String[] rowHeaders = new String[length]; for (int i = 0; i < length; i++) rowHeaders[i] = "" + i; return new TwoDimTable(tableHeader, "models sorted in order of metric, best first", rowHeaders, Leaderboard.colHeaders, Leaderboard.colTypes, Leaderboard.colFormats, " } public void addTwoDimTableRow(TwoDimTable table, int row, String[] modelIDs, long[] timestamps, double[] errors) { int col = 0; table.set(row, col++, modelIDs[row]); table.set(row, col++, timestampFormat.format(new Date(timestamps[row]))); table.set(row, col++, errors[row]); } public TwoDimTable toTwoDimTable() { return toTwoDimTable("Leaderboard for project: " + project, false); } public TwoDimTable toTwoDimTable(String tableHeader, boolean leftJustifyModelIds) { Model[] models = this.models(); long[] timestamps = timestamps(models); String[] modelIDsFormatted = new String[models.length]; TwoDimTable table = makeTwoDimTable(tableHeader, models.length); // %-s doesn't work in TwoDimTable.toString(), so fake it here: int maxModelIdLen = -1; for (Model m : models) maxModelIdLen = Math.max(maxModelIdLen, m._key.toString().length()); for (int i = 0; i < models.length; i++) if (leftJustifyModelIds) { modelIDsFormatted[i] = (models[i]._key.toString() + " ") .substring(0, maxModelIdLen); } else { modelIDsFormatted[i] = models[i]._key.toString(); } for (int i = 0; i < models.length; i++) addTwoDimTableRow(table, i, modelIDsFormatted, timestamps, sort_metrics); return table; } private static final SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS"); public static String toString(String project, Model[] models, String fieldSeparator, String lineSeparator, boolean includeTitle, boolean includeHeader, boolean includeTimestamp) { StringBuilder sb = new StringBuilder(); if (includeTitle) { sb.append("Leaderboard for project \"") .append(project) .append("\": "); if (models.length == 0) { sb.append("<empty>"); return sb.toString(); } sb.append(lineSeparator); } boolean printedHeader = false; for (Model m : models) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. if (includeHeader && ! printedHeader) { sb.append("Model_ID"); sb.append(fieldSeparator); sb.append(defaultMetricNameForModel(m)); if (includeTimestamp) { sb.append(fieldSeparator); sb.append("timestamp"); } sb.append(lineSeparator); printedHeader = true; } sb.append(m._key.toString()); sb.append(fieldSeparator); sb.append(defaultMetricForModel(m)); if (includeTimestamp) { sb.append(fieldSeparator); sb.append(timestampFormat.format(m._output._end_time)); } sb.append(lineSeparator); } return sb.toString(); } public String toString(String fieldSeparator, String lineSeparator) { return toString(project, models(), fieldSeparator, lineSeparator, true, true, false); } @Override public String toString() { return toString(" ; ", " | "); } }
package com.getbeamapp.transit; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.getbeamapp.transit.prompt.TransitChromeClient; import junit.framework.TestCase; import android.os.ConditionVariable; public class MainTest extends TestCase { private final TransitCallable noop; public MainTest() { this.noop = new TransitCallable() { @Override public Object evaluate(Object thisArg, Object... arguments) { return null; } }; } public void testExpressionsFromCode() { assertEquals("no arguments", TransitProxy.jsExpressionFromCode("no arguments")); assertEquals("int: 23", TransitProxy.jsExpressionFromCode("int: @", 23)); assertEquals("float: 42.5", TransitProxy.jsExpressionFromCode("float: @", 42.5)); assertEquals("bool: true", TransitProxy.jsExpressionFromCode("bool: @", true)); assertEquals("bool: false", TransitProxy.jsExpressionFromCode("bool: @", false)); assertEquals("string: \"foobar\"", TransitProxy.jsExpressionFromCode("string: @", "foobar")); assertEquals("\"foo\" + \"bar\"", TransitProxy.jsExpressionFromCode("@ + @", "foo", "bar")); assertEquals("'baz' + \"bam\" + 23", TransitProxy.jsExpressionFromCode("'baz' + @ + @", "bam", 23)); } public void testWrongArgumentCount() { assertEquals("arg: @", TransitProxy.jsExpressionFromCode("arg: @")); assertEquals("arg: 1", TransitProxy.jsExpressionFromCode("arg: @", 1, 2)); } public void testCustomRepresentation() { JavaScriptRepresentable object = new JavaScriptRepresentable() { @Override public String getJavaScriptRepresentation() { return "myRepresentation"; } }; assertEquals("return myRepresentation", TransitProxy.jsExpressionFromCode("return @", object)); } public void testInvalidObject() { try { TransitProxy.jsExpressionFromCode("@", this); fail(); } catch (IllegalArgumentException e) { } } public void testFunction() { TransitNativeFunction function = new TransitNativeFunction(null, noop, "some-id"); assertEquals("transit.nativeFunction(\"some-id\")", function.getJavaScriptRepresentation()); } public void testFunctionInExpression() { TransitNativeFunction function = new TransitNativeFunction(null, noop, "some-id"); assertEquals("transit.nativeFunction(\"some-id\")('foo')", TransitProxy.jsExpressionFromCode("@('foo')", function)); } @SuppressWarnings("unchecked") public void testJsonParsing() throws JSONException { JSONObject o = new JSONObject(); o.put("null", null); o.put("a", 1); JSONObject o2 = new JSONObject(); o2.put("c", "2"); o.put("b", o2); JSONArray a = new JSONArray(); a.put(3); a.put("4"); o.put("d", a); Map<String, Object> map = JsonConverter.toNativeMap(o); assertNull(map.get("null")); assertEquals(1, map.get("a")); assertEquals("2", ((Map<String, Object>) map.get("b")).get("c")); assertEquals(3, ((List<Object>) map.get("d")).get(0)); assertEquals("4", ((List<Object>) map.get("d")).get(1)); } public void testFunctionDisposal() { final ConditionVariable lock = new ConditionVariable(); @SuppressWarnings("unused") TransitNativeFunction function = new TransitNativeFunction(null, noop, "some-id") { @Override protected void finalize() throws Throwable { super.finalize(); lock.open(); } }; function = null; System.gc(); assertTrue("Function not garbage collected.", lock.block(1000)); } }
package sample.hazelcast; import com.hazelcast.config.ClasspathXmlConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) throws Exception { ClasspathXmlConfig config = new ClasspathXmlConfig("my-hazelcast.xml"); HazelcastInstance instance = Hazelcast.newHazelcastInstance(config); IMap<String, List<String>> map = instance.getMap("sample"); List<String> list = new ArrayList<>(); list.add("foo"); list.add("bar"); map.put("one", list); print(map); List<String> saved = map.get("one"); saved.add("fizz"); saved.add("buzz"); System.out.println("original list=" + list); System.out.println("saved list=" + saved); print(map); } private static void print(IMap<?, ?> map) { String text = map.keySet().stream().sorted().map(key -> key + "=" + map.get(key)).collect(Collectors.joining(", ")); System.out.println("map={" + text + "}"); } }
package mil.nga.giat.mage.sdk.login; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.Log; import com.google.common.base.Predicate; import com.google.gson.Gson; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import mil.nga.giat.mage.sdk.R; import mil.nga.giat.mage.sdk.connectivity.ConnectivityUtility; import mil.nga.giat.mage.sdk.datastore.DaoStore; import mil.nga.giat.mage.sdk.datastore.user.User; import mil.nga.giat.mage.sdk.gson.deserializer.UserDeserializer; import mil.nga.giat.mage.sdk.http.client.HttpClientManager; import mil.nga.giat.mage.sdk.preferences.PreferenceHelper; import mil.nga.giat.mage.sdk.utils.DateFormatFactory; import mil.nga.giat.mage.sdk.utils.DeviceUuidFactory; import mil.nga.giat.mage.sdk.utils.PasswordUtility; /** * Performs login to specified server with username and password. * * @author wiedemanns */ public class FormAuthLoginTask extends AbstractAccountTask { private static final String LOG_NAME = FormAuthLoginTask.class.getName(); private DateFormat iso8601Format = DateFormatFactory.ISO8601(); private volatile AccountStatus callbackStatus = null; public FormAuthLoginTask(AccountDelegate delegate, Context context) { super(delegate, context); } /** * Called from execute * * @param params Should contain username, password, and serverURL; in that * order. * @return On success, {@link AccountStatus#getAccountInformation()} * contains the user's token */ @Override protected AccountStatus doInBackground(String... params) { return login(params); } private AccountStatus login(String... params) { // get inputs String username = params[0]; String password = params[1]; String serverURL = params[2]; Boolean needToRegisterDevice = Boolean.valueOf(params[3]); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mApplicationContext); // Make sure you have connectivity if (!ConnectivityUtility.isOnline(mApplicationContext)) { // try disconnected login try { String oldUsername = sharedPreferences.getString(mApplicationContext.getString(R.string.usernameKey), mApplicationContext.getString(R.string.usernameDefaultValue)); String serverURLPref = sharedPreferences.getString(mApplicationContext.getString(R.string.serverURLKey), mApplicationContext.getString(R.string.serverURLDefaultValue)); String oldPasswordHash = sharedPreferences.getString(mApplicationContext.getString(R.string.passwordHashKey), null); if (oldUsername != null && oldPasswordHash != null && !oldPasswordHash.trim().isEmpty()) { if (oldUsername.equals(username) && serverURL.equals(serverURLPref) && PasswordUtility.equal(password, oldPasswordHash)) { // put the token expiration information in the shared preferences long tokenExpirationLength = Math.max(sharedPreferences.getLong(mApplicationContext.getString(R.string.tokenExpirationLengthKey), 0), 0); Date tokenExpiration = new Date(System.currentTimeMillis() + tokenExpirationLength); sharedPreferences.edit().putString(mApplicationContext.getString(R.string.tokenExpirationDateKey), iso8601Format.format(tokenExpiration)).commit(); return new AccountStatus(AccountStatus.Status.DISCONNECTED_LOGIN); } else { return new AccountStatus(AccountStatus.Status.FAILED_LOGIN); } } } catch (Exception e) { Log.e(LOG_NAME, "Could not hash password", e); } List<Integer> errorIndices = new ArrayList<Integer>(); errorIndices.add(2); List<String> errorMessages = new ArrayList<String>(); errorMessages.add("No connection."); return new AccountStatus(AccountStatus.Status.FAILED_LOGIN, errorIndices, errorMessages); } String uuid = new DeviceUuidFactory(mApplicationContext).getDeviceUuid().toString(); if (uuid == null) { List<Integer> errorIndices = new ArrayList<Integer>(); errorIndices.add(2); List<String> errorMessages = new ArrayList<String>(); errorMessages.add("Problem generating device uuid"); return new AccountStatus(AccountStatus.Status.FAILED_LOGIN, errorIndices, errorMessages); } // is server a valid URL? (already checked username and password) try { final URL sURL = new URL(serverURL); ConnectivityUtility.isResolvable(sURL.getHost(), new Predicate<Exception>() { @Override public boolean apply(Exception e) { if (e == null) { PreferenceHelper.getInstance(mApplicationContext).readRemoteApi(sURL, new Predicate<Exception>() { @Override public boolean apply(Exception e) { if (e == null) { callbackStatus = new AccountStatus(AccountStatus.Status.SUCCESSFUL_LOGIN); return true; } else { List<Integer> errorIndices = new ArrayList<Integer>(); errorIndices.add(2); List<String> errorMessages = new ArrayList<String>(); errorMessages.add("Problem connecting to server"); callbackStatus = new AccountStatus(AccountStatus.Status.FAILED_LOGIN, errorIndices, errorMessages); return false; } } }); return true; } else { List<Integer> errorIndices = new ArrayList<Integer>(); errorIndices.add(2); List<String> errorMessages = new ArrayList<String>(); errorMessages.add("Bad hostname"); callbackStatus = new AccountStatus(AccountStatus.Status.FAILED_LOGIN, errorIndices, errorMessages); return false; } } }); int sleepcount = 0; while (callbackStatus == null && sleepcount < 60) { try { Thread.sleep(500); } catch (Exception e) { Log.e(LOG_NAME, "Problem sleeping."); } finally { sleepcount++; } } if (callbackStatus == null) { return new AccountStatus(AccountStatus.Status.FAILED_LOGIN); } else if (!callbackStatus.getStatus().equals(AccountStatus.Status.SUCCESSFUL_LOGIN)) { return callbackStatus; } // else the callback was a success HttpEntity entity = null; try { DefaultHttpClient httpClient = HttpClientManager.getInstance(mApplicationContext).getHttpClient(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("password", password)); nameValuePairs.add(new BasicNameValuePair("uid", uuid)); nameValuePairs.add(new BasicNameValuePair("username", username)); String buildVersion = sharedPreferences.getString(mApplicationContext.getString(R.string.buildVersionKey), null); if (buildVersion != null) { nameValuePairs.add(new BasicNameValuePair("appVersion", buildVersion)); } UrlEncodedFormEntity authParams = new UrlEncodedFormEntity(nameValuePairs); // Does the device need to be registered? if (needToRegisterDevice) { AccountStatus.Status regStatus = registerDevice(serverURL, authParams); if (regStatus.equals(AccountStatus.Status.SUCCESSFUL_REGISTRATION)) { return new AccountStatus(regStatus); } else if (regStatus == AccountStatus.Status.FAILED_LOGIN) { return new AccountStatus(regStatus); } } HttpPost post = new HttpPost(new URL(new URL(serverURL), "api/login").toURI()); post.setEntity(authParams); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); JSONObject json = new JSONObject(EntityUtils.toString(entity)); // put the token information in the shared preferences Editor editor = sharedPreferences.edit(); editor.putString(mApplicationContext.getString(R.string.tokenKey), json.getString("token").trim()).commit(); Log.d(LOG_NAME, "Storing token: " + String.valueOf(sharedPreferences.getString(mApplicationContext.getString(R.string.tokenKey), null))); try { Date tokenExpiration = iso8601Format.parse(json.getString("expirationDate").trim()); long tokenExpirationLength = tokenExpiration.getTime() - (new Date()).getTime(); editor.putString(mApplicationContext.getString(R.string.tokenExpirationDateKey), iso8601Format.format(tokenExpiration)).commit(); editor.putLong(mApplicationContext.getString(R.string.tokenExpirationLengthKey), tokenExpirationLength).commit(); } catch (java.text.ParseException e) { Log.e(LOG_NAME, "Problem parsing token expiration date.", e); } // initialize the current user JSONObject userJson = json.getJSONObject("user"); // if username is different, then clear the db String oldUsername = sharedPreferences.getString(mApplicationContext.getString(R.string.usernameKey), mApplicationContext.getString(R.string.usernameDefaultValue)); String newUsername = userJson.getString("username"); if (oldUsername == null || !oldUsername.equals(newUsername)) { DaoStore.getInstance(mApplicationContext).resetDatabase(); } final Gson userDeserializer = UserDeserializer.getGsonBuilder(mApplicationContext); User user = userDeserializer.fromJson(userJson.toString(), User.class); if (user != null) { user.setCurrentUser(true); user.setFetchedDate(new Date()); user = userHelper.createOrUpdate(user); } else { Log.e(LOG_NAME, "Unable to Deserializer user."); List<Integer> errorIndices = new ArrayList<Integer>(); errorIndices.add(2); List<String> errorMessages = new ArrayList<String>(); errorMessages.add("Problem retrieving your user."); return new AccountStatus(AccountStatus.Status.FAILED_LOGIN, errorIndices, errorMessages); } return new AccountStatus(AccountStatus.Status.SUCCESSFUL_LOGIN, new ArrayList<Integer>(), new ArrayList<String>(), json); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { entity = response.getEntity(); entity.consumeContent(); // Could be that the device is not registered. if (!needToRegisterDevice) { // Try to register it params[3] = Boolean.TRUE.toString(); return login(params); } } } catch (Exception e) { Log.e(LOG_NAME, "Problem logging in.", e); } finally { try { if (entity != null) { entity.consumeContent(); } } catch (Exception e) { } } } catch (MalformedURLException e) { List<Integer> errorIndices = new ArrayList<Integer>(); errorIndices.add(2); List<String> errorMessages = new ArrayList<String>(); errorMessages.add("Bad URL"); return new AccountStatus(AccountStatus.Status.FAILED_LOGIN, errorIndices, errorMessages); } return new AccountStatus(AccountStatus.Status.FAILED_LOGIN); } private AccountStatus.Status registerDevice(String serverURL, UrlEncodedFormEntity authParams) { HttpEntity entity = null; try { DefaultHttpClient httpClient = HttpClientManager.getInstance(mApplicationContext).getHttpClient(); HttpPost register = new HttpPost(new URL(new URL(serverURL), "api/devices").toURI()); register.setEntity(authParams); HttpResponse response = httpClient.execute(register); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); JSONObject jsonObject = new JSONObject(EntityUtils.toString(entity)); if (jsonObject.getBoolean("registered")) { return AccountStatus.Status.ALREADY_REGISTERED; } else { // device registration has been submitted return AccountStatus.Status.SUCCESSFUL_REGISTRATION; } } else { entity = response.getEntity(); String error = EntityUtils.toString(entity); Log.e(LOG_NAME, "Bad request."); Log.e(LOG_NAME, error); } } catch (Exception e) { Log.e(LOG_NAME, "Problem registering device.", e); } finally { try { if (entity != null) { entity.consumeContent(); } } catch (Exception e) { } } return AccountStatus.Status.FAILED_LOGIN; } }
package org.ccnx.ccn.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.util.Arrays; import javax.crypto.Cipher; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.impl.security.crypto.ContentKeys; import org.ccnx.ccn.impl.security.crypto.UnbufferedCipherInputStream; import org.ccnx.ccn.impl.support.DataUtils; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.profiles.access.AccessControlManager; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.SignedInfo; import org.ccnx.ccn.protocol.SignedInfo.ContentType; /** * This abstract class is the superclass of all classes representing an input stream of * bytes segmented and stored in CCN. * * @see SegmentationProfile for description of CCN segmentation */ public abstract class CCNAbstractInputStream extends InputStream implements ContentVerifier { protected static final int MAX_TIMEOUT = 5000; protected CCNHandle _handle; /** * The segment we are currently reading from. */ protected ContentObject _currentSegment = null; /** * information if the stream we are reading is marked GONE (see {@link SignedInfo.ContentType}). */ protected ContentObject _goneSegment = null; /** * Internal stream used for buffering reads. May include filters. */ protected InputStream _segmentReadStream = null; /** * The name prefix of the segmented stream we are reading, up to (but not including) * a segment number. */ protected ContentName _baseName = null; protected PublisherPublicKeyDigest _publisher = null; /** * The segment number to start with. If not specified, is {@link SegmentationProfile.baseSegment()}. */ protected Long _startingSegmentNumber = null; /** * The timeout to use for segment retrieval. * TODO -- provide constructor arguments to set. */ protected int _timeout = MAX_TIMEOUT; /** * Encryption/decryption handler. */ protected Cipher _cipher; protected ContentKeys _keys; /** * If this content uses Merkle Hash Trees or other bulk signatures to amortize * signature cost, we can amortize verification cost as well by caching verification * data as follows: store the currently-verified root signature, so we don't have to re-verify it; * and the verified root hash. For each piece of incoming content, see if it aggregates * to the same root, if so don't reverify signature. If not, assume it's part of * a new tree and change the root. */ protected byte [] _verifiedRootSignature = null; protected byte [] _verifiedProxy = null; /** * The key locator of the content publisher as we read it. */ protected KeyLocator _publisherKeyLocator; protected boolean _atEOF = false; /** * Used for {@link #mark(int)} and {@link #reset()}. */ protected int _readlimit = 0; protected int _markOffset = 0; protected long _markBlock = 0; /** * Set up an input stream to read segmented CCN content under a given name. * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If contains a segment number, will start to read from that * segment. * @param startingSegmentNumber Alternative specification of starting segment number. If * unspecified, will be {@link SegmentationProfile.baseSegment()}. * @param publisher The key we require to have signed this content. If null, will accept any publisher * (subject to higher-level verification). * @param keys The keys to use to decrypt this content. Null if content unencrypted, or another * process will be used to retrieve the keys (for example, an {@link AccessControlManager}). * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by {@link CCNHandle.getHandle()} will be used. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNAbstractInputStream( ContentName baseName, Long startingSegmentNumber, PublisherPublicKeyDigest publisher, ContentKeys keys, CCNHandle handle) throws IOException { super(); if (null == baseName) { throw new IllegalArgumentException("baseName cannot be null!"); } _handle = handle; if (null == _handle) { _handle = CCNHandle.getHandle(); } _publisher = publisher; if (null != keys) { keys.requireDefaultAlgorithm(); _keys = keys; } // So, we assume the name we get in is up to but not including the sequence // numbers, whatever they happen to be. If a starting segment is given, we // open from there, otherwise we open from the leftmost number available. // We assume by the time you've called this, you have a specific version or // whatever you want to open -- this doesn't crawl versions. If you don't // offer a starting segment index, but instead offer the name of a specific // segment, this will use that segment as the starting segment. _baseName = baseName; if (startingSegmentNumber != null) { _startingSegmentNumber = startingSegmentNumber; } else { if (SegmentationProfile.isSegment(baseName)) { _startingSegmentNumber = SegmentationProfile.getSegmentNumber(baseName); baseName = _baseName.parent(); } else { _startingSegmentNumber = SegmentationProfile.baseSegment(); } } } /** * Set up an input stream to read segmented CCN content starting with a given * {@link ContentObject} that has already been retrieved. * @param startingSegment The first segment to read from. If this is not the * first segment of the stream, reading will begin from this point. * We assume that the signature on this segment was verified by our caller. * @param keys The keys to use to decrypt this content. Null if content unencrypted, or another * process will be used to retrieve the keys (for example, an {@link AccessControlManager}). * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by {@link CCNHandle.getHandle()} will be used. * @throws IOException */ public CCNAbstractInputStream(ContentObject startingSegment, ContentKeys keys, CCNHandle handle) throws IOException { super(); _handle = handle; if (null == _handle) { _handle = CCNHandle.getHandle(); } if (null != keys) { keys.requireDefaultAlgorithm(); _keys = keys; } setFirstSegment(startingSegment); _baseName = SegmentationProfile.segmentRoot(startingSegment.name()); try { _startingSegmentNumber = SegmentationProfile.getSegmentNumber(startingSegment.name()); } catch (NumberFormatException nfe) { throw new IOException("Stream starter segment name does not contain a valid segment number, so the stream does not know what content to start with."); } } /** * Set the timeout that will be used for all content retrievals on this stream. * @param timeout */ public void setTimeout(int timeout) { _timeout = timeout; } /** * @return The name used to retrieve segments of this stream (not including the segment number). */ public ContentName getBaseName() { return _baseName; } /** * @return The version of the stream being read, if its name is versioned. */ public CCNTime getVersion() { if (null == _baseName) return null; return VersioningProfile.getTerminalVersionAsTimestampIfVersioned(_baseName); } @Override public int read() throws IOException { byte [] b = new byte[1]; if (read(b, 0, 1) < 0) { return -1; } return (0x000000FF & b[0]); } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] buf, int offset, int len) throws IOException { if (null == buf) throw new NullPointerException("Buffer cannot be null!"); return readInternal(buf, offset, len); } /** * Actual mechanism used to trigger segment retrieval and perform content reads. * Subclasses define different schemes for retrieving content across segments. * See {@link CCNInputStream} and {@link CCNBlockInputStream} for examples. * @param buf As in {@link #read(byte[], int, int)}. * @param offset As in {@link #readInternal(byte[], int, int)}. * @param len As in {@link #read(byte[], int, int)}. * @return As in {@link #readInternal(byte[], int, int)}. * @throws IOException if a segment cannot be retrieved, or there is an error in lower-level * segment retrieval mechanisms. Uses subclasses of IOException to help provide * more information. In particular, throws {@link NoMatchingContentFoundException} when * no content found within the timeout given. */ protected abstract int readInternal(byte [] buf, int offset, int len) throws IOException; /** * Called to set the first segment when opening a stream. This does initialization * and setup particular to the first segment of a stream. Subclasses should not override * unless they really know what they are doing. Calls {@link #setCurrentSegment(ContentObject)} * for the first segment. * @param newSegment Must not be null * @throws IOException */ protected void setFirstSegment(ContentObject newSegment) throws IOException { if (null == newSegment) { throw new NoMatchingContentFoundException("Cannot find first segment of " + getBaseName()); } if (newSegment.signedInfo().getType().equals(ContentType.GONE)) { _goneSegment = newSegment; Log.info("getFirstSegment: got gone segment: " + _goneSegment.name()); } setCurrentSegment(newSegment); } /** * Set up current segment for reading, including preparation for decryption if necessary. * Called after getSegment/getFirstSegment/getNextSegment, which take care of verifying * the segment for us. Assumes newSegment has been verified. * @throws IOException */ protected void setCurrentSegment(ContentObject newSegment) throws IOException { _currentSegment = null; _segmentReadStream = null; if (null == newSegment) { Log.info("FINDME: Setting current segment to null! Did a segment fail to verify?"); return; } _currentSegment = newSegment; // Should we only set these on the first retrieval? // getSegment will ensure we get a requested publisher (if we have one) for the // first segment; once we have a publisher, it will ensure that future segments match it. _publisher = newSegment.signedInfo().getPublisherKeyID(); _publisherKeyLocator = newSegment.signedInfo().getKeyLocator(); if (_goneSegment != newSegment) { // want pointer ==, not equals() here _segmentReadStream = new ByteArrayInputStream(_currentSegment.content()); // if we're decrypting, then set it up now if (_keys != null) { try { // Reuse of current segment OK. Don't expect to have two separate readers // independently use this stream without state confusion anyway. _cipher = _keys.getSegmentDecryptionCipher( SegmentationProfile.getSegmentNumber(_currentSegment.name())); } catch (InvalidKeyException e) { Log.warning("InvalidKeyException: " + e.getMessage()); throw new IOException("InvalidKeyException: " + e.getMessage()); } catch (InvalidAlgorithmParameterException e) { Log.warning("InvalidAlgorithmParameterException: " + e.getMessage()); throw new IOException("InvalidAlgorithmParameterException: " + e.getMessage()); } _segmentReadStream = new UnbufferedCipherInputStream(_segmentReadStream, _cipher); } else { if (_currentSegment.signedInfo().getType().equals(ContentType.ENCR)) { Log.warning("Asked to read encrypted content, but not given a key to decrypt it. Decryption happening at higher level?"); } } } } /** * Rewinds read buffers for current segment to beginning of the segment. * @throws IOException */ protected void rewindSegment() throws IOException { if (null == _currentSegment) { Log.info("Cannot reqind null segment."); } if (null == _segmentReadStream) { setCurrentSegment(_currentSegment); } _segmentReadStream.reset(); // will reset to 0 if mark not caled } /** * Retrieves a specific segment of this stream, indicated by segment number. * Three navigation options: get first (leftmost) segment, get next segment, * or get a specific segment. * Have to assume that everyone is using our segment number encoding. Probably * easier to ask raw streams to use that encoding (e.g. for packet numbers) * than to flag streams as to whether they are using integers or segments. * @param number Segment number to retrieve. See {@link SegmentationProfile} for numbering. * If we already have this segment as {@link #currentSegmentNumber()}, will just * return the current segment, and will not re-retrieve it from the network. * @throws IOException If no matching content found ({@link NoMatchingContentFoundException}), * or if there is an error at lower layers. **/ protected ContentObject getSegment(long number) throws IOException { if (_currentSegment != null) { // what segment do we have right now? maybe we already have it if (currentSegmentNumber() == number){ // we already have this segment... just use it return _currentSegment; } } // If no publisher specified a priori, _publisher will be null and we will get whoever is // available that verifies for first segment. If _publisher specified a priori, or once we have // retrieved a segment and set _publisher to the publisher of that segment, we will continue to // retrieve segments by the same publisher. return SegmentationProfile.getSegment(_baseName, number, _publisher, _timeout, this, _handle); } /** * Checks whether we might have a next segment. * @return Returns false if this content is marked as GONE (#{@link ContentType}), or if we have * retrieved the segment marked as the last one. */ protected boolean hasNextSegment() { // We're looking at content marked GONE if (null != _goneSegment) { Log.info("getNextSegment: We have a gone segment, no next segment. Gone segment: " + _goneSegment.name()); return false; } // Check to see if finalBlockID is the current segment. If so, there should // be no next segment. (If the writer makes a mistake and guesses the wrong // value for finalBlockID, they won't put that wrong value in the segment they're // guessing itself -- unless they want to try to extend a "closed" stream. // Normally by the time they write that segment, they either know they're done or not. if (null != _currentSegment.signedInfo().getFinalBlockID()) { if (Arrays.equals(_currentSegment.signedInfo().getFinalBlockID(), _currentSegment.name().lastComponent())) { Log.info("getNextSegment: there is no next segment. We have segment: " + DataUtils.printHexBytes(_currentSegment.name().lastComponent()) + " which is marked as the final segment."); return false; } } return true; } /** * Retrieve the next segment of the stream. Convenience method, uses {@link #getSegment(long)}. * @return * @throws IOException */ protected ContentObject getNextSegment() throws IOException { if (null == _currentSegment) { Log.info("getNextSegment: no current segment, getting first segment."); return getFirstSegment(); } Log.info("getNextSegment: getting segment after " + _currentSegment.name()); return getSegment(nextSegmentNumber()); } /** * Retrieves the first segment of the stream, based on specified startingSegmentNumber * (see {@link #CCNAbstractInputStream(ContentName, Long, PublisherPublicKeyDigest, ContentKeys, CCNHandle)}). * Convenience method, uses {@link #getSegment(long)}. * @return * @throws IOException */ protected ContentObject getFirstSegment() throws IOException { if (null != _startingSegmentNumber) { ContentObject firstSegment = getSegment(_startingSegmentNumber); Log.info("getFirstSegment: segment number: " + _startingSegmentNumber + " got segment? " + ((null == firstSegment) ? "no " : firstSegment.name())); return firstSegment; } else { throw new IOException("Stream does not have a valid starting segment number."); } } /** * Method to determine whether a retrieved block is the first segment of this stream (as * specified by startingSegmentNumber, (see {@link #CCNAbstractInputStream(ContentName, Long, PublisherPublicKeyDigest, ContentKeys, CCNHandle)}). * Overridden by subclasses to implement narrower constraints on names. Once first * segment is retrieved, further segments can be identified just by segment-naming * conventions (see {@link SegmentationProfile}). * * @param desiredName The expected name prefix for the stream. * For CCNAbstractInputStream, assume that desiredName contains the name up to but not including * segmentation information. * @param segment The potential first segment. * @return True if it is the first segment, false otherwise. */ protected boolean isFirstSegment(ContentName desiredName, ContentObject segment) { if ((null != segment) && (SegmentationProfile.isSegment(segment.name()))) { Log.info("is " + segment.name() + " a first segment of " + desiredName); // In theory, the segment should be at most a versioning component different from desiredName. // In the case of complex segmented objects (e.g. a KeyDirectory), where there is a version, // then some name components, then a segment, desiredName should contain all of those other // name components -- you can't use the usual versioning mechanisms to pull first segment anyway. if (!desiredName.equals(SegmentationProfile.segmentRoot(segment.name()))) { Log.info("Desired name :" + desiredName + " is not a prefix of segment: " + segment.name()); return false; } if (null != _startingSegmentNumber) { return (_startingSegmentNumber.equals(SegmentationProfile.getSegmentNumber(segment.name()))); } else { return SegmentationProfile.isFirstSegment(segment.name()); } } return false; } /** * Verifies the signature on a segment using cached bulk signature data (from Merkle Hash Trees) * if it is available. * TODO -- check to see if it matches desired publisher. * @param segment the segment whose signature to verify in the context of this stream. */ public boolean verify(ContentObject segment) { // First we verify. // Low-level verify just checks that signer actually signed. // High-level verify checks trust. try { // We could have several options here. This segment could be simply signed. // or this could be part of a Merkle Hash Tree. If the latter, we could // already have its signing information. if (null == segment.signature().witness()) { return segment.verify(null); } // Compare to see whether this segment matches the root signature we previously verified, if // not, verify and store the current signature. // We need to compute the proxy regardless. byte [] proxy = segment.computeProxy(); // OK, if we have an existing verified signature, and it matches this segment's // signature, the proxy ought to match as well. if ((null != _verifiedRootSignature) && (Arrays.equals(_verifiedRootSignature, segment.signature().signature()))) { if ((null == proxy) || (null == _verifiedProxy) || (!Arrays.equals(_verifiedProxy, proxy))) { Log.warning("Found segment: " + segment.name() + " whose digest fails to verify; segment length: " + segment.contentLength()); Log.info("Verification failure: " + segment.name() + " timestamp: " + segment.signedInfo().getTimestamp() + " content length: " + segment.contentLength() + " content digest: " + DataUtils.printBytes(segment.contentDigest()) + " proxy: " + DataUtils.printBytes(proxy) + " expected proxy: " + DataUtils.printBytes(_verifiedProxy)); return false; } } else { // Verifying a new segment. See if the signature verifies, otherwise store the signature // and proxy. if (!ContentObject.verify(proxy, segment.signature().signature(), segment.signedInfo(), segment.signature().digestAlgorithm(), null)) { Log.warning("Found segment: " + segment.name().toString() + " whose signature fails to verify; segment length: " + segment.contentLength() + "."); return false; } else { // Remember current verifiers _verifiedRootSignature = segment.signature().signature(); _verifiedProxy = proxy; } } Log.info("Got segment: " + segment.name().toString() + ", verified."); } catch (Exception e) { Log.warning("Got an " + e.getClass().getName() + " exception attempting to verify segment: " + segment.name().toString() + ", treat as failure to verify."); Log.warningStackTrace(e); return false; } return true; } /** * Returns the segment number for the next segment. * Default segmentation generates sequentially-numbered stream * segments but this method may be overridden in subclasses to * perform re-assembly on streams that have been segmented differently. * @return The index of the next segment of stream data. */ public long nextSegmentNumber() { if (null == _currentSegment) { return _startingSegmentNumber.longValue(); } else { return segmentNumber() + 1; } } /** * @return Returns the segment number of the current segment if we have one, otherwise * the expected startingSegmentNumber. */ public long segmentNumber() { if (null == _currentSegment) { return _startingSegmentNumber; } else { // This needs to work on streaming content that is not traditional fragments. // The segmentation profile tries to do that, though it is seeming like the // new segment representation means we will have to assume that representation // even for stream content. return SegmentationProfile.getSegmentNumber(_currentSegment.name()); } } /** * @return Returns the segment number of the current segment if we have one, otherwise -1. */ protected long currentSegmentNumber() { if (null == _currentSegment) { return -1; // make sure we don't match inappropriately } return segmentNumber(); } /** * Checks to see whether this content has been marked as GONE (deleted). Will retrieve the first * segment if we do not already have it in order to make this determination. * @return true if stream is GONE. * @throws IOException if there is difficulty retrieving the first segment. */ public boolean isGone() throws IOException { // TODO: once first segment is always read in constructor this code will change if (null == _currentSegment) { ContentObject firstSegment = getFirstSegment(); if (null != firstSegment) { setFirstSegment(firstSegment); // sets _goneSegment } else { // don't know anything return false; } } // We might have set first segment in constructor, in which case we will also have set _goneSegment if (null != _goneSegment) { return true; } return false; } /** * Return the single segment of a stream marked as GONE. * @return */ public ContentObject deletionInformation() { return _goneSegment; } /** * Callers may need to access information about this stream's publisher. * We eventually should (TODO) ensure that all the segments we're reading * match in publisher information, and cache the verified publisher info. * (In particular once we're doing trust calculations, to ensure we do them * only once per stream.) * But we do verify each segment, so start by pulling what's in the current segment. * @return */ public PublisherPublicKeyDigest publisher() { return _publisher; } /** * @return the key locator for this stream's publisher. */ public KeyLocator publisherKeyLocator() { return _publisherKeyLocator; } /** * @return the name of the current segment held by this string, or "null". Used for debugging. */ public String currentSegmentName() { return ((null == _currentSegment) ? "null" : _currentSegment.name().toString()); } @Override public int available() throws IOException { if (null == _segmentReadStream) return 0; return _segmentReadStream.available(); } /** * @return Whether this stream believes it as at eof (has read past the end of the * last segment of the stream). */ public boolean eof() { //Log.info("Checking eof: there yet? " + _atEOF); return _atEOF; } @Override public void close() throws IOException { // don't have to do anything. } @Override public synchronized void mark(int readlimit) { _readlimit = readlimit; _markBlock = segmentNumber(); if (null == _segmentReadStream) { _markOffset = 0; } else { try { _markOffset = _currentSegment.contentLength() - _segmentReadStream.available(); if (_segmentReadStream.markSupported()) { _segmentReadStream.mark(readlimit); } } catch (IOException e) { throw new RuntimeException(e); } } Log.finer("mark: block: " + segmentNumber() + " offset: " + _markOffset); } @Override public boolean markSupported() { return true; } @Override public synchronized void reset() throws IOException { // TODO: when first block is read in constructor this check can be removed if (_currentSegment == null) { setFirstSegment(getSegment(_markBlock)); } else if (currentSegmentNumber() == _markBlock) { //already have the correct segment if (tell() == _markOffset){ //already have the correct offset } else { // Reset and skip. if (_segmentReadStream.markSupported()) { _segmentReadStream.reset(); Log.finer("reset within block: block: " + segmentNumber() + " offset: " + _markOffset + " eof? " + _atEOF); return; } else { setCurrentSegment(_currentSegment); } } } else { // getSegment doesn't pull segment if we already have the right one setCurrentSegment(getSegment(_markBlock)); } _segmentReadStream.skip(_markOffset); _atEOF = false; Log.finer("reset: block: " + segmentNumber() + " offset: " + _markOffset + " eof? " + _atEOF); } @Override public long skip(long n) throws IOException { Log.info("in skip("+n+")"); if (n < 0) { return 0; } return readInternal(null, 0, (int)n); } /** * @return Currently returns 0. Can be optionally overridden by subclasses. * @throws IOException */ protected int segmentCount() throws IOException { return 0; } /** * Seek a stream to a specific byte offset from the start. Tries to avoid retrieving * extra segments. * @param position * @throws IOException */ public void seek(long position) throws IOException { Log.info("Seeking stream to " + position); // TODO: when first block is read in constructor this check can be removed if ((_currentSegment == null) || (!SegmentationProfile.isFirstSegment(_currentSegment.name()))) { setFirstSegment(getFirstSegment()); skip(position); } else if (position > tell()) { // we are on the first segment already, just move forward skip(position - tell()); } else { // we are on the first segment already, just rewind back to the beginning rewindSegment(); skip(position); } } /** * @return Returns position in byte offset. For CCNAbstractInputStream, provide an inadequate * base implementation that returns the offset into the current segment (not the stream as * a whole). * @throws IOException */ public long tell() throws IOException { return _currentSegment.contentLength() - _segmentReadStream.available(); } /** * @return Total length of the stream, if known, otherwise -1. * @throws IOException */ public long length() throws IOException { return -1; } }