pax_global_header00006660000000000000000000000064136151106640014515gustar00rootroot0000000000000052 comment=93a432e3dbc783b9e091a5c1587bd93f245fed5c wildfly-common-1.5.3.Final/000077500000000000000000000000001361511066400155135ustar00rootroot00000000000000wildfly-common-1.5.3.Final/.gitignore000066400000000000000000000016211361511066400175030ustar00rootroot00000000000000# ignore .svn metadata files .svn # ignore Maven generated target folders ~ target # ignore downloaded maven tools/maven # ignore eclipse files .project .classpath .settings .metadata # ignore m2e annotation processing files .factorypath # ignore IDEA files *.iml *.ipr *.iws .idea # ignore NetBeans files nbactions.xml nb-configuration.xml catalog.xml # maven-ant-tasks.jar test-output transaction.log # vim files *.swp /.gitk-tmp.* atlassian-ide-plugin.xml # temp files *~ # maven versions plugin pom.xml.versionsBackup # hprof dumps /*.hprof # ignore 'randomly' strewn around logs server.log # ignore java crashes hs_err_pid*.log # H2 databases produced by tests *.h2.db # JBoss transaction generated files PutObjectStoreDirHere # ignore mvn-rpmbuild repo /.m2 # ignore eap repo local-repo-eap #These keep hanging around arquillian/*/server.log* client/shade/dependency-reduced-pom.xml #OS X stuff .DS_Store wildfly-common-1.5.3.Final/LICENSE000066400000000000000000000261361361511066400165300ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. wildfly-common-1.5.3.Final/build-include-jdk-misc000066400000000000000000000000001361511066400216430ustar00rootroot00000000000000wildfly-common-1.5.3.Final/build-test-java10000066400000000000000000000000001361511066400205600ustar00rootroot00000000000000wildfly-common-1.5.3.Final/build-test-java11000066400000000000000000000000001361511066400205610ustar00rootroot00000000000000wildfly-common-1.5.3.Final/build-test-java8000066400000000000000000000000001361511066400205070ustar00rootroot00000000000000wildfly-common-1.5.3.Final/build-test-java9000066400000000000000000000000001361511066400205100ustar00rootroot00000000000000wildfly-common-1.5.3.Final/pom.xml000066400000000000000000000161571361511066400170420ustar00rootroot00000000000000 4.0.0 org.wildfly.common wildfly-common 1.5.3.Final org.jboss jboss-parent 34 Apache License 2.0 http://repository.jboss.org/licenses/apache-2.0.txt repo 3.4.0.Final 2.2.0.Final 11 --release=8 org.graalvm.sdk graal-sdk 1.0.0-rc9 provided true com.oracle.substratevm svm 1.0.0-rc9 provided true org.jboss.logging jboss-logging-annotations ${version.org.jboss.logging.jboss-logging-tools} provided org.jboss.logging jboss-logging-processor ${version.org.jboss.logging.jboss-logging-tools} provided org.jboss.logging jboss-logging ${version.org.jboss.logging.jboss-logging} compile true javax.annotation javax.annotation-api 1.3 provided junit junit 4.12 test src/main/resources false target/generated-resources false maven-javadoc-plugin false false ${project.version}
${project.version}
${project.version}
Copyright © 2019 JBoss, a division of Red Hat, Inc.]]> https://docs.oracle.com/javase/8/docs/api/ none org.jboss jdk-misc ${version.jdk-misc}
org.apache.felix maven-bundle-plugin <_fixupmessages>"Classes found in the wrong directory";is:=warning !*._private, org.wildfly.common*;version=${project.version};-noimport:=true * manifest manifest maven-enforcer-plugin enforce-java8-tests deploy enforce java8.home The "java8.home" property must be set on deploy to run tests under Java 8
wildfly-common-1.5.3.Final/src/000077500000000000000000000000001361511066400163025ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/000077500000000000000000000000001361511066400172265ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/000077500000000000000000000000001361511066400201475ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/000077500000000000000000000000001361511066400207365ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/000077500000000000000000000000001361511066400224105ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/000077500000000000000000000000001361511066400237005ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/Assert.java000066400000000000000000000547641361511066400260240ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common; import java.util.Collection; import java.util.Map; import org.wildfly.common._private.CommonMessages; import org.wildfly.common.annotation.NotNull; /** * A set of assertions and checks. * * @author David M. Lloyd */ public final class Assert { private Assert() { } /** * Check that the named parameter is not {@code null}. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @param the value type * @return the value that was passed in * @throws IllegalArgumentException if the value is {@code null} */ @NotNull public static T checkNotNullParam(String name, T value) throws IllegalArgumentException { checkNotNullParamChecked("name", name); checkNotNullParamChecked(name, value); return value; } /** * Check that the named parameter is not {@code null}, using a {@code NullPointerException} as some specifications * require. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @param the value type * @return the value that was passed in * @throws NullPointerException if the value is {@code null} */ @NotNull public static T checkNotNullParamWithNullPointerException(String name, T value) throws NullPointerException { checkNotNullParamChecked("name", name); if (value == null) throw CommonMessages.msg.nullParamNPE(name); return value; } private static void checkNotNullParamChecked(final String name, final T value) { if (value == null) throw CommonMessages.msg.nullParam(name); } /** * Check that a value within the named array parameter is not {@code null}. Use a standard exception message if it * is. * * @param name the parameter name * @param index the array index * @param value the array element value * @param the element value type * @return the array element value that was passed in * @throws IllegalArgumentException if the value is {@code null} */ @NotNull public static T checkNotNullArrayParam(String name, int index, T value) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (value == null) throw CommonMessages.msg.nullArrayParam(index, name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static String checkNotEmptyParam(String name, String value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.isEmpty()) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static CharSequence checkNotEmptyParam(String name, CharSequence value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length() == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static > T checkNotEmptyParam(String name, T value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.isEmpty()) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static > T checkNotEmptyParam(String name, T value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.isEmpty()) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static T[] checkNotEmptyParam(String name, T[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static boolean[] checkNotEmptyParam(String name, boolean[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static byte[] checkNotEmptyParam(String name, byte[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static short[] checkNotEmptyParam(String name, short[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static int[] checkNotEmptyParam(String name, int[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static long[] checkNotEmptyParam(String name, long[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static float[] checkNotEmptyParam(String name, float[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is not empty. Use a standard exception message if it is. * * @param name the parameter name * @param value the parameter value * @return the value that was passed in * @throws IllegalArgumentException if the value is empty */ @NotNull public static double[] checkNotEmptyParam(String name, double[] value) { checkNotNullParamChecked("name", name); checkNotNullParamChecked("value", value); if (value.length == 0) throw CommonMessages.msg.emptyParam(name); return value; } /** * Check that the named parameter is greater than or equal to {@code min}. * * @param name the parameter name * @param min the minimum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is less than the minimum value */ public static void checkMinimumParameter(String name, int min, int actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual < min) throw CommonMessages.msg.paramLessThan(name, min); } /** * Check that the named parameter is greater than or equal to {@code min}. * * @param name the parameter name * @param min the minimum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is less than the minimum value */ public static void checkMinimumParameter(String name, long min, long actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual < min) throw CommonMessages.msg.paramLessThan(name, min); } /** * Check that the named parameter is greater than or equal to {@code min}. * * @param name the parameter name * @param min the minimum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is less than the minimum value */ public static void checkMinimumParameter(String name, float min, float actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual < min) throw CommonMessages.msg.paramLessThan(name, min); } /** * Check that the named parameter is greater than or equal to {@code min}. * * @param name the parameter name * @param min the minimum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is less than the minimum value */ public static void checkMinimumParameter(String name, double min, double actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual < min) throw CommonMessages.msg.paramLessThan(name, min); } /** * Check that the named parameter is less than or equal to {@code max}. * * @param name the parameter name * @param max the maximum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is greater than the minimum value */ public static void checkMaximumParameter(String name, int max, int actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual > max) throw CommonMessages.msg.paramGreaterThan(name, max); } /** * Check that the named parameter is less than or equal to {@code max}. * * @param name the parameter name * @param max the maximum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is greater than the minimum value */ public static void checkMaximumParameter(String name, long max, long actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual > max) throw CommonMessages.msg.paramGreaterThan(name, max); } /** * Check that the named parameter is less than or equal to {@code max}. * * @param name the parameter name * @param max the maximum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is greater than the minimum value */ public static void checkMaximumParameter(String name, float max, float actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual > max) throw CommonMessages.msg.paramGreaterThan(name, max); } /** * Check that the named parameter is less than or equal to {@code max}. * * @param name the parameter name * @param max the maximum value * @param actual the actual parameter value * @throws IllegalArgumentException if the actual value is greater than the minimum value */ public static void checkMaximumParameter(String name, double max, double actual) throws IllegalArgumentException { checkNotNullParamChecked("name", name); if (actual > max) throw CommonMessages.msg.paramGreaterThan(name, max); } /** * Check that the given offset and length fall completely within the bounds of the given array. * * @param array the array to check * @param offs the array offset * @param len the array length * @throws ArrayIndexOutOfBoundsException if the range of the offset and length do not fall within the array bounds */ public static void checkArrayBounds(final Object[] array, final int offs, final int len) throws ArrayIndexOutOfBoundsException { checkNotNullParamChecked("array", array); checkArrayBounds(array.length, offs, len); } /** * Check that the given offset and length fall completely within the bounds of the given array. * * @param array the array to check * @param offs the array offset * @param len the array length * @throws ArrayIndexOutOfBoundsException if the range of the offset and length do not fall within the array bounds */ public static void checkArrayBounds(final byte[] array, final int offs, final int len) throws ArrayIndexOutOfBoundsException { checkNotNullParamChecked("array", array); checkArrayBounds(array.length, offs, len); } /** * Check that the given offset and length fall completely within the bounds of the given array. * * @param array the array to check * @param offs the array offset * @param len the array length * @throws ArrayIndexOutOfBoundsException if the range of the offset and length do not fall within the array bounds */ public static void checkArrayBounds(final char[] array, final int offs, final int len) throws ArrayIndexOutOfBoundsException { checkNotNullParamChecked("array", array); checkArrayBounds(array.length, offs, len); } /** * Check that the given offset and length fall completely within the bounds of the given array. * * @param array the array to check * @param offs the array offset * @param len the array length * @throws ArrayIndexOutOfBoundsException if the range of the offset and length do not fall within the array bounds */ public static void checkArrayBounds(final int[] array, final int offs, final int len) throws ArrayIndexOutOfBoundsException { checkNotNullParamChecked("array", array); checkArrayBounds(array.length, offs, len); } /** * Check that the given offset and length fall completely within the bounds of the given array. * * @param array the array to check * @param offs the array offset * @param len the array length * @throws ArrayIndexOutOfBoundsException if the range of the offset and length do not fall within the array bounds */ public static void checkArrayBounds(final long[] array, final int offs, final int len) throws ArrayIndexOutOfBoundsException { checkNotNullParamChecked("array", array); checkArrayBounds(array.length, offs, len); } /** * Check that the given offset and length fall completely within the bounds of the given array length. * * @param arrayLength the array length to check against * @param offs the array offset * @param len the array length * @throws ArrayIndexOutOfBoundsException if the range of the offset and length do not fall within the array bounds */ public static void checkArrayBounds(final int arrayLength, final int offs, final int len) throws ArrayIndexOutOfBoundsException { checkMinimumParameter("offs", 0, offs); checkMinimumParameter("len", 0, len); if (offs > arrayLength) throw CommonMessages.msg.arrayOffsetGreaterThanLength(offs, arrayLength); if (offs + len > arrayLength) throw CommonMessages.msg.arrayOffsetLengthGreaterThanLength(offs, len, arrayLength); } /** * Assert that the value is not {@code null}. Use a standard assertion failure message if it is. Only * runs if {@code assert} is enabled. * * @param value the not-{@code null} value * @param the value type * @return the value that was passed in */ @NotNull public static T assertNotNull(T value) { assert value != null : CommonMessages.msg.unexpectedNullValue(); return value; } /** * Assert that the given monitor is held by the current thread. Use a standard assertion failure message if it is not. * Only runs if {@code assert} is enabled. * * @param monitor the monitor object * @param the monitor's type * @return the value that was passed in * @throws IllegalArgumentException if the monitor is {@code null} */ @NotNull public static T assertHoldsLock(@NotNull T monitor) { assert Thread.holdsLock(checkNotNullParam("monitor", monitor)) : CommonMessages.msg.expectedLockHold(monitor); return monitor; } /** * Assert that the given monitor is not held by the current thread. Use a standard assertion failure message if it is. * Only runs if {@code assert} is enabled. * * @param monitor the monitor object * @param the monitor's type * @return the value that was passed in * @throws IllegalArgumentException if the monitor is {@code null} */ @NotNull public static T assertNotHoldsLock(@NotNull T monitor) { assert ! Thread.holdsLock(checkNotNullParam("monitor", monitor)) : CommonMessages.msg.expectedLockNotHold(monitor); return monitor; } /** * Assert that the given expression is always {@code true}. * * @param expr the boolean expression * @return the boolean expression */ @SuppressWarnings("ConstantConditions") public static boolean assertTrue(boolean expr) { assert expr : CommonMessages.msg.expectedBoolean(expr); return expr; } /** * Assert that the given expression is always {@code false}. * * @param expr the boolean expression * @return the boolean expression */ @SuppressWarnings("ConstantConditions") public static boolean assertFalse(boolean expr) { assert ! expr : CommonMessages.msg.expectedBoolean(expr); return expr; } /** * Return an exception indicating that the current code was intended to be unreachable. * * @return the exception which may be immediately thrown */ public static IllegalStateException unreachableCode() { return CommonMessages.msg.unreachableCode(); } /** * Return an exception indicating that the current switch case was intended to be unreachable. * * @param obj the switch case value * @return the exception which may be immediately thrown */ @NotNull public static IllegalStateException impossibleSwitchCase(@NotNull Object obj) { Assert.checkNotNullParamChecked("obj", obj); return CommonMessages.msg.impossibleSwitchCase(obj); } /** * Return an exception indicating that the current switch case was intended to be unreachable. * * @param val the switch case value * @return the exception which may be immediately thrown */ @NotNull public static IllegalStateException impossibleSwitchCase(int val) { return CommonMessages.msg.impossibleSwitchCase(Integer.valueOf(val)); } /** * Return an exception indicating that the current switch case was intended to be unreachable. * * @param val the switch case value * @return the exception which may be immediately thrown */ @NotNull public static IllegalStateException impossibleSwitchCase(long val) { return CommonMessages.msg.impossibleSwitchCase(Long.valueOf(val)); } /** * Return an exception explaining that the caller's method is not supported. * * @return the exception */ @NotNull public static UnsupportedOperationException unsupported() { final StackTraceElement element = new Throwable().getStackTrace()[1]; return CommonMessages.msg.unsupported(element.getMethodName(), element.getClassName()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/Branch.java000066400000000000000000000047351361511066400257510ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common; /** * Branch probability directives. On JVMs which support these constructs, */ public final class Branch { private Branch() {} /** * Assert that the given expression is on the "fast path", which is to say, it will be {@code true} more than 99.9% * of the time. * * @param expr the expression value * @return the expression value */ public static boolean veryLikely(boolean expr) { return expr; } /** * Assert that the given expression is on the "slow path", which is to say, it will be {@code false} more than 99.9% * of the time. * * @param expr the expression value * @return the expression value */ public static boolean veryUnlikely(boolean expr) { return expr; } /** * Assert that the given expression is likely, which is to say, it will be {@code true} more than 75% * of the time. * * @param expr the expression value * @return the expression value */ public static boolean likely(boolean expr) { return expr; } /** * Assert that the given expression is unlikely, which is to say, it will be {@code false} more than 75% * of the time. * * @param expr the expression value * @return the expression value */ public static boolean unlikely(boolean expr) { return expr; } /** * Assert that the given expression has the given probability of being {@code true}. * * @param prob the probability where {@code 0.0f ≤ prob ≤ 1.0f} * @param expr the expression value * @return the expression value */ public static boolean probability(float prob, boolean expr) { assert 0.0f <= prob && prob <= 1.0f; return expr; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/Factory.java000066400000000000000000000020201361511066400261440ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common; import java.util.function.Supplier; /** * An object which produces another object. * * @author David M. Lloyd * @see Supplier */ public interface Factory { /** * Create the object. * * @return the object */ T create(); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/HostName.java000066400000000000000000000024451361511066400262660ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common; /** * @deprecated Please use {@link org.wildfly.common.net.HostName} instead. */ public final class HostName { /** * @deprecated Please use {@link org.wildfly.common.net.HostName#getHostName()} instead. */ public static String getHostName() { return org.wildfly.common.net.HostName.getHostName(); } /** * @deprecated Please use {@link org.wildfly.common.net.HostName#getQualifiedHostName()} instead. */ public static String getQualifiedHostName() { return org.wildfly.common.net.HostName.getQualifiedHostName(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/Substitutions.java000066400000000000000000000055271361511066400274530ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.AlwaysInline; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; /** */ final class Substitutions { @TargetClass(Branch.class) static final class Target_Branch { @AlwaysInline("Straight call to GraalVM") @Substitute public static boolean veryLikely(boolean expr) { return Target_GraalDirectives.injectBranchProbability(Target_GraalDirectives.FASTPATH_PROBABILITY, expr); } @AlwaysInline("Straight call to GraalVM") @Substitute public static boolean veryUnlikely(boolean expr) { return Target_GraalDirectives.injectBranchProbability(Target_GraalDirectives.SLOWPATH_PROBABILITY, expr); } @AlwaysInline("Straight call to GraalVM") @Substitute public static boolean likely(boolean expr) { return Target_GraalDirectives.injectBranchProbability(Target_GraalDirectives.LIKELY_PROBABILITY, expr); } @AlwaysInline("Straight call to GraalVM") @Substitute public static boolean unlikely(boolean expr) { return Target_GraalDirectives.injectBranchProbability(Target_GraalDirectives.UNLIKELY_PROBABILITY, expr); } @AlwaysInline("Straight call to GraalVM") @Substitute public static boolean probability(float prob, boolean expr) { return Target_GraalDirectives.injectBranchProbability(prob, expr); } } @TargetClass(className = "org.graalvm.compiler.api.directives.GraalDirectives") static final class Target_GraalDirectives { @Alias public static double LIKELY_PROBABILITY; @Alias public static double UNLIKELY_PROBABILITY; @Alias public static double SLOWPATH_PROBABILITY; @Alias public static double FASTPATH_PROBABILITY; @Alias public static boolean injectBranchProbability(double probability, boolean condition) { assert probability >= 0.0 && probability <= 1.0; return condition; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/_private/000077500000000000000000000000001361511066400255115ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/_private/CommonMessages.java000066400000000000000000000156221361511066400313020ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common._private; import java.io.IOException; import java.security.Permission; import java.security.PrivilegedActionException; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.wildfly.common.codec.DecodeException; /** * @author David M. Lloyd */ @MessageBundle(projectCode = "COM", length = 5) public interface CommonMessages { CommonMessages msg = Messages.getBundle(CommonMessages.class); // simple validation @Message(id = 0, value = "Parameter '%s' may not be null") IllegalArgumentException nullParam(String paramName); @Message(id = 1, value = "Parameter '%s' must not be less than %d") IllegalArgumentException paramLessThan(String name, long min); IllegalArgumentException paramLessThan(String name, double min); @Message(id = 2, value = "Parameter '%s' must not be greater than than %d") IllegalArgumentException paramGreaterThan(String name, long max); IllegalArgumentException paramGreaterThan(String name, double max); @Message(id = 3, value = "Given offset of %d is greater than array length of %d") ArrayIndexOutOfBoundsException arrayOffsetGreaterThanLength(int offs, int arrayLength); @Message(id = 4, value = "Given offset of %d plus length of %d is greater than array length of %d") ArrayIndexOutOfBoundsException arrayOffsetLengthGreaterThanLength(int offs, int len, int arrayLength); @Message(id = 5, value = "Array index %d of parameter '%s' may not be null") IllegalArgumentException nullArrayParam(int index, String name); @Message(id = 6, value = "Parameter '%s' may not be null") NullPointerException nullParamNPE(String name); @Message(id = 7, value = "Invalid permission action '%s'") IllegalArgumentException invalidPermissionAction(String action); @Message(id = 8, value = "Parameter '%s' must not be empty") IllegalArgumentException emptyParam(String name); @Message(id = 9, value = "Invalid expression syntax at position %d") String invalidExpressionSyntax(int index); @Message(id = 10, value = "No environment property found named \"%s\"") IllegalArgumentException unresolvedEnvironmentProperty(String name); @Message(id = 11, value = "No system property found named \"%s\"") IllegalArgumentException unresolvedSystemProperty(String name); @Message(id = 12, value = "Invalid address length of %d; must be 4 or 16") IllegalArgumentException invalidAddressBytes(int length); @Message(id = 13, value = "Invalid address string \"%s\"") IllegalArgumentException invalidAddress(String address); // execution path validation @Message(id = 100, value = "Method \"%s\" of class \"%s\" is not implemented") UnsupportedOperationException unsupported(String methodName, String className); // context classes @Message(id = 200, value = "Privileged action failed") PrivilegedActionException privilegedActionFailed(@Cause Exception e); // permissions @Message(id = 300, value = "Permission collection is read-only") SecurityException readOnlyPermissionCollection(); @Message(id = 301, value = "Invalid permission type (expected %s, actual value was %s)") IllegalArgumentException invalidPermissionType(Class expectedType, Class actualType); // rpc package @Message(id = 400, value = "Invalid serialized remote exception cause object with odd number of strings in fields key/value list") IllegalStateException invalidOddFields(); @Message(id = 401, value = "Field name or field value cannot be null") IllegalArgumentException cannotContainNullFieldNameOrValue(); @Message(id = 402, value = "Remote exception stream is corrupted and cannot be read") IOException corruptedStream(); @Message(value = "Remote exception %s: %s") String remoteException(String exceptionClassName, String message); @Message(value = "Remote exception %s") String remoteException(String exceptionClassName); // bytes package @Message(id = 500, value = "Unexpected padding") DecodeException unexpectedPadding(); @Message(id = 501, value = "Expected padding") DecodeException expectedPadding(); @Message(id = 502, value = "Incomplete decode") DecodeException incompleteDecode(); @Message(id = 503, value = "Expected %d padding characters") DecodeException expectedPaddingCharacters(int numExpected); @Message(id = 504, value = "Invalid base 32 character") DecodeException invalidBase32Character(); @Message(id = 505, value = "Expected an even number of hex characters") DecodeException expectedEvenNumberOfHexCharacters(); @Message(id = 506, value = "Invalid hex character") DecodeException invalidHexCharacter(); @Message(id = 507, value = "Expected two padding characters") DecodeException expectedTwoPaddingCharacters(); @Message(id = 508, value = "Invalid base 64 character") DecodeException invalidBase64Character(); @Message(id = 509, value = "Byte string builder is too large to grow") IllegalStateException tooLarge(); // assertion errors @Message(id = 1000, value = "Internal error: Assertion failure: Unexpectedly null value") String unexpectedNullValue(); @Message(id = 1001, value = "Internal error: Assertion failure: Current thread expected to hold lock for %s") String expectedLockHold(Object monitor); @Message(id = 1002, value = "Internal error: Assertion failure: Current thread expected to not hold lock for %s") String expectedLockNotHold(Object monitor); @Message(id = 1003, value = "Internal error: Assertion failure: Expected boolean value to be %s") String expectedBoolean(boolean expr); // internal state errors @Message(id = 2000, value = "Internal error: Unreachable code has been reached") IllegalStateException unreachableCode(); @Message(id = 2001, value = "Internal error: Impossible switch condition encountered: %s") IllegalStateException impossibleSwitchCase(Object cond); // 3000-3099 reserved for reference queue logging (see {@link org.wildfly.common.ref.Log}) } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/annotation/000077500000000000000000000000001361511066400260525ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/annotation/NotNull.java000066400000000000000000000024351361511066400303140ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An advisory annotation indicating that the given variable, method, or parameter is not nullable. * * @author David M. Lloyd */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER }) @Documented public @interface NotNull { } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/annotation/Nullable.java000066400000000000000000000024321361511066400304540ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An advisory annotation indicating that the given variable, method, or parameter is nullable. * * @author David M. Lloyd */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER }) @Documented public @interface Nullable { } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/000077500000000000000000000000001361511066400253215ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/Archive.java000066400000000000000000000737041361511066400275600ustar00rootroot00000000000000package org.wildfly.common.archive; import static java.lang.Math.min; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import org.wildfly.common.Assert; /** */ public final class Archive implements Closeable { public static final int GP_ENCRYPTED = 1 << 0; // only if method == implode public static final int GP_IMPLODE_8K_DICTIONARY = 1 << 1; public static final int GP_IMPLODE_3_TREES = 1 << 2; // only if method == deflate public static final int GP_DEFLATE_COMP_OPT_MASK = 0b11 << 1; public static final int GP_DEFLATE_COMP_OPT_NORMAL = 0b00 << 1; public static final int GP_DEFLATE_COMP_OPT_MAXIMUM = 0b01 << 1; public static final int GP_DEFLATE_COMP_OPT_FAST = 0b10 << 1; public static final int GP_DEFLATE_COMP_OPT_SUPER_FAST = 0b11 << 1; // only if method == lzma public static final int GP_LZMA_EOS_USED = 1 << 1; public static final int GP_LATE_SIZES = 1 << 3; // reserved 1 << 4 public static final int GP_COMPRESSED_PATCHED = 1 << 5; public static final int GP_STRONG_ENCRYPTION = 1 << 6; // reserved 1 << 7 // reserved 1 << 8 // reserved 1 << 9 // reserved 1 << 10 public static final int GP_UTF_8 = 1 << 11; // reserved 1 << 12 public static final int GP_CD_MASKED = 1 << 13; // reserved 1 << 14 // reserved 1 << 15 public static final int METHOD_STORED = 0; public static final int METHOD_SHRINK = 1; public static final int METHOD_REDUCE_1 = 2; public static final int METHOD_REDUCE_2 = 3; public static final int METHOD_REDUCE_3 = 4; public static final int METHOD_REDUCE_4 = 5; public static final int METHOD_IMPLODE = 6; public static final int METHOD_DEFLATE = 8; public static final int METHOD_DEFLATE64 = 9; public static final int METHOD_BZIP2 = 12; public static final int METHOD_LZMA = 14; public static final int MADE_BY_MS_DOS = 0; public static final int MADE_BY_UNIX = 3; public static final int MADE_BY_NTFS = 10; public static final int MADE_BY_OS_X = 19; public static final int SIG_LH = 0x04034b50; public static final int LH_SIGNATURE = 0; public static final int LH_MIN_VERSION = 4; public static final int LH_GP_BITS = 6; public static final int LH_COMP_METHOD = 8; public static final int LH_MOD_TIME = 10; public static final int LH_MOD_DATE = 12; public static final int LH_CRC_32 = 14; public static final int LH_COMPRESSED_SIZE = 18; public static final int LH_UNCOMPRESSED_SIZE = 22; public static final int LH_FILE_NAME_LENGTH = 26; public static final int LH_EXTRA_LENGTH = 28; public static final int LH_END = 30; public static final int SIG_DD = 0x08074b50; public static final int DD_SIGNATURE = 0; public static final int DD_CRC_32 = 4; public static final int DD_COMPRESSED_SIZE = 8; public static final int DD_UNCOMPRESSED_SIZE = 12; public static final int DD_END = 16; public static final int DD_ZIP64_COMPRESSED_SIZE = 8; public static final int DD_ZIP64_UNCOMPRESSED_SIZE = 16; public static final int DD_ZIP64_END = 24; public static final int SIG_CDE = 0x02014b50; public static final int CDE_SIGNATURE = 0; public static final int CDE_VERSION_MADE_BY = 4; public static final int CDE_VERSION_NEEDED = 6; public static final int CDE_GP_BITS = 8; public static final int CDE_COMP_METHOD = 10; public static final int CDE_MOD_TIME = 12; public static final int CDE_MOD_DATE = 14; public static final int CDE_CRC_32 = 16; public static final int CDE_COMPRESSED_SIZE = 20; public static final int CDE_UNCOMPRESSED_SIZE = 24; public static final int CDE_FILE_NAME_LENGTH = 28; public static final int CDE_EXTRA_LENGTH = 30; public static final int CDE_COMMENT_LENGTH = 32; public static final int CDE_FIRST_DISK_NUMBER = 34; public static final int CDE_INTERNAL_ATTRIBUTES = 36; public static final int CDE_EXTERNAL_ATTRIBUTES = 38; public static final int CDE_LOCAL_HEADER_OFFSET = 42; // relative to the start of the above first disk number public static final int CDE_END = 46; public static final int SIG_EOCD = 0x06054b50; public static final int EOCD_SIGNATURE = 0; public static final int EOCD_DISK_NUMBER = 4; public static final int EOCD_CD_FIRST_DISK_NUMBER = 6; public static final int EOCD_CDE_COUNT_THIS_DISK = 8; public static final int EOCD_CDE_COUNT_ALL = 10; public static final int EOCD_CD_SIZE = 12; public static final int EOCD_CD_START_OFFSET = 16; public static final int EOCD_COMMENT_LENGTH = 20; public static final int EOCD_END = 22; public static final int EXT_ID_ZIP64 = 0x0001; public static final int ZIP64_UNCOMPRESSED_SIZE = 0; public static final int ZIP64_COMPRESSED_SIZE = 8; public static final int ZIP64_LOCAL_HEADER_OFFSET = 16; public static final int ZIP64_FIRST_DISK_NUMBER = 24; // 4 bytes public static final int ZIP64_END = 28; public static final int EXT_ID_UNIX = 0x000d; public static final int UNIX_ACCESS_TIME = 0; public static final int UNIX_MODIFIED_TIME = 4; public static final int UNIX_UID = 8; public static final int UNIX_GID = 10; public static final int UNIX_END = 12; // symlink target public static final int UNIX_DEV_MAJOR = 12; // if it's a device node public static final int UNIX_DEV_MINOR = 16; public static final int UNIX_DEV_END = 20; public static final int SIG_EOCD_ZIP64 = 0x06064b50; public static final int EOCD_ZIP64_SIGNATURE = 0; public static final int EOCD_ZIP64_SIZE = 4; public static final int EOCD_ZIP64_VERSION_MADE_BY = 12; public static final int EOCD_ZIP64_VERSION_NEEDED = 14; public static final int EOCD_ZIP64_DISK_NUMBER = 16; public static final int EOCD_ZIP64_CD_FIRST_DISK_NUMBER = 20; public static final int EOCD_ZIP64_CDE_COUNT_THIS_DISK = 24; public static final int EOCD_ZIP64_CDE_COUNT_ALL = 28; public static final int EOCD_ZIP64_CD_SIZE = 36; public static final int EOCD_ZIP64_CD_START_OFFSET = 44; public static final int EOCD_ZIP64_END = 52; public static final int SIG_EOCDL_ZIP64 = 0x07064b50; public static final int EOCDL_ZIP64_SIGNATURE = 0; public static final int EOCDL_ZIP64_EOCD_DISK_NUMBER = 4; public static final int EOCDL_ZIP64_EOCD_OFFSET = 8; public static final int EOCDL_ZIP64_DISK_COUNT = 16; public static final int EOCDL_ZIP64_END = 20; /** * Maximum size of a single buffer. */ private static final int BUF_SIZE_MAX = 0x4000_0000; private static final int BUF_SHIFT = Integer.numberOfTrailingZeros(BUF_SIZE_MAX); private static final int BUF_SIZE_MASK = BUF_SIZE_MAX - 1; private final ByteBuffer[] bufs; private final long offset; private final long length; private final long cd; private final Index index; private Archive(final ByteBuffer[] bufs, final long offset, final long length, final long cd, final Index index) { this.bufs = bufs; this.offset = offset; this.length = length; this.cd = cd; this.index = index; } public static Archive open(Path path) throws IOException { try (FileChannel fc = FileChannel.open(path, StandardOpenOption.READ)) { long size = fc.size(); final int bufCnt = Math.toIntExact((size + BUF_SIZE_MASK) >> BUF_SHIFT); final ByteBuffer[] array = new ByteBuffer[bufCnt]; long offs = 0; int idx = 0; while (size > BUF_SIZE_MASK) { array[idx++] = fc.map(FileChannel.MapMode.READ_ONLY, offs, BUF_SIZE_MAX).order(ByteOrder.LITTLE_ENDIAN); size -= BUF_SIZE_MAX; offs += BUF_SIZE_MAX; } array[idx] = fc.map(FileChannel.MapMode.READ_ONLY, offs, size).order(ByteOrder.LITTLE_ENDIAN); return open(array); } } public static Archive open(ByteBuffer buf) throws IOException { Assert.checkNotNullParam("buf", buf); if (buf.order() == ByteOrder.BIG_ENDIAN) { buf = buf.duplicate().order(ByteOrder.LITTLE_ENDIAN); } return open(new ByteBuffer[] { buf }); } static Archive open(ByteBuffer[] bufs) throws IOException { return open(bufs, 0, capacity(bufs)); } static Archive open(ByteBuffer[] bufs, long offset, long length) throws IOException { // find the directory by looking first at its expected location and working our way backwards long eocd = length - EOCD_END; // todo: this could be optimized a bit (boyer-moore for example) while (getUnsignedInt(bufs, offset + eocd) != SIG_EOCD) { if (eocd == 0) { throw new IOException("Invalid archive"); } eocd--; } int entries = getUnsignedShort(bufs, offset + eocd + EOCD_CDE_COUNT_ALL); // validate the EOCD record if (getUnsignedShort(bufs, offset + eocd + EOCD_CD_FIRST_DISK_NUMBER) != 0 || getUnsignedShort(bufs, offset + eocd + EOCD_DISK_NUMBER) != 0 || entries != getUnsignedShort(bufs, offset + eocd + EOCD_CDE_COUNT_THIS_DISK)) { throw new IOException("Multi-disk archives are not supported"); } // check now for zip64 long eocdLocZip64 = eocd - EOCDL_ZIP64_END; long eocdZip64 = -1; if (getInt(bufs, offset + eocdLocZip64 + EOCDL_ZIP64_SIGNATURE) == SIG_EOCDL_ZIP64) { // probably zip64 // validate the EOCDL_ZIP64 if (getInt(bufs, offset + eocdLocZip64 + EOCDL_ZIP64_DISK_COUNT) != 1 || getInt(bufs, offset + eocdLocZip64 + EOCDL_ZIP64_EOCD_DISK_NUMBER) != 0) { throw new IOException("Multi-disk archives are not supported"); } eocdZip64 = getLong(bufs, offset + eocdLocZip64 + EOCDL_ZIP64_EOCD_OFFSET); if (getUnsignedInt(bufs, offset + eocdZip64 + EOCD_ZIP64_SIGNATURE) != SIG_EOCD_ZIP64) { // oops, zip64 isn't really present, just bad luck eocdZip64 = -1; } } long cd; cd = getUnsignedInt(bufs, offset + eocd + EOCD_CD_START_OFFSET); if (cd == 0xffffffffL && eocdZip64 != -1) { cd = getLong(bufs, offset + eocdZip64 + EOCD_ZIP64_CD_START_OFFSET); } if (entries == 0xffff && eocdZip64 != -1) { final long cnt = getUnsignedInt(bufs, offset + eocdZip64 + EOCD_ZIP64_CDE_COUNT_ALL); if (cnt > 0x07ff_ffffL) { throw new IOException("Archive has too many entries"); } entries = (int) cnt; } // generate the index Index index; if (length <= 0xfffe) { index = new TinyIndex(entries); } else if (length <= 0xffff_ffffeL) { index = new LargeIndex(entries); } else { index = new HugeIndex(entries); } // iterate the directory final int mask = index.getMask(); long cde = cd; for (int i = 0; i < entries; i ++) { if (getInt(bufs, offset + cde + CDE_SIGNATURE) != SIG_CDE) { throw new IOException("Archive appears to be corrupted"); } int hc = getHashCodeOfEntry(bufs, offset + cde); index.put(hc & mask, cde); cde = cde + CDE_END + getUnsignedShort(bufs, offset + cde + CDE_FILE_NAME_LENGTH) + getUnsignedShort(bufs, offset + cde + CDE_EXTRA_LENGTH) + getUnsignedShort(bufs, offset + cde + CDE_COMMENT_LENGTH); } return new Archive(bufs, offset, length, cd, index); } private static String getNameOfEntry(ByteBuffer[] bufs, long cde) { long name = cde + CDE_END; int nameLen = getUnsignedShort(bufs, cde + CDE_FILE_NAME_LENGTH); boolean utf8 = (getUnsignedShort(bufs, cde + CDE_GP_BITS) & GP_UTF_8) != 0; if (utf8) { return new String(getBytes(bufs, name, nameLen), StandardCharsets.UTF_8); } else { char[] nameChars = new char[nameLen]; for (int i = 0; i < nameLen; i ++) { nameChars[i] = Cp437.charFor(getUnsignedByte(bufs, name + i)); } return new String(nameChars); } } private static int getHashCodeOfEntry(ByteBuffer[] bufs, long cde) { long name = cde + CDE_END; int nameLen = getUnsignedShort(bufs, cde + CDE_FILE_NAME_LENGTH); boolean utf8 = (getUnsignedShort(bufs, cde + CDE_GP_BITS) & GP_UTF_8) != 0; int hc = 0; if (utf8) { int cp; for (int i = 0; i < nameLen; i += Utf8.getByteCount(getUnsignedByte(bufs, name + i))) { cp = Utf8.codePointAt(bufs, name + i); if (Character.isSupplementaryCodePoint(cp)) { hc = hc * 31 + Character.highSurrogate(cp); hc = hc * 31 + Character.lowSurrogate(cp); } else { hc = hc * 31 + cp; } } } else { for (int i = 0; i < nameLen; i ++) { hc = hc * 31 + Cp437.charFor(getUnsignedByte(bufs, name + i)); } } return hc; } public long getFirstEntryHandle() { return cd; } public long getNextEntryHandle(long entryHandle) { final long next = entryHandle + CDE_END + getUnsignedShort(bufs, offset + entryHandle + CDE_FILE_NAME_LENGTH) + getUnsignedShort(bufs, offset + entryHandle + CDE_EXTRA_LENGTH); if (next >= length || getInt(bufs, offset + next + CDE_SIGNATURE) != SIG_CDE) { return -1; } return next; } public long getEntryHandle(String fileName) { final int mask = index.getMask(); final int base = fileName.hashCode(); long entryHandle; for (int i = 0; i < mask; i ++) { entryHandle = index.get(base + i & mask); if (entryHandle == -1) { return -1; } if (entryNameEquals(entryHandle, fileName)) { return entryHandle; } } return -1; } public boolean entryNameEquals(final long entryHandle, final String fileName) { long name = entryHandle + CDE_END; int nameLen = getUnsignedShort(bufs, offset + entryHandle + CDE_FILE_NAME_LENGTH); boolean utf8 = (getUnsignedShort(bufs, offset + entryHandle + CDE_GP_BITS) & GP_UTF_8) != 0; final int length = fileName.length(); if (utf8) { long i; int j; for (i = 0, j = 0; i < nameLen && j < length; i += Utf8.getByteCount(getUnsignedByte(bufs, offset + name + i)), j = fileName.offsetByCodePoints(j, 1)) { if (Utf8.codePointAt(bufs, offset + name + i) != fileName.codePointAt(j)) { return false; } } return i == nameLen && j == length; } else { int i, j; for (i = 0, j = 0; i < nameLen && j < length; i++, j = fileName.offsetByCodePoints(j, 1)) { if (Cp437.charFor(getUnsignedByte(bufs, offset + i + entryHandle + CDE_END)) != fileName.codePointAt(j)) { return false; } } return i == nameLen && j == length; } } private long getLocalHeader(long entryHandle) { long lh = getUnsignedInt(bufs, offset + entryHandle + CDE_LOCAL_HEADER_OFFSET); if (lh == 0xffff_ffffL) { long zip64 = getExtraRecord(entryHandle, EXT_ID_ZIP64); if (zip64 != -1) { lh = getLong(bufs, offset + zip64 + ZIP64_LOCAL_HEADER_OFFSET); } } return lh; } public String getEntryName(long entryHandle) { return getNameOfEntry(bufs, entryHandle); } public ByteBuffer getEntryContents(long entryHandle) throws IOException { long size = getUncompressedSize(entryHandle); long compSize = getCompressedSize(entryHandle); if (size > 0x1000_0000 || compSize > 0x1000_0000) { throw new IOException("Entry is too large to read into RAM"); } long localHeader = getLocalHeader(entryHandle); if ((getUnsignedShort(bufs, offset + localHeader + LH_GP_BITS) & (GP_ENCRYPTED | GP_STRONG_ENCRYPTION)) != 0) { throw new IOException("Cannot read encrypted entries"); } final long offset = getDataOffset(localHeader); final int method = getCompressionMethod(entryHandle); switch (method) { case METHOD_STORED: { return bufferOf(bufs, this.offset + offset, (int) size); } case METHOD_DEFLATE: { final Inflater inflater = new Inflater(true); try { return JDKSpecific.inflate(inflater, bufs, this.offset + offset, (int) compSize, (int) size); } catch (DataFormatException e) { throw new IOException(e); } finally { inflater.end(); } } default: { throw new IOException("Unsupported compression scheme"); } } } private long getDataOffset(final long localHeader) { return localHeader + LH_END + getUnsignedShort(bufs, offset + localHeader + LH_FILE_NAME_LENGTH) + getUnsignedShort(bufs, offset + localHeader + LH_EXTRA_LENGTH); } public InputStream getEntryStream(final long entryHandle) throws IOException { long size = getCompressedSize(entryHandle); long localHeader = getLocalHeader(entryHandle); if ((getUnsignedShort(bufs, offset + localHeader + LH_GP_BITS) & (GP_ENCRYPTED | GP_STRONG_ENCRYPTION)) != 0) { throw new IOException("Cannot read encrypted entries"); } final long offset = getDataOffset(localHeader); final int method = getCompressionMethod(entryHandle); switch (method) { case METHOD_STORED: { return new ByteBufferInputStream(bufs, this.offset + offset, size); } case METHOD_DEFLATE: { return new InflaterInputStream(new ByteBufferInputStream(bufs, this.offset + offset, size)); } default: { throw new IOException("Unsupported compression scheme"); } } } public Archive getNestedArchive(long entryHandle) throws IOException { long localHeader = getLocalHeader(entryHandle); if ((getUnsignedShort(bufs, this.offset + localHeader + LH_GP_BITS) & (GP_ENCRYPTED | GP_STRONG_ENCRYPTION)) != 0) { throw new IOException("Cannot read encrypted entries"); } final long offset = getDataOffset(localHeader); final int method = getCompressionMethod(entryHandle); if (method != METHOD_STORED) { throw new IOException("Cannot open compressed nested archive"); } long size = getUncompressedSize(entryHandle); if (size < Integer.MAX_VALUE) { final ByteBuffer slice = sliceOf(bufs, this.offset + offset, (int) size); if (slice != null) { return Archive.open(slice); } } return Archive.open(bufs, this.offset + offset, size); } public boolean isCompressed(long entryHandle) { return getCompressionMethod(entryHandle) != METHOD_STORED; } private int getCompressionMethod(final long entryHandle) { return getUnsignedShort(bufs, offset + entryHandle + CDE_COMP_METHOD); } private long getExtraRecord(final long entryHandle, final int headerId) { long extra = entryHandle + CDE_END + getUnsignedShort(bufs, offset + entryHandle + CDE_FILE_NAME_LENGTH) + getUnsignedShort(bufs, offset + entryHandle + CDE_COMMENT_LENGTH); int extraLen = getUnsignedShort(bufs, offset + entryHandle + CDE_EXTRA_LENGTH); for (int i = 0; i < extraLen; i = i + getUnsignedShort(bufs, offset + extra + i + 2)) { if (getUnsignedShort(bufs, offset + extra + i) == headerId) { return extra + i + 4; } } return -1; } public long getUncompressedSize(long entryHandle) { long size = getUnsignedInt(bufs, offset + entryHandle + CDE_UNCOMPRESSED_SIZE); if (size == 0xffffffff) { long zip64 = getExtraRecord(entryHandle, EXT_ID_ZIP64); if (zip64 != -1) { size = getLong(bufs, offset + zip64 + ZIP64_UNCOMPRESSED_SIZE); } } return size; } public long getCompressedSize(long entryHandle) { long size = getUnsignedInt(bufs, offset + entryHandle + CDE_COMPRESSED_SIZE); if (size == 0xffffffff) { long zip64 = getExtraRecord(entryHandle, EXT_ID_ZIP64); if (zip64 != -1) { size = getLong(bufs, offset + zip64 + ZIP64_COMPRESSED_SIZE); } } return size; } public long getModifiedTime(long entryHandle) { long unix = getExtraRecord(entryHandle, EXT_ID_UNIX); if (unix != -1) { long unixTime = getUnsignedInt(bufs, offset + unix + UNIX_MODIFIED_TIME); if (unixTime != 0) { return unixTime * 1000; } } // todo: NTFS (0x000a) sub-tag ID 0x0001 contains an 8-byte mtime return dosTimeStamp(getUnsignedShort(bufs, offset + entryHandle + CDE_MOD_TIME), getUnsignedShort(bufs, offset + entryHandle + CDE_MOD_DATE)); } public void close() { } private static long dosTimeStamp(int modTime, int modDate) { int year = 1980 + (modDate >> 9); int month = 1 + ((modDate >> 5) & 0b1111); int day = modDate & 0b11111; int hour = modTime >> 11; int minute = (modTime >> 5) & 0b111111; int second = (modTime & 0b11111) << 1; return LocalDateTime.of(year, month, day, hour, minute, second).toInstant(ZoneOffset.UTC).toEpochMilli(); } public boolean isDirectory(final long entryHandle) { final int madeBy = getUnsignedShort(bufs, offset + entryHandle + CDE_VERSION_MADE_BY); final int extAttr = getInt(bufs, entryHandle + CDE_EXTERNAL_ATTRIBUTES); switch (madeBy) { case MADE_BY_UNIX: { //noinspection OctalInteger return (extAttr & 0170000) == 0040000; } default: { return (extAttr & 0b10000) != 0; } } } /** * Only loaded if CP-437 zip entries exist, which is unlikely but allowed. */ static final class Cp437 { static final char[] codePoints = { '\0','☺', '☻', '♥', '♦', '♣', '♠', '•', '◘', '○', '◙', '♂', '♀', '♪', '♫', '☼', '►', '◄', '↕', '‼', '¶', '§', '▬', '↨', '↑', '↓', '→', '←', '∟', '↔', '▲', '▼', ' ', '!', '"', '#', '$', '%', '&', '\'','(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\',']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '⌂', 'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å', 'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ', 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»', '░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐', '└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧', '╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀', 'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', 0xA0 }; private Cp437() {} static char charFor(int c) { return codePoints[c]; } } static final class Utf8 { private Utf8() {} static int getByteCount(final int a) { if (a <= 0b0111_1111) { return 1; } else if (a <= 0b1011_1111) { // invalid garbage (1 byte) return 1; } else if (a <= 0b1101_1111) { return 2; } else if (a <= 0b1110_1111) { return 3; } else if (a <= 0b1111_0111) { return 4; } else { // invalid garbage (1 byte) return 1; } } static int codePointAt(final ByteBuffer[] bufs, final long i) { final int a = getUnsignedByte(bufs, i); if (a <= 0b0111_1111) { return a; } else if (a <= 0b1011_1111) { // invalid garbage (1 byte) return '�'; } int b = getUnsignedByte(bufs, i + 1); if ((b & 0b11_000000) != 0b10_000000) { // second byte is invalid; return � instead return '�'; } if (a <= 0b1101_1111) { // two bytes return (a & 0b000_11111) << 6 | b & 0b00_111111; } int c = getUnsignedByte(bufs, i + 2); if ((c & 0b11_000000) != 0b10_000000) { // third byte is invalid; return � instead return '�'; } if (a <= 0b1110_1111) { // three bytes return (a & 0b0000_1111) << 12 | (b & 0b00_111111) << 6 | c & 0b00_111111; } int d = getUnsignedByte(bufs, i + 3); if ((d & 0b11_000000) != 0b10_000000) { // fourth byte is invalid; return � instead return '�'; } if (a <= 0b1111_0111) { // four bytes return (a & 0b00000_111) << 18 | (b & 0b00_111111) << 12 | (c & 0b00_111111) << 6 | d & 0b00_111111; } // invalid garbage (1 byte) return '�'; } } static int bufIdx(long idx) { return (int) (idx >>> BUF_SHIFT); } static int bufOffs(long idx) { return ((int)idx) & BUF_SIZE_MASK; } static byte getByte(ByteBuffer[] bufs, long idx) { return bufs[bufIdx(idx)].get(bufOffs(idx)); } static int getUnsignedByte(ByteBuffer[] bufs, long idx) { return getByte(bufs, idx) & 0xff; } static int getUnsignedByte(ByteBuffer buf, int idx) { return buf.get(idx) & 0xff; } static short getShort(ByteBuffer[] bufs, long idx) { final int bi = bufIdx(idx); return bi == bufIdx(idx + 1) ? bufs[bi].getShort(bufOffs(idx)) : (short) (getUnsignedByte(bufs, idx) | getByte(bufs, idx + 1) << 8); } static int getUnsignedShort(ByteBuffer[] bufs, long idx) { return getShort(bufs, idx) & 0xffff; } static int getMedium(ByteBuffer[] bufs, long idx) { return getUnsignedByte(bufs, idx) | getUnsignedShort(bufs, idx + 1) << 8; } static long getUnsignedMedium(ByteBuffer[] bufs, long idx) { return getUnsignedByte(bufs, idx) | getUnsignedShort(bufs, idx + 1) << 8; } static int getInt(ByteBuffer[] bufs, long idx) { final int bi = bufIdx(idx); return bi == bufIdx(idx + 3) ? bufs[bi].getInt(bufOffs(idx)) : getUnsignedShort(bufs, idx) | getShort(bufs, idx + 2) << 16; } static long getUnsignedInt(ByteBuffer[] bufs, long idx) { return getInt(bufs, idx) & 0xffff_ffffL; } static long getLong(ByteBuffer[] bufs, long idx) { final int bi = bufIdx(idx); return bi == bufIdx(idx + 7) ? bufs[bi].getLong(bufOffs(idx)) : getUnsignedInt(bufs, idx) | (long)getInt(bufs, idx + 4) << 32; } static void readBytes(ByteBuffer[] bufs, long idx, byte[] dest, int off, int len) { while (len > 0) { final int bi = bufIdx(idx); final int bo = bufOffs(idx); ByteBuffer buf = bufs[bi].duplicate(); buf.position(bo); final int cnt = min(len, buf.remaining()); buf.get(dest, 0, cnt); len -= cnt; off += cnt; idx += cnt; } } static byte[] getBytes(ByteBuffer[] bufs, long idx, int len) { final byte[] bytes = new byte[len]; readBytes(bufs, idx, bytes, 0, len); return bytes; } private static final ByteBuffer EMPTY_BUF = ByteBuffer.allocateDirect(0); static ByteBuffer sliceOf(ByteBuffer[] bufs, long idx, int len) { if (len == 0) return EMPTY_BUF; final int biStart = bufIdx(idx); final int biEnd = bufIdx(idx + len - 1); if (biStart == biEnd) { final ByteBuffer buf = bufs[biStart].duplicate(); buf.position(bufOffs(idx)); buf.limit(buf.position() + len); return buf.slice(); } else { return null; } } static ByteBuffer bufferOf(ByteBuffer[] bufs, long idx, int len) { ByteBuffer buf = sliceOf(bufs, idx, len); if (buf == null) { buf = ByteBuffer.wrap(getBytes(bufs, idx, len)); } return buf; } static long capacity(ByteBuffer[] bufs) { final int lastIdx = bufs.length - 1; return ((long) lastIdx) * BUF_SIZE_MAX + bufs[lastIdx].capacity(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/ByteBufferInputStream.java000066400000000000000000000030501361511066400324130ustar00rootroot00000000000000package org.wildfly.common.archive; import java.io.InputStream; import java.nio.ByteBuffer; final class ByteBufferInputStream extends InputStream { private final ByteBuffer[] bufs; private final long offset; private final long size; long pos; long mark; ByteBufferInputStream(final ByteBuffer[] bufs, final long offset, final long size) { this.bufs = bufs; this.offset = offset; this.size = size; } public int read() { return pos < size ? Archive.getByte(bufs, offset + pos++) : -1; } public int read(final byte[] b) { return read(b, 0, b.length); } public int read(final byte[] b, final int off, final int len) { final long rem = size - pos; if (rem == 0) return -1; final int realLen = (int) Math.min(len, rem); if (realLen > 0) { Archive.readBytes(bufs, offset + pos, b, off, realLen); return realLen; } else { return 0; } } public long skip(final long n) { final long rem = size - pos; final long cnt = Math.min(rem, n); if (cnt > 0) { pos += cnt; return cnt; } else { return 0; } } public int available() { return (int) Math.min(Integer.MAX_VALUE, size - pos); } public void close() { } public void mark(final int readLimit) { mark = pos; } public void reset() { pos = mark; } public boolean markSupported() { return true; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/HugeIndex.java000066400000000000000000000013021361511066400300400ustar00rootroot00000000000000package org.wildfly.common.archive; import java.util.Arrays; /** * An index for archives greater than 4GB in size. */ final class HugeIndex extends Index { private final long[] table; HugeIndex(final int entries) { super(entries); final long[] array = new long[size()]; Arrays.fill(array, -1); this.table = array; } long get(final int index) { return table[index]; } void put(int index, final long offset) { final long[] table = this.table; long val = table[index]; while (val != -1L) { index = index + 1 & getMask(); val = table[index]; } table[index] = offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/Index.java000066400000000000000000000007661361511066400272440ustar00rootroot00000000000000package org.wildfly.common.archive; /** */ abstract class Index { final int tableSize; Index(final int entries) { if (entries >= 1 << 30) { throw new IllegalStateException("Index is too large"); } this.tableSize = Integer.highestOneBit(entries << 2); } final int size() { return tableSize; } abstract long get(int index); abstract void put(int index, long offset); int getMask() { return tableSize - 1; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/JDKSpecific.java000066400000000000000000000021501361511066400302400ustar00rootroot00000000000000package org.wildfly.common.archive; import static java.lang.Math.min; import java.io.IOException; import java.nio.ByteBuffer; import java.util.zip.DataFormatException; import java.util.zip.Inflater; /** */ final class JDKSpecific { private JDKSpecific() {} static ByteBuffer inflate(final Inflater inflater, final ByteBuffer[] bufs, final long offset, final int compSize, final int uncompSize) throws DataFormatException, IOException { int cnt = 0; byte[] b = new byte[min(16384, compSize)]; byte[] out = new byte[uncompSize]; int op = 0; while (cnt < compSize) { int rem = compSize - cnt; final int acnt = min(rem, b.length); Archive.readBytes(bufs, offset, b, 0, acnt); cnt += acnt; inflater.setInput(b, 0, acnt); do { op += inflater.inflate(out, op, uncompSize - op); } while (! inflater.needsInput()); } if (! inflater.finished()) { throw new IOException("Corrupted compression stream"); } return ByteBuffer.wrap(out); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/LargeIndex.java000066400000000000000000000014171361511066400302110ustar00rootroot00000000000000package org.wildfly.common.archive; import java.util.Arrays; /** * An index for archives between 64KB and 4GB in size. */ final class LargeIndex extends Index { private final int[] table; LargeIndex(final int entries) { super(entries); final int[] array = new int[size()]; Arrays.fill(array, -1); this.table = array; } long get(final int index) { final int val = table[index]; return val == -1 ? -1 : val & 0xffffffff; } void put(int index, final long offset) { final int[] table = this.table; int val = table[index]; while (val != -1L) { index = index + 1 & getMask(); val = table[index]; } table[index] = Math.toIntExact(offset); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/TinyIndex.java000066400000000000000000000014121361511066400300750ustar00rootroot00000000000000package org.wildfly.common.archive; import java.util.Arrays; /** * An index for archives less than 64KB in size. */ final class TinyIndex extends Index { private final short[] table; TinyIndex(final int entries) { super(entries); final short[] array = new short[size()]; Arrays.fill(array, (short) -1); this.table = array; } long get(final int index) { final int val = table[index]; return val == -1 ? -1 : val & 0xffff; } void put(int index, final long offset) { final short[] table = this.table; int val = table[index]; while (val != -1L) { index = index + 1 & getMask(); val = table[index]; } table[index] = (short) offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/archive/package-info.java000066400000000000000000000001451361511066400305100ustar00rootroot00000000000000/** * Classes for dealing with Zip and JAR format archives. */ package org.wildfly.common.archive; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/array/000077500000000000000000000000001361511066400250165ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/array/ArrayIterator.java000066400000000000000000000112161361511066400304520ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.array; import java.util.ListIterator; import java.util.NoSuchElementException; import org.wildfly.common.Assert; import org.wildfly.common.iteration.EnumerationIterator; /** * A read-only iterator over an array. * * @author David M. Lloyd */ public final class ArrayIterator implements ListIterator, EnumerationIterator { private final E[] elements; private final boolean descending; private int idx; /** * Construct a new instance. * * @param elements the elements to iterate over */ public ArrayIterator(final E[] elements) { this(elements, false); } /** * Construct a new instance. * * @param elements the elements to iterate over * @param descending {@code true} to iterate in descending order, {@code false} otherwise */ public ArrayIterator(final E[] elements, final boolean descending) { this(elements, descending, descending ? elements.length : 0); } /** * Construct a new instance. * * @param elements the elements to iterate over * @param startIdx the starting index (must be within the bounds of {@code elements}) */ public ArrayIterator(final E[] elements, final int startIdx) { this(elements, false, startIdx); } /** * Construct a new instance. * * @param elements the elements to iterate over * @param descending {@code true} to iterate in descending order, {@code false} otherwise * @param startIdx the starting index (must be within the bounds of {@code elements}) */ public ArrayIterator(final E[] elements, final boolean descending, final int startIdx) { Assert.checkNotNullParam("elements", elements); Assert.checkMinimumParameter("startIdx", 0, startIdx); Assert.checkMaximumParameter("startIdx", elements.length, startIdx); this.elements = elements; this.descending = descending; this.idx = startIdx; } // ListIterator methods /** * Determine if there are more elements to iterate over in the reverse direction of this iterator. * * @return {@code true} if there are more elements, {@code false} otherwise */ public boolean hasPrevious() { return descending ? idx < elements.length : idx > 0; } /** * Determine if there are more elements to iterate over in the direction of this iterator. * * @return {@code true} if there are more elements, {@code false} otherwise */ public boolean hasNext() { return descending ? idx > 0 : idx < elements.length; } /** * Get the next element in the reverse direction of this iterator. * * @return the next element */ public E previous() { if (! hasPrevious()) throw new NoSuchElementException(); return elements[descending ? idx ++ : -- idx]; } /** * Get the next element in the direction of this iterator. * * @return the next element */ public E next() { if (! hasNext()) throw new NoSuchElementException(); return elements[descending ? -- idx : idx ++]; } /** * Get the next index in the direction of this iterator. * * @return the next index */ public int nextIndex() { return descending ? idx - 1 : idx; } /** * Get the next index in the reverse direction of this iterator. * * @return the next index */ public int previousIndex() { return descending ? idx : idx - 1; } // Unsupported stuff /** * Unsupported. */ public void remove() { throw Assert.unsupported(); } /** * Unsupported. * * @param e ignored */ public void set(final E e) { throw Assert.unsupported(); } /** * Unsupported. * * @param e ignored */ public void add(final E e) { throw Assert.unsupported(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/array/Arrays2.java000066400000000000000000000250241361511066400272070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.array; import java.lang.reflect.Array; import java.util.Arrays; /** * Useful general array manipulations beyond what {@link Arrays} provides. * * @author David M. Lloyd */ public final class Arrays2 { private Arrays2() { } /** * Compare two sub-regions of the given arrays. * * @param a1 the first array (must not be {@code null}) * @param offs1 the offset into the first array * @param a2 the second array (must not be {@code null}) * @param offs2 the offset into the second array * @param len the length to compare * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for an array */ public static boolean equals(byte[] a1, int offs1, byte[] a2, int offs2, int len) { if (offs1 < 0 || offs1 + len > a1.length) return false; if (offs2 < 0 || offs2 + len > a2.length) return false; for (int i = 0; i < len; i ++) { if (a1[i + offs1] != a2[i + offs2]) { return false; } } return true; } /** * Compare two sub-regions of the given arrays. * * @param a1 the first array (must not be {@code null}) * @param offs1 the offset into the first array * @param a2 the second array (must not be {@code null}) * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for an array */ public static boolean equals(byte[] a1, int offs1, byte[] a2) { return equals(a1, offs1, a2, 0, a2.length); } /** * Compare two sub-regions of the given arrays. * * @param a1 the first array (must not be {@code null}) * @param offs1 the offset into the first array * @param a2 the second array (must not be {@code null}) * @param offs2 the offset into the second array * @param len the length to compare * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for an array */ public static boolean equals(char[] a1, int offs1, char[] a2, int offs2, int len) { if (offs1 + len > a1.length) return false; if (offs2 + len > a2.length) return false; for (int i = 0; i < len; i ++) { if (a1[i + offs1] != a2[i + offs2]) { return false; } } return true; } /** * Compare two sub-regions of the given arrays. * * @param a1 the first array (must not be {@code null}) * @param offs1 the offset into the first array * @param a2 the second array (must not be {@code null}) * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for an array */ public static boolean equals(char[] a1, int offs1, char[] a2) { return equals(a1, offs1, a2, 0, a2.length); } /** * Compare two sub-regions of the given array and string. * * @param a1 the array (must not be {@code null}) * @param offs1 the offset into the array * @param a2 the string (must not be {@code null}) * @param offs2 the offset into the string * @param len the length to compare * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for the array or string */ public static boolean equals(char[] a1, int offs1, String a2, int offs2, int len) { if (offs1 + len > a1.length) return false; if (offs2 + len > a2.length()) return false; for (int i = 0; i < len; i ++) { if (a1[i + offs1] != a2.charAt(i + offs2)) { return false; } } return true; } /** * Compare two sub-regions of the given array and string. * * @param a1 the array (must not be {@code null}) * @param offs1 the offset into the array * @param a2 the string (must not be {@code null}) * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for the array or string */ public static boolean equals(char[] a1, int offs1, String a2) { return equals(a1, offs1, a2, 0, a2.length()); } /** * Compare two sub-regions of the given array and string. * * @param a1 the string (must not be {@code null}) * @param offs1 the offset into the string * @param a2 the array (must not be {@code null}) * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for the array or string */ public static boolean equals(String a1, int offs1, char[] a2) { return equals(a2, 0, a1, offs1, a2.length); } /** * Compare the given array and string. * * @param a1 the string (must not be {@code null}) * @param a2 the array (must not be {@code null}) * @return {@code true} if the regions are equal, or {@code false} if the regions are not equal or a length or offset * is out of bounds for the array or string */ public static boolean equals(String a1, char[] a2) { return equals(a1, 0, a2); } /** * Return the varargs list as its array representation. * * @param items the items * @param the item type * @return the array */ @SafeVarargs public static T[] of(final T... items) { return items; } private static char hex(int v) { return (char) (v < 10 ? '0' + v : 'a' + v - 10); } /** * Render the given byte array as a hexadecimal string in big-endian order. * * @param bytes the byte array (must not be {@code null}) * @return the string */ public static String toString(final byte[] bytes) { final StringBuilder b = new StringBuilder(bytes.length * 2); for (byte x : bytes) { b.append(hex((x & 0xf0) >> 4)).append(hex(x & 0x0f)); } return b.toString(); } /** * Find the first occurrence of a byte in a byte array. * * @param array the array to search * @param search the byte to search for * @param offs the offset in the array to start searching * @param len the length of the segment to search * @return the index, or -1 if the byte is not found */ public static int indexOf(byte[] array, int search, int offs, int len) { for (int i = 0; i < len; i ++) { if (array[offs + i] == (byte) search) { return offs + i; } } return -1; } /** * Find the first occurrence of a byte in a byte array. * * @param array the array to search * @param search the byte to search for * @param offs the offset in the array to start searching * @return the index, or -1 if the byte is not found */ public static int indexOf(byte[] array, int search, int offs) { return indexOf(array, search, offs, array.length - offs); } /** * Find the first occurrence of a byte in a byte array. * * @param array the array to search * @param search the byte to search for * @return the index, or -1 if the byte is not found */ public static int indexOf(byte[] array, int search) { return indexOf(array, search, 0, array.length); } /** * Create an array of the given size, ensuring type safety. * * @param elementType the element type class * @param size the array size * @param the element type * @return the array */ @SuppressWarnings("unchecked") public static E[] createArray(Class elementType, int size) { return (E[]) Array.newInstance(elementType, size); } /** * Create a new array from the original which contains no {@code null} values, possibly destroying the * contents of the original array. If the original contains no {@code null} values, the original array is returned. * * @param original the original array (not {@code null}, will be modified) * @param the element type * @return the compacted (possibly empty) array */ public static E[] compactNulls(E[] original) { int r = 0; E item; for (;;) { item = original[r++]; if (item == null) { break; } if (r == original.length) { // already null-free return original; } } // we must destroy the original array int w = r - 1; for (;;) { item = original[r++]; if (item != null) { original[w++] = item; } if (r == original.length) { return Arrays.copyOf(original, w); } } } /** * Deeply convert an object to a string, expanding arrays as they are encountered. * * @param value the value to convert * @return the string */ public static String objectToString(Object value) { if (value == null) { return "null"; } else if (value instanceof Object[]) { return Arrays.deepToString((Object[]) value); } else if (value.getClass().isArray()) { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < Array.getLength(value); i++) { if (i != 0) sb.append(", "); sb.append(String.valueOf(Array.get(value, i))); } sb.append(']'); return sb.toString(); } else { return value.toString(); } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/bytes/000077500000000000000000000000001361511066400250265ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/bytes/ByteStringBuilder.java000066400000000000000000000275101361511066400312770ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.bytes; import static org.wildfly.common._private.CommonMessages.msg; import java.security.DigestException; import java.security.MessageDigest; import java.util.Arrays; import javax.crypto.Mac; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; /** * A builder for byte arrays. */ public final class ByteStringBuilder { private byte[] content; private int length; public ByteStringBuilder() { this.content = new byte[16]; } public ByteStringBuilder(final byte[] content) { if (content != null && content.length != 0) { this.content = content.clone(); this.length = this.content.length; } else { this.content = new byte[16]; } } public ByteStringBuilder append(boolean b) { appendLatin1(Boolean.toString(b)); return this; } public ByteStringBuilder append(byte b) { doAppend(b); return this; } public ByteStringBuilder append(char c) { return appendUtf8Raw((int) c); } public ByteStringBuilder appendUtf8Raw(int codePoint) { if (codePoint < 0) { throw new IllegalArgumentException(); } else if (codePoint < 0x80) { doAppend((byte) codePoint); } else if (codePoint < 0x800) { doAppend((byte) (0xC0 | 0x1F & codePoint >>> 6)); doAppend((byte) (0x80 | 0x3F & codePoint)); } else if (codePoint < 0x10000) { doAppend((byte) (0xE0 | 0x0F & codePoint >>> 12)); doAppend((byte) (0x80 | 0x3F & codePoint >>> 6)); doAppend((byte) (0x80 | 0x3F & codePoint)); } else if (codePoint < 0x110000) { doAppend((byte) (0xF0 | 0x07 & codePoint >>> 18)); doAppend((byte) (0x80 | 0x3F & codePoint >>> 12)); doAppend((byte) (0x80 | 0x3F & codePoint >>> 6)); doAppend((byte) (0x80 | 0x3F & codePoint)); } else { throw new IllegalArgumentException(); } return this; } public ByteStringBuilder appendUtf8(CodePointIterator iterator) { while (iterator.hasNext()) { appendUtf8Raw(iterator.next()); } return this; } public ByteStringBuilder appendLatin1(CodePointIterator iterator) { int cp; while (iterator.hasNext()) { cp = iterator.next(); if (cp > 255) throw new IllegalArgumentException(); append((byte) cp); } return this; } public ByteStringBuilder appendAscii(CodePointIterator iterator) { int cp; while (iterator.hasNext()) { cp = iterator.next(); if (cp > 127) throw new IllegalArgumentException(); append((byte) cp); } return this; } public ByteStringBuilder append(ByteIterator iterator) { return iterator.appendTo(this); } public ByteStringBuilder append(byte[] bytes) { int length = this.length; int bl = bytes.length; reserve(bl, false); System.arraycopy(bytes, 0, content, length, bl); this.length = length + bl; return this; } public ByteStringBuilder append(byte[] bytes, int offs, int len) { reserve(len, false); int length = this.length; System.arraycopy(bytes, offs, content, length, len); this.length = length + len; return this; } public ByteStringBuilder appendLatin1(CharSequence s) { int len = s.length(); reserve(len, false); char c; for (int i = 0; i < len; i ++) { c = s.charAt(i); if (c > 255) throw new IllegalArgumentException(); doAppendNoCheck((byte) c); } return this; } public ByteStringBuilder appendLatin1(CharSequence s, int offs, int len) { reserve(len, false); char c; for (int i = 0; i < len; i ++) { c = s.charAt(i + offs); if (c > 255) throw new IllegalArgumentException(); doAppendNoCheck((byte) c); } return this; } public ByteStringBuilder appendLatin1(String s) { int len = s.length(); reserve(len, false); char c; for (int i = 0; i < len; i ++) { c = s.charAt(i); if (c > 255) throw new IllegalArgumentException(); doAppendNoCheck((byte) c); } return this; } public ByteStringBuilder appendLatin1(String s, int offs, int len) { reserve(len, false); char c; for (int i = 0; i < len; i ++) { c = s.charAt(i + offs); if (c > 255) throw new IllegalArgumentException(); doAppendNoCheck((byte) c); } return this; } public ByteStringBuilder append(CharSequence s) { return append(s, 0, s.length()); } public ByteStringBuilder append(CharSequence s, int offs, int len) { int c; int i = 0; while (i < len) { c = s.charAt(offs + i++); if (Character.isHighSurrogate((char) c)) { if (i < len) { char t = s.charAt(offs + i ++); if (! Character.isLowSurrogate(t)) { throw new IllegalArgumentException(); } c = Character.toCodePoint((char) c, t); } else { throw new IllegalArgumentException(); } } appendUtf8Raw(c); } return this; } public ByteStringBuilder append(String s) { return append(s, 0, s.length()); } public ByteStringBuilder append(String s, int offs, int len) { int c; int i = 0; while (i < len) { c = s.charAt(offs + i++); if (Character.isHighSurrogate((char) c)) { if (i < len) { char t = s.charAt(offs + i ++); if (! Character.isLowSurrogate(t)) { throw new IllegalArgumentException(); } c = Character.toCodePoint((char) c, t); } else { throw new IllegalArgumentException(); } } appendUtf8Raw(c); } return this; } public ByteStringBuilder appendPackedUnsignedBE(int v) { if (v > 0) { final int bits = Integer.numberOfTrailingZeros(Integer.highestOneBit(v)) + 1; final int size = (bits + 7) / 7; for (int x = 0, b = (size - 1) * 7; x < size - 1; x ++, b -= 7) { doAppend((byte) (0x80 | v >>> b)); } } doAppend((byte) (~0x80 & v)); return this; } public ByteStringBuilder appendPackedUnsignedBE(long v) { if (v > 0) { final int bits = Long.numberOfTrailingZeros(Long.highestOneBit(v)) + 1; final int size = (bits + 7) / 7; for (int x = 0, b = (size - 1) * 7; x < size - 1; x ++, b -= 7) { doAppend((byte) (0x80L | v >>> b)); } } doAppend((byte) (~0x80L & v)); return this; } public ByteStringBuilder appendBE(short s) { doAppend((byte) (s >>> 8)); doAppend((byte) s); return this; } public ByteStringBuilder appendNumber(int i) { appendLatin1(Integer.toString(i)); return this; } public ByteStringBuilder appendBE(int i) { doAppend((byte) (i >>> 24)); doAppend((byte) (i >>> 16)); doAppend((byte) (i >>> 8)); doAppend((byte) i); return this; } public ByteStringBuilder appendNumber(long l) { appendLatin1(Long.toString(l)); return this; } public ByteStringBuilder appendBE(long l) { doAppend((byte) (l >>> 56)); doAppend((byte) (l >>> 48)); doAppend((byte) (l >>> 40)); doAppend((byte) (l >>> 32)); doAppend((byte) (l >>> 24)); doAppend((byte) (l >>> 16)); doAppend((byte) (l >>> 8)); doAppend((byte) l); return this; } public ByteStringBuilder appendObject(Object o) { appendLatin1(String.valueOf(o)); return this; } public ByteStringBuilder append(ByteStringBuilder other) { append(other.content, 0, other.length); return this; } public ByteStringBuilder updateDigest(final MessageDigest messageDigest) { messageDigest.update(content, 0, length); return this; } public ByteStringBuilder appendDigestResult(final MessageDigest messageDigest) throws DigestException { reserve(messageDigest.getDigestLength(), false); final int length = this.length; final byte[] content = this.content; this.length = length + messageDigest.digest(content, length, content.length - length); return this; } public ByteStringBuilder updateMac(final Mac mac) { mac.update(content, 0, length); return this; } public byte[] toArray() { return Arrays.copyOf(content, length); } public byte byteAt(int index) { if (index < 0 || index > length) throw new IndexOutOfBoundsException(); return content[index]; } public int capacity() { return content.length; } public int length() { return length; } public void setLength(int newLength) { if (newLength > length) { // grow reserve(newLength - length, true); } length = newLength; } public boolean contentEquals(final byte[] other) { return contentEquals(other, 0, other.length); } public boolean contentEquals(final byte[] other, final int offs, final int length) { if (length != this.length) return false; for (int i = 0; i < length; i++) { if (content[i] != other[offs + i]) { return false; } } return true; } private void reserve(final int count, final boolean clear) { final int length = this.length; final byte[] content = this.content; int cl = content.length; if (cl - length >= count) { if (clear) Arrays.fill(content, length, length + count, (byte) 0); return; } // clear remainder if (clear) Arrays.fill(content, length, cl, (byte) 0); do { // not enough space... grow by 1.5x cl = cl + (cl + 1 >> 1); if (cl < 0) throw msg.tooLarge(); } while (cl - length < count); this.content = Arrays.copyOf(content, cl); } private void doAppend(final byte b) { byte[] content = this.content; final int cl = content.length; final int length = this.length; if (length == cl) { content = this.content = Arrays.copyOf(content, cl + (cl + 1 >> 1)); // content must not be blank } content[length] = b; this.length = length + 1; } private void doAppendNoCheck(final byte b) { content[length ++] = b; } public ByteIterator iterate() { return ByteIterator.ofBytes(content, 0, length); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/bytes/package-info.java000066400000000000000000000014501361511066400302150ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes related to the manipulation of byte sequences. */ package org.wildfly.common.bytes; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/codec/000077500000000000000000000000001361511066400247555ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/codec/Alphabet.java000066400000000000000000000033521361511066400273430ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; /** * A base-n encoder/decoder alphabet. Alphabets may be little-endian or big-endian. Each base has its own subclass. */ public abstract class Alphabet { private final boolean littleEndian; Alphabet(final boolean littleEndian) { this.littleEndian = littleEndian; } /** * Determine whether this is a little-endian or big-endian alphabet. * * @return {@code true} if the alphabet is little-endian, {@code false} if it is big-endian */ public boolean isLittleEndian() { return littleEndian; } /** * Encode the given byte value to a code point. * * @param val the value * @return the Unicode code point */ public abstract int encode(int val); /** * Decode the given code point (character). If the code point is not valid, -1 is returned. * * @param codePoint the Unicode code point * @return the decoded value or -1 if the code point is not valid */ public abstract int decode(int codePoint); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/codec/Base32Alphabet.java000066400000000000000000000063241361511066400303050ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; /** * A base-32 alphabet. * * @see ByteIterator#base32Encode(Base32Alphabet) * @see CodePointIterator#base32Decode(Base32Alphabet) */ public abstract class Base32Alphabet extends Alphabet { /** * Construct a new instance. * * @param littleEndian {@code true} if the alphabet is little-endian (LSB first), {@code false} otherwise */ protected Base32Alphabet(final boolean littleEndian) { super(littleEndian); } /** * Encode the given 5-bit value to a code point. * * @param val the 5-bit value * @return the Unicode code point */ public abstract int encode(int val); /** * Decode the given code point. If the code point is not valid, -1 is returned. * * @param codePoint the code point * @return the decoded 5-bit value or -1 if the code point is not valid */ public abstract int decode(int codePoint); /** * The standard RFC 4648 base-32 alphabet. */ public static final Base32Alphabet STANDARD = new Base32Alphabet(false) { public int encode(final int val) { if (val <= 25) { return 'A' + val; } else { assert val < 32; return '2' + val - 26; } } public int decode(final int codePoint) { if ('A' <= codePoint && codePoint <= 'Z') { return codePoint - 'A'; } else if ('2' <= codePoint && codePoint <= '7') { return codePoint - '2' + 26; } else { return -1; } } }; /** * The standard RFC 4648 base-32 alphabet mapped to lowercase. */ public static final Base32Alphabet LOWERCASE = new Base32Alphabet(false) { public int encode(final int val) { if (val <= 25) { return 'a' + val; } else { assert val < 32; return '2' + val - 26; } } public int decode(final int codePoint) { if ('a' <= codePoint && codePoint <= 'z') { return codePoint - 'a'; } else if ('2' <= codePoint && codePoint <= '7') { return codePoint - '2' + 26; } else { return -1; } } }; } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/codec/Base64Alphabet.java000066400000000000000000000056671361511066400303230ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; /** * A base-64 alphabet. * * @see ByteIterator#base64Encode(Base64Alphabet) * @see CodePointIterator#base64Decode(Base64Alphabet) */ public abstract class Base64Alphabet extends Alphabet { /** * Construct a new instance. * * @param littleEndian {@code true} if the alphabet is little-endian (LSB first), {@code false} otherwise */ protected Base64Alphabet(final boolean littleEndian) { super(littleEndian); } /** * Encode the given 6-bit value to a code point. * * @param val the 6-bit value * @return the Unicode code point */ public abstract int encode(int val); /** * Decode the given code point. If the code point is not valid, -1 is returned. * * @param codePoint the code point * @return the decoded 6-bit value or -1 if the code point is not valid */ public abstract int decode(int codePoint); /** * The standard RFC 4648 base-64 alphabet. */ public static final Base64Alphabet STANDARD = new Base64Alphabet(false) { public int encode(final int val) { if (val <= 25) { return 'A' + val; } else if (val <= 51) { return 'a' + val - 26; } else if (val <= 61) { return '0' + val - 52; } else if (val == 62) { return '+'; } else { assert val == 63; return '/'; } } public int decode(final int codePoint) throws IllegalArgumentException { if ('A' <= codePoint && codePoint <= 'Z') { return codePoint - 'A'; } else if ('a' <= codePoint && codePoint <= 'z') { return codePoint - 'a' + 26; } else if ('0' <= codePoint && codePoint <= '9') { return codePoint - '0' + 52; } else if (codePoint == '+') { return 62; } else if (codePoint == '/') { return 63; } else { return -1; } } }; } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/codec/DecodeException.java000066400000000000000000000040441361511066400306640ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; /** * An exception which indicates that decoding has failed due to invalid or truncated input. */ public class DecodeException extends IllegalArgumentException { private static final long serialVersionUID = 5823281980783313991L; /** * Constructs a new {@code DecodeException} instance. The message is left blank ({@code null}), and no cause is * specified. */ public DecodeException() { } /** * Constructs a new {@code DecodeException} instance with an initial message. No cause is specified. * * @param msg the message */ public DecodeException(final String msg) { super(msg); } /** * Constructs a new {@code DecodeException} instance with an initial cause. If a non-{@code null} cause is * specified, its message is used to initialize the message of this {@code DecodeException}; otherwise the message * is left blank ({@code null}). * * @param cause the cause */ public DecodeException(final Throwable cause) { super(cause); } /** * Constructs a new {@code DecodeException} instance with an initial message and cause. * * @param msg the message * @param cause the cause */ public DecodeException(final String msg, final Throwable cause) { super(msg, cause); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/codec/package-info.java000066400000000000000000000014341361511066400301460ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes relating to encoding and decoding. */ package org.wildfly.common.codec; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/000077500000000000000000000000001361511066400253645ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/ContextManager.java000066400000000000000000000316351361511066400311560ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.context; import static java.security.AccessController.doPrivileged; import java.security.PrivilegedAction; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.wildfly.common.Assert; /** * A context manager for a {@link Contextual} type. * * @param the public type of the contextual object * @author David M. Lloyd */ public final class ContextManager> implements Supplier { private final AtomicReference> globalDefaultSupplierRef = new AtomicReference<>(); private final ConcurrentHashMap> perClassLoaderDefault = new ConcurrentHashMap<>(); private final Class type; private final String name; private final ThreadLocal> stateRef = ThreadLocal.withInitial(State::new); private final ContextPermission getPermission; /** * Construct a new instance, with a name matching the class name of the given {@code type}. * * @param type the type class of the context object (must not be {@code null}) */ public ContextManager(final Class type) { this(type, type.getName()); } /** * Construct a new instance. * * @param type the type class of the context object (must not be {@code null}) * @param name the name to use for permission checks (must not be {@code null} or empty) */ public ContextManager(final Class type, final String name) { Assert.checkNotNullParam("type", type); Assert.checkNotNullParam("name", name); Assert.checkNotEmptyParam("name", name); this.type = type; this.name = name; // construct commonly-used permission object getPermission = new ContextPermission(name, ContextPermission.STR_GET); } /** * Get the global default context instance. Note that the global default is determined by way of a {@link Supplier} so * the returned value may vary from call to call, depending on the policy of that {@code Supplier}. * * @return the global default, or {@code null} if none is installed or available */ public C getGlobalDefault() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_GET_GLOBAL_DEF)); } final Supplier globalDefault = globalDefaultSupplierRef.get(); return globalDefault == null ? null : globalDefault.get(); } /** * Set the global default instance supplier. The supplier, if one is given, should have a reasonable policy such * that callers of {@link #getGlobalDefault()} will obtain results consistent with a general expectation of stability. * * @param supplier the supplier, or {@code null} to remove the global default */ public void setGlobalDefaultSupplier(final Supplier supplier) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_SET_GLOBAL_DEF_SUP)); } globalDefaultSupplierRef.set(supplier); } /** * Set the global default instance supplier, but only if it was not already set. If no supplier is set, the given * supplier supplier is queried to get the new value to set. * * @param supplierSupplier the supplier supplier (must not be {@code null}) * @return {@code true} if the supplier was set, {@code false} if it was already set to something else * @see #setGlobalDefaultSupplier(Supplier) */ public boolean setGlobalDefaultSupplierIfNotSet(final Supplier> supplierSupplier) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_SET_GLOBAL_DEF_SUP)); } final AtomicReference> ref = this.globalDefaultSupplierRef; // try not to compute the value if not needed return ref.get() == null && ref.compareAndSet(null, supplierSupplier.get()); } /** * Set the global default instance. This instance will be returned from all subsequent calls to {@link #getGlobalDefault()}, * replacing any previous instance or {@linkplain #setGlobalDefaultSupplier(Supplier) supplier} that was set. * * @param globalDefault the global default value, or {@code null} to remove the global default */ public void setGlobalDefault(final C globalDefault) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_GET_GLOBAL_DEF)); } globalDefaultSupplierRef.set(globalDefault == null ? null : () -> globalDefault); } /** * Get the class loader default instance. Note that the class loader default is determined by way of a {@link Supplier} so * the returned value may vary from call to call, depending on the policy of that {@code Supplier}. * * @param classLoader the class loader * @return the global default, or {@code null} if none is installed or available */ public C getClassLoaderDefault(final ClassLoader classLoader) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_GET_CLASSLOADER_DEF)); } final Supplier supplier; if (classLoader == null) { return null; } supplier = perClassLoaderDefault.get(classLoader); return supplier == null ? null : supplier.get(); } /** * Set the per-class loader default instance supplier. The supplier, if one is given, should have a reasonable policy such * that callers of {@link #getClassLoaderDefault(ClassLoader)} will obtain results consistent with a general expectation of stability. * * @param classLoader the class loader (must not be {@code null}) * @param supplier the supplier, or {@code null} to remove the default for this class loader */ public void setClassLoaderDefaultSupplier(final ClassLoader classLoader, final Supplier supplier) { Assert.checkNotNullParam("classLoader", classLoader); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_SET_CLASSLOADER_DEF_SUP)); } if (supplier == null) { perClassLoaderDefault.remove(classLoader); } else { perClassLoaderDefault.put(classLoader, supplier); } } /** * Set the per-class loader default instance supplier. The supplier, if one is given, should have a reasonable policy such * that callers of {@link #getClassLoaderDefault(ClassLoader)} will obtain results consistent with a general expectation of stability. * * @param classLoader the class loader (must not be {@code null}) * @param classLoaderDefault the class loader default value, or {@code null} to remove the default */ public void setClassLoaderDefault(final ClassLoader classLoader, final C classLoaderDefault) { Assert.checkNotNullParam("classLoader", classLoader); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_SET_CLASSLOADER_DEF)); } if (classLoaderDefault == null) { perClassLoaderDefault.remove(classLoader); } else { perClassLoaderDefault.put(classLoader, () -> classLoaderDefault); } } /** * Get the per-thread default context instance. Note that the per-thread default is determined by way of a {@link Supplier} so * the returned value may vary from call to call, depending on the policy of that {@code Supplier}. * * @return the per-thread default, or {@code null} if none is installed or available */ public C getThreadDefault() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_GET_THREAD_DEF)); } final Supplier defaultSupplier = stateRef.get().defaultSupplier; return defaultSupplier == null ? null : defaultSupplier.get(); } /** * Set the per-thread default instance supplier. The supplier, if one is given, should have a reasonable policy such * that callers of {@link #getThreadDefault()} will obtain results consistent with a general expectation of stability. * * @param supplier the supplier, or {@code null} to remove the per-thread default */ public void setThreadDefaultSupplier(final Supplier supplier) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_SET_THREAD_DEF_SUP)); } stateRef.get().defaultSupplier = supplier; } /** * Set the per-thread default instance. This instance will be returned from all subsequent calls to {@link #getThreadDefault()}, * replacing any previous instance or {@linkplain #setThreadDefaultSupplier(Supplier) supplier} that was set. * * @param threadDefault the per-thread default value, or {@code null} to remove the per-thread default */ public void setThreadDefault(final C threadDefault) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_SET_THREAD_DEF)); } stateRef.get().defaultSupplier = threadDefault == null ? null : () -> threadDefault; } /** * Get the currently active context, possibly examining the per-thread or global defaults. * * @return the current context, or {@code null} if none is active */ public C get() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(getPermission); } return getPrivileged(); } /** * Get a privileged supplier for this context manager which returns the currently active context without a permission * check. * * @return the privileged supplier */ public Supplier getPrivilegedSupplier() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new ContextPermission(name, ContextPermission.STR_GET_PRIV_SUP)); } return this::getPrivileged; } private C getPrivileged() { final State state = stateRef.get(); C c = state.current; if (c != null) return c; final Thread currentThread = Thread.currentThread(); final SecurityManager sm = System.getSecurityManager(); ClassLoader classLoader; if (sm != null) { classLoader = doPrivileged((PrivilegedAction) currentThread::getContextClassLoader); } else { classLoader = currentThread.getContextClassLoader(); } Supplier supplier; if (classLoader != null) { supplier = perClassLoaderDefault.get(classLoader); if (supplier != null) { c = supplier.get(); if (c != null) return c; } } supplier = state.defaultSupplier; if (supplier != null) { c = supplier.get(); if (c != null) return c; } supplier = globalDefaultSupplierRef.get(); return supplier != null ? supplier.get() : null; } C getAndSetCurrent(Contextual newVal) { final C cast = type.cast(newVal); final State state = stateRef.get(); try { return state.current; } finally { state.current = cast; } } void restoreCurrent(C oldVal) { stateRef.get().current = oldVal; } static class State { T current; Supplier defaultSupplier; State() { } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/ContextPermission.java000066400000000000000000000307541361511066400317350ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.context; import java.security.Permission; import java.security.PermissionCollection; import java.util.function.Supplier; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; import org.wildfly.common.annotation.NotNull; /** * A permission object for operations on {@link ContextManager} instances. *

* This type of permission requires a {@code name} and an {@code action}. The {@code name} may be the name * of a context manager, or the special {@code *} name which means the permission applies to all context managers. *

* The {@code action} may be one or more of the following (each action name being separated by a comma): *

    *
  • {@code get} - allow {@linkplain ContextManager#get() getting} the current context
  • *
  • {@code getPrivilegedSupplier} - allow access to the {@link ContextManager#getPrivilegedSupplier()} method
  • *
  • {@code getGlobalDefault} - allow access to the {@linkplain ContextManager#getGlobalDefault() global default context}
  • *
  • {@code setGlobalDefault} - allow {@linkplain ContextManager#setGlobalDefault(Contextual) setting the global default instance}
  • *
  • {@code setGlobalDefaultSupplier} - allow {@linkplain ContextManager#setGlobalDefaultSupplier(Supplier) setting the global default instance supplier}
  • *
  • {@code getThreadDefault} - allow access to the {@linkplain ContextManager#getThreadDefault() per-thread default context}
  • *
  • {@code setThreadDefault} - allow {@linkplain ContextManager#setThreadDefault(Contextual) setting the per-thread default instance}
  • *
  • {@code setThreadDefaultSupplier} - allow {@linkplain ContextManager#setThreadDefaultSupplier(Supplier) setting the per-thread default instance supplier}
  • *
* Additionally, the special {@code *} action name is allowed which implies all of the above actions. *

* The {@link #newPermissionCollection()} method returns an optimized container for context permissions. * * @author David M. Lloyd */ public final class ContextPermission extends Permission { private static final long serialVersionUID = 2149744699461086708L; private static final int ACTION_GET = 0b00000000001; private static final int ACTION_GET_PRIV_SUP = 0b00000000010; private static final int ACTION_GET_GLOBAL_DEF = 0b00000000100; private static final int ACTION_SET_GLOBAL_DEF = 0b00000001000; private static final int ACTION_SET_GLOBAL_DEF_SUP = 0b00000010000; private static final int ACTION_GET_THREAD_DEF = 0b00000100000; private static final int ACTION_SET_THREAD_DEF = 0b00001000000; private static final int ACTION_SET_THREAD_DEF_SUP = 0b00010000000; private static final int ACTION_GET_CLASSLOADER_DEF = 0b00100000000; private static final int ACTION_SET_CLASSLOADER_DEF = 0b01000000000; private static final int ACTION_SET_CLASSLOADER_DEF_SUP = 0b10000000000; private static final int ACTION_ALL = 0b11111111111; static final String STR_GET = "get"; static final String STR_GET_PRIV_SUP = "getPrivilegedSupplier"; static final String STR_GET_GLOBAL_DEF = "getGlobalDefault"; static final String STR_SET_GLOBAL_DEF = "setGlobalDefault"; static final String STR_SET_GLOBAL_DEF_SUP = "setGlobalDefaultSupplier"; static final String STR_GET_THREAD_DEF = "getThreadDefault"; static final String STR_SET_THREAD_DEF = "setThreadDefault"; static final String STR_SET_THREAD_DEF_SUP = "setThreadDefaultSupplier"; static final String STR_GET_CLASSLOADER_DEF = "getClassLoaderDefault"; static final String STR_SET_CLASSLOADER_DEF = "setClassLoaderDefault"; static final String STR_SET_CLASSLOADER_DEF_SUP = "setClassLoaderDefaultSupplier"; private final transient int actionBits; private transient String actionString; /** * Constructs a permission with the specified name. * * @param name name of the Permission object being created (must not be {@code null}) * @param actions the actions string (must not be {@code null}) */ public ContextPermission(final String name, final String actions) { super(name); Assert.checkNotNullParam("name", name); Assert.checkNotNullParam("actions", actions); actionBits = parseActions(actions); } ContextPermission(final String name, final int actionBits) { super(name); Assert.checkNotNullParam("name", name); this.actionBits = actionBits & ACTION_ALL; } private static int parseActions(final String actions) throws IllegalArgumentException { int bits = 0; int start = 0; int idx = actions.indexOf(','); if (idx == -1) { return parseAction(actions); } else do { bits |= parseAction(actions.substring(start, idx)); start = idx + 1; idx = actions.indexOf(',', start); } while (idx != -1); bits |= parseAction(actions.substring(start)); return bits; } private static int parseAction(final String action) { switch (action.trim()) { case STR_GET: return ACTION_GET; case STR_GET_PRIV_SUP: return ACTION_GET_PRIV_SUP; case STR_GET_GLOBAL_DEF: return ACTION_GET_GLOBAL_DEF; case STR_SET_GLOBAL_DEF: return ACTION_SET_GLOBAL_DEF; case STR_SET_GLOBAL_DEF_SUP: return ACTION_SET_GLOBAL_DEF_SUP; case STR_GET_THREAD_DEF: return ACTION_GET_THREAD_DEF; case STR_SET_THREAD_DEF: return ACTION_SET_THREAD_DEF; case STR_SET_THREAD_DEF_SUP: return ACTION_SET_THREAD_DEF_SUP; case STR_GET_CLASSLOADER_DEF: return ACTION_GET_CLASSLOADER_DEF; case STR_SET_CLASSLOADER_DEF: return ACTION_SET_CLASSLOADER_DEF; case STR_SET_CLASSLOADER_DEF_SUP: return ACTION_SET_CLASSLOADER_DEF_SUP; case "*": return ACTION_ALL; case "": return 0; default: { throw CommonMessages.msg.invalidPermissionAction(action); } } } /** * Determine if the given permission is implied by this permission. * * @param permission the other permission * @return {@code true} if the other permission is not {@code null} and is a context permission which is implied by * this permission instance; {@code false} otherwise */ public boolean implies(final Permission permission) { return permission instanceof ContextPermission && implies((ContextPermission) permission); } /** * Determine if the given permission is implied by this permission. * * @param permission the other permission * @return {@code true} if the other permission is not {@code null} and is a context permission which is implied by * this permission instance; {@code false} otherwise */ public boolean implies(final ContextPermission permission) { return this == permission || permission != null && isSet(this.actionBits, permission.actionBits) && impliesName(permission.getName()); } private boolean impliesName(String otherName) { final String myName = getName(); return myName.equals("*") || myName.equals(otherName); } static boolean isSet(int mask, int test) { return (mask & test) == test; } /** * Determine if this permission is equal to the given object. * * @param obj the other object * @return {@code true} if the object is a context permission that is exactly equal to this one; {@code false} otherwise */ public boolean equals(final Object obj) { return obj instanceof ContextPermission && equals((ContextPermission) obj); } /** * Determine if this permission is equal to the given permission. * * @param permission the other permission * @return {@code true} if the permission is a context permission that is exactly equal to this one; {@code false} otherwise */ public boolean equals(final ContextPermission permission) { return this == permission || permission != null && actionBits == permission.actionBits && getName().equals(permission.getName()); } /** * Get the hash code of this permission. * * @return the hash code of this permission */ public int hashCode() { return getName().hashCode() * 17 + actionBits; } /** * Get the actions string. This string will be returned in a canonical format. * * @return the actions string */ public String getActions() { String actionString = this.actionString; if (actionString == null) { final int actionBits = this.actionBits; if (isSet(actionBits, ACTION_ALL)) { return this.actionString = "*"; } else if (actionBits == 0) { return this.actionString = ""; } final StringBuilder b = new StringBuilder(); if (isSet(actionBits, ACTION_GET)) b.append(STR_GET).append(','); if (isSet(actionBits, ACTION_GET_PRIV_SUP)) b.append(STR_GET_PRIV_SUP).append(','); if (isSet(actionBits, ACTION_GET_GLOBAL_DEF)) b.append(STR_GET_GLOBAL_DEF).append(','); if (isSet(actionBits, ACTION_SET_GLOBAL_DEF)) b.append(STR_SET_GLOBAL_DEF).append(','); if (isSet(actionBits, ACTION_SET_GLOBAL_DEF_SUP)) b.append(STR_SET_GLOBAL_DEF_SUP).append(','); if (isSet(actionBits, ACTION_GET_THREAD_DEF)) b.append(STR_GET_THREAD_DEF).append(','); if (isSet(actionBits, ACTION_SET_THREAD_DEF)) b.append(STR_SET_THREAD_DEF).append(','); if (isSet(actionBits, ACTION_SET_THREAD_DEF_SUP)) b.append(STR_SET_THREAD_DEF_SUP).append(','); if (isSet(actionBits, ACTION_GET_CLASSLOADER_DEF)) b.append(STR_GET_CLASSLOADER_DEF).append(','); if (isSet(actionBits, ACTION_SET_CLASSLOADER_DEF)) b.append(STR_SET_CLASSLOADER_DEF).append(','); if (isSet(actionBits, ACTION_SET_CLASSLOADER_DEF_SUP)) b.append(STR_SET_CLASSLOADER_DEF_SUP).append(','); assert b.length() > 0; b.setLength(b.length() - 1); return this.actionString = b.toString(); } return actionString; } /** * Create a copy of this permission with the additional given actions. * * @param actions the additional actions (must not be {@code null}) * @return the new permission (not {@code null}) */ @NotNull public ContextPermission withActions(String actions) { return withActionBits(parseActions(actions)); } ContextPermission withActionBits(int actionBits) { if (isSet(this.actionBits, actionBits)) { return this; } else { return new ContextPermission(getName(), this.actionBits | actionBits); } } /** * Create a copy of this permission without any of the given actions. * * @param actions the actions to subtract (must not be {@code null}) * @return the new permission (not {@code null}) */ @NotNull public ContextPermission withoutActions(String actions) { return withoutActionBits(parseActions(actions)); } ContextPermission withoutActionBits(final int actionBits) { if ((actionBits & this.actionBits) == 0) { return this; } else { return new ContextPermission(getName(), this.actionBits & ~actionBits); } } /** * Get a new permission collection instance which can hold this type of permissions. * * @return a new permission collection instance (not {@code null}) */ public PermissionCollection newPermissionCollection() { return new ContextPermissionCollection(); } int getActionBits() { return actionBits; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/ContextPermissionCollection.java000066400000000000000000000233051361511066400337430ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.context; import java.security.Permission; import java.security.PermissionCollection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; /** * @author David M. Lloyd */ final class ContextPermissionCollection extends PermissionCollection { private static final long serialVersionUID = - 3651721703337368351L; private volatile State state = emptyState; private static final AtomicReferenceFieldUpdater stateUpdater = AtomicReferenceFieldUpdater.newUpdater(ContextPermissionCollection.class, State.class, "state"); public void add(final Permission permission) throws SecurityException, IllegalArgumentException { Assert.checkNotNullParam("permission", permission); if (permission instanceof ContextPermission) { add((ContextPermission) permission); } else { throw CommonMessages.msg.invalidPermissionType(ContextPermission.class, permission.getClass()); } } public void add(final ContextPermission contextPermission) throws SecurityException { Assert.checkNotNullParam("contextPermission", contextPermission); if (isReadOnly()) { throw CommonMessages.msg.readOnlyPermissionCollection(); } final int actionBits = contextPermission.getActionBits(); if (actionBits == 0) { // no operation return; } final String name = contextPermission.getName(); State oldState, newState; do { oldState = this.state; final ContextPermission oldGlobalPermission = oldState.globalPermission; final int globalActions = oldGlobalPermission == null ? 0 : oldGlobalPermission.getActionBits(); if (oldGlobalPermission != null && oldGlobalPermission.implies(contextPermission)) { // already fully implied by global permission return; } else { final Map oldPermissions = oldState.permissions; final Map newPermissions; final ContextPermission newGlobalPermission; if (name.equals("*")) { // it's global but with some bits we don't have; calculate the new global actions and subtract from the map if (oldGlobalPermission == null) { newGlobalPermission = contextPermission; } else { newGlobalPermission = oldGlobalPermission.withActionBits(contextPermission.getActionBits()); } // now subtract newPermissions = cloneWithout(oldPermissions, newGlobalPermission); } else { newGlobalPermission = oldGlobalPermission; // it's not global; check & add actions to our map permission final ContextPermission mapPermission = oldPermissions.get(name); if (mapPermission == null) { // no map entry; just create one (but without any global actions we have defined) if (oldPermissions.isEmpty()) { // change empty map to singleton map newPermissions = Collections.singletonMap(name, contextPermission.withoutActionBits(globalActions)); } else { // make a copy of the map plus the new entry newPermissions = new HashMap<>(oldPermissions); newPermissions.put(name, contextPermission.withoutActionBits(globalActions)); } } else if (((mapPermission.getActionBits() | globalActions) & actionBits) == actionBits) { // already fully implied by a map entry return; } else { // replace the map entry if (oldPermissions.size() == 1) { // it was a singleton map, just replace it newPermissions = Collections.singletonMap(name, mapPermission.withActionBits(actionBits & ~globalActions)); } else { // copy the map and replace the entry newPermissions = new HashMap<>(oldPermissions); newPermissions.put(name, mapPermission.withActionBits(actionBits & ~globalActions)); } } } newState = new State(newGlobalPermission, newPermissions); } } while (! stateUpdater.compareAndSet(this, oldState, newState)); } private static Map cloneWithout(final Map oldPermissions, final ContextPermission newGlobalPermission) { final Iterator iterator = oldPermissions.values().iterator(); ContextPermission first; for (;;) { if (! iterator.hasNext()) { return Collections.emptyMap(); } first = iterator.next(); if (! newGlobalPermission.implies(first)) { // break into next phase break; } } final int globalActionBits = newGlobalPermission.getActionBits(); ContextPermission second; for (;;) { if (! iterator.hasNext()) { return Collections.singletonMap(first.getName(), first.withoutActionBits(globalActionBits)); } second = iterator.next(); if (! newGlobalPermission.implies(second)) { // break into next phase break; } } HashMap newMap = new HashMap<>(); newMap.put(first.getName(), first.withoutActionBits(globalActionBits)); newMap.put(second.getName(), second.withoutActionBits(globalActionBits)); ContextPermission subsequent; while (iterator.hasNext()) { subsequent = iterator.next(); if (! newGlobalPermission.implies(subsequent)) { newMap.put(subsequent.getName(), subsequent.withoutActionBits(globalActionBits)); } } return newMap; } public boolean implies(final Permission permission) { return permission instanceof ContextPermission && implies((ContextPermission) permission); } public boolean implies(final ContextPermission permission) { if (permission == null) return false; final State state = this.state; final ContextPermission globalPermission = state.globalPermission; final int globalBits; if (globalPermission != null) { if (globalPermission.implies(permission)) { return true; } globalBits = globalPermission.getActionBits(); } else { globalBits = 0; } final int bits = permission.getActionBits(); final String name = permission.getName(); if (name.equals("*")) { return false; } final ContextPermission ourPermission = state.permissions.get(name); if (ourPermission == null) { return false; } final int ourBits = ourPermission.getActionBits() | globalBits; return (bits & ourBits) == bits; } public Enumeration elements() { final State state = this.state; final Iterator iterator = state.permissions.values().iterator(); return new Enumeration() { Permission next = state.globalPermission; public boolean hasMoreElements() { if (next != null) { return true; } if (iterator.hasNext()) { next = iterator.next(); return true; } return false; } public Permission nextElement() { if (! hasMoreElements()) throw new NoSuchElementException(); try { return next; } finally { next = null; } } }; } static class State { private final ContextPermission globalPermission; private final Map permissions; State(final ContextPermission globalPermission, final Map permissions) { this.globalPermission = globalPermission; this.permissions = permissions; } } private static final State emptyState = new State(null, Collections.emptyMap()); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/Contextual.java000066400000000000000000000407661361511066400303720ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.context; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.concurrent.Callable; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.LongFunction; import java.util.function.Predicate; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; import org.wildfly.common.annotation.NotNull; import org.wildfly.common.function.ExceptionBiConsumer; import org.wildfly.common.function.ExceptionBiFunction; import org.wildfly.common.function.ExceptionBiPredicate; import org.wildfly.common.function.ExceptionConsumer; import org.wildfly.common.function.ExceptionFunction; import org.wildfly.common.function.ExceptionIntFunction; import org.wildfly.common.function.ExceptionLongFunction; import org.wildfly.common.function.ExceptionPredicate; /** * A base class for contexts which are activated in a thread-local context. * * @param the public type of the contextual object * * @author David M. Lloyd */ public interface Contextual> { /** * Get the context manager for this object. The implementation of this method normally should return a constant * instance. * * @return the context manager (must not be {@code null}) */ @NotNull ContextManager getInstanceContextManager(); /** * Run the given task with this contextual object selected. * * @param runnable the task to run (must not be {@code null}) */ default void run(Runnable runnable) { Assert.checkNotNullParam("runnable", runnable); final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { runnable.run(); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param action the task to run (must not be {@code null}) * @param the return value type * @return the action return value */ default R runAction(PrivilegedAction action) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return action.run(); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param action the task to run (must not be {@code null}) * @param the return value type * @return the action return value * @throws PrivilegedActionException if the action fails with an exception */ default R runExceptionAction(PrivilegedExceptionAction action) throws PrivilegedActionException { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return action.run(); } catch (Exception e) { throw CommonMessages.msg.privilegedActionFailed(e); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param callable the task to run (must not be {@code null}) * @param the return value type * @return the action return value */ default V runCallable(Callable callable) throws Exception { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return callable.call(); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param consumer the task to run (must not be {@code null}) * @param param1 the first parameter to pass to the task * @param param2 the second parameter to pass to the task * @param the first parameter type * @param the second parameter type */ default void runBiConsumer(BiConsumer consumer, T param1, U param2) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { consumer.accept(param1, param2); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param consumer the task to run (must not be {@code null}) * @param param1 the first parameter to pass to the task * @param param2 the second parameter to pass to the task * @param the first parameter type * @param the second parameter type * @param the exception type * @throws E if an exception occurs in the task */ default void runExBiConsumer(ExceptionBiConsumer consumer, T param1, U param2) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { consumer.accept(param1, param2); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param consumer the task to run (must not be {@code null}) * @param param the parameter to pass to the task * @param the parameter type */ default void runConsumer(Consumer consumer, T param) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { consumer.accept(param); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param consumer the task to run (must not be {@code null}) * @param param the parameter to pass to the task * @param the parameter type * @param the exception type * @throws E if an exception occurs in the task */ default void runExConsumer(ExceptionConsumer consumer, T param) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { consumer.accept(param); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param param1 the first parameter to pass to the task * @param param2 the second parameter to pass to the task * @param the first parameter type * @param the second parameter type * @param the return value type * @return the action return value */ default R runBiFunction(BiFunction function, T param1, U param2) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(param1, param2); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param param1 the first parameter to pass to the task * @param param2 the second parameter to pass to the task * @param the first parameter type * @param the second parameter type * @param the return value type * @param the exception type * @return the action return value * @throws E if an exception occurs in the task */ default R runExBiFunction(ExceptionBiFunction function, T param1, U param2) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(param1, param2); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param param the parameter to pass to the task * @param the parameter type * @param the return value type * @return the action return value */ default R runFunction(Function function, T param) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(param); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param param the parameter to pass to the task * @param the parameter type * @param the return value type * @param the exception type * @return the action return value * @throws E if an exception occurs in the task */ default R runExFunction(ExceptionFunction function, T param) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(param); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param predicate the task to run (must not be {@code null}) * @param param1 the first parameter to pass to the task * @param param2 the second parameter to pass to the task * @param the first parameter type * @param the second parameter type * @return the action return value */ default boolean runBiPredicate(BiPredicate predicate, T param1, U param2) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return predicate.test(param1, param2); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param predicate the task to run (must not be {@code null}) * @param param1 the first parameter to pass to the task * @param param2 the second parameter to pass to the task * @param the first parameter type * @param the second parameter type * @param the exception type * @return the action return value * @throws E if an exception occurs in the task */ default boolean runExBiPredicate(ExceptionBiPredicate predicate, T param1, U param2) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return predicate.test(param1, param2); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param predicate the task to run (must not be {@code null}) * @param param the parameter to pass to the task * @param the first parameter type * @return the action return value */ default boolean runPredicate(Predicate predicate, T param) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return predicate.test(param); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param predicate the task to run (must not be {@code null}) * @param param the parameter to pass to the task * @param the first parameter type * @param the exception type * @return the action return value * @throws E if an exception occurs in the task */ default boolean runExPredicate(ExceptionPredicate predicate, T param) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return predicate.test(param); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param value the parameter to pass to the task * @param the return value type * @return the action return value */ default T runIntFunction(IntFunction function, int value) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(value); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param value the parameter to pass to the task * @param the return value type * @param the exception type * @return the action return value * @throws E if an exception occurs in the task */ default T runExIntFunction(ExceptionIntFunction function, int value) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(value); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param value the parameter to pass to the task * @param the return value type * @return the action return value */ default T runLongFunction(LongFunction function, long value) { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(value); } finally { contextManager.restoreCurrent(old); } } /** * Run the given task with this contextual object selected. * * @param function the task to run (must not be {@code null}) * @param value the parameter to pass to the task * @param the return value type * @param the exception type * @return the action return value * @throws E if an exception occurs in the task */ default T runExLongFunction(ExceptionLongFunction function, long value) throws E { final ContextManager contextManager = getInstanceContextManager(); final C old = contextManager.getAndSetCurrent(this); try { return function.apply(value); } finally { contextManager.restoreCurrent(old); } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/package-info.java000066400000000000000000000017631361511066400305620ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Types related to management of contextual objects. Such objects may implement {@link org.wildfly.common.context.Contextual Contextual} * to gain thread-contextual functionality. * * @author David M. Lloyd */ package org.wildfly.common.context; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/000077500000000000000000000000001361511066400244675ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/CacheInfo.java000066400000000000000000000267331361511066400271640ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.cpu; import static java.security.AccessController.doPrivileged; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Locale; /** * A class which exposes any available cache line information for the current CPU. * * @author David M. Lloyd */ public final class CacheInfo { private static final CacheLevelInfo[] cacheLevels; /** * Get the number of CPU cache level entries. If no cache information could be gathered, 0 is returned. * * @return the number of CPU cache levels, or 0 if unknown */ public static int getLevelEntryCount() { return cacheLevels.length; } /** * Get the CPU cache level information for a cache level. The {@code index} argument must be greater than zero and * less than the number of levels returned by {@link #getLevelEntryCount()}. * * @param index the cache level index * @return the CPU cache level information */ public static CacheLevelInfo getCacheLevelInfo(int index) { return cacheLevels[index]; } /** * Get the smallest known data cache line size. If no cache line sizes are known, 0 is returned. Note that smaller * cache lines may exist if one or more cache line sizes are unknown. * * @return the smallest cache line size, or 0 if unknown */ public static int getSmallestDataCacheLineSize() { int minSize = Integer.MAX_VALUE; for (CacheLevelInfo cacheLevel : cacheLevels) { if (cacheLevel.getCacheType().isData()) { final int cacheLineSize = cacheLevel.getCacheLineSize(); if (cacheLineSize != 0 && cacheLineSize < minSize) { minSize = cacheLineSize; } } } return minSize == Integer.MAX_VALUE ? 0 : minSize; } /** * Get the smallest known instruction cache line size. If no cache line sizes are known, 0 is returned. Note that smaller * cache lines may exist if one or more cache line sizes are unknown. * * @return the smallest cache line size, or 0 if unknown */ public static int getSmallestInstructionCacheLineSize() { int minSize = Integer.MAX_VALUE; for (CacheLevelInfo cacheLevel : cacheLevels) { if (cacheLevel.getCacheType().isInstruction()) { final int cacheLineSize = cacheLevel.getCacheLineSize(); if (cacheLineSize != 0 && cacheLineSize < minSize) { minSize = cacheLineSize; } } } return minSize == Integer.MAX_VALUE ? 0 : minSize; } static { cacheLevels = doPrivileged((PrivilegedAction) () -> { try { String osArch = System.getProperty("os.name", "unknown").toLowerCase(Locale.US); if (osArch.contains("linux")) { // try to read /sys fs final File cpu0 = new File("/sys/devices/system/cpu/cpu0/cache"); if (cpu0.exists()) { // great! final File[] files = cpu0.listFiles(); if (files != null) { ArrayList indexes = new ArrayList(); for (File file : files) { if (file.getName().startsWith("index")) { indexes.add(file); } } final CacheLevelInfo[] levelInfoArray = new CacheLevelInfo[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { File file = indexes.get(i); int index = parseIntFile(new File(file, "level")); final CacheType type; switch (parseStringFile(new File(file, "type"))) { case "Data": type = CacheType.DATA; break; case "Instruction": type = CacheType.INSTRUCTION; break; case "Unified": type = CacheType.UNIFIED; break; default: type = CacheType.UNKNOWN; break; } int size = parseIntKBFile(new File(file, "size")); int lineSize = parseIntFile(new File(file, "coherency_line_size")); levelInfoArray[i] = new CacheLevelInfo(index, type, size, lineSize); } return levelInfoArray; } } } else if (osArch.contains("mac os x")) { // cache line size final int lineSize = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.cachelinesize")); if (lineSize != 0) { // cache sizes final int l1d = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l1dcachesize")); final int l1i = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l1icachesize")); final int l2 = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l2cachesize")); final int l3 = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l3cachesize")); ArrayList list = new ArrayList(); if (l1d != 0) { list.add(new CacheLevelInfo(1, CacheType.DATA, l1d / 1024, lineSize)); } if (l1i != 0) { list.add(new CacheLevelInfo(1, CacheType.INSTRUCTION, l1i / 1024, lineSize)); } if (l2 != 0) { list.add(new CacheLevelInfo(2, CacheType.UNIFIED, l2 / 1024, lineSize)); } if (l3 != 0) { list.add(new CacheLevelInfo(3, CacheType.UNIFIED, l3 / 1024, lineSize)); } if (list.size() > 0) { return list.toArray(new CacheLevelInfo[list.size()]); } } } else if (osArch.contains("windows")) { // TODO: use the wmic utility to get cache line info } } catch (Throwable ignored) {} // all has failed return new CacheLevelInfo[0]; }); } static int parseIntFile(final File file) { return safeParseInt(parseStringFile(file)); } static int safeParseInt(final String string) { try { return Integer.parseInt(string); } catch (Throwable ignored) { return 0; } } static int parseIntKBFile(final File file) { try { final String s = parseStringFile(file); if (s.endsWith("K")) { return Integer.parseInt(s.substring(0, s.length() - 1)); } else if (s.endsWith("M")) { return Integer.parseInt(s.substring(0, s.length() - 1)) * 1024; } else if (s.endsWith("G")) { return Integer.parseInt(s.substring(0, s.length() - 1)) * 1024 * 1024; } else { return Integer.parseInt(s); } } catch (Throwable ignored) { return 0; } } static String parseStringFile(final File file) { try (FileInputStream is = new FileInputStream(file)) { return parseStringStream(is); } catch (Throwable ignored) { return ""; } } static String parseStringStream(final InputStream is) { try (Reader r = new InputStreamReader(is, StandardCharsets.UTF_8)) { StringBuilder b = new StringBuilder(); char[] cb = new char[64]; int res; while ((res = r.read(cb)) != -1) { b.append(cb, 0, res); } return b.toString().trim(); } catch (Throwable ignored) { return ""; } } static String parseProcessOutput(final String... args) { final ProcessBuilder processBuilder = new ProcessBuilder(args); try { final Process process = processBuilder.start(); process.getOutputStream().close(); final InputStream errorStream = process.getErrorStream(); final Thread errorThread = new Thread(null, new StreamConsumer(errorStream), "Process thread", 32768L); errorThread.start(); final String result; try (final InputStream inputStream = process.getInputStream()) { result = parseStringStream(inputStream); } boolean intr = false; try { process.waitFor(); } catch (InterruptedException e) { intr = true; return null; } finally { try { errorThread.join(); } catch (InterruptedException e) { intr = true; } finally { if (intr) { Thread.currentThread().interrupt(); } } } return result; } catch (IOException e) { return ""; } } static class StreamConsumer implements Runnable { private final InputStream stream; StreamConsumer(final InputStream stream) { this.stream = stream; } public void run() { byte[] buffer = new byte[128]; try { while (stream.read(buffer) != -1) ; } catch (IOException ignored) { } finally { try { stream.close(); } catch (IOException ignored) { } } } } public static void main(String[] args) { System.out.println("Detected cache info:"); for (CacheLevelInfo levelInfo : cacheLevels) { System.out.printf("Level %d cache: type %s, size %d KiB, cache line is %d bytes%n", Integer.valueOf(levelInfo.getCacheLevel()), levelInfo.getCacheType(), Integer.valueOf(levelInfo.getCacheLevelSizeKB()), Integer.valueOf(levelInfo.getCacheLineSize()) ); } } }wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/CacheLevelInfo.java000066400000000000000000000044431361511066400301460ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.cpu; /** * @author David M. Lloyd */ public final class CacheLevelInfo { private final int cacheLevel; private final CacheType cacheType; private final int cacheLevelSizeKB; private final int cacheLineSize; CacheLevelInfo(final int cacheLevel, final CacheType cacheType, final int cacheLevelSizeKB, final int cacheLineSize) { this.cacheLevel = cacheLevel; this.cacheType = cacheType; this.cacheLevelSizeKB = cacheLevelSizeKB; this.cacheLineSize = cacheLineSize; } /** * Get the level index. For example, the level of L1 cache will be "1", L2 will be "2", etc. If the level is * not known, 0 is returned. * * @return the level index, or 0 if unknown */ public int getCacheLevel() { return cacheLevel; } /** * Get the type of cache. If the type is unknown, {@link CacheType#UNKNOWN} is returned. * * @return the type of cache (not {@code null}) */ public CacheType getCacheType() { return cacheType; } /** * Get the size of this cache level in kilobytes. If the size is unknown, 0 is returned. * * @return the size of this cache level in kilobytes, or 0 if unknown */ public int getCacheLevelSizeKB() { return cacheLevelSizeKB; } /** * Get the cache line size in bytes. If the size is unknown, 0 is returned. * * @return the cache line size in bytes, or 0 if unknown */ public int getCacheLineSize() { return cacheLineSize; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/CacheType.java000066400000000000000000000075461361511066400272130ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.cpu; import java.util.EnumSet; /** * The type of cache. * * @author David M. Lloyd */ public enum CacheType { /** * Unknown cache type. */ UNKNOWN(false, false), /** * Data cache. */ DATA(false, true), /** * Instruction cache. */ INSTRUCTION(true, false), /** * Unified instruction/data cache. */ UNIFIED(true, true), ; private static final int fullSize = values().length; private final boolean instruction; private final boolean data; CacheType(final boolean instruction, final boolean data) { this.instruction = instruction; this.data = data; } /** * Determine if this cache line type holds instructions. * * @return {@code true} if the cache line holds instructions, {@code false} if it does not or it cannot be determined */ public boolean isInstruction() { return instruction; } /** * Determine if this cache line type holds data. * * @return {@code true} if the cache line holds data, {@code false} if it does not or it cannot be determined */ public boolean isData() { return data; } /** * Determine whether the given set is fully populated (or "full"), meaning it contains all possible values. * * @param set the set * * @return {@code true} if the set is full, {@code false} otherwise */ public static boolean isFull(final EnumSet set) { return set != null && set.size() == fullSize; } /** * Determine whether this instance is equal to one of the given instances. * * @param v1 the first instance * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final CacheType v1) { return this == v1; } /** * Determine whether this instance is equal to one of the given instances. * * @param v1 the first instance * @param v2 the second instance * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final CacheType v1, final CacheType v2) { return this == v1 || this == v2; } /** * Determine whether this instance is equal to one of the given instances. * * @param v1 the first instance * @param v2 the second instance * @param v3 the third instance * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final CacheType v1, final CacheType v2, final CacheType v3) { return this == v1 || this == v2 || this == v3; } /** * Determine whether this instance is equal to one of the given instances. * * @param values the possible values * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final CacheType... values) { if (values != null) for (CacheType value : values) { if (this == value) return true; } return false; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/ProcessorInfo.java000066400000000000000000000101701361511066400301240ustar00rootroot00000000000000package org.wildfly.common.cpu; /* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Locale; /** * Provides general information about the processors on this host. * * @author Jason T. Greene */ public class ProcessorInfo { private ProcessorInfo() { } private static final String CPUS_ALLOWED = "Cpus_allowed:"; private static final byte[] BITS = new byte[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; private static final Charset ASCII = Charset.forName("US-ASCII"); /** * Returns the number of processors available to this process. On most operating systems this method * simply delegates to {@link Runtime#availableProcessors()}. However, on Linux, this strategy * is insufficient, since the JVM does not take into consideration the process' CPU set affinity * which is employed by cgroups and numactl. Therefore this method will analyze the Linux proc filesystem * to make the determination. Since the CPU affinity of a process can be change at any time, this method does * not cache the result. Calls should be limited accordingly. *
* Note tha on Linux, both SMT units (Hyper-Threading) and CPU cores are counted as a processor. * * @return the available processors on this system. */ public static int availableProcessors() { if (System.getSecurityManager() != null) { return AccessController.doPrivileged((PrivilegedAction) () -> Integer.valueOf(determineProcessors())).intValue(); } return determineProcessors(); } private static int determineProcessors() { int javaProcs = Runtime.getRuntime().availableProcessors(); if (!isLinux()) { return javaProcs; } int maskProcs = 0; try { maskProcs = readCPUMask(); } catch (Exception e) { // yum } return maskProcs > 0 ? Math.min(javaProcs, maskProcs) : javaProcs; } private static int readCPUMask() throws IOException { final FileInputStream stream = new FileInputStream("/proc/self/status"); final InputStreamReader inputReader = new InputStreamReader(stream, ASCII); try (BufferedReader reader = new BufferedReader(inputReader)) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith(CPUS_ALLOWED)) { int count = 0; int start = CPUS_ALLOWED.length(); for (int i = start; i < line.length(); i++) { char ch = line.charAt(i); if (ch >= '0' && ch <= '9') { count += BITS[ch - '0']; } else if (ch >= 'a' && ch <= 'f') { count += BITS[ch - 'a' + 10]; } else if (ch >= 'A' && ch <= 'F') { count += BITS[ch - 'A' + 10]; } } return count; } } } return -1; } private static boolean isLinux() { String osArch = System.getProperty("os.name", "unknown").toLowerCase(Locale.US); return (osArch.contains("linux")); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/package-info.java000066400000000000000000000016351361511066400276630ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A set of utility classes to determine information about the runtime environment's CPU configuration. * * @author David M. Lloyd */ package org.wildfly.common.cpu; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/000077500000000000000000000000001361511066400260775ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/CompositeNode.java000066400000000000000000000035061361511066400315160ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import java.util.HashSet; import java.util.List; import org.wildfly.common.function.ExceptionBiConsumer; /** * @author David M. Lloyd */ final class CompositeNode extends Node { private final Node[] subNodes; CompositeNode(final Node[] subNodes) { this.subNodes = subNodes; } CompositeNode(final List subNodes) { this.subNodes = subNodes.toArray(NO_NODES); } void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E { for (Node subNode : subNodes) { subNode.emit(context, resolveFunction); } } void catalog(final HashSet strings) { for (Node node : subNodes) { node.catalog(strings); } } public String toString() { StringBuilder b = new StringBuilder(); b.append('*'); for (Node subNode : subNodes) { b.append('<').append(subNode.toString()).append('>'); } return b.toString(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/Expression.java000066400000000000000000000774651361511066400311240ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.BiConsumer; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; import org.wildfly.common.function.ExceptionBiConsumer; /** * A compiled property-expansion expression string. An expression string is a mix of plain strings and expression * segments, which are wrapped by the sequence "{@code ${ ... }}". * * @author David M. Lloyd */ public final class Expression { private final Node content; private final Set referencedStrings; Expression(Node content) { this.content = content; HashSet strings = new HashSet<>(); content.catalog(strings); referencedStrings = strings.isEmpty() ? Collections.emptySet() : strings.size() == 1 ? Collections.singleton(strings.iterator().next()) : Collections.unmodifiableSet(strings); } /** * Get the immutable set of string keys that are referenced by expressions in this compiled expression. If there * are no expansions in this expression, the set is empty. Note that this will not include any string keys * that themselves contain expressions, in the case that {@link Flag#NO_RECURSE_KEY} was not specified. * * @return the immutable set of strings (not {@code null}) */ public Set getReferencedStrings() { return referencedStrings; } /** * Evaluate the expression with the given expansion function, which may throw a checked exception. The given "function" * is a predicate which returns {@code true} if the expansion succeeded or {@code false} if it failed (in which case * a default value may be used). If expansion succeeds, the expansion function should append the result to the * given {@link StringBuilder}. * * @param expandFunction the expansion function to apply (must not be {@code null}) * @param the exception type thrown by the expansion function * @return the expanded string * @throws E if the expansion function throws an exception */ public String evaluateException(final ExceptionBiConsumer, StringBuilder, E> expandFunction) throws E { Assert.checkNotNullParam("expandFunction", expandFunction); final StringBuilder b = new StringBuilder(); content.emit(new ResolveContext(expandFunction, b), expandFunction); return b.toString(); } /** * Evaluate the expression with the given expansion function. The given "function" * is a predicate which returns {@code true} if the expansion succeeded or {@code false} if it failed (in which case * a default value may be used). If expansion succeeds, the expansion function should append the result to the * given {@link StringBuilder}. * * @param expandFunction the expansion function to apply (must not be {@code null}) * @return the expanded string */ public String evaluate(BiConsumer, StringBuilder> expandFunction) { return evaluateException(expandFunction::accept); } /** * Evaluate the expression using a default expansion function that evaluates system and environment properties * in the JBoss style (i.e. using the prefix {@code "env."} to designate an environment property). * The caller must have all required security manager permissions. * * @param failOnNoDefault {@code true} to throw an {@link IllegalArgumentException} if an unresolvable key has no * default value; {@code false} to expand such keys to an empty string * @return the expanded string */ public String evaluateWithPropertiesAndEnvironment(boolean failOnNoDefault) { return evaluate((c, b) -> { final String key = c.getKey(); if (key.startsWith("env.")) { final String env = key.substring(4); final String val = System.getenv(env); if (val == null) { if (failOnNoDefault && ! c.hasDefault()) { throw CommonMessages.msg.unresolvedEnvironmentProperty(env); } c.expandDefault(); } else { b.append(val); } } else { final String val = System.getProperty(key); if (val == null) { if (failOnNoDefault && ! c.hasDefault()) { throw CommonMessages.msg.unresolvedSystemProperty(key); } c.expandDefault(); } else { b.append(val); } } }); } /** * Evaluate the expression using a default expansion function that evaluates system properties. * The caller must have all required security manager permissions. * * @param failOnNoDefault {@code true} to throw an {@link IllegalArgumentException} if an unresolvable key has no * default value; {@code false} to expand such keys to an empty string * @return the expanded string */ public String evaluateWithProperties(boolean failOnNoDefault) { return evaluate((c, b) -> { final String key = c.getKey(); final String val = System.getProperty(key); if (val == null) { if (failOnNoDefault && ! c.hasDefault()) { throw CommonMessages.msg.unresolvedSystemProperty(key); } c.expandDefault(); } else { b.append(val); } }); } /** * Evaluate the expression using a default expansion function that evaluates environment properties. * The caller must have all required security manager permissions. * * @param failOnNoDefault {@code true} to throw an {@link IllegalArgumentException} if an unresolvable key has no * default value; {@code false} to expand such keys to an empty string * @return the expanded string */ public String evaluateWithEnvironment(boolean failOnNoDefault) { return evaluate((c, b) -> { final String key = c.getKey(); final String val = System.getenv(key); if (val == null) { if (failOnNoDefault && ! c.hasDefault()) { throw CommonMessages.msg.unresolvedEnvironmentProperty(key); } c.expandDefault(); } else { b.append(val); } }); } /** * Compile an expression string. * * @param string the expression string (must not be {@code null}) * @param flags optional flags to apply which affect the compilation * @return the compiled expression (not {@code null}) */ public static Expression compile(String string, Flag... flags) { return compile(string, flags == null || flags.length == 0 ? NO_FLAGS : EnumSet.of(flags[0], flags)); } /** * Compile an expression string. * * @param string the expression string (must not be {@code null}) * @param flags optional flags to apply which affect the compilation (must not be {@code null}) * @return the compiled expression (not {@code null}) */ public static Expression compile(String string, EnumSet flags) { Assert.checkNotNullParam("string", string); Assert.checkNotNullParam("flags", flags); final Node content; final Itr itr; if (flags.contains(Flag.NO_TRIM)) { itr = new Itr(string); } else { itr = new Itr(string.trim()); } content = parseString(itr, true, false, false, flags); return content == Node.NULL ? EMPTY : new Expression(content); } private static final Expression EMPTY = new Expression(Node.NULL); static final class Itr { private final String str; private int idx; Itr(final String str) { this.str = str; } boolean hasNext() { return idx < str.length(); } int next() { final int idx = this.idx; try { return str.codePointAt(idx); } finally { this.idx = str.offsetByCodePoints(idx, 1); } } int prev() { final int idx = this.idx; try { return str.codePointBefore(idx); } finally { this.idx = str.offsetByCodePoints(idx, -1); } } int getNextIdx() { return idx; } int getPrevIdx() { return str.offsetByCodePoints(idx, -1); } String getStr() { return str; } int peekNext() { return str.codePointAt(idx); } int peekPrev() { return str.codePointBefore(idx); } void rewind(final int newNext) { idx = newNext; } } private static Node parseString(Itr itr, final boolean allowExpr, final boolean endOnBrace, final boolean endOnColon, final EnumSet flags) { int ignoreBraceLevel = 0; final List list = new ArrayList<>(); int start = itr.getNextIdx(); while (itr.hasNext()) { // index of this character int idx = itr.getNextIdx(); int ch = itr.next(); switch (ch) { case '$': { if (! allowExpr) { // TP 1 // treat as plain content continue; } // check to see if it's a dangling $ if (! itr.hasNext()) { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 2 throw invalidExpressionSyntax(itr.getStr(), idx); } // TP 3 list.add(new LiteralNode(itr.getStr(), start, itr.getNextIdx())); start = itr.getNextIdx(); continue; } // enqueue what we have acquired so far if (idx > start) { // TP 4 list.add(new LiteralNode(itr.getStr(), start, idx)); } // next char should be an expression starter of some sort idx = itr.getNextIdx(); ch = itr.next(); switch (ch) { case '{': { // ${ boolean general = flags.contains(Flag.GENERAL_EXPANSION) && itr.hasNext() && itr.peekNext() == '{'; // consume double-{ if (general) itr.next(); // set start to the beginning of the key for later start = itr.getNextIdx(); // the expression name starts in the next position Node keyNode = parseString(itr, ! flags.contains(Flag.NO_RECURSE_KEY), true, true, flags); if (! itr.hasNext()) { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 5 throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx()); } // TP 6 // otherwise treat it as a properly terminated expression list.add(new ExpressionNode(general, keyNode, Node.NULL)); start = itr.getNextIdx(); continue; } else if (itr.peekNext() == ':') { if (flags.contains(Flag.DOUBLE_COLON) && itr.hasNext() && itr.peekNext() == ':') { // TP 7 // OK actually the whole thing is really going to be part of the key // Best approach is, rewind and do it over again, but without end-on-colon itr.rewind(start); keyNode = parseString(itr, ! flags.contains(Flag.NO_RECURSE_KEY), true, false, flags); list.add(new ExpressionNode(general, keyNode, Node.NULL)); } else { // TP 8 itr.next(); // consume it final Node defaultValueNode = parseString(itr, ! flags.contains(Flag.NO_RECURSE_DEFAULT), true, false, flags); list.add(new ExpressionNode(general, keyNode, defaultValueNode)); } // now expect } if (! itr.hasNext()) { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 9 throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx()); } // TP 10 // otherwise treat it as a properly terminated expression start = itr.getNextIdx(); continue; } else { // TP 11 assert itr.peekNext() == '}'; itr.next(); // consume if (general) { if (! itr.hasNext()) { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 11_1 throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx()); } // TP 11_2 // otherwise treat it as a properly terminated expression start = itr.getNextIdx(); continue; } else { if (itr.peekNext() == '}') { itr.next(); // consume it // TP 11_3 start = itr.getNextIdx(); continue; } else { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 11_4 throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx()); } // otherwise treat it as a properly terminated expression start = itr.getNextIdx(); continue; } } } else { start = itr.getNextIdx(); continue; } //throw Assert.unreachableCode(); } } else { // TP 12 assert itr.peekNext() == '}'; itr.next(); // consume list.add(new ExpressionNode(general, keyNode, Node.NULL)); if (general) { if (! itr.hasNext()) { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 12_1 throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx()); } // TP 12_2 // otherwise treat it as a properly terminated expression start = itr.getNextIdx(); continue; } else { if (itr.peekNext() == '}') { itr.next(); // consume it // TP 12_3 start = itr.getNextIdx(); continue; } else { if (! flags.contains(Flag.LENIENT_SYNTAX)) { // TP 12_4 throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx()); } // otherwise treat it as a properly terminated expression start = itr.getNextIdx(); continue; } } } start = itr.getNextIdx(); continue; } //throw Assert.unreachableCode(); } case '$': { // $$ if (flags.contains(Flag.MINI_EXPRS)) { // TP 13 list.add(new ExpressionNode(false, LiteralNode.DOLLAR, Node.NULL)); } else { // just resolve $$ to $ // TP 14 list.add(LiteralNode.DOLLAR); } start = itr.getNextIdx(); continue; } case '}': { // $} if (flags.contains(Flag.MINI_EXPRS)) { // TP 15 list.add(new ExpressionNode(false, LiteralNode.CLOSE_BRACE, Node.NULL)); start = itr.getNextIdx(); continue; } else if (endOnBrace) { if (flags.contains(Flag.LENIENT_SYNTAX)) { // TP 16 // just treat the $ that we got like plain text, and return list.add(LiteralNode.DOLLAR); itr.prev(); // back up to point at } again return Node.fromList(list); } else { // TP 17 throw invalidExpressionSyntax(itr.getStr(), idx); } } else { if (flags.contains(Flag.LENIENT_SYNTAX)) { // TP 18 // just treat $} like plain text list.add(LiteralNode.DOLLAR); list.add(LiteralNode.CLOSE_BRACE); start = itr.getNextIdx(); continue; } else { // TP 19 throw invalidExpressionSyntax(itr.getStr(), idx); } } //throw Assert.unreachableCode(); } case ':': { // $: if (flags.contains(Flag.MINI_EXPRS)) { // $: is an expression // TP 20 list.add(new ExpressionNode(false, LiteralNode.COLON, Node.NULL)); start = itr.getNextIdx(); continue; } else if (endOnColon) { if (flags.contains(Flag.LENIENT_SYNTAX)) { // TP 21 // just treat the $ that we got like plain text, and return itr.prev(); // back up to point at : again list.add(LiteralNode.DOLLAR); return Node.fromList(list); } else { // TP 22 throw invalidExpressionSyntax(itr.getStr(), idx); } } else { if (flags.contains(Flag.LENIENT_SYNTAX)) { // TP 23 // just treat $: like plain text list.add(LiteralNode.DOLLAR); list.add(LiteralNode.COLON); start = itr.getNextIdx(); continue; } else { // TP 24 throw invalidExpressionSyntax(itr.getStr(), idx); } } //throw Assert.unreachableCode(); } default: { // $ followed by anything else if (flags.contains(Flag.MINI_EXPRS)) { // TP 25 list.add(new ExpressionNode(false, new LiteralNode(itr.getStr(), idx, itr.getNextIdx()), Node.NULL)); start = itr.getNextIdx(); continue; } else if (flags.contains(Flag.LENIENT_SYNTAX)) { // TP 26 // just treat it as literal start = itr.getPrevIdx() - 1; // we can use 1 here because unicode '$' is one char in size continue; } else { // TP 27 throw invalidExpressionSyntax(itr.getStr(), idx); } //throw Assert.unreachableCode(); } } //throw Assert.unreachableCode(); } case ':': { if (endOnColon) { // TP 28 itr.prev(); // back up to point at : again if (idx > start) { list.add(new LiteralNode(itr.getStr(), start, idx)); } return Node.fromList(list); } else { // TP 29 // plain content always continue; } //throw Assert.unreachableCode(); } case '{': { if (! flags.contains(Flag.NO_SMART_BRACES)) { // TP 1.2 ignoreBraceLevel++; } // TP 1.3 continue; } case '}': { if (! flags.contains(Flag.NO_SMART_BRACES) && ignoreBraceLevel > 0) { // TP 1.1 ignoreBraceLevel--; continue; } else if (endOnBrace) { // TP 30 itr.prev(); // back up to point at } again // TP 46 // allow an empty default value if (idx >= start) { list.add(new LiteralNode(itr.getStr(), start, idx)); } return Node.fromList(list); } else { // TP 31 // treat as plain content continue; } //throw Assert.unreachableCode(); } case '\\': { if (flags.contains(Flag.ESCAPES)) { if (idx > start) { list.add(new LiteralNode(itr.getStr(), start, idx)); start = idx; } if (! itr.hasNext()) { if (flags.contains(Flag.LENIENT_SYNTAX)) { // just treat it like plain content // TP 33 continue; } else { // TP 34 throw invalidExpressionSyntax(itr.getStr(), idx); } } else { ch = itr.next(); final LiteralNode node; switch (ch) { case 'n': { // TP 35 node = LiteralNode.NEWLINE; break; } case 'r': { // TP 36 node = LiteralNode.CARRIAGE_RETURN; break; } case 't': { // TP 37 node = LiteralNode.TAB; break; } case 'b': { // TP 38 node = LiteralNode.BACKSPACE; break; } case 'f': { // TP 39 node = LiteralNode.FORM_FEED; break; } case '\\': { // TP 45 node = LiteralNode.BACKSLASH; break; } default: { if (flags.contains(Flag.LENIENT_SYNTAX)) { // TP 40 // just append the literal character after the \, whatever it was start = itr.getPrevIdx(); continue; } // TP 41 throw invalidExpressionSyntax(itr.getStr(), idx); } } list.add(node); start = itr.getNextIdx(); continue; } } // TP 42 // otherwise, just... continue; } default: { // TP 43 // treat as plain content //noinspection UnnecessaryContinue continue; } } //throw Assert.unreachableCode(); } final int length = itr.getStr().length(); if (length > start) { // TP 44 list.add(new LiteralNode(itr.getStr(), start, length)); } return Node.fromList(list); } private static IllegalArgumentException invalidExpressionSyntax(final String string, final int index) { String msg = CommonMessages.msg.invalidExpressionSyntax(index); StringBuilder b = new StringBuilder(msg.length() + string.length() + string.length() + 5); b.append(msg); b.append('\n').append('\t').append(string); b.append('\n').append('\t'); for (int i = 0; i < index; i = string.offsetByCodePoints(i, 1)) { final int cp = string.codePointAt(i); if (Character.isWhitespace(cp)) { b.append(cp); } else if (Character.isValidCodePoint(cp) && ! Character.isISOControl(cp)) { b.append(' '); } } b.append('^'); return new IllegalArgumentException(b.toString()); } private static final EnumSet NO_FLAGS = EnumSet.noneOf(Flag.class); /** * Flags that can apply to a property expression compilation */ public enum Flag { /** * Do not trim leading and trailing whitespace off of the expression string before parsing it. */ NO_TRIM, /** * Ignore syntax problems instead of throwing an exception. */ LENIENT_SYNTAX, /** * Support single-character expressions that can be interpreted without wrapping in curly braces. */ MINI_EXPRS, /** * Do not support recursive expression expansion in the key part of the expression. */ NO_RECURSE_KEY, /** * Do not support recursion in default values. */ NO_RECURSE_DEFAULT, /** * Do not support smart braces. */ NO_SMART_BRACES, /** * Support {@code Policy} file style "general" expansion alternate expression syntax. "Smart" braces * will only work if the opening brace is not the first character in the expression key. */ GENERAL_EXPANSION, /** * Support standard escape sequences in plain text and default value fields, which begin with a backslash ("{@code \}") character. */ ESCAPES, /** * Treat expressions containing a double-colon delimiter as special, encoding the entire content into the key. */ DOUBLE_COLON, } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/ExpressionNode.java000066400000000000000000000042271361511066400317140ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import java.util.HashSet; import org.wildfly.common.function.ExceptionBiConsumer; /** * @author David M. Lloyd */ class ExpressionNode extends Node { private final boolean generalExpression; private final Node key; private final Node defaultValue; ExpressionNode(final boolean generalExpression, final Node key, final Node defaultValue) { this.generalExpression = generalExpression; this.key = key; this.defaultValue = defaultValue; } void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E { ExpressionNode oldCurrent = context.setCurrent(this); try { resolveFunction.accept(context, context.getStringBuilder()); } finally { context.setCurrent(oldCurrent); } } void catalog(final HashSet strings) { if (key instanceof LiteralNode) { strings.add(key.toString()); } else { key.catalog(strings); } defaultValue.catalog(strings); } boolean isGeneralExpression() { return generalExpression; } Node getKey() { return key; } Node getDefaultValue() { return defaultValue; } public String toString() { return String.format("Expr<%s:%s>", key, defaultValue); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/LiteralNode.java000066400000000000000000000046731361511066400311560ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import java.io.File; import java.util.HashSet; import org.wildfly.common.function.ExceptionBiConsumer; /** * @author David M. Lloyd */ class LiteralNode extends Node { static final LiteralNode DOLLAR = new LiteralNode("$"); static final LiteralNode CLOSE_BRACE = new LiteralNode("}"); static final LiteralNode FILE_SEP = new LiteralNode(File.separator); static final LiteralNode COLON = new LiteralNode(":"); static final LiteralNode NEWLINE = new LiteralNode("\n"); static final LiteralNode CARRIAGE_RETURN = new LiteralNode("\r"); static final LiteralNode TAB = new LiteralNode("\t"); static final LiteralNode BACKSPACE = new LiteralNode("\b"); static final LiteralNode FORM_FEED = new LiteralNode("\f"); static final LiteralNode BACKSLASH = new LiteralNode("\\"); private final String literalValue; private final int start; private final int end; private String toString; LiteralNode(final String literalValue, final int start, final int end) { this.literalValue = literalValue; this.start = start; this.end = end; } LiteralNode(final String literalValue) { this(literalValue, 0, literalValue.length()); } void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E { context.getStringBuilder().append(literalValue, start, end); } void catalog(final HashSet strings) { } public String toString() { final String toString = this.toString; return toString != null ? toString : (this.toString = literalValue.substring(start, end)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/Node.java000066400000000000000000000035351361511066400276350ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import java.util.HashSet; import java.util.List; import org.wildfly.common.function.ExceptionBiConsumer; /** * @author David M. Lloyd */ abstract class Node { static final Node[] NO_NODES = new Node[0]; Node() { } static Node fromList(List list) { if (list == null || list.isEmpty()) { return NULL; } else if (list.size() == 1) { return list.get(0); } else { return new CompositeNode(list); } } static final Node NULL = new Node() { void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E { } void catalog(final HashSet strings) { } public String toString() { return "<>"; } }; abstract void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E; abstract void catalog(final HashSet strings); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/ResolveContext.java000066400000000000000000000125401361511066400317300ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import org.wildfly.common.function.ExceptionBiConsumer; /** * The expression resolve context, which can be used to query the current expression key, write out expansions or * default values, or perform validation. *

* The expression context is not thread-safe and is not valid outside of the property expansion function body. * * @param the exception type that can be thrown by the expansion function * * @author David M. Lloyd */ public final class ResolveContext { private final ExceptionBiConsumer, StringBuilder, E> function; private StringBuilder builder; private ExpressionNode current; ResolveContext(final ExceptionBiConsumer, StringBuilder, E> function, final StringBuilder builder) { this.function = function; this.builder = builder; } /** * Get the expression resolution key, as a string. If the key contains an expression, it will have been expanded * unless {@link Expression.Flag#NO_RECURSE_KEY} was given. * The result is not cached and will be re-expanded every time this method is called. * * @return the expanded key (not {@code null}) * @throws E if the recursive expansion threw an exception */ public String getKey() throws E { if (current == null) throw new IllegalStateException(); final Node key = current.getKey(); if (key instanceof LiteralNode) { return key.toString(); } else if (key == Node.NULL) { return ""; } final StringBuilder b = new StringBuilder(); emitToBuilder(b, key); return b.toString(); } /** * Expand the default value to the given string builder. If the default value contains an expression, it will * have been expanded unless {@link Expression.Flag#NO_RECURSE_DEFAULT} was given. * The result is not cached and will be re-expanded every time this method is called. * * @param target the string builder target * @throws E if the recursive expansion threw an exception */ public void expandDefault(StringBuilder target) throws E { if (current == null) throw new IllegalStateException(); emitToBuilder(target, current.getDefaultValue()); } private void emitToBuilder(final StringBuilder target, final Node node) throws E { if (node == Node.NULL) { return; } else if (node instanceof LiteralNode) { target.append(node.toString()); return; } else { final StringBuilder old = builder; try { builder = target; node.emit(this, function); } finally { builder = old; } } } /** * Expand the default value to the current target string builder. If the default value contains an expression, it will * have been expanded unless {@link Expression.Flag#NO_RECURSE_DEFAULT} was given. * The result is not cached and will be re-expanded every time this method is called. * * @throws E if the recursive expansion threw an exception */ public void expandDefault() throws E { expandDefault(builder); } /** * Expand the default value to a string. If the default value contains an expression, it will * have been expanded unless {@link Expression.Flag#NO_RECURSE_DEFAULT} was given. * The result is not cached and will be re-expanded every time this method is called. * * @return the expanded string (not {@code null}) * @throws E if the recursive expansion threw an exception */ public String getExpandedDefault() throws E { if (current == null) throw new IllegalStateException(); final Node defaultValue = current.getDefaultValue(); if (defaultValue instanceof LiteralNode) { return defaultValue.toString(); } else if (defaultValue == Node.NULL) { return ""; } final StringBuilder b = new StringBuilder(); emitToBuilder(b, defaultValue); return b.toString(); } /** * Determine if the current expression has a default value. * * @return {@code true} if there is a default value, {@code false} otherwise */ public boolean hasDefault() { return current.getDefaultValue() != Node.NULL; } StringBuilder getStringBuilder() { return builder; } ExpressionNode setCurrent(final ExpressionNode current) { try { return this.current; } finally { this.current = current; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/package-info.java000066400000000000000000000015611361511066400312710ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Expression string parsing and expansion classes. * * @author David M. Lloyd */ package org.wildfly.common.expression; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/flags/000077500000000000000000000000001361511066400247745ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/flags/Flags.java000066400000000000000000000376421361511066400267070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.flags; import static java.lang.Integer.bitCount; import static java.lang.Integer.highestOneBit; import static java.lang.Integer.lowestOneBit; import static java.lang.Integer.numberOfTrailingZeros; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.function.Consumer; import org.wildfly.common.Assert; /** * A base class for implementing value-like flags and flag sets, where flags and flag sets may be used without allocation * overhead. *

*/ public abstract class Flags, This extends Flags> extends AbstractSet implements SortedSet { final int bits; /** * Construct a new instance. This constructor should only be called during initial array construction. * * @param bits the bits of this set */ protected Flags(final int bits) { this.bits = bits; } /** * Get the set value of the given bit combination. The bit combination may contain extraneous one-bits so * any bits beyond the bit of the last flag should be masked off if an array is used for lookup. * * @param bits the bit combination (possibly with extra bits) * @return the set instance */ protected abstract This value(int bits); /** * Return {@code this}. * * @return {@code this} */ protected abstract This this_(); /** * Get the flag item with the given index. * * @param index the index * @return the flag */ protected abstract E itemOf(int index); /** * Get the item (cast to the correct {@code enum} type), or {@code null} if it is not of the correct type. * * @param obj the object to cast * @return the cast object, or {@code null} */ protected abstract E castItemOrNull(Object obj); /** * Cast the given object to this class, throwing an exception if the cast fails. * * @param obj the object to cast * @return the cast object */ protected abstract This castThis(Object obj); /** * Get the size of the flag set. * * @return the flag set size */ public final int size() { return bitCount(bits); } /** * Get the first flag in the set. * * @return the first flag */ public final E first() { final int bits = this.bits; if (bits == 0) throw new NoSuchElementException(); return itemOf(numberOfTrailingZeros(lowestOneBit(bits))); } /** * Get the last flag in the set. * * @return the last flag */ public final E last() { final int bits = this.bits; if (bits == 0) throw new NoSuchElementException(); return itemOf(numberOfTrailingZeros(highestOneBit(bits))); } /** * Get the {@code null} comparator, indicating that this set is always sorted in natural order. * * @return {@code null} */ public final Comparator comparator() { return null; } /** * Determine if this flag set is empty. * * @return {@code true} if the flag set is empty, {@code false} otherwise */ public boolean isEmpty() { return bits == 0; } /** * Get the subset of flags from this set, up to (but not including) the given element. * * @param toElement the "to" element (must not be {@code null}) * @return the subset */ public final This headSet(final E toElement) { Assert.checkNotNullParam("toElement", toElement); return value(bits & bitOf(toElement) - 1); } /** * Get the subset of flags from this set, starting from the given element. * * @param fromElement the "from" element (must not be {@code null}) * @return the subset */ public final This tailSet(final E fromElement) { Assert.checkNotNullParam("fromElement", fromElement); return value(bits & ~(bitOf(fromElement) - 1)); } /** * Get the subset of flags, starting from {@code fromElement} up to (but not including) {@code toElement}. * * @param fromElement the "from" element (must not be {@code null}) * @param toElement the "to" element (must not be {@code null}) * @return the subset */ public final This subSet(final E fromElement, final E toElement) { Assert.checkNotNullParam("fromElement", fromElement); Assert.checkNotNullParam("toElement", toElement); return value(bits & (bitOf(toElement) - 1) & ~(bitOf(fromElement) - 1)); } /** * Get an {@code Object} array containing all the flag values of this set. * * @return the {@code Object} array */ public final Object[] toArray() { int b = bits; final Object[] array = new Object[bitCount(b)]; int idx = 0; while (bitCount(b) > 0) { final int lob = lowestOneBit(b); array[idx + 1] = itemOf(numberOfTrailingZeros(lob)); b ^= lob; } return array; } /** * Get a typed array containing all the flag values of this set. * * @param array the array to populate or clone * @param the element type * @return the populated array */ @SuppressWarnings("unchecked") public final T[] toArray(T[] array) { int b = bits; final int size = bitCount(b); if (size > array.length) { array = Arrays.copyOf(array, size); } int idx = 0; while (bitCount(b) > 0) { final int lob = lowestOneBit(b); array[idx + 1] = (T) itemOf(numberOfTrailingZeros(lob)); b ^= lob; } return array; } /** * Determine if this flag set contains the given flag. * * @param flag the flag * @return {@code true} if the flag is contained by this set */ public final boolean contains(E flag) { return flag != null && (bits & bitOf(flag)) != 0; } /** * Determine if this flag set contains the given object. * * @param o the object * @return {@code true} if the object is contained by this set */ public final boolean contains(final Object o) { return contains(castItemOrNull(o)); } /** * Determine if this flag set contains all of the objects in the given collection. * * @param c the collection * @return {@code true} if all of the collection's objects are contained by this set */ public final boolean containsAll(final Collection c) { if (c.getClass() == getClass()) { return containsAll(castThis(c)); } else { for (Object o : c) { if (! contains(o)) return false; } return true; } } /** * Determine if this flag set contains all of the flags in the given flag set. * * @param other the flag set * @return {@code true} if all of the given set's flags are contained by this set */ public final boolean containsAll(This other) { final int otherBits = other.bits; return (this.bits & otherBits) == otherBits; } /** * Determine if this flag set contains all of the given flags. * * @param flag1 the first flag * @param flag2 the second flag * @return {@code true} if all of the given flags are contained by this set */ public final boolean containsAll(E flag1, E flag2) { return contains(flag1) && contains(flag2); } /** * Determine if this flag set contains all of the given flags. * * @param flag1 the first flag * @param flag2 the second flag * @param flag3 the third flag * @return {@code true} if all of the given flags are contained by this set */ public final boolean containsAll(E flag1, E flag2, E flag3) { return containsAll(flag1, flag2) && contains(flag3); } /** * Determine if this flag set contains any of the flags in the given flag set. * * @param other the flag set * @return {@code true} if all of the given set's flags are contained by this set */ public final boolean containsAny(This other) { return other != null && (bits & other.bits) != 0; } /** * Determine if this flag set contains any of the given flags. * * @param flag1 the first flag * @param flag2 the second flag * @return {@code true} if any of the given flags are contained by this set */ public final boolean containsAny(E flag1, E flag2) { return contains(flag1) || contains(flag2); } /** * Determine if this flag set contains any of the given flags. * * @param flag1 the first flag * @param flag2 the second flag * @param flag3 the third flag * @return {@code true} if any of the given flags are contained by this set */ public final boolean containsAny(E flag1, E flag2, E flag3) { return containsAny(flag1, flag2) || contains(flag3); } /** * Get the complement of this set. * * @return the complement of this set */ public final This complement() { return value(~bits); } /** * Return a set which includes all of the flags in this set and the given additional flag. * * @param flag the additional flag * @return the combined set */ public final This with(E flag) { return flag == null ? this_() : value(bits | bitOf(flag)); } /** * Return a set which includes all of the flags in this set and the given additional flags. * * @param flag1 the first flag * @param flag2 the second flag * @return the combined set */ public final This with(E flag1, E flag2) { return with(flag1).with(flag2); } /** * Return a set which includes all of the flags in this set and the given additional flags. * * @param flag1 the first flag * @param flag2 the second flag * @param flag3 the third flag * @return the combined set */ public final This with(E flag1, E flag2, E flag3) { return with(flag1, flag2).with(flag3); } /** * Return a set which includes all of the flags in this set and the given additional flags. * * @param flags the additional flags * @return the combined set */ @SafeVarargs public final This with(E... flags) { if (flags == null) return this_(); int b = bits; for (E flag : flags) { if (flag != null) b |= bitOf(flag); } return value(b); } /** * Return a set which includes all of the flags in this set and the given additional flags. * * @param other the additional flags * @return the combined set */ public final This with(This other) { return other == null ? this_() : value(bits | other.bits); } /** * Return a set which includes all of the flags except for the given flag. * * @param flag the flag * @return the reduced set */ public final This without(E flag) { return flag == null ? this_() : value(bits & ~bitOf(flag)); } /** * Return a set which includes all of the flags except for the given flags. * * @param other the flags * @return the reduced set */ public final This without(This other) { return other == null ? this_() : value(bits & ~other.bits); } /** * Determine if this flag set is equal to the given object. * * @param o the other object * @return {@code true} if the object is equal to this set, {@code false} otherwise */ public final boolean equals(final Object o) { return o == this || o instanceof Set && equals((Set) o); } /** * Determine if this flag set is equal to the given set. * * @param o the other set * @return {@code true} if the set is equal to this set, {@code false} otherwise */ public final boolean equals(final Set o) { return o == this || o.containsAll(this) && containsAll(o); } /** * Determine if this flag set is equal to the given flag set. * * @param o the other flag set * @return {@code true} if the flag set is equal to this set, {@code false} otherwise */ public final boolean equals(final This o) { return o == this; } /** * Get the hash code of this flag set. * * @return the flag set hash code */ public final int hashCode() { int hc = 0; int b = this.bits; while (b != 0) { int lob = lowestOneBit(b); hc += itemOf(numberOfTrailingZeros(lob)).hashCode(); b ^= lob; } return hc; } /** * Iterate this set in order from first to last flag. * * @return the iterator */ public final Iterator iterator() { return new Iterator() { int b = bits; public boolean hasNext() { return b != 0; } public E next() { int b = this.b; if (b == 0) throw new NoSuchElementException(); final int lob = lowestOneBit(b); final E item = itemOf(numberOfTrailingZeros(lob)); this.b = b ^ lob; return item; } }; } /** * Iterate this set in order from last to first flag. * * @return the iterator */ public final Iterator descendingIterator() { return new Iterator() { int b = bits; public boolean hasNext() { return b != 0; } public E next() { int b = this.b; if (b == 0) throw new NoSuchElementException(); final int hob = highestOneBit(b); final E item = itemOf(numberOfTrailingZeros(hob)); this.b = b ^ hob; return item; } }; } /** * Apply the given action for every flag in this set. * * @param action the action to apply */ public void forEach(final Consumer action) { Assert.checkNotNullParam("action", action); int b = this.bits; while (b != 0) { int lob = lowestOneBit(b); action.accept(itemOf(numberOfTrailingZeros(lob))); b = b ^ lob; } } /** * Get a string representation of this flag set. * * @return the string representation */ public final String toString() { StringBuilder buf = new StringBuilder(); buf.append(getClass().getSimpleName()).append('['); int lob; int bits = this.bits; if (bits != 0) { lob = lowestOneBit(bits); buf.append(itemOf(numberOfTrailingZeros(lob))); bits ^= lob; while (bits != 0) { buf.append(' '); lob = lowestOneBit(bits); buf.append(itemOf(numberOfTrailingZeros(lob))); bits ^= lob; } } buf.append(']'); return buf.toString(); } private static int bitOf(Enum item) { return 1 << item.ordinal(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/000077500000000000000000000000001361511066400255255ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBiConsumer.java000066400000000000000000000034361361511066400323230ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument consumer which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionBiConsumer { /** * Performs this operation on the given arguments. * * @param t the first argument * @param u the second argument * @throws E if an exception occurs */ void accept(T t, U u) throws E; default ExceptionBiConsumer andThen(ExceptionBiConsumer after) { Assert.checkNotNullParam("after", after); return (t, u) -> { accept(t, u); after.accept(t, u); }; } default ExceptionRunnable compose(ExceptionSupplier before1, ExceptionSupplier before2) { Assert.checkNotNullParam("before1", before1); Assert.checkNotNullParam("before2", before2); return () -> accept(before1.get(), before2.get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBiFunction.java000066400000000000000000000037461361511066400323210ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionBiFunction { /** * Applies this function to the given arguments. * * @param t the first argument * @param u the second argument * @return the function result * @throws E if an exception occurs */ R apply(T t, U u) throws E; default ExceptionBiFunction andThen(ExceptionFunction after) { Assert.checkNotNullParam("after", after); return (t, u) -> after.apply(apply(t, u)); } default ExceptionBiConsumer andThen(ExceptionConsumer after) { Assert.checkNotNullParam("after", after); return (t, u) -> after.accept(apply(t, u)); } default ExceptionSupplier compose(ExceptionSupplier before1, ExceptionSupplier before2) { Assert.checkNotNullParam("before1", before1); Assert.checkNotNullParam("before2", before2); return () -> apply(before1.get(), before2.get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBiPredicate.java000066400000000000000000000034331361511066400324250ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; /** * A two-argument predicate which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionBiPredicate { /** * Evaluate this predicate on the given arguments. * * @param t the first argument * @param u the second argument * @return {@code true} if the predicate passes, {@code false} otherwise * @throws E if an exception occurs */ boolean test(T t, U u) throws E; default ExceptionBiPredicate and(ExceptionBiPredicate other) { return (t, u) -> test(t, u) && other.test(t, u); } default ExceptionBiPredicate or(ExceptionBiPredicate other) { return (t, u) -> test(t, u) || other.test(t, u); } default ExceptionBiPredicate xor(ExceptionBiPredicate other) { return (t, u) -> test(t, u) != other.test(t, u); } default ExceptionBiPredicate not() { return (t, u) -> !test(t, u); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBinaryOperator.java000066400000000000000000000023411361511066400332070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A binary operator which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionBinaryOperator extends ExceptionBiFunction { default ExceptionBinaryOperator andThen(ExceptionUnaryOperator after) { Assert.checkNotNullParam("after", after); return (t, u) -> after.apply(apply(t, u)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionConsumer.java000066400000000000000000000034771361511066400320550ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A one-argument consumer which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionConsumer { /** * Performs this operation on the given argument. * * @param t the argument * @throws E if an exception occurs */ void accept(T t) throws E; default ExceptionConsumer andThen(ExceptionConsumer after) { Assert.checkNotNullParam("after", after); return t -> { accept(t); after.accept(t); }; } default ExceptionConsumer compose(ExceptionConsumer before) { Assert.checkNotNullParam("before", before); return t -> { accept(t); before.accept(t); }; } default ExceptionRunnable compose(ExceptionSupplier before) { Assert.checkNotNullParam("before", before); return () -> accept(before.get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionFunction.java000066400000000000000000000055261361511066400320440ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A one-argument function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionFunction { /** * Applies this function to the given arguments. * * @param t the argument * @return the function result * @throws E if an exception occurs */ R apply(T t) throws E; default ExceptionFunction andThen(ExceptionFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionFunction andThen(ExceptionBiFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(t, apply(t)); } default ExceptionFunction compose(ExceptionFunction before) { Assert.checkNotNullParam("before", before); return t -> apply(before.apply(t)); } default ExceptionConsumer andThen(ExceptionConsumer after) { Assert.checkNotNullParam("after", after); return t -> after.accept(apply(t)); } default ExceptionConsumer andThen(ExceptionBiConsumer after) { Assert.checkNotNullParam("after", after); return t -> after.accept(t, apply(t)); } default ExceptionPredicate andThen(ExceptionPredicate after) { Assert.checkNotNullParam("after", after); return t -> after.test(apply(t)); } default ExceptionPredicate andThen(ExceptionBiPredicate after) { Assert.checkNotNullParam("after", after); return t -> after.test(t, apply(t)); } default ExceptionSupplier compose(ExceptionSupplier before) { Assert.checkNotNullParam("before", before); return () -> apply(before.get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionIntFunction.java000066400000000000000000000031741361511066400325140ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A one-argument integer function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionIntFunction { /** * Applies this function to the given arguments. * * @param value the argument * @return the function result * @throws E if an exception occurs */ R apply(int value) throws E; default ExceptionIntFunction andThen(ExceptionFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionFunction compose(ExceptionToIntFunction before) { Assert.checkNotNullParam("before", before); return t -> apply(before.apply(t)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionLongFunction.java000066400000000000000000000032051361511066400326540ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A one-argument long integer function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionLongFunction { /** * Applies this function to the given arguments. * * @param value the argument * @return the function result * @throws E if an exception occurs */ R apply(long value) throws E; default ExceptionLongFunction andThen(ExceptionFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionFunction compose(ExceptionToLongFunction before) { Assert.checkNotNullParam("before", before); return t -> apply(before.apply(t)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionObjIntConsumer.java000066400000000000000000000044111361511066400331500ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument object and integer consumer which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionObjIntConsumer { /** * Performs this operation on the given arguments. * * @param t the first argument * @param value the second argument * @throws E if an exception occurs */ void accept(T t, int value) throws E; default ExceptionObjIntConsumer andThen(ExceptionObjIntConsumer after) { Assert.checkNotNullParam("after", after); return (t, v) -> { accept(t, v); after.accept(t, v); }; } default ExceptionObjIntConsumer compose(ExceptionObjIntConsumer before) { Assert.checkNotNullParam("before", before); return (t, v) -> { before.accept(t, v); accept(t, v); }; } default ExceptionObjIntConsumer andThen(ExceptionObjLongConsumer after) { Assert.checkNotNullParam("after", after); return (t, v) -> { accept(t, v); after.accept(t, v); }; } default ExceptionObjIntConsumer compose(ExceptionObjLongConsumer before) { Assert.checkNotNullParam("before", before); return (t, v) -> { before.accept(t, v); accept(t, v); }; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionObjLongConsumer.java000066400000000000000000000034061361511066400333200ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument object and long integer consumer which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionObjLongConsumer { /** * Performs this operation on the given arguments. * * @param t the first argument * @param value the second argument * @throws E if an exception occurs */ void accept(T t, long value) throws E; default ExceptionObjLongConsumer andThen(ExceptionObjLongConsumer after) { Assert.checkNotNullParam("after", after); return (t, v) -> { accept(t, v); after.accept(t, v); }; } default ExceptionObjLongConsumer compose(ExceptionObjLongConsumer before) { Assert.checkNotNullParam("before", before); return (t, v) -> { before.accept(t, v); accept(t, v); }; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionPredicate.java000066400000000000000000000035021361511066400321470ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; /** * A one-argument predicate which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionPredicate { /** * Evaluate this predicate on the given arguments. * * @param t the first argument * @return {@code true} if the predicate passes, {@code false} otherwise * @throws E if an exception occurs */ boolean test(T t) throws E; default ExceptionPredicate and(ExceptionPredicate other) { return t -> test(t) && other.test(t); } default ExceptionPredicate or(ExceptionPredicate other) { return t -> test(t) || other.test(t); } default ExceptionPredicate xor(ExceptionPredicate other) { return t -> test(t) != other.test(t); } default ExceptionPredicate not() { return t -> !test(t); } default ExceptionBiPredicate with(ExceptionPredicate other) { return (t, u) -> test(t) && other.test(u); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionRunnable.java000066400000000000000000000027551361511066400320260ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * An operation that can throw an exception. * * @author David M. Lloyd */ public interface ExceptionRunnable { /** * Run the operation. * * @throws E if an exception occurs */ void run() throws E; default ExceptionRunnable andThen(ExceptionRunnable after) { Assert.checkNotNullParam("after", after); return () -> { run(); after.run(); }; } default ExceptionRunnable compose(ExceptionRunnable before) { Assert.checkNotNullParam("before", before); return () -> { before.run(); run(); }; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionSupplier.java000066400000000000000000000027641361511066400320630ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A supplier which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionSupplier { /** * Gets a result. * * @return the result * @throws E if an exception occurs */ T get() throws E; default ExceptionRunnable andThen(ExceptionConsumer after) { Assert.checkNotNullParam("after", after); return () -> after.accept(get()); } default ExceptionSupplier andThen(ExceptionFunction after) { Assert.checkNotNullParam("after", after); return () -> after.apply(get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionToIntBiFunction.java000066400000000000000000000032041361511066400332640ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionToIntBiFunction { /** * Apply this function to the given arguments. * * @param t the first argument * @param u the second argument * @return the function result * @throws E if an exception occurs */ int apply(T t, U u) throws E; default ExceptionBiFunction andThen(ExceptionIntFunction after) { Assert.checkNotNullParam("after", after); return (t, u) -> after.apply(apply(t, u)); } default ExceptionBiFunction andThen(ExceptionLongFunction after) { Assert.checkNotNullParam("after", after); return (t, u) -> after.apply(apply(t, u)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionToIntFunction.java000066400000000000000000000035041361511066400330140ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionToIntFunction { /** * Apply this function to the given arguments. * * @param t the first argument * @return the function result * @throws E if an exception occurs */ int apply(T t) throws E; default ExceptionFunction andThen(ExceptionIntFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionFunction andThen(ExceptionLongFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionToIntFunction compose(ExceptionFunction before) { Assert.checkNotNullParam("before", before); return t -> apply(before.apply(t)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionToLongBiFunction.java000066400000000000000000000026761361511066400334450ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionToLongBiFunction { /** * Apply this function to the given arguments. * * @param t the first argument * @param u the second argument * @return the function result * @throws E if an exception occurs */ long apply(T t, U u) throws E; default ExceptionBiFunction andThen(ExceptionLongFunction after) { Assert.checkNotNullParam("after", after); return (t, u) -> after.apply(apply(t, u)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionToLongFunction.java000066400000000000000000000031441361511066400331610ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A two-argument function which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionToLongFunction { /** * Apply this function to the given arguments. * * @param t the first argument * @return the function result * @throws E if an exception occurs */ long apply(T t) throws E; default ExceptionFunction andThen(ExceptionLongFunction after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionToLongFunction compose(ExceptionFunction before) { Assert.checkNotNullParam("before", before); return t -> apply(before.apply(t)); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionUnaryOperator.java000066400000000000000000000033361361511066400330660ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import org.wildfly.common.Assert; /** * A unary operator which can throw an exception. * * @author David M. Lloyd */ @FunctionalInterface public interface ExceptionUnaryOperator extends ExceptionFunction { default ExceptionUnaryOperator andThen(ExceptionUnaryOperator after) { Assert.checkNotNullParam("after", after); return t -> after.apply(apply(t)); } default ExceptionUnaryOperator compose(ExceptionUnaryOperator before) { Assert.checkNotNullParam("before", before); return t -> apply(before.apply(t)); } static ExceptionUnaryOperator of(ExceptionFunction func) { return func instanceof ExceptionUnaryOperator ? (ExceptionUnaryOperator) func : func::apply; } static ExceptionUnaryOperator identity() { return t -> t; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/Functions.java000066400000000000000000000501431361511066400303430ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.function; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.wildfly.common.Assert; /** * A set of utility methods which return common functions. */ public final class Functions { private Functions() {} /** * Get the singleton consumer which accepts and runs runnable instances. * * @return the runnable consumer */ public static Consumer runnableConsumer() { return RunnableConsumer.INSTANCE; } /** * Get the singleton exception consumer which accepts and runs exception runnable instances. * * @param the exception type * @return the runnable consumer */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionConsumer, E> exceptionRunnableConsumer() { return ExceptionRunnableConsumer.INSTANCE; } /** * Get the singleton exception consumer which accepts and runs runnable instances. * * @return the runnable consumer */ public static ExceptionConsumer runnableExceptionConsumer() { return RunnableExceptionConsumer.INSTANCE; } /** * Get the singleton consumer which accepts a consumer and an argument to hand to it. * * @param the argument type * @return the consumer */ @SuppressWarnings({"unchecked", "rawtypes"}) public static BiConsumer, T> consumerBiConsumer() { return ConsumerBiConsumer.INSTANCE; } /** * Get the singleton consumer which accepts a consumer and an argument to hand to it. * * @param the argument type * @param the exception type * @return the consumer */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionBiConsumer, T, E> exceptionConsumerBiConsumer() { return ExceptionConsumerBiConsumer.INSTANCE; } /** * Get the singleton consumer which accepts a consumer and an argument to hand to it. * * @param the argument type * @return the consumer */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionBiConsumer, T, RuntimeException> consumerExceptionBiConsumer() { return ConsumerExceptionBiConsumer.INSTANCE; } /** * Get the singleton function which accepts a supplier and returns the result of the supplier. * * @param the result type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Function, R> supplierFunction() { return SupplierFunction.INSTANCE; } /** * Get the singleton function which accepts a supplier and returns the result of the supplier. * * @param the result type * @param the exception type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionFunction, R, E> exceptionSupplierFunction() { return ExceptionSupplierFunction.INSTANCE; } /** * Get the singleton function which accepts a supplier and returns the result of the supplier. * * @param the result type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionFunction, R, RuntimeException> supplierExceptionFunction() { return SupplierExceptionFunction.INSTANCE; } /** * Get the singleton function which accepts a function which accepts a supplier, all of which return the result * of the supplier. * * @param the result type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static BiFunction, R>, Supplier, R> supplierFunctionBiFunction() { return FunctionSupplierBiFunction.INSTANCE; } /** * Get the singleton function which accepts a function which accepts a supplier, all of which return the result * of the supplier. * * @param the result type * @param the exception type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionBiFunction, R, E>, ExceptionSupplier, R, E> exceptionSupplierFunctionBiFunction() { return ExceptionFunctionSupplierBiFunction.INSTANCE; } /** * Get the singleton function which accepts a function and a parameter to pass to the function, and returns the * result of the function. * * @param the argument type * @param the result type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static BiFunction, T, R> functionBiFunction() { return FunctionBiFunction.INSTANCE; } /** * Get the singleton function which accepts a function and a parameter to pass to the function, and returns the * result of the function. * * @param the argument type * @param the result type * @param the exception type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionBiFunction, T, R, E> exceptionFunctionBiFunction() { return ExceptionFunctionBiFunction.INSTANCE; } /** * Get the singleton function which accepts a function and a parameter to pass to the function, and returns the * result of the function. * * @param the argument type * @param the result type * @return the function */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionBiFunction, T, R, RuntimeException> functionExceptionBiFunction() { return FunctionExceptionBiFunction.INSTANCE; } /** * Get a supplier which always returns the same value. * * @param value the value to return * @param the value type * @return the value supplier */ @SuppressWarnings("unchecked") public static Supplier constantSupplier(T value) { return value == null ? ConstantSupplier.NULL : new ConstantSupplier<>(value); } /** * Get a supplier which always returns the same value. * * @param value the value to return * @param the value type * @param the exception type * @return the value supplier */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ExceptionSupplier constantExceptionSupplier(T value) { return value == null ? ConstantSupplier.NULL : new ConstantSupplier(value); } /** * Get a runnable which executes the given consumer with captured values. * * @param consumer the consumer to run (must not be {@code null}) * @param param1 the first parameter to pass * @param param2 the second parameter to pass * @param the first parameter type * @param the second parameter type * @return the capturing runnable */ public static Runnable capturingRunnable(BiConsumer consumer, T param1, U param2) { Assert.checkNotNullParam("consumer", consumer); return new BiConsumerRunnable(consumer, param1, param2); } /** * Get a runnable which executes the given consumer with captured values. * * @param consumer the consumer to run (must not be {@code null}) * @param param the parameter to pass * @param the parameter type * @return the capturing runnable */ public static Runnable capturingRunnable(Consumer consumer, T param) { Assert.checkNotNullParam("consumer", consumer); return new ConsumerRunnable(consumer, param); } /** * Get a runnable which executes the given consumer with captured values. * * @param consumer the consumer to run (must not be {@code null}) * @param param1 the first parameter to pass * @param param2 the second parameter to pass * @param the first parameter type * @param the second parameter type * @param the exception type * @return the capturing runnable */ public static ExceptionRunnable exceptionCapturingRunnable(ExceptionBiConsumer consumer, T param1, U param2) { Assert.checkNotNullParam("consumer", consumer); return new ExceptionBiConsumerRunnable(consumer, param1, param2); } /** * Get a runnable which executes the given consumer with captured values. * * @param consumer the consumer to run (must not be {@code null}) * @param param the parameter to pass * @param the parameter type * @param the exception type * @return the capturing runnable */ public static ExceptionRunnable exceptionCapturingRunnable(ExceptionConsumer consumer, T param) { Assert.checkNotNullParam("consumer", consumer); return new ExceptionConsumerRunnable(consumer, param); } /** * Get a consumer which discards the values it is given. * * @param the parameter type * @return the discarding consumer */ @SuppressWarnings("unchecked") public static Consumer discardingConsumer() { return DiscardingConsumer.INSTANCE; } /** * Get a consumer which discards the values it is given. * * @param the parameter type * @param the exception type * @return the discarding consumer */ @SuppressWarnings("unchecked") public static ExceptionConsumer discardingExceptionConsumer() { return DiscardingConsumer.INSTANCE; } /** * Get a consumer which discards the values it is given. * * @param the first parameter type * @param the second parameter type * @return the discarding consumer */ @SuppressWarnings("unchecked") public static BiConsumer discardingBiConsumer() { return DiscardingBiConsumer.INSTANCE; } /** * Get a consumer which discards the values it is given. * * @param the first parameter type * @param the second parameter type * @param the exception type * @return the discarding consumer */ @SuppressWarnings("unchecked") public static ExceptionBiConsumer discardingExceptionBiConsumer() { return DiscardingBiConsumer.INSTANCE; } static class RunnableConsumer implements Consumer { static final Consumer INSTANCE = new RunnableConsumer(); private RunnableConsumer() {} public void accept(final Runnable runnable) { runnable.run(); } } static class ExceptionRunnableConsumer implements ExceptionConsumer, E> { static final ExceptionConsumer INSTANCE = new ExceptionRunnableConsumer<>(); private ExceptionRunnableConsumer() {} public void accept(final ExceptionRunnable ExceptionRunnable) throws E { ExceptionRunnable.run(); } } static class RunnableExceptionConsumer implements ExceptionConsumer { static final RunnableExceptionConsumer INSTANCE = new RunnableExceptionConsumer(); private RunnableExceptionConsumer() {} public void accept(final Runnable runnable) throws RuntimeException { runnable.run(); } } static class ConsumerBiConsumer implements BiConsumer, Object> { static final BiConsumer INSTANCE = new ConsumerBiConsumer(); private ConsumerBiConsumer() {} public void accept(final Consumer consumer, final Object o) { consumer.accept(o); } } static class ExceptionConsumerBiConsumer implements ExceptionBiConsumer, Object, E> { static final ExceptionBiConsumer INSTANCE = new ExceptionConsumerBiConsumer<>(); private ExceptionConsumerBiConsumer() {} public void accept(final ExceptionConsumer consumer, final Object o) throws E { consumer.accept(o); } } static class ConsumerExceptionBiConsumer implements ExceptionBiConsumer, T, RuntimeException> { static final ExceptionBiConsumer INSTANCE = new ConsumerExceptionBiConsumer(); private ConsumerExceptionBiConsumer() {} public void accept(final Consumer consumer, final T t) throws RuntimeException { consumer.accept(t); } } static class SupplierFunction implements Function, Object> { static final Function INSTANCE = new SupplierFunction(); private SupplierFunction() {} public Object apply(final Supplier supplier) { return supplier.get(); } } static class ExceptionSupplierFunction implements ExceptionFunction, Object, E> { static final ExceptionFunction INSTANCE = new ExceptionSupplierFunction<>(); private ExceptionSupplierFunction() {} public Object apply(final ExceptionSupplier supplier) throws E { return supplier.get(); } } static class SupplierExceptionFunction implements ExceptionFunction, R, RuntimeException> { static final SupplierExceptionFunction INSTANCE = new SupplierExceptionFunction(); private SupplierExceptionFunction() {} public R apply(final Supplier supplier) throws RuntimeException { return supplier.get(); } } static class FunctionSupplierBiFunction implements BiFunction, Object>, Supplier, Object> { static final BiFunction INSTANCE = new FunctionSupplierBiFunction(); private FunctionSupplierBiFunction() {} public Object apply(final Function, Object> function, final Supplier supplier) { return function.apply(supplier); } } static class ExceptionFunctionSupplierBiFunction implements ExceptionBiFunction, Object, E>, ExceptionSupplier, Object, E> { static final ExceptionBiFunction INSTANCE = new ExceptionFunctionSupplierBiFunction(); private ExceptionFunctionSupplierBiFunction() {} public Object apply(final ExceptionFunction, Object, E> function, final ExceptionSupplier supplier) throws E { return function.apply(supplier); } } static class FunctionExceptionBiFunction implements ExceptionBiFunction, T, R, RuntimeException> { static final FunctionExceptionBiFunction INSTANCE = new FunctionExceptionBiFunction(); private FunctionExceptionBiFunction() {} public R apply(final Function function, final T t) throws RuntimeException { return function.apply(t); } } static class FunctionBiFunction implements BiFunction, T, R> { static final BiFunction INSTANCE = new FunctionBiFunction(); private FunctionBiFunction() { } public R apply(final Function function, final T t) { return function.apply(t); } } static class ExceptionFunctionBiFunction implements ExceptionBiFunction, T, R, E> { static final ExceptionBiFunction INSTANCE = new ExceptionFunctionBiFunction(); private ExceptionFunctionBiFunction() { } public R apply(final ExceptionFunction function, final T t) throws E { return function.apply(t); } } static class ConstantSupplier implements Supplier, ExceptionSupplier { static final ConstantSupplier NULL = new ConstantSupplier<>(null); private final T arg1; ConstantSupplier(final T arg1) { this.arg1 = arg1; } public T get() { return arg1; } public String toString() { return String.format("supplier(%s)", arg1); } } static class BiConsumerRunnable implements Runnable { private final BiConsumer consumer; private final T param1; private final U param2; BiConsumerRunnable(final BiConsumer consumer, final T param1, final U param2) { this.consumer = consumer; this.param1 = param1; this.param2 = param2; } public void run() { consumer.accept(param1, param2); } public String toString() { return String.format("%s(%s,%s)", consumer, param1, param2); } } static class ConsumerRunnable implements Runnable { private final Consumer consumer; private final T param; ConsumerRunnable(final Consumer consumer, final T param) { this.consumer = consumer; this.param = param; } public void run() { consumer.accept(param); } public String toString() { return String.format("%s(%s)", consumer, param); } } static class ExceptionBiConsumerRunnable implements ExceptionRunnable { private final ExceptionBiConsumer consumer; private final T param1; private final U param2; ExceptionBiConsumerRunnable(final ExceptionBiConsumer consumer, final T param1, final U param2) { this.consumer = consumer; this.param1 = param1; this.param2 = param2; } public void run() throws E { consumer.accept(param1, param2); } public String toString() { return String.format("%s(%s,%s)", consumer, param1, param2); } } static class ExceptionConsumerRunnable implements ExceptionRunnable { private final ExceptionConsumer consumer; private final T param; ExceptionConsumerRunnable(final ExceptionConsumer consumer, final T param) { this.consumer = consumer; this.param = param; } public void run() throws E { consumer.accept(param); } public String toString() { return String.format("%s(%s)", consumer, param); } } static class DiscardingConsumer implements Consumer, ExceptionConsumer { static final DiscardingConsumer INSTANCE = new DiscardingConsumer(); private DiscardingConsumer() { } public void accept(final T t) { } } static class DiscardingBiConsumer implements BiConsumer, ExceptionBiConsumer { static final DiscardingBiConsumer INSTANCE = new DiscardingBiConsumer(); private DiscardingBiConsumer() { } public void accept(final T t, final U u) { } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/package-info.java000066400000000000000000000015201361511066400307120ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes which implement useful functions which are missing from {@code java.util.function}. */ package org.wildfly.common.function; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/000077500000000000000000000000001361511066400256765ustar00rootroot00000000000000Base16DecodingByteIterator.java000066400000000000000000000054761361511066400335120ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import java.util.NoSuchElementException; /** */ final class Base16DecodingByteIterator extends ByteIterator { private final CodePointIterator iter; private int b; private long offset; private boolean havePair; Base16DecodingByteIterator(final CodePointIterator iter) { this.iter = iter; } private int calc(final int b0, final int b1) { int d0 = Character.digit(b0, 16); int d1 = Character.digit(b1, 16); if (d0 == - 1 || d1 == - 1) throw msg.invalidHexCharacter(); return ((d0 << 4) | d1) & 0xff; } public boolean hasNext() { if (havePair) { return true; } if (! iter.hasNext()) { return false; } int b0 = iter.next(); if (! iter.hasNext()) { throw msg.expectedEvenNumberOfHexCharacters(); } int b1 = iter.next(); b = calc(b0, b1); havePair = true; return true; } public boolean hasPrevious() { return offset > 0; } public int next() throws NoSuchElementException { if (! hasNext()) { throw new NoSuchElementException(); } offset++; havePair = false; return b; } public int peekNext() throws NoSuchElementException { if (! hasNext()) { throw new NoSuchElementException(); } return b; } public int previous() throws NoSuchElementException { if (! hasPrevious()) { throw new NoSuchElementException(); } int b1 = iter.previous(); int b0 = iter.previous(); b = calc(b0, b1); offset--; havePair = true; return b; } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) { throw new NoSuchElementException(); } int b1 = iter.previous(); int b0 = iter.peekPrevious(); iter.next(); return calc(b0, b1); } public long getIndex() { return offset; } } Base16EncodingCodePointIterator.java000066400000000000000000000052761361511066400345030ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class Base16EncodingCodePointIterator extends CodePointIterator { private ByteIterator iter; private final boolean toUpperCase; int b; boolean lo; Base16EncodingCodePointIterator(final ByteIterator iter, final boolean toUpperCase) { this.iter = iter; this.toUpperCase = toUpperCase; } public boolean hasNext() { return lo || iter.hasNext(); } public boolean hasPrevious() { return lo || iter.hasPrevious(); } private int hex(final int i) { if (i < 10) { return '0' + i; } else { assert i < 16; return (toUpperCase ? 'A' : 'a') + i - 10; } } public int next() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); if (lo) { lo = false; return hex(b & 0xf); } else { b = iter.next(); lo = true; return hex(b >> 4); } } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); if (lo) { return hex(b & 0xf); } else { return hex(iter.peekNext() >> 4); } } public int previous() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); if (lo) { lo = false; iter.previous(); return hex(b >> 4); } else { b = iter.peekPrevious(); lo = true; return hex(b & 0xf); } } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); if (lo) { return hex(b >> 4); } else { return hex(iter.peekPrevious() & 0xf); } } public long getIndex() { return iter.getIndex() * 2 + (lo ? 1 : 0); } } Base32DecodingByteIterator.java000066400000000000000000000374051361511066400335050ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import java.util.NoSuchElementException; /** */ abstract class Base32DecodingByteIterator extends ByteIterator { private final CodePointIterator iter; private final boolean requirePadding; // states: // 0x00: nothing read // 0x01: five bytes to return o0..o4 // 0x02: four bytes to return o1..o4 (o0 still populated) // 0x03: three byte to return o2..o4 (o0..o1 still populated) // 0x04: two bytes to return o3..o4 (o0..o2 still populated) // 0x05: one byte to return o4 (o0..o3 still populated) // 0x06: four bytes then eof o0..o3 = // 0x07: three bytes then eof o1..o3 = (o0 still populated) // 0x08: two bytes then eof o2..o3 = (o0..o1 still populated) // 0x09: one byte then eof o3 = (o0..o2 still populated) // 0x0a: three bytes then eof o0..o2 === // 0x0b: two bytes then eof o1..o2 === (o0 still populated) // 0x0c: one byte then eof o2 === (o0..o1 still populated) // 0x0d: two bytes then eof o0..o1 ==== // 0x0e: one byte then eof o1 ==== (o0 still populated) // 0x0f: one byte then eof o0 ====== // 0x10: four bytes then eof o0..o3 no pad // 0x11: three bytes then eof o1..o3 no pad (o0 still populated) // 0x12: two bytes then eof o2..o3 no pad (o0..o1 still populated) // 0x13: one byte then eof o3 no pad (o0..o2 still populated) // 0x14: three bytes then eof o0..o2 no pad // 0x15: two bytes then eof o1..o2 no pad (o0 still populated) // 0x16: one byte then eof o2 no pad (o0..o1 still populated) // 0x17: two bytes then eof o0..o1 no pad // 0x18: one byte then eof o1 no pad (o0 still populated) // 0x19: one byte then eof o0 no pad // 0x1a: end (=) (o0..o3 still populated) // 0x1b: end (===) (o0..o2 still populated) // 0x1c: end (====) (o0..o1 still populated) // 0x1d: end (======) (o0 still populated) // 0x1e: end (= but no pad) (o0..o3 still populated) // 0x1f: end (=== but no pad) (o0..o2 still populated) // 0x20: end (==== but no pad) (o0..o1 still populated) // 0x21: end (====== but no pad) (o0 still populated) private int state = 0; private int o0, o1, o2, o3, o4; private int offset; Base32DecodingByteIterator(final CodePointIterator iter, final boolean requirePadding) { this.iter = iter; this.requirePadding = requirePadding; } public boolean hasNext() { if (state == 0) { if (! iter.hasNext()) { return false; } int b0 = iter.next(); if (b0 == '=') { throw msg.unexpectedPadding(); } if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } else { throw msg.incompleteDecode(); } } int b1 = iter.next(); if (b1 == '=') { throw msg.unexpectedPadding(); } o0 = calc0(b0, b1); if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } state = 0x19; return true; } int b2 = iter.next(); if (b2 == '=') { for (int i = 0; i < 5; i++) { if (! iter.hasNext()) { throw msg.expectedPaddingCharacters(6); } if (iter.next() != '=') { throw msg.expectedPaddingCharacters(6); } } state = 0x0f; return true; } if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } else { throw msg.incompleteDecode(); } } int b3 = iter.next(); if (b3 == '=') { throw msg.unexpectedPadding(); } o1 = calc1(b1, b2, b3); if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } state = 0x17; return true; } int b4 = iter.next(); if (b4 == '=') { for (int i = 0; i < 3; i++) { if (! iter.hasNext()) { throw msg.expectedPaddingCharacters(4); } if (iter.next() != '=') { throw msg.expectedPaddingCharacters(4); } } state = 0x0d; return true; } o2 = calc2(b3, b4); if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } state = 0x14; return true; } int b5 = iter.next(); if (b5 == '=') { for (int i = 0; i < 2; i++) { if (! iter.hasNext()) { throw msg.expectedPaddingCharacters(3); } if (iter.next() != '=') { throw msg.expectedPaddingCharacters(3); } } state = 0x0a; return true; } if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } else { throw msg.incompleteDecode(); } } int b6 = iter.next(); if (b6 == '=') { throw msg.unexpectedPadding(); } o3 = calc3(b4, b5, b6); if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } state = 0x10; return true; } int b7 = iter.next(); if (b7 == '=') { state = 0x06; return true; } o4 = calc4(b6, b7); state = 1; return true; } else { return state < 0x1a; } } public boolean hasPrevious() { return offset > 0; } abstract int calc0(int b0, int b1); abstract int calc1(int b1, int b2, int b3); abstract int calc2(int b3, int b4); abstract int calc3(int b4, int b5, int b6); abstract int calc4(int b6, int b7); public int next() { if (! hasNext()) { throw new NoSuchElementException(); } switch (state) { case 1: case 6: case 0x0a: case 0x0d: case 0x10: case 0x14: case 0x17: { state++; offset++; return o0; } case 2: case 7: case 0x0b: case 0x11: case 0x15: { state++; offset++; return o1; } case 3: case 8: case 0x12: { state++; offset++; return o2; } case 4: { state = 5; offset++; return o3; } case 5: { state = 0; offset++; return o4; } case 9: { state = 0x1a; offset++; return o3; } case 0x0c: { state = 0x1b; offset++; return o2; } case 0x0e: { state = 0x1c; offset++; return o1; } case 0x0f: { state = 0x1d; offset++; return o0; } case 0x13: { state = 0x1e; offset++; return o3; } case 0x16: { state = 0x1f; offset++; return o2; } case 0x18: { state = 0x20; offset++; return o1; } case 0x19: { state = 0x21; offset++; return o0; } default: { // padding throw new NoSuchElementException(); } } } public int peekNext() throws NoSuchElementException { if (! hasNext()) { throw new NoSuchElementException(); } switch (state) { case 1: case 6: case 0x0a: case 0x0d: case 0x0f: case 0x10: case 0x14: case 0x17: case 0x19: { return o0; } case 2: case 7: case 0x0b: case 0x0e: case 0x11: case 0x15: case 0x18: { return o1; } case 3: case 8: case 0x0c: case 0x12: case 0x16: { return o2; } case 4: case 9: case 0x13: { return o3; } case 5: { return o4; } default: { // padding throw new NoSuchElementException(); } } } public int previous() { if (! hasPrevious()) { throw new NoSuchElementException(); } int skipChars = 0; switch (state) { case 0: case 1: case 6: case 0x0a: case 0x0d: case 0x0f: case 0x10: case 0x14: case 0x17: case 0x19: { if (state == 6 || state == 0x0a || state == 0x0d || state == 0x0f) { skipChars = 8; } else if (state == 0x10) { skipChars = 7; } else if (state == 0x14) { skipChars = 5; } else if (state == 0x17) { skipChars = 4; } else if (state == 0x19) { skipChars = 2; } for (int i = 0; i < skipChars; i++) { iter.previous(); // consume character } int b7 = iter.previous(); int b6 = iter.previous(); int b5 = iter.previous(); int b4 = iter.previous(); int b3 = iter.previous(); int b2 = iter.previous(); int b1 = iter.previous(); int b0 = iter.previous(); o0 = calc0(b0, b1); o1 = calc1(b1, b2, b3); o2 = calc2(b3, b4); o3 = calc3(b4, b5, b6); o4 = calc4(b6, b7); state = 5; offset--; return o4; } case 2: case 7: case 0x0b: case 0x0e: case 0x11: case 0x15: case 0x18: { state--; offset--; return o0; } case 3: case 8: case 0x0c: case 0x12: case 0x16: { state--; offset--; return o1; } case 4: case 9: case 0x13: { state--; offset--; return o2; } case 5: { state = 4; offset--; return o3; } case 0x1a: { state = 9; offset--; return o3; } case 0x1b: { state = 0x0c; offset--; return o2; } case 0x1c: { state = 0x0e; offset--; return o1; } case 0x1d: { state = 0x0f; offset--; return o0; } case 0x1e: { state = 0x13; offset--; return o3; } case 0x1f: { state = 0x16; offset--; return o2; } case 0x20: { state = 0x18; offset--; return o1; } case 0x21: { state = 0x19; offset--; return o0; } default: { throw new NoSuchElementException(); } } } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) { throw new NoSuchElementException(); } int skipChars = 0; switch (state) { case 0: case 1: case 6: case 0x0a: case 0x0d: case 0x0f: case 0x10: case 0x14: case 0x17: case 0x19: { if (state == 6 || state == 0x0a || state == 0x0d || state == 0x0f) { skipChars = 8; } else if (state == 0x10) { skipChars = 7; } else if (state == 0x14) { skipChars = 5; } else if (state == 0x17) { skipChars = 4; } else if (state == 0x19) { skipChars = 2; } for (int i = 0; i < skipChars; i++) { iter.previous(); // consume character } int b7 = iter.previous(); int b6 = iter.peekPrevious(); iter.next(); for (int i = 0; i < skipChars; i++) { iter.next(); } return calc4(b6, b7); } case 2: case 7: case 0x0b: case 0x0e: case 0x11: case 0x15: case 0x18: case 0x1d: case 0x21: { return o0; } case 3: case 8: case 0x0c: case 0x12: case 0x16: case 0x1c: case 0x20: { return o1; } case 4: case 9: case 0x13: case 0x1b: case 0x1f: { return o2; } case 5: case 0x1a: case 0x1e: { return o3; } default: { throw new NoSuchElementException(); } } } public long getIndex() { return offset; } } Base32EncodingCodePointIterator.java000066400000000000000000000377131361511066400345020ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; import org.wildfly.common.Assert; /** */ abstract class Base32EncodingCodePointIterator extends CodePointIterator { private final ByteIterator iter; private final boolean addPadding; private int c0, c1, c2, c3, c4, c5, c6, c7; private int state; private int offset; Base32EncodingCodePointIterator(final ByteIterator iter, final boolean addPadding) { this.iter = iter; this.addPadding = addPadding; } // states: // 0x00 - need another five data bytes // 0x01 - 8 characters to read // 0x02 - 7 characters to read // 0x03 - 6 characters to read // 0x04 - 5 characters to read // 0x05 - 4 characters to read // 0x06 - 3 characters to read // 0x07 - 2 characters to read // 0x08 - 1 character to read // 0x09 - 2 characters + ====== to read // 0x0a - 1 character (c1) + ====== to read // 0x0b - ====== to read // 0x0c - ===== to read // 0x0d - ==== to read // 0x0e - === to read // 0x0f - == to read // 0x10 - = to read // 0x11 - 4 characters + ==== to read // 0x12 - 3 characters (c1, c2, c3) + ==== to read // 0x13 - 2 characters (c2, c3) + ==== to read // 0x14 - 1 character (c3) + ==== to read // 0x15 - ==== to read // 0x16 - === to read // 0x17 - == to read // 0x18 - = to read // 0x19 - 5 characters + === to read // 0x1a - 4 characters (c1, c2, c3, c4) + === to read // 0x1b - 3 characters (c2, c3, c4) + === to read // 0x1c - 2 characters (c3, c4) + === to read // 0x1d - 1 character (c4) + === to read // 0x1e - === to read // 0x1f - == to read // 0x20 - = to read // 0x21 - 7 characters + = to read // 0x22 - 6 characters (c1, c2, c3, c4, c5, c6) + = to read // 0x23 - 5 characters (c2, c3, c4, c5, c6) + = to read // 0x24 - 4 characters (c3, c4, c5, c6) + = to read // 0x25 - 3 characters (c4, c5, c6) + = to read // 0x26 - 2 characters (c5, c6) + = to read // 0x27 - 1 characters (c6) + = to read // 0x28 - = to read // 0x29 - after ====== // 0x2a - after ==== // 0x2b - after === // 0x2c - after = // 0x2d - end public boolean hasNext() { return state == 0 && iter.hasNext() || state > 0 && state < 0x29; } public boolean hasPrevious() { return offset > 0; } abstract int calc0(int b0); abstract int calc1(int b0, int b1); abstract int calc2(final int b1); abstract int calc3(final int b1, final int b2); abstract int calc4(final int b2, final int b3); abstract int calc5(final int b3); abstract int calc6(final int b3, final int b4); abstract int calc7(final int b4); public int next() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); offset++; switch (state) { case 0: { assert iter.hasNext(); int b0 = iter.next(); c0 = calc0(b0); if (! iter.hasNext()) { c1 = calc1(b0, 0); state = 0x0a; return c0; } int b1 = iter.next(); c1 = calc1(b0, b1); c2 = calc2(b1); if (! iter.hasNext()) { c3 = calc3(b1, 0); state = 0x12; return c0; } int b2 = iter.next(); c3 = calc3(b1, b2); if (! iter.hasNext()) { c4 = calc4(b2, 0); state = 0x1a; return c0; } int b3 = iter.next(); c4 = calc4(b2, b3); c5 = calc5(b3); if (! iter.hasNext()) { c6 = calc6(b3, 0); state = 0x22; return c0; } int b4 = iter.next(); c6 = calc6(b3, b4); c7 = calc7(b4); state = 2; return c0; } case 1: case 9: case 0x11: case 0x19: case 0x21: { state++; return c0; } case 2: case 0x12: case 0x1a: case 0x22: { state++; return c1; } case 3: case 0x13: case 0x1b: case 0x23: { state++; return c2; } case 4: case 0x1c: case 0x24: { state++; return c3; } case 5: case 0x25: { state++; return c4; } case 6: case 0x26: { state++; return c5; } case 7: { state = 8; return c6; } case 8: { state = 0; return c7; } case 0x0a: { state = addPadding ? 0x0b : 0x29; return c1; } case 0x14: { state = addPadding ? 0x15 : 0x2a; return c3; } case 0x1d: { state = addPadding ? 0x1e : 0x2b; return c4; } case 0x27: { state = addPadding ? 0x28 : 0x2c; return c6; } case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x15: case 0x16: case 0x17: case 0x1e: case 0x1f: { state++; return '='; } case 0x10: { state = 0x29; return '='; } case 0x18: { state = 0x2a; return '='; } case 0x20: { state = 0x2b; return '='; } case 0x28: { state = 0x2c; return '='; } default: { throw Assert.impossibleSwitchCase(state); } } } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); switch (state) { case 0: { assert iter.hasNext(); int b0 = iter.next(); c0 = calc0(b0); if (! iter.hasNext()) { c1 = calc1(b0, 0); state = 9; return c0; } int b1 = iter.next(); c1 = calc1(b0, b1); c2 = calc2(b1); if (! iter.hasNext()) { c3 = calc3(b1, 0); state = 0x11; return c0; } int b2 = iter.next(); c3 = calc3(b1, b2); if (! iter.hasNext()) { c4 = calc4(b2, 0); state = 0x19; return c0; } int b3 = iter.next(); c4 = calc4(b2, b3); c5 = calc5(b3); if (! iter.hasNext()) { c6 = calc6(b3, 0); state = 0x21; return c0; } int b4 = iter.next(); c6 = calc6(b3, b4); c7 = calc7(b4); state = 1; return c0; } case 1: case 9: case 0x11: case 0x19: case 0x21: { return c0; } case 2: case 0x0a: case 0x12: case 0x1a: case 0x22: { return c1; } case 3: case 0x13: case 0x1b: case 0x23: { return c2; } case 4: case 0x14: case 0x1c: case 0x24: { return c3; } case 5: case 0x1d: case 0x25: { return c4; } case 6: case 0x26: { return c5; } case 7: case 0x27: { return c6; } case 8: { return c7; } case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x15: case 0x16: case 0x17: case 0x18: case 0x1e: case 0x1f: case 0x20: case 0x28: { return '='; } default: { throw Assert.impossibleSwitchCase(state); } } } public int previous() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); offset--; switch (state) { case 0x21: { iter.previous(); // skip and fall through } case 0x19: { iter.previous(); // skip and fall through } case 0x11: { iter.previous(); // skip and fall through } case 9: { iter.previous(); // skip and fall through } case 0: case 1: case 0x2d: { int b4 = iter.previous(); int b3 = iter.previous(); int b2 = iter.previous(); int b1 = iter.previous(); int b0 = iter.previous(); c0 = calc0(b0); c1 = calc1(b0, b1); c2 = calc2(b1); c3 = calc3(b1, b2); c4 = calc4(b2, b3); c5 = calc5(b3); c6 = calc6(b3, b4); c7 = calc7(b4); state = 8; return c7; } case 2: case 0x0a: case 0x1a: case 0x12: case 0x22: { state--; return c0; } case 3: case 0x0b: case 0x13: case 0x1b: case 0x23: { state--; return c1; } case 4: case 0x14: case 0x1c: case 0x24: { state--; return c2; } case 5: case 0x15: case 0x1d: case 0x25: { state--; return c3; } case 6: case 0x1e: case 0x26: { state--; return c4; } case 7: case 0x27: { state--; return c5; } case 8: case 0x28: { state--; return c6; } case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x16: case 0x17: case 0x18: case 0x1f: case 0x20: { state--; return '='; } case 0x29: { if (addPadding) { state = 0x10; return '='; } else { state = 0x0a; return c1; } } case 0x2a: { if (addPadding) { state = 0x18; return '='; } else { state = 0x14; return c3; } } case 0x2b: { if (addPadding) { state = 0x20; return '='; } else { state = 0x1d; return c4; } } case 0x2c: { if (addPadding) { state = 0x28; return '='; } else { state = 0x27; return c6; } } default: { throw Assert.impossibleSwitchCase(state); } } } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); switch (state) { case 0x21: iter.previous(); // skip and fall through case 0x19: iter.previous(); // skip and fall through case 0x11: iter.previous(); // skip and fall through case 9: iter.previous(); // skip and fall through case 0: case 1: case 0x2d: { int result = calc7(iter.peekPrevious()); if (state == 9) { iter.next(); } else if (state == 0x11) { iter.next(); iter.next(); } else if (state == 0x19) { iter.next(); iter.next(); iter.next(); } else if (state == 0x21) { iter.next(); iter.next(); iter.next(); iter.next(); } return result; } case 2: case 0x0a: case 0x1a: case 0x12: case 0x22: { return c0; } case 3: case 0x0b: case 0x13: case 0x1b: case 0x23: { return c1; } case 4: case 0x14: case 0x1c: case 0x24: { return c2; } case 5: case 0x15: case 0x1d: case 0x25: { return c3; } case 6: case 0x1e: case 0x26: { return c4; } case 7: case 0x27: { return c5; } case 8: case 0x28: { return c6; } case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x16: case 0x17: case 0x18: case 0x1f: case 0x20: { return '='; } case 0x29: { return addPadding ? '=' : c1; } case 0x2a: { return addPadding ? '=' : c3; } case 0x2b: { return addPadding ? '=' : c4; } case 0x2c: { return addPadding ? '=' : c6; } default: { throw Assert.impossibleSwitchCase(state); } } } public long getIndex() { return offset; } } Base64DecodingByteIterator.java000066400000000000000000000217511361511066400335070ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import java.util.NoSuchElementException; /** */ abstract class Base64DecodingByteIterator extends ByteIterator { private final CodePointIterator iter; private final boolean requirePadding; // states: // 0: nothing read // 1: three bytes to return o0..2 // 2: two bytes to return o1..2 (o0 still populated) // 3: one byte to return o2 (o0..o1 still populated) // 4: two bytes then eof o0..1 = // 5: one bytes then eof o1 = (o0 still populated) // 6: one byte then eof o0 == // 7: two bytes then eof o0..1 no pad // 8: one byte then eof o1 no pad (o0 still populated) // 9: one byte then eof o0 no pad // a: end (==) (o0 still populated) // b: end (=) (o0..o1 still populated) // c: end (== but no pad) (o0 still populated) // d: end (= but no pad) (o0..o1 still populated) private int state = 0; private int o0, o1, o2; private int offset; Base64DecodingByteIterator(final CodePointIterator iter, final boolean requirePadding) { this.iter = iter; this.requirePadding = requirePadding; } public boolean hasNext() { if (state == 0) { if (! iter.hasNext()) { return false; } int b0 = iter.next(); if (b0 == '=') { throw msg.unexpectedPadding(); } if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } else { throw msg.incompleteDecode(); } } int b1 = iter.next(); if (b1 == '=') { throw msg.unexpectedPadding(); } o0 = calc0(b0, b1); if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } state = 9; return true; } int b2 = iter.next(); if (b2 == '=') { if (! iter.hasNext()) { throw msg.expectedTwoPaddingCharacters(); } if (iter.next() != '=') { throw msg.expectedTwoPaddingCharacters(); } state = 6; return true; } o1 = calc1(b1, b2); if (! iter.hasNext()) { if (requirePadding) { throw msg.expectedPadding(); } state = 7; return true; } int b3 = iter.next(); if (b3 == '=') { state = 4; return true; } o2 = calc2(b2, b3); state = 1; return true; } else { return state < 0xa; } } public boolean hasPrevious() { return state != 0 || offset > 0; } abstract int calc0(int b0, int b1); abstract int calc1(int b1, int b2); abstract int calc2(int b2, int b3); public int next() { if (! hasNext()) { throw new NoSuchElementException(); } switch (state) { case 1: { state = 2; offset++; return o0; } case 2: { state = 3; offset++; return o1; } case 3: { state = 0; offset++; return o2; } case 4: { state = 5; offset++; return o0; } case 5: { state = 0xb; offset++; return o1; } case 6: { state = 0xa; offset++; return o0; } case 7: { state = 8; offset++; return o0; } case 8: { state = 0xd; offset++; return o1; } case 9: { state = 0xc; offset++; return o0; } default: { // padding throw new NoSuchElementException(); } } } public int peekNext() throws NoSuchElementException { if (! hasNext()) { throw new NoSuchElementException(); } switch (state) { case 1: case 4: case 6: case 7: case 9: { return o0; } case 2: case 5: case 8: { return o1; } case 3: { return o2; } default: { // padding throw new NoSuchElementException(); } } } public int previous() { if (! hasPrevious()) { throw new NoSuchElementException(); } switch (state) { case 6: { iter.previous(); // skip = // fall thru } case 4: { iter.previous(); // skip = // fall thru } case 0: case 1: case 7: case 9: { int b3 = iter.previous(); int b2 = iter.previous(); int b1 = iter.previous(); int b0 = iter.previous(); o0 = calc0(b0, b1); o1 = calc1(b1, b2); state = 3; offset--; return o2 = calc2(b2, b3); } case 2: { state = 1; offset--; return o0; } case 3: { state = 2; offset--; return o1; } case 5: { state = 4; offset--; return o0; } case 8: { state = 7; offset--; return o0; } case 0xa: { state = 6; offset--; return o0; } case 0xb: { state = 5; offset--; return o1; } case 0xc: { state = 9; offset--; return o0; } case 0xd: { state = 8; offset--; return o1; } default: { // padding throw new NoSuchElementException(); } } } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) { throw new NoSuchElementException(); } switch (state) { case 6: { iter.previous(); // skip = // fall thru } case 4: { iter.previous(); // skip = // fall thru } case 0: case 1: case 7: case 9: { int b3 = iter.previous(); int b2 = iter.peekPrevious(); iter.next(); if (state == 4) { iter.next(); } else if (state == 6) { iter.next(); iter.next(); } return calc2(b2, b3); } case 2: { return o0; } case 3: { return o1; } case 5: { return o0; } case 8: { return o0; } case 0xa: { return o0; } case 0xb: { return o1; } case 0xc: { return o0; } case 0xd: { return o1; } default: { // padding throw new NoSuchElementException(); } } } public long getIndex() { return offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/Base64EncodingIterator.java000066400000000000000000000211271361511066400327510ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; import org.wildfly.common.Assert; /** */ abstract class Base64EncodingIterator extends CodePointIterator { private final ByteIterator iter; private final boolean addPadding; private int c0, c1, c2, c3; private int state; private int offset; Base64EncodingIterator(final ByteIterator iter, final boolean addPadding) { this.iter = iter; this.addPadding = addPadding; } // states: // 0 - need another three data bytes // 1 - 4 characters to read // 2 - 3 characters to read // 3 - 2 characters to read // 4 - 1 character to read // 5 - 2 characters + == to read // 6 - 1 character (c1) + == to read // 7 - == to read // 8 - second = to read // 9 - 3 characters + = to read // a - 2 characters (c1, c2) + = to read // b - 1 character (c2) + = to read // c - = to read // d - after == // e - after = // f - clean end public boolean hasNext() { return state == 0 && iter.hasNext() || state > 0 && state < 0xd; } public boolean hasPrevious() { return offset > 0; } abstract int calc0(int b0); abstract int calc1(int b0, int b1); abstract int calc2(int b1, int b2); abstract int calc3(int b2); public int next() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); offset++; switch (state) { case 0: { assert iter.hasNext(); int b0 = iter.next(); c0 = calc0(b0); if (! iter.hasNext()) { c1 = calc1(b0, 0); state = 6; return c0; } int b1 = iter.next(); c1 = calc1(b0, b1); if (! iter.hasNext()) { c2 = calc2(b1, 0); state = 0xa; return c0; } int b2 = iter.next(); c2 = calc2(b1, b2); c3 = calc3(b2); state = 2; return c0; } case 1: { state = 2; return c0; } case 2: { state = 3; return c1; } case 3: { state = 4; return c2; } case 4: { state = 0; return c3; } case 5: { state = 6; return c0; } case 6: { state = addPadding ? 7 : 0xd; return c1; } case 7: { state = 8; return '='; } case 8: { state = 0xd; return '='; } case 9: { state = 0xa; return c0; } case 0xa: { state = 0xb; return c1; } case 0xb: { state = addPadding ? 0xc : 0xe; return c2; } case 0xc: { state = 0xe; return '='; } default: { throw Assert.impossibleSwitchCase(state); } } } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); switch (state) { case 0: { assert iter.hasNext(); int b0 = iter.next(); c0 = calc0(b0); if (! iter.hasNext()) { c1 = calc1(b0, 0); state = 5; return c0; } int b1 = iter.next(); c1 = calc1(b0, b1); if (! iter.hasNext()) { c2 = calc2(b1, 0); state = 9; return c0; } int b2 = iter.next(); c2 = calc2(b1, b2); c3 = calc3(b2); state = 1; return c0; } case 1: { return c0; } case 2: { return c1; } case 3: { return c2; } case 4: { return c3; } case 5: { return c0; } case 6: { return c1; } case 7: { return '='; } case 8: { return '='; } case 9: { return c0; } case 0xa: { return c1; } case 0xb: { return c2; } case 0xc: { return '='; } default: { throw Assert.impossibleSwitchCase(state); } } } public int previous() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); offset--; switch (state) { case 0: case 1: case 5: case 9: case 0xf: { int b2 = iter.previous(); int b1 = iter.previous(); int b0 = iter.previous(); c0 = calc0(b0); c1 = calc1(b0, b1); c2 = calc2(b1, b2); c3 = calc3(b2); state = 4; return c3; } case 2: { state = 1; return c0; } case 3: { state = 2; return c1; } case 4: { state = 3; return c2; } case 6: { state = 5; return c0; } case 7: { state = 6; return c1; } case 8: { state = 7; return '='; } case 0xa: { state = 9; return c0; } case 0xb: { state = 0xa; return c1; } case 0xc: { state = 0xb; return c2; } case 0xd: { state = 8; return '='; } case 0xe: { state = 0xc; return '='; } default: { throw Assert.impossibleSwitchCase(state); } } } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); switch (state) { case 0: case 1: case 5: case 9: case 0xf: { return calc3(iter.peekPrevious()); } case 2: { return c0; } case 3: { return c1; } case 4: { return c2; } case 6: { return c0; } case 7: { return c1; } case 8: { return '='; } case 0xa: { return c0; } case 0xb: { return c1; } case 0xc: { return c2; } case 0xd: { return '='; } case 0xe: { return '='; } default: { throw Assert.impossibleSwitchCase(state); } } } public long getIndex() { return offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/BiDirIntIterator.java000066400000000000000000000032531361511066400317220ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** * A bi-directional primitive iterator. */ public interface BiDirIntIterator extends IntIterator { boolean hasNext(); int next() throws NoSuchElementException; int peekNext() throws NoSuchElementException; /** * Determine if there is a previous element in this sequence. * * @return {@code true} if there is a previous element, {@code false} otherwise */ boolean hasPrevious(); /** * Get the previous element in the sequence. * * @return the previous element * @throws NoSuchElementException if there are no more elements */ int previous() throws NoSuchElementException; /** * Observe the previous element in the sequence without moving the iterator. * * @return the previous element * @throws NoSuchElementException if there are no more elements */ int peekPrevious() throws NoSuchElementException; } BigEndianBase32DecodingByteIterator.java000066400000000000000000000057031361511066400352420ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import org.wildfly.common.codec.Base32Alphabet; /** */ final class BigEndianBase32DecodingByteIterator extends Base32DecodingByteIterator { private final Base32Alphabet alphabet; BigEndianBase32DecodingByteIterator(final CodePointIterator iter, final boolean requirePadding, final Base32Alphabet alphabet) { super(iter, requirePadding); this.alphabet = alphabet; } int calc0(final int b0, final int b1) { final int d0 = alphabet.decode(b0); final int d1 = alphabet.decode(b1); // d0 = r0[7..3] // d1 = r0[2..0] + r1[7..6] if (d0 == - 1 || d1 == - 1) throw msg.invalidBase32Character(); return (d0 << 3 | d1 >> 2) & 0xff; } int calc1(final int b1, final int b2, final int b3) { final int d1 = alphabet.decode(b1); final int d2 = alphabet.decode(b2); final int d3 = alphabet.decode(b3); // d1 = r0[2..0] + r1[7..6] // d2 = r1[5..1] // d3 = r1[0] + r2[7..4] if (d1 == - 1 || d2 == - 1 || d3 == - 1) throw msg.invalidBase32Character(); return (d1 << 6 | d2 << 1 | d3 >> 4) & 0xff; } int calc2(final int b3, final int b4) { final int d3 = alphabet.decode(b3); final int d4 = alphabet.decode(b4); // d3 = r1[0] + r2[7..4] // d4 = r2[3..0] + r3[7] if (d3 == - 1 || d4 == - 1) throw msg.invalidBase32Character(); return (d3 << 4 | d4 >> 1) & 0xff; } int calc3(final int b4, final int b5, final int b6) { final int d4 = alphabet.decode(b4); final int d5 = alphabet.decode(b5); final int d6 = alphabet.decode(b6); // d4 = r2[3..0] + r3[7] // d5 = r3[6..2] // d6 = r3[1..0] + r4[7..5] if (d4 == - 1 || d5 == - 1 || d6 == - 1) throw msg.invalidBase32Character(); return (d4 << 7 | d5 << 2 | d6 >> 3) & 0xff; } int calc4(final int b6, final int b7) { final int d6 = alphabet.decode(b6); final int d7 = alphabet.decode(b7); // d6 = r3[1..0] + r4[7..5] // d7 = r4[4..0] if (d6 == - 1 || d7 == - 1) throw msg.invalidBase32Character(); return (d6 << 5 | d7) & 0xff; } } BigEndianBase32EncodingIterator.java000066400000000000000000000041501361511066400344230ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import org.wildfly.common.codec.Base32Alphabet; /** */ final class BigEndianBase32EncodingIterator extends Base32EncodingCodePointIterator { private final Base32Alphabet alphabet; BigEndianBase32EncodingIterator(final ByteIterator iter, final boolean addPadding, final Base32Alphabet alphabet) { super(iter, addPadding); this.alphabet = alphabet; } int calc0(final int b0) { // d0 = r0[7..3] return alphabet.encode((b0 >> 3) & 0x1f); } int calc1(final int b0, final int b1) { // d1 = r0[2..0] + r1[7..6] return alphabet.encode((b0 << 2 | b1 >> 6) & 0x1f); } int calc2(final int b1) { // d2 = r1[5..1] return alphabet.encode((b1 >> 1) & 0x1f); } int calc3(final int b1, final int b2) { // d3 = r1[0] + r2[7..4] return alphabet.encode((b1 << 4 | b2 >> 4) & 0x1f); } int calc4(final int b2, final int b3) { // d4 = r2[3..0] + r3[7] return alphabet.encode((b2 << 1 | b3 >> 7) & 0x1f); } int calc5(final int b3) { // d5 = r3[6..2] return alphabet.encode((b3 >> 2) & 0x1f); } int calc6(final int b3, final int b4) { // d6 = r3[1..0] + r4[7..5] return alphabet.encode((b3 << 3 | b4 >> 5) & 0x1f); } int calc7(final int b4) { // d7 = r4[4..0] return alphabet.encode(b4 & 0x1f); } } BigEndianBase64DecodingByteIterator.java000066400000000000000000000041571361511066400352510ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import org.wildfly.common.codec.Base64Alphabet; /** */ final class BigEndianBase64DecodingByteIterator extends Base64DecodingByteIterator { private final Base64Alphabet alphabet; BigEndianBase64DecodingByteIterator(final CodePointIterator iter, final boolean requirePadding, final Base64Alphabet alphabet) { super(iter, requirePadding); this.alphabet = alphabet; } int calc0(final int b0, final int b1) { final int d0 = alphabet.decode(b0); final int d1 = alphabet.decode(b1); // d0 = r0[7..2] // d1 = r0[1..0] + r1[7..4] if (d0 == - 1 || d1 == - 1) throw msg.invalidBase64Character(); return (d0 << 2 | d1 >> 4) & 0xff; } int calc1(final int b1, final int b2) { final int d1 = alphabet.decode(b1); final int d2 = alphabet.decode(b2); // d1 = r0[1..0] + r1[7..4] // d2 = r1[3..0] + r2[7..6] if (d1 == - 1 || d2 == - 1) throw msg.invalidBase64Character(); return (d1 << 4 | d2 >> 2) & 0xff; } int calc2(final int b2, final int b3) { final int d2 = alphabet.decode(b2); final int d3 = alphabet.decode(b3); // d2 = r1[3..0] + r2[7..6] // d3 = r2[5..0] if (d2 == - 1 || d3 == - 1) throw msg.invalidBase64Character(); return (d2 << 6 | d3) & 0xff; } } BigEndianBase64EncodingIterator.java000066400000000000000000000031371361511066400344340ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import org.wildfly.common.codec.Base64Alphabet; /** */ final class BigEndianBase64EncodingIterator extends Base64EncodingIterator { private final Base64Alphabet alphabet; BigEndianBase64EncodingIterator(final ByteIterator iter, final boolean addPadding, final Base64Alphabet alphabet) { super(iter, addPadding); this.alphabet = alphabet; } int calc0(final int b0) { // d0 = r0[7..2] return alphabet.encode((b0 >> 2) & 0x3f); } int calc1(final int b0, final int b1) { // d1 = r0[1..0] + r1[7..4] return alphabet.encode((b0 << 4 | b1 >> 4) & 0x3f); } int calc2(final int b1, final int b2) { // d2 = r1[3..0] + r2[7..6] return alphabet.encode((b1 << 2 | b2 >> 6) & 0x3f); } int calc3(final int b2) { // d3 = r2[5..0] return alphabet.encode(b2 & 0x3f); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/ByteArrayIterator.java000066400000000000000000000105401361511066400321550ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.Signature; import java.security.SignatureException; import java.util.Arrays; import java.util.NoSuchElementException; import javax.crypto.Mac; import org.wildfly.common.bytes.ByteStringBuilder; /** */ final class ByteArrayIterator extends ByteIterator { private final int len; private final byte[] bytes; private final int offs; private int idx; ByteArrayIterator(final int len, final byte[] bytes, final int offs) { this.len = len; this.bytes = bytes; this.offs = offs; idx = 0; } public boolean hasNext() { return idx < len; } public boolean hasPrevious() { return idx > 0; } public int next() { if (! hasNext()) throw new NoSuchElementException(); return bytes[offs + idx++] & 0xff; } public int previous() { if (! hasPrevious()) throw new NoSuchElementException(); return bytes[offs + -- idx] & 0xff; } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return bytes[offs + idx] & 0xff; } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return bytes[offs + idx - 1] & 0xff; } public long getIndex() { return idx; } public void update(final MessageDigest digest) throws IllegalStateException { digest.update(bytes, offs + idx, len - idx); idx = len; } public ByteIterator doFinal(final MessageDigest digest) throws IllegalStateException { update(digest); return ByteIterator.ofBytes(digest.digest()); } public void update(final Mac mac) throws IllegalStateException { mac.update(bytes, offs + idx, len - idx); idx = len; } public ByteIterator doFinal(final Mac mac) throws IllegalStateException { update(mac); return ByteIterator.ofBytes(mac.doFinal()); } public void update(final Signature signature) throws SignatureException { signature.update(bytes, offs + idx, len - idx); idx = len; } public boolean verify(final Signature signature) throws SignatureException { try { return signature.verify(bytes, offs + idx, len - idx); } finally { idx = len; } } public ByteArrayOutputStream drainTo(final ByteArrayOutputStream stream) { stream.write(bytes, offs + idx, len - idx); idx = len; return stream; } public byte[] drain() { try { return Arrays.copyOfRange(bytes, offs + idx, offs + len); } finally { idx = len; } } public int drain(final byte[] dst, final int offs, final int dlen) { int cnt = Math.min(len - idx, dlen); System.arraycopy(bytes, offs + idx, dst, offs, cnt); idx += cnt; return cnt; } public String drainToUtf8(final int count) { int cnt = Math.min(len - idx, count); String s = new String(bytes, idx, cnt, StandardCharsets.UTF_8); idx += cnt; return s; } public String drainToLatin1(final int count) { int cnt = Math.min(len - idx, count); String s = new String(bytes, idx, cnt, StandardCharsets.ISO_8859_1); idx += cnt; return s; } public ByteStringBuilder appendTo(final ByteStringBuilder builder) { builder.append(bytes, offs + idx, len - idx); idx = len; return builder; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/ByteBufferIterator.java000066400000000000000000000040401361511066400323060ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.nio.ByteBuffer; import java.util.NoSuchElementException; /** */ final class ByteBufferIterator extends ByteIterator { private final ByteBuffer buffer; private final int initialPosition; ByteBufferIterator(final ByteBuffer buffer) { this.buffer = buffer; initialPosition = buffer.position(); } public boolean hasNext() { return buffer.hasRemaining(); } public boolean hasPrevious() { return buffer.position() > initialPosition; } public int next() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return buffer.get() & 0xff; } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return buffer.get(buffer.position()) & 0xff; } public int previous() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); buffer.position(buffer.position() - 1); return peekNext(); } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return buffer.get(buffer.position() - 1) & 0xff; } public long getIndex() { return buffer.position() - initialPosition; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/ByteIterator.java000066400000000000000000000500541361511066400311620ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.Signature; import java.security.SignatureException; import java.util.Arrays; import java.util.NoSuchElementException; import javax.crypto.Mac; import org.wildfly.common.Assert; import org.wildfly.common.bytes.ByteStringBuilder; import org.wildfly.common.codec.Base32Alphabet; import org.wildfly.common.codec.Base64Alphabet; /** * A byte iterator. */ public abstract class ByteIterator implements BiDirIntIterator, IndexIterator { private static final int OP_BUFFER_SIZE = 8192; private static final ThreadLocal OP_BUFFER = new ThreadLocal() { protected byte[] initialValue() { return new byte[OP_BUFFER_SIZE]; } }; ByteIterator() { } /** * Determine if there are more bytes after the current byte. * * @return {@code true} if there are more bytes, {@code false} otherwise */ public abstract boolean hasNext(); /** * Determine if there are more bytes before the current byte. * * @return {@code true} if there are more bytes, {@code false} otherwise */ public abstract boolean hasPrevious(); /** * Get the next byte. * * @return the next byte * @throws NoSuchElementException if {@link #hasNext()} returns {@code false} */ public abstract int next() throws NoSuchElementException; /** * Peek at the next byte without advancing. * * @return the next byte * @throws NoSuchElementException if {@link #hasNext()} returns {@code false} */ public abstract int peekNext() throws NoSuchElementException; /** * Get the previous byte. * * @return the previous byte * @throws NoSuchElementException if {@link #hasPrevious()} returns {@code false} */ public abstract int previous() throws NoSuchElementException; /** * Peek at the previous byte without moving backwards. * * @return the previous byte * @throws NoSuchElementException if {@link #hasPrevious()} returns {@code false} */ public abstract int peekPrevious() throws NoSuchElementException; /** * Get the current offset, in bytes. * * @return the byte offset */ public abstract long getIndex(); public int getBE16() throws NoSuchElementException { return next() << 8 | next(); } public int getBE32() throws NoSuchElementException { return next() << 24 | next() << 16 | next() << 8 | next(); } public long getBE64() throws NoSuchElementException { return (long)next() << 56 | (long)next() << 48 | (long)next() << 40 | (long)next() << 32 | (long)next() << 24 | (long)next() << 16 | (long)next() << 8 | (long)next(); } public int getLE16() throws NoSuchElementException { return next() | next() << 8; } public int getLE32() throws NoSuchElementException { return next() | next() << 8 | next() << 16 | next() << 24; } public long getLE64() throws NoSuchElementException { return (long) next() | (long) next() << 8 | (long) next() << 16 | (long) next() << 24 | (long) next() << 32 | (long) next() << 40 | (long) next() << 48 | (long) next() << 56; } public int getPackedBE32() throws NoSuchElementException { int v = next(); int t = 0; while ((v & 0x80) != 0) { t = t << 7 | v & 0x7f; v = next(); } t = t << 7 | v; return t; } public long getPackedBE64() throws NoSuchElementException { int v = next(); long t = 0; while ((v & 0x80) != 0) { t = t << 7 | (long)(v & 0x7f); v = next(); } t = t << 7 | v; return t; } public ByteStringBuilder appendTo(final ByteStringBuilder builder) { final byte[] buffer = OP_BUFFER.get(); int cnt = drain(buffer); while (cnt > 0) { builder.append(buffer, 0, cnt); cnt = drain(buffer); } return builder; } public void update(MessageDigest digest) { final byte[] buffer = OP_BUFFER.get(); int cnt = drain(buffer); while (cnt > 0) { digest.update(buffer, 0, cnt); cnt = drain(buffer); } } public ByteIterator doFinal(MessageDigest digest) { update(digest); return ByteIterator.ofBytes(digest.digest()); } public void update(Mac mac) { final byte[] buffer = OP_BUFFER.get(); int cnt = drain(buffer); while (cnt > 0) { mac.update(buffer, 0, cnt); cnt = drain(buffer); } } public ByteIterator doFinal(Mac mac) { return ByteIterator.ofBytes(mac.doFinal(drain())); } public void update(Signature signature) throws SignatureException { final byte[] buffer = OP_BUFFER.get(); int cnt = drain(buffer); while (cnt > 0) { signature.update(buffer, 0, cnt); cnt = drain(buffer); } signature.update(drain()); } public ByteIterator sign(Signature signature) throws SignatureException { update(signature); return ByteIterator.ofBytes(signature.sign()); } public boolean verify(Signature signature) throws SignatureException { final byte[] buffer = OP_BUFFER.get(); int cnt = drain(buffer); while (cnt > 0) { signature.update(buffer, 0, cnt); cnt = drain(buffer); } return signature.verify(NO_BYTES); } /** * Base64-encode the current stream. * * @param alphabet the alphabet to use * @param addPadding {@code true} to add trailing padding, {@code false} to leave it off * @return an iterator over the encoded characters */ public CodePointIterator base64Encode(final Base64Alphabet alphabet, final boolean addPadding) { if (alphabet.isLittleEndian()) { return new LittleEndianBase64EncodingIterator(this, addPadding, alphabet); } else { return new BigEndianBase64EncodingIterator(this, addPadding, alphabet); } } /** * Base64-encode the current stream. * * @param alphabet the alphabet to use * @return an iterator over the encoded characters */ public CodePointIterator base64Encode(final Base64Alphabet alphabet) { return base64Encode(alphabet, true); } /** * Base64-encode the current stream. * * @return an iterator over the encoded characters */ public CodePointIterator base64Encode() { return base64Encode(Base64Alphabet.STANDARD, true); } /** * Base32-encode the current stream. * * @param alphabet the alphabet to use * @param addPadding {@code true} to add trailing padding, {@code false} to leave it off * @return an iterator over the encoded characters */ public CodePointIterator base32Encode(final Base32Alphabet alphabet, final boolean addPadding) { if (alphabet.isLittleEndian()) { return new LittleEndianBase32EncodingIterator(this, addPadding, alphabet); } else { return new BigEndianBase32EncodingIterator(this, addPadding, alphabet); } } /** * Base32-encode the current stream. * * @param alphabet the alphabet to use * @return an iterator over the encoded characters */ public CodePointIterator base32Encode(final Base32Alphabet alphabet) { return base32Encode(alphabet, true); } /** * Base32-encode the current stream. * * @return an iterator over the encoded characters */ public CodePointIterator base32Encode() { return base32Encode(Base32Alphabet.STANDARD, true); } /** * Hex-encode the current stream. * * @param toUpperCase {@code true} to use upper case characters when encoding, * {@code false} to use lower case characters * @return an iterator over the encoded characters */ public CodePointIterator hexEncode(boolean toUpperCase) { return new Base16EncodingCodePointIterator(this, toUpperCase); } /** * Hex-encode the current stream. * * @return an iterator over the encoded characters */ public CodePointIterator hexEncode() { return hexEncode(false); } /** * Get this byte iterator as a UTF-8 string. * * @return the code point iterator */ public CodePointIterator asUtf8String() { if (! hasNext()) { return CodePointIterator.EMPTY; } return new Utf8DecodingIterator(this); } /** * Get this byte iterator as a Latin-1 string. * * @return the code point iterator */ public CodePointIterator asLatin1String() { if (! hasNext()) { return CodePointIterator.EMPTY; } return new Latin1DecodingIterator(this, getIndex()); } /** * Determine if the remaining contents of this iterator are identical to the remaining contents of the other iterator. If the * contents are not equal, the iterators will be positioned at the location of the first difference. If the contents * are equal, the iterators will both be positioned at the end of their contents. * * @param other the other byte iterator * @return {@code true} if the contents are equal, {@code false} otherwise */ public final boolean contentEquals(ByteIterator other) { Assert.checkNotNullParam("other", other); for (;;) { if (hasNext()) { if (! other.hasNext()) { return false; } if (next() != other.next()) { return false; } } else { return ! other.hasNext(); } } } /** * Return a copy of this iterator which is limited to the given number of bytes after the current one. Advancing * the returned iterator will also advance this one. * * @param size the number of bytes * @return the limited byte iterator */ public final ByteIterator limitedTo(final int size) { if (size <= 0 || ! hasNext()) { return EMPTY; } return new LimitedByteIterator(this, size); } /** * Get a sub-iterator that is delimited by the given bytes. The returned iterator offset starts at 0 and cannot * be backed up before that point. The returned iterator will return {@code false} for {@code hasNext()} if the next * character in the encapsulated iterator is a delimiter or if the underlying iterator returns {@code false} for * {@code hasNext()}. * * @param delims the byte delimiters * @return the sub-iterator */ public final ByteIterator delimitedBy(final int... delims) { if ((delims == null) || (delims.length == 0) || ! hasNext()) { return EMPTY; } for (int delim : delims) { if (delim < 0 || delim > 0xff) { return EMPTY; } } return new DelimitedByteIterator(this, delims); } /** * Get a byte iterator which translates this byte iterator through an interleaving table. The table should be * 256 entries in size or exceptions may result. * * @param table the interleaving table * @return the interleaving byte iterator */ public ByteIterator interleavedWith(final byte[] table) { return new ByteTableTranslatingByteIterator(this, table); } /** * Get a byte iterator which translates this byte iterator through an interleaving table. The table should be * 256 entries in size or exceptions may result. * * @param table the interleaving table * @return the interleaving byte iterator */ public ByteIterator interleavedWith(final int[] table) { return new IntTableTranslatingByteIterator(this, table); } /** * Drain all the remaining bytes in this iterator to the given stream. * * @param stream the stream * @return the same stream */ public ByteArrayOutputStream drainTo(ByteArrayOutputStream stream) { while (hasNext()) { stream.write(next()); } return stream; } /** * Drain all the remaining bytes in this iterator. * * @return the remaining bytes as a single array */ public byte[] drain() { return drainTo(new ByteArrayOutputStream()).toByteArray(); } /** * Drain up to {@code count} bytes from this iterator, returning the result. * * @param count the number of bytes to read * @return the array of consumed bytes (may be smaller than {@code count}) */ public byte[] drain(int count) { if (count == 0) return NO_BYTES; final byte[] b = new byte[count]; final int cnt = drain(b); return cnt == 0 ? NO_BYTES : cnt < b.length ? Arrays.copyOf(b, cnt) : b; } /** * Drain exactly {@code count} bytes from this iterator, returning the result. * * @param count the number of bytes to read * @return the array of consumed bytes * @throws NoSuchElementException if there are not enough bytes to fill the array */ public byte[] drainAll(int count) throws NoSuchElementException { if (count == 0) return NO_BYTES; final byte[] b = new byte[count]; final int cnt = drain(b); if (cnt < b.length) { throw new NoSuchElementException(); } return b; } /** * Drains up to {@code dst.length} bytes from this iterator into the given {@code dst} array. * An attempt is made to drain as many as {@code dst.length} bytes, but a smaller number may * be drained. *

* The number of bytes actually drained is returned as an integer. Unlike * {@link InputStream#read(byte[], int, int)}, this method never returns a negative result. * * @param dst the buffer into which the data is drained * @return the total number of bytes drained into {@code dst}, always greater or equal to {@code 0} */ public int drain(byte[] dst) { return drain(dst, 0, dst.length); } /** * Drains up to {@code len} bytes from this iterator into the given {@code dst} array. * An attempt is made to drain as many as {@code len} bytes, but a smaller number may * be drained. *

* The number of bytes actually drained is returned as an integer. Unlike * {@link InputStream#read(byte[], int, int)}, this method never returns a negative result. * * @param dst the buffer into which the data is drained * @param offs the start offset in array {@code dst} at which the data is written. * @param len the maximum number of bytes to drain * @return the total number of bytes drained into {@code dst}, always greater or equal to {@code 0} */ public int drain(byte[] dst, int offs, int len) { for (int i = 0; i < len; i ++) { if (! hasNext()) return i; dst[offs + i] = (byte) next(); } return len; } /** * Convenience method to directly drain a certain number of bytes to a UTF-8 string. If fewer than {@code count} * bytes are available, only the available bytes will be used to construct the string. * * @param count the maximum number of bytes to consume * @return the UTF-8 string */ public String drainToUtf8(int count) { return new String(drain(count), StandardCharsets.UTF_8); } /** * Convenience method to directly drain a certain number of bytes to a Latin-1 string. If fewer than {@code count} * bytes are available, only the available bytes will be used to construct the string. * * @param count the maximum number of bytes to consume * @return the Latin-1 string */ public String drainToLatin1(int count) { return new String(drain(count), StandardCharsets.ISO_8859_1); } /** * Get a byte iterator for a byte array. * * @param bytes the array * @return the byte iterator */ public static ByteIterator ofBytes(final byte... bytes) { Assert.checkNotNullParam("bytes", bytes); return ofBytes(bytes, 0, bytes.length); } /** * Get a byte iterator for a byte array. * * @param bytes the array * @param offs the array offset * @param len the number of bytes to include * @return the byte iterator */ public static ByteIterator ofBytes(final byte[] bytes, final int offs, final int len) { Assert.checkNotNullParam("bytes", bytes); if (len <= 0) { return EMPTY; } return new ByteArrayIterator(len, bytes, offs); } /** * Get a byte iterator for a byte array with interleave. * * @param bytes the array * @param offs the array offset * @param len the number of bytes to include * @param interleave the interleave table to use * @return the byte iterator */ public static ByteIterator ofBytes(final byte[] bytes, final int offs, final int len, final int[] interleave) { Assert.checkNotNullParam("bytes", bytes); Assert.checkNotNullParam("interleave", interleave); if (len <= 0) { return EMPTY; } return new InterleavedByteArrayIterator(len, bytes, offs, interleave); } /** * Get a byte iterator for a byte array with interleave. * * @param bytes the array * @param interleave the interleave table to use * @return the byte iterator */ public static ByteIterator ofBytes(final byte[] bytes, final int[] interleave) { return ofBytes(bytes, 0, bytes.length, interleave); } /** * Get a byte iterator for a byte buffer. The buffer's position is kept up to date with the number of bytes * consumed by the iterator. The iterator cannot be moved before the position that the buffer had when the * iterator was constructed (this position is considered the zero offset). * * @param buffer the byte buffer (must not be {@code null}) * @return the byte iterator (not {@code null}) */ public static ByteIterator ofByteBuffer(ByteBuffer buffer) { Assert.checkNotNullParam("buffer", buffer); return new ByteBufferIterator(buffer); } /** * Get a concatenated byte iterator. The array and the byte iterators in the array must not be modified or * inconsistent behavior will result. * * @param iterators the iterators array (must not be {@code null} or contain {@code null} elements) * @return a concatenated iterator */ public static ByteIterator ofIterators(ByteIterator... iterators) { Assert.checkNotNullParam("iterators", iterators); if (iterators.length == 0) return EMPTY; if (iterators.length == 1) return iterators[0]; return new ConcatByteIterator(iterators); } private static final byte[] NO_BYTES = new byte[0]; /** * The empty byte iterator. */ public static final ByteIterator EMPTY = new ByteArrayIterator(0, NO_BYTES, 0); /** * Get this iterator as an input stream. * * @return the input stream (not {@code null}) */ public final InputStream asInputStream() { return new ByteIteratorInputStream(this); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/ByteIteratorInputStream.java000066400000000000000000000024321361511066400333530ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.io.IOException; import java.io.InputStream; /** */ final class ByteIteratorInputStream extends InputStream { private final ByteIterator iter; ByteIteratorInputStream(final ByteIterator iter) { this.iter = iter; } public int read() throws IOException { return iter.hasNext() ? iter.next() : - 1; } public int read(final byte[] b, final int off, final int len) throws IOException { if (len == 0) return 0; if (! iter.hasNext()) return - 1; return iter.drain(b, off, len); } } ByteTableTranslatingByteIterator.java000066400000000000000000000033131361511066400351020ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class ByteTableTranslatingByteIterator extends ByteIterator { private final ByteIterator iter; private final byte[] table; ByteTableTranslatingByteIterator(final ByteIterator iter, final byte[] table) { this.iter = iter; this.table = table; } public boolean hasNext() { return iter.hasNext(); } public boolean hasPrevious() { return iter.hasPrevious(); } public int next() throws NoSuchElementException { return table[iter.next()] & 0xff; } public int peekNext() throws NoSuchElementException { return table[iter.peekNext()] & 0xff; } public int previous() throws NoSuchElementException { return table[iter.previous()] & 0xff; } public int peekPrevious() throws NoSuchElementException { return table[iter.peekPrevious()] & 0xff; } public long getIndex() { return iter.getIndex(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/CharArrayIterator.java000066400000000000000000000044211361511066400321300ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class CharArrayIterator extends CodePointIterator { private final int len; private final char[] chars; private final int offs; private int idx; private int offset; CharArrayIterator(final int len, final char[] chars, final int offs) { this.len = len; this.chars = chars; this.offs = offs; idx = 0; offset = 0; } public boolean hasNext() { return idx < len; } public boolean hasPrevious() { return idx > 0; } public int next() { if (! hasNext()) throw new NoSuchElementException(); try { offset++; return Character.codePointAt(chars, offs + idx); } finally { idx = Character.offsetByCodePoints(chars, offs, len, offs + idx, 1) - offs; } } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return Character.codePointAt(chars, offs + idx); } public int previous() { if (! hasPrevious()) throw new NoSuchElementException(); idx = Character.offsetByCodePoints(chars, offs, len, offs + idx, - 1) - offs; offset--; return Character.codePointAt(chars, offs + idx); } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return Character.codePointBefore(chars, offs + idx); } public long getIndex() { return offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/CodePointIterator.java000066400000000000000000000431331361511066400321430ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; import java.util.function.IntPredicate; import org.wildfly.common.codec.Base32Alphabet; import org.wildfly.common.codec.Base64Alphabet; /** * A code point by code point iterator. */ public abstract class CodePointIterator implements BiDirIntIterator, IndexIterator { CodePointIterator() { } /** * Determine if there are more code points after the current code point. * * @return {@code true} if there are more code points, {@code false} otherwise */ public abstract boolean hasNext(); /** * Determine if there are more code points before the current code point. * * @return {@code true} if there are more code points, {@code false} otherwise */ public abstract boolean hasPrevious(); /** * Get the next code point. * * @return the next code point * @throws NoSuchElementException if {@link #hasNext()} returns {@code false} */ public abstract int next() throws NoSuchElementException; /** * Peek at the next code point without advancing. * * @return the next code point * @throws NoSuchElementException if {@link #hasNext()} returns {@code false} */ public abstract int peekNext() throws NoSuchElementException; /** * Get the previous code point. * * @return the previous code point * @throws NoSuchElementException if {@link #hasPrevious()} returns {@code false} */ public abstract int previous() throws NoSuchElementException; /** * Peek at the previous code point without moving backwards. * * @return the previous code point * @throws NoSuchElementException if {@link #hasPrevious()} returns {@code false} */ public abstract int peekPrevious() throws NoSuchElementException; /** * Get the current offset, by code point. * * @return the code point offset */ public abstract long getIndex(); /** * Determine if the remaining contents of this iterator are identical to the remaining contents of the other iterator. If the * contents are not equal, the iterators will be positioned at the location of the first difference (i.e. the code point * returned by {@link #next()} will be the differing code point. If the contents are equal, the iterators will both be * positioned at the end of their contents. * * @param other the other byte iterator * @return {@code true} if the contents are equal, {@code false} otherwise */ public final boolean contentEquals(CodePointIterator other) { for (;;) { if (hasNext()) { if (! other.hasNext()) { return false; } if (peekNext() != other.peekNext()) { return false; } next(); other.next(); } else { return ! other.hasNext(); } } } /** * Determine if the remaining contents of this iterator are identical to the given string. If the * contents are not equal, the iterator will be positioned at the location of the first difference (i.e. the code point * returned by {@link #next()} will be the differing code point. If the contents are equal, the iterator will be * positioned at the end of its contents. * * @param other the other string * @return {@code true} if the contents are equal, {@code false} otherwise */ public boolean contentEquals(String other) { return contentEquals(CodePointIterator.ofString(other)); } /** * Return a copy of this iterator which is limited to the given number of code points after the current one. Advancing * the returned iterator will also advance this one. * * @param size the number of code points * @return the limited code point iterator */ public final CodePointIterator limitedTo(final long size) { if (size <= 0 || ! hasNext()) { return EMPTY; } return new LimitedCodePointIterator(this, size); } /** * Get a sub-iterator that is delimited by the given code points. The returned iterator offset starts at 0 and cannot * be backed up before that point. The returned iterator will return {@code false} for {@code hasNext()} if the next * character in the encapsulated iterator is a delimiter or if the underlying iterator returns {@code false} for * {@code hasNext()}. * * @param delims the code point delimiters * @return the sub-iterator */ public final CodePointIterator delimitedBy(final int... delims) { if ((delims == null) || (delims.length == 0) || ! hasNext()) { return EMPTY; } return new DelimitedCodePointIterator(this, delims); } /** * Drain all the remaining code points in this iterator to the given string builder. * * @param b the string builder * @return the same string builder */ public StringBuilder drainTo(StringBuilder b) { while (hasNext()) { b.appendCodePoint(next()); } return b; } /** * Skip all the remaining code points in this iterator. * (Useful in combination with {@link #delimitedBy(int...)}) * * @return the same code point iterator */ public CodePointIterator skipAll() { while (hasNext()) next(); return this; } /** * Drain all the remaining code points in this iterator to the given string builder, * inserting the given prefix and delimiter before and after every {@code n} code points, * respectively. * * @param b the string builder * @param prefix the prefix * @param delim the delimiter * @param n the number of code points between each prefix and delimiter * @return the same string builder */ public StringBuilder drainTo(StringBuilder b, final String prefix, final int delim, final int n) { int i = 0; boolean insertPrefix = (prefix != null); boolean insertDelim = Character.isValidCodePoint(delim); if (hasNext()) { if (insertPrefix) { b.append(prefix); } b.appendCodePoint(next()); i ++; while (hasNext()) { if (i == n) { if (insertDelim) { b.appendCodePoint(delim); } if (insertPrefix) { b.append(prefix); } b.appendCodePoint(next()); i = 1; } else { b.appendCodePoint(next()); i ++; } } } return b; } /** * Drain all the remaining code points in this iterator to the given string builder, * inserting the given delimiter after every {@code n} code points. * * @param b the string builder * @param delim the delimiter * @param n the number of code points between each delimiter * @return the same string builder */ public StringBuilder drainTo(StringBuilder b, final int delim, final int n) { return drainTo(b, null, delim, n); } /** * Drain all the remaining code points in this iterator to the given string builder, * inserting the given prefix before every {@code n} code points. * * @param b the string builder * @param prefix the prefix * @param n the number of code points between each prefix * @return the same string builder */ public StringBuilder drainTo(StringBuilder b, final String prefix, final int n) { return drainTo(b, prefix, -1, n); } /** * Drain all the remaining code points in this iterator to a new string. * * @return the string */ public String drainToString() { return hasNext() ? drainTo(new StringBuilder()).toString() : ""; } /** * Drain all the remaining code points in this iterator to a new string, * inserting the given prefix and delimiter before and after every {@code n} * code points, respectively. * * @param prefix the prefix * @param delim the delimiter * @param n the number of code points between each prefix and delimiter * @return the string */ public String drainToString(final String prefix, final int delim, final int n) { return hasNext() ? drainTo(new StringBuilder(), prefix, delim, n).toString() : ""; } /** * Drain all the remaining code points in this iterator to a new string, * inserting the given delimiter after every {@code n} code points. * * @param delim the delimiter * @param n the number of code points between each delimiter * @return the string */ public String drainToString(final int delim, final int n) { return hasNext() ? drainTo(new StringBuilder(), null, delim, n).toString() : ""; } /** * Drain all the remaining code points in this iterator to a new string, * inserting the given prefix before every {@code n} code points. * * @param prefix the prefix * @param n the number of code points between each prefix * @return the string */ public String drainToString(final String prefix, final int n) { return hasNext() ? drainTo(new StringBuilder(), prefix, -1, n).toString() : ""; } /** * Base64-decode the current stream. * * @param alphabet the alphabet to use * @param requirePadding {@code true} to require padding, {@code false} if padding is optional * @return an iterator over the decoded bytes */ public ByteIterator base64Decode(final Base64Alphabet alphabet, boolean requirePadding) { if (! hasNext()) return ByteIterator.EMPTY; if (alphabet.isLittleEndian()) { return new LittleEndianBase64DecodingByteIterator(this, requirePadding, alphabet); } else { return new BigEndianBase64DecodingByteIterator(this, requirePadding, alphabet); } } /** * Base32-decode the current stream. * * @param alphabet the alphabet to use * @param requirePadding {@code true} to require padding, {@code false} if padding is optional * @return an iterator over the decoded bytes */ public ByteIterator base32Decode(final Base32Alphabet alphabet, boolean requirePadding) { if (! hasNext()) return ByteIterator.EMPTY; if (alphabet.isLittleEndian()) { return new LittleEndianBase32DecodingByteIterator(this, requirePadding, alphabet); } else { return new BigEndianBase32DecodingByteIterator(this, requirePadding, alphabet); } } /** * Hex-decode the current stream. * * @return an iterator over the decoded bytes */ public ByteIterator hexDecode() { if (! hasNext()) return ByteIterator.EMPTY; return new Base16DecodingByteIterator(this); } /** * Base64-decode the current stream. * * @param alphabet the alphabet to use * @return an iterator over the decoded bytes */ public ByteIterator base64Decode(final Base64Alphabet alphabet) { return base64Decode(alphabet, true); } /** * Base64-decode the current stream. * * @return an iterator over the decoded bytes */ public ByteIterator base64Decode() { return base64Decode(Base64Alphabet.STANDARD, true); } /** * Base32-decode the current stream. * * @param alphabet the alphabet to use * @return an iterator over the decoded bytes */ public ByteIterator base32Decode(final Base32Alphabet alphabet) { return base32Decode(alphabet, true); } /** * Base32-decode the current stream. * * @return an iterator over the decoded bytes */ public ByteIterator base32Decode() { return base32Decode(Base32Alphabet.STANDARD, true); } /** * Get a byte iterator over the latin-1 encoding of this code point iterator. * * @return the byte iterator */ public ByteIterator asLatin1() { return new Latin1EncodingByteIterator(this); } /** * Get a byte iterator over the UTF-8 encoding of this code point iterator. * * @return the byte iterator */ public ByteIterator asUtf8() { return asUtf8(false); } /** * Get a byte iterator over the UTF-8 encoding of this code point iterator. * * @param escapeNul {@code true} to escape NUL (0) characters as two bytes, {@code false} to encode them as one byte * @return the byte iterator */ public ByteIterator asUtf8(final boolean escapeNul) { return new Utf8EncodingByteIterator(this, escapeNul); } /** * Get a code point iterator for a string. * * @param string the string * @return the code point iterator */ public static CodePointIterator ofString(final String string) { return ofString(string, 0, string.length()); } /** * Get a code point iterator for a string. * * @param string the string * @return the code point iterator */ public static CodePointIterator ofString(final String string, final int offs, final int len) { if (len == 0) { return EMPTY; } return new StringIterator(len, string, offs); } /** * Get a code point iterator for a character array. * * @param chars the array * @return the code point iterator */ public static CodePointIterator ofChars(final char[] chars) { return ofChars(chars, 0, chars.length); } /** * Get a code point iterator for a character array. * * @param chars the array * @param offs the array offset * @return the code point iterator */ public static CodePointIterator ofChars(final char[] chars, final int offs) { return ofChars(chars, offs, chars.length - offs); } /** * Get a code point iterator for a character array. * * @param chars the array * @param offs the array offset * @param len the number of characters to include * @return the code point iterator */ public static CodePointIterator ofChars(final char[] chars, final int offs, final int len) { if (len <= 0) { return EMPTY; } return new CharArrayIterator(len, chars, offs); } /** * Get a code point iterator for a UTF-8 encoded byte array. * * @param bytes the array * @return the code point iterator */ public static CodePointIterator ofUtf8Bytes(final byte[] bytes) { return ofUtf8Bytes(bytes, 0, bytes.length); } /** * Get a code point iterator for a UTF-8 encoded array. * * @param bytes the array * @param offs the array offset * @param len the number of characters to include * @return the code point iterator */ public static CodePointIterator ofUtf8Bytes(final byte[] bytes, final int offs, final int len) { if (len <= 0) { return EMPTY; } return ByteIterator.ofBytes(bytes, offs, len).asUtf8String(); } /** * Get a code point iterator for a ISO-8859-1 (Latin-1) encoded array. * * @param bytes the array * @return the code point iterator */ public static CodePointIterator ofLatin1Bytes(final byte[] bytes) { return ofLatin1Bytes(bytes, 0, bytes.length); } /** * Get a code point iterator for a ISO-8859-1 (Latin-1) encoded array. * * @param bytes the array * @param offs the array offset * @param len the number of characters to include * @return the code point iterator */ public static CodePointIterator ofLatin1Bytes(final byte[] bytes, final int offs, final int len) { if (len <= 0) { return EMPTY; } return ByteIterator.ofBytes(bytes, offs, len).asLatin1String(); } /** * Get a sub-iterator that removes the following code points: 10(\n) and 13(\r). * * @return the code point iterator */ public CodePointIterator skipCrLf() { return skip(value -> value == '\n' || value == '\r'); } /** * Get a sub-iterator that removes code points based on a predicate. * * @param predicate a {@link IntPredicate} that evaluates the code points that should be skipper. Returning true from the predicate * indicates that the code point must be skipped. * @return the code point iterator */ public CodePointIterator skip(IntPredicate predicate) { if (!hasNext()) { return EMPTY; } return new SkippingCodePointIterator(this, predicate); } private static final char[] NO_CHARS = new char[0]; /** * The empty code point iterator. */ public static final CodePointIterator EMPTY = new CharArrayIterator(0, NO_CHARS, 0); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/ConcatByteIterator.java000066400000000000000000000050241361511066400323070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class ConcatByteIterator extends ByteIterator { private final ByteIterator[] iterators; private long index = 0; ConcatByteIterator(final ByteIterator[] iterators) { this.iterators = iterators; } private int seekNext() { for (int i = 0; i < iterators.length; i ++) { if (iterators[i].hasNext()) { return i; } } return -1; } private int seekPrevious() { for (int i = iterators.length - 1; i >= 0; i --) { if (iterators[i].hasPrevious()) { return i; } } return -1; } public boolean hasNext() { return seekNext() != -1; } public boolean hasPrevious() { return seekPrevious() != -1; } public int next() throws NoSuchElementException { final int seek = seekNext(); if (seek == -1) throw new NoSuchElementException(); final int next = iterators[seek].next(); index++; return next; } public int peekNext() throws NoSuchElementException { final int seek = seekNext(); if (seek == -1) throw new NoSuchElementException(); return iterators[seek].peekNext(); } public int previous() throws NoSuchElementException { final int seek = seekPrevious(); if (seek == -1) throw new NoSuchElementException(); final int previous = iterators[seek].previous(); index--; return previous; } public int peekPrevious() throws NoSuchElementException { final int seek = seekPrevious(); if (seek == -1) throw new NoSuchElementException(); return iterators[seek].peekPrevious(); } public long getIndex() { return index; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/DelimitedByteIterator.java000066400000000000000000000041161361511066400330010ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class DelimitedByteIterator extends ByteIterator { private final ByteIterator iter; private final int[] delims; long offset; DelimitedByteIterator(final ByteIterator iter, final int... delims) { this.iter = iter; this.delims = delims; offset = 0; } public boolean hasNext() { return iter.hasNext() && ! isDelim(iter.peekNext()); } public boolean hasPrevious() { return offset > 0; } public int next() { if (! hasNext()) throw new NoSuchElementException(); offset++; return iter.next(); } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return iter.peekNext(); } public int previous() { if (! hasPrevious()) throw new NoSuchElementException(); offset--; return iter.previous(); } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return iter.peekPrevious(); } public long getIndex() { return offset; } private boolean isDelim(int b) { for (int delim : delims) { if (delim == b) { return true; } } return false; } } DelimitedCodePointIterator.java000066400000000000000000000041471361511066400337070ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class DelimitedCodePointIterator extends CodePointIterator { private final CodePointIterator iter; private final int[] delims; long offset; DelimitedCodePointIterator(final CodePointIterator iter, final int... delims) { this.iter = iter; this.delims = delims; offset = 0; } public boolean hasNext() { return iter.hasNext() && ! isDelim(iter.peekNext()); } public boolean hasPrevious() { return offset > 0; } public int next() { if (! hasNext()) throw new NoSuchElementException(); offset++; return iter.next(); } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return iter.peekNext(); } public int previous() { if (! hasPrevious()) throw new NoSuchElementException(); offset--; return iter.previous(); } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return iter.peekPrevious(); } public long getIndex() { return offset; } private boolean isDelim(int b) { for (int delim : delims) { if (delim == b) { return true; } } return false; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/EnumerationIterator.java000066400000000000000000000040411361511066400325400ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; /** * An enumeration which is also an iterator. * * @author David M. Lloyd */ public interface EnumerationIterator extends Enumeration, Iterator { /** * Determine if there are more elements to iterate over in the direction of this iterator. * * @return {@code true} if there are more elements, {@code false} otherwise */ default boolean hasMoreElements() { return hasNext(); } /** * Get the next element in the direction of this iterator. * * @return the next element */ default E nextElement() { return next(); } /** * Get an enumeration iterator over one element. * * @param item the element * @param the element type * @return the enumeration iterator */ static EnumerationIterator over(E item) { return new EnumerationIterator() { boolean done; public boolean hasNext() { return ! done; } public E next() { if (! hasNext()) throw new NoSuchElementException(); done = true; return item; } }; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/IndexIterator.java000066400000000000000000000016761361511066400313340ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; /** * An iterator which can report the current iterator index. */ public interface IndexIterator { /** * Get the current iterator index. * * @return the index */ long getIndex(); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/IntIterator.java000066400000000000000000000030721361511066400310070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** * A primitive iterator, which can be used as the basis for string parsing, tokenizing, and other purposes. */ public interface IntIterator { /** * Determine if there is another element in this sequence. * * @return {@code true} if there is another element, {@code false} otherwise */ boolean hasNext(); /** * Get the next element in the sequence. * * @return the next element * @throws NoSuchElementException if there are no more elements */ int next() throws NoSuchElementException; /** * Observe the next element in the sequence without moving the iterator. * * @return the next element * @throws NoSuchElementException if there are no more elements */ int peekNext() throws NoSuchElementException; } IntTableTranslatingByteIterator.java000066400000000000000000000033071361511066400347340ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class IntTableTranslatingByteIterator extends ByteIterator { private final ByteIterator iter; private final int[] table; IntTableTranslatingByteIterator(final ByteIterator iter, final int[] table) { this.iter = iter; this.table = table; } public boolean hasNext() { return iter.hasNext(); } public boolean hasPrevious() { return iter.hasPrevious(); } public int next() throws NoSuchElementException { return table[iter.next()] & 0xff; } public int peekNext() throws NoSuchElementException { return table[iter.peekNext()] & 0xff; } public int previous() throws NoSuchElementException { return table[iter.previous()] & 0xff; } public int peekPrevious() throws NoSuchElementException { return table[iter.peekPrevious()] & 0xff; } public long getIndex() { return iter.getIndex(); } } InterleavedByteArrayIterator.java000066400000000000000000000041041361511066400342600ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class InterleavedByteArrayIterator extends ByteIterator { private final int len; private final byte[] bytes; private final int offs; private final int[] interleave; private int idx; InterleavedByteArrayIterator(final int len, final byte[] bytes, final int offs, final int[] interleave) { this.len = len; this.bytes = bytes; this.offs = offs; this.interleave = interleave; idx = 0; } public boolean hasNext() { return idx < len; } public boolean hasPrevious() { return idx > 0; } public int next() { if (! hasNext()) throw new NoSuchElementException(); return bytes[offs + interleave[idx++]] & 0xff; } public int previous() { if (! hasPrevious()) throw new NoSuchElementException(); return bytes[offs + interleave[-- idx]] & 0xff; } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return bytes[offs + interleave[idx]] & 0xff; } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return bytes[offs + interleave[idx - 1]] & 0xff; } public long getIndex() { return idx; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/Latin1DecodingIterator.java000066400000000000000000000032251361511066400330420ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class Latin1DecodingIterator extends CodePointIterator { private final ByteIterator iter; private final long start; Latin1DecodingIterator(final ByteIterator iter, final long start) { this.iter = iter; this.start = start; } public boolean hasNext() { return iter.hasNext(); } public boolean hasPrevious() { return start > 0 && iter.hasPrevious(); } public int next() { return iter.next(); } public int peekNext() throws NoSuchElementException { return iter.peekNext(); } public int previous() { if (start == 0) throw new NoSuchElementException(); return iter.previous(); } public int peekPrevious() throws NoSuchElementException { return iter.peekPrevious(); } public long getIndex() { return iter.getIndex() - start; } } Latin1EncodingByteIterator.java000066400000000000000000000033451361511066400336240ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class Latin1EncodingByteIterator extends ByteIterator { private final CodePointIterator iter; Latin1EncodingByteIterator(final CodePointIterator iter) { this.iter = iter; } public boolean hasNext() { return iter.hasNext(); } public boolean hasPrevious() { return iter.hasPrevious(); } public int next() throws NoSuchElementException { final int v = iter.next(); return v > 255 ? '?' : v; } public int peekNext() throws NoSuchElementException { final int v = iter.peekNext(); return v > 255 ? '?' : v; } public int previous() throws NoSuchElementException { final int v = iter.previous(); return v > 255 ? '?' : v; } public int peekPrevious() throws NoSuchElementException { final int v = iter.peekPrevious(); return v > 255 ? '?' : v; } public long getIndex() { return iter.getIndex(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/LimitedByteIterator.java000066400000000000000000000041621361511066400324710ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class LimitedByteIterator extends ByteIterator { private final ByteIterator iter; private final long size; long offset; LimitedByteIterator(final ByteIterator iter, final long size) { this.iter = iter; this.size = size; offset = 0; } public boolean hasNext() { return offset < size && iter.hasNext(); } public boolean hasPrevious() { return offset > 0; } public int next() { if (offset == size) { throw new NoSuchElementException(); } offset++; return iter.next(); } public int peekNext() throws NoSuchElementException { if (offset == size) { throw new NoSuchElementException(); } return iter.peekNext(); } public int previous() { if (offset == 0) { throw new NoSuchElementException(); } offset--; return iter.previous(); } public int peekPrevious() throws NoSuchElementException { if (offset == 0) { throw new NoSuchElementException(); } return iter.peekPrevious(); } public int drain(final byte[] dst, final int offs, final int len) { return super.drain(dst, offs, (int) Math.min(len, size - offset)); } public long getIndex() { return offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/LimitedCodePointIterator.java000066400000000000000000000037731361511066400334610ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class LimitedCodePointIterator extends CodePointIterator { private final CodePointIterator iter; private final long size; private long offset; LimitedCodePointIterator(final CodePointIterator iter, final long size) { this.iter = iter; this.size = size; offset = 0; } public boolean hasNext() { return offset < size && iter.hasNext(); } public boolean hasPrevious() { return offset > 0; } public int next() { if (! hasNext()) { throw new NoSuchElementException(); } offset++; return iter.next(); } public int peekNext() throws NoSuchElementException { if (! hasNext()) { throw new NoSuchElementException(); } return iter.peekNext(); } public int previous() { if (! hasPrevious()) { throw new NoSuchElementException(); } offset--; return iter.previous(); } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) { throw new NoSuchElementException(); } return iter.peekPrevious(); } public long getIndex() { return offset; } } LittleEndianBase32DecodingByteIterator.java000066400000000000000000000057111361511066400357750ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import org.wildfly.common.codec.Base32Alphabet; /** */ final class LittleEndianBase32DecodingByteIterator extends Base32DecodingByteIterator { private final Base32Alphabet alphabet; LittleEndianBase32DecodingByteIterator(final CodePointIterator iter, final boolean requirePadding, final Base32Alphabet alphabet) { super(iter, requirePadding); this.alphabet = alphabet; } int calc0(final int b0, final int b1) { final int d0 = alphabet.decode(b0); final int d1 = alphabet.decode(b1); // d0 = r0[4..0] // d1 = r1[1..0] + r0[7..5] if (d0 == - 1 || d1 == - 1) throw msg.invalidBase32Character(); return (d0 | d1 << 5) & 0xff; } int calc1(final int b1, final int b2, final int b3) { final int d1 = alphabet.decode(b1); final int d2 = alphabet.decode(b2); final int d3 = alphabet.decode(b3); // d1 = r1[1..0] + r0[7..5] // d2 = r1[6..2] // d3 = r2[3..0] + r1[7] if (d1 == - 1 || d2 == - 1 || d3 == - 1) throw msg.invalidBase32Character(); return (d1 >> 3 | d2 << 2 | d3 << 7) & 0xff; } int calc2(final int b3, final int b4) { final int d3 = alphabet.decode(b3); final int d4 = alphabet.decode(b4); // d3 = r2[3..0] + r1[7] // d4 = r3[0] + r2[7..4] if (d3 == - 1 || d4 == - 1) throw msg.invalidBase32Character(); return (d3 >> 1 | d4 << 4) & 0xff; } int calc3(final int b4, final int b5, final int b6) { final int d4 = alphabet.decode(b4); final int d5 = alphabet.decode(b5); final int d6 = alphabet.decode(b6); // d4 = r3[0] + r2[7..4] // d5 = r3[5..1] // d6 = r4[2..0] + r3[7..6] if (d4 == - 1 || d5 == - 1 || d6 == - 1) throw msg.invalidBase32Character(); return (d4 >> 4 | d5 << 1 | d6 << 6) & 0xff; } int calc4(final int b6, final int b7) { final int d6 = alphabet.decode(b6); final int d7 = alphabet.decode(b7); // d6 = r4[2..0] + r3[7..6] // d7 = r4[7..3] if (d6 == - 1 || d7 == - 1) throw msg.invalidBase32Character(); return (d6 >> 2 | d7 << 3) & 0xff; } } LittleEndianBase32EncodingIterator.java000066400000000000000000000041561361511066400351650ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import org.wildfly.common.codec.Base32Alphabet; /** */ final class LittleEndianBase32EncodingIterator extends Base32EncodingCodePointIterator { private final Base32Alphabet alphabet; LittleEndianBase32EncodingIterator(final ByteIterator iter, final boolean addPadding, final Base32Alphabet alphabet) { super(iter, addPadding); this.alphabet = alphabet; } int calc0(final int b0) { // d0 = r0[4..0] return alphabet.encode(b0 & 0x1f); } int calc1(final int b0, final int b1) { // d1 = r1[1..0] + r0[7..5] return alphabet.encode((b1 << 3 | b0 >> 5) & 0x1f); } int calc2(final int b1) { // d2 = r1[6..2] return alphabet.encode((b1 >> 2) & 0x1f); } int calc3(final int b1, final int b2) { // d3 = r2[3..0] + r1[7] return alphabet.encode((b2 << 1 | b1 >> 7) & 0x1f); } int calc4(final int b2, final int b3) { // d4 = r3[0] + r2[7..4] return alphabet.encode((b3 << 4 | b2 >> 4) & 0x1f); } int calc5(final int b3) { // d5 = r3[5..1] return alphabet.encode((b3 >> 1) & 0x1f); } int calc6(final int b3, final int b4) { // d6 = r4[2..0] + r3[7..6] return alphabet.encode((b4 << 2 | b3 >> 6) & 0x1f); } int calc7(final int b4) { // d7 = r4[7..3] return alphabet.encode((b4 >> 3) & 0x1f); } } LittleEndianBase64DecodingByteIterator.java000066400000000000000000000041651361511066400360040ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import static org.wildfly.common._private.CommonMessages.msg; import org.wildfly.common.codec.Base64Alphabet; /** */ final class LittleEndianBase64DecodingByteIterator extends Base64DecodingByteIterator { private final Base64Alphabet alphabet; LittleEndianBase64DecodingByteIterator(final CodePointIterator iter, final boolean requirePadding, final Base64Alphabet alphabet) { super(iter, requirePadding); this.alphabet = alphabet; } int calc0(final int b0, final int b1) { final int d0 = alphabet.decode(b0); final int d1 = alphabet.decode(b1); // d0 = r0[5..0] // d1 = r1[3..0] + r0[7..6] if (d0 == - 1 || d1 == - 1) throw msg.invalidBase64Character(); return (d0 | d1 << 6) & 0xff; } int calc1(final int b1, final int b2) { final int d1 = alphabet.decode(b1); final int d2 = alphabet.decode(b2); // d1 = r1[3..0] + r0[7..6] // d2 = r2[1..0] + r1[7..4] if (d1 == - 1 || d2 == - 1) throw msg.invalidBase64Character(); return (d1 >> 2 | d2 << 4) & 0xff; } int calc2(final int b2, final int b3) { final int d2 = alphabet.decode(b2); final int d3 = alphabet.decode(b3); // d2 = r2[1..0] + r1[7..4] // d3 = r2[7..2] if (d2 == - 1 || d3 == - 1) throw msg.invalidBase64Character(); return (d2 >> 4 | d3 << 2) & 0xff; } } LittleEndianBase64EncodingIterator.java000066400000000000000000000031451361511066400351670ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import org.wildfly.common.codec.Base64Alphabet; /** */ final class LittleEndianBase64EncodingIterator extends Base64EncodingIterator { private final Base64Alphabet alphabet; LittleEndianBase64EncodingIterator(final ByteIterator iter, final boolean addPadding, final Base64Alphabet alphabet) { super(iter, addPadding); this.alphabet = alphabet; } int calc0(final int b0) { // d0 = r0[5..0] return alphabet.encode(b0 & 0x3f); } int calc1(final int b0, final int b1) { // d1 = r1[3..0] + r0[7..6] return alphabet.encode((b1 << 2 | b0 >> 6) & 0x3f); } int calc2(final int b1, final int b2) { // d2 = r2[1..0] + r1[7..4] return alphabet.encode((b2 << 4 | b1 >> 4) & 0x3f); } int calc3(final int b2) { // d3 = r2[7..2] return alphabet.encode((b2 >> 2) & 0x3f); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/SkippingCodePointIterator.java000066400000000000000000000056211361511066400336500ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; import java.util.function.IntPredicate; /** */ final class SkippingCodePointIterator extends CodePointIterator { private final CodePointIterator iter; private final IntPredicate predicate; SkippingCodePointIterator(final CodePointIterator iter, final IntPredicate predicate) { this.iter = iter; this.predicate = predicate; } public boolean hasNext() { return iter.hasNext() && ! skip(peekNext()); } public boolean hasPrevious() { return iter.hasPrevious() && ! skip(peekPrevious()); } public int next() { if (! hasNext()) { throw new NoSuchElementException(); } return iter.next(); } public int peekNext() throws NoSuchElementException { if (! iter.hasNext()) { throw new NoSuchElementException(); } int next = seekNext(iter.peekNext()); if (! skip(next)) { return next; } return next; } private int seekNext(int next) throws NoSuchElementException { if (! iter.hasNext()) { return next; } next = iter.next(); if (skip(next)) { return seekNext(next); } iter.previous(); return next; } public int previous() { if (! hasPrevious()) { throw new NoSuchElementException(); } return iter.previous(); } public int peekPrevious() throws NoSuchElementException { if (! iter.hasPrevious()) { throw new NoSuchElementException(); } int prev = seekPrev(iter.peekPrevious()); if (! skip(prev)) { return prev; } return prev; } private int seekPrev(int prev) throws NoSuchElementException { if (! iter.hasPrevious()) { return prev; } prev = iter.previous(); if (skip(prev)) { return seekPrev(prev); } iter.next(); return prev; } public long getIndex() { return iter.getIndex(); } private boolean skip(int c) { return predicate.test(c); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/StringIterator.java000066400000000000000000000052671361511066400315330ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ final class StringIterator extends CodePointIterator { private final int len; private final String string; private final int offs; private int idx; private long offset; StringIterator(final int len, final String string, final int offs) { this.len = len; this.string = string; this.offs = offs; idx = 0; offset = 0; } public boolean hasNext() { return idx < len; } public boolean hasPrevious() { return offset > 0; } public int next() { if (! hasNext()) throw new NoSuchElementException(); try { offset++; return string.codePointAt(idx + offs); } finally { idx = string.offsetByCodePoints(idx + offs, 1) - offs; } } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); return string.codePointAt(idx + offs); } public int previous() { if (! hasPrevious()) throw new NoSuchElementException(); idx = string.offsetByCodePoints(idx + offs, - 1) - offs; offset--; return string.codePointAt(idx + offs); } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); return string.codePointBefore(idx + offs); } public long getIndex() { return offset; } public StringBuilder drainTo(final StringBuilder b) { try { return b.append(string, idx + offs, offs + len); } finally { offset += string.codePointCount(idx + offs, offs + len); idx = len; } } public String drainToString() { try { return string.substring(idx + offs, offs + len); } finally { offset += string.codePointCount(idx + offs, offs + len); idx = len; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/Utf8DecodingIterator.java000066400000000000000000000230071361511066400325400ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; /** */ class Utf8DecodingIterator extends CodePointIterator { private final ByteIterator iter; private long offset = 0; Utf8DecodingIterator(final ByteIterator iter) { this.iter = iter; } public boolean hasNext() { return iter.hasNext(); } public boolean hasPrevious() { return offset > 0; } private void seekToNext() { int b; while (iter.hasNext()) { b = iter.next(); if ((b & 0b11_000000) != 0b10_000000) { // back up one spot iter.previous(); return; } } } private void seekToPrev() { int b; while (iter.hasPrevious()) { b = iter.previous(); if ((b & 0b11_000000) != 0b10_000000) { return; } } } public int next() { if (! iter.hasNext()) throw new NoSuchElementException(); offset++; // >= 1 byte int a = iter.next(); if ((a & 0b1_0000000) == 0b0_0000000) { // one byte return a; } if ((a & 0b11_000000) == 0b10_000000) { // first byte is invalid; return � instead seekToNext(); return '�'; } // >= 2 bytes if (! iter.hasNext()) { // truncated return '�'; } int b = iter.next(); if ((b & 0b11_000000) != 0b10_000000) { // second byte is invalid; return � instead seekToNext(); return '�'; } if ((a & 0b111_00000) == 0b110_00000) { // two bytes return (a & 0b000_11111) << 6 | b & 0b00_111111; } // >= 3 bytes if (! iter.hasNext()) { // truncated return '�'; } int c = iter.next(); if ((c & 0b11_000000) != 0b10_000000) { // third byte is invalid; return � instead seekToNext(); return '�'; } if ((a & 0b1111_0000) == 0b1110_0000) { // three bytes return (a & 0b0000_1111) << 12 | (b & 0b00_111111) << 6 | c & 0b00_111111; } // >= 4 bytes if (! iter.hasNext()) { // truncated return '�'; } int d = iter.next(); if ((d & 0b11_000000) != 0b10_000000) { // fourth byte is invalid; return � instead seekToNext(); return '�'; } if ((a & 0b11111_000) == 0b11110_000) { // four bytes return (a & 0b00000_111) << 18 | (b & 0b00_111111) << 12 | (c & 0b00_111111) << 6 | d & 0b00_111111; } // only invalid possibilities are left; return � instead seekToNext(); return '�'; } public int peekNext() throws NoSuchElementException { if (! iter.hasNext()) throw new NoSuchElementException(); int a = iter.peekNext(); if ((a & 0b1_0000000) == 0b0_0000000) { // one byte return a; } if ((a & 0b11_000000) == 0b10_000000) { // first byte is invalid; return � instead return '�'; } // >= 2 bytes iter.next(); if (! iter.hasNext()) { iter.previous(); // truncated return '�'; } int b = iter.peekNext(); if ((b & 0b11_000000) != 0b10_000000) { // second byte is invalid; return � instead iter.previous(); return '�'; } if ((a & 0b111_00000) == 0b110_00000) { // two bytes iter.previous(); return (a & 0b000_11111) << 6 | b & 0b00_111111; } // >= 3 bytes iter.next(); if (! iter.hasNext()) { // truncated iter.previous(); iter.previous(); return '�'; } int c = iter.peekNext(); if ((c & 0b11_000000) != 0b10_000000) { // third byte is invalid; return � instead iter.previous(); iter.previous(); return '�'; } if ((a & 0b1111_0000) == 0b1110_0000) { // three bytes iter.previous(); iter.previous(); return (a & 0b0000_1111) << 12 | (b & 0b00_111111) << 6 | c & 0b00_111111; } // >= 4 bytes iter.next(); if (! iter.hasNext()) { // truncated iter.previous(); iter.previous(); iter.previous(); return '�'; } int d = iter.peekNext(); if ((d & 0b11_000000) != 0b10_000000) { // fourth byte is invalid; return � instead iter.previous(); iter.previous(); iter.previous(); return '�'; } if ((a & 0b11111_000) == 0b11110_000) { // four bytes iter.previous(); iter.previous(); iter.previous(); return (a & 0b00000_111) << 18 | (b & 0b00_111111) << 12 | (c & 0b00_111111) << 6 | d & 0b00_111111; } // only invalid possibilities are left; return � instead iter.previous(); iter.previous(); iter.previous(); return '�'; } public int previous() { // read backwards if (! iter.hasPrevious()) throw new NoSuchElementException(); offset--; // >= 1 byte int a = iter.previous(); if ((a & 0b1_0000000) == 0b0_0000000) { // one byte return a; } if ((a & 0b11_000000) != 0b10_000000) { // last byte is invalid; return � instead seekToPrev(); return '�'; } int cp = a & 0b00_111111; // >= 2 bytes a = iter.previous(); if ((a & 0b111_00000) == 0b110_00000) { // two bytes return (a & 0b000_11111) << 6 | cp; } if ((a & 0b11_000000) != 0b10_000000) { // second-to-last byte is invalid; return � instead seekToPrev(); return '�'; } cp |= (a & 0b00_111111) << 6; // >= 3 bytes a = iter.previous(); if ((a & 0b1111_0000) == 0b1110_0000) { // three bytes return (a & 0b0000_1111) << 12 | cp; } if ((a & 0b11_000000) != 0b10_000000) { // third-to-last byte is invalid; return � instead seekToPrev(); return '�'; } cp |= (a & 0b00_111111) << 12; // >= 4 bytes a = iter.previous(); if ((a & 0b11111_000) == 0b11110_000) { // four bytes return (a & 0b00000_111) << 18 | cp; } // only invalid possibilities are left; return � instead seekToPrev(); return '�'; } public int peekPrevious() throws NoSuchElementException { // read backwards if (! iter.hasPrevious()) throw new NoSuchElementException(); // >= 1 byte int a = iter.peekPrevious(); if ((a & 0b1_0000000) == 0b0_0000000) { // one byte return a; } if ((a & 0b11_000000) != 0b10_000000) { // last byte is invalid; return � instead return '�'; } int cp = a & 0b00_111111; // >= 2 bytes iter.previous(); a = iter.peekPrevious(); if ((a & 0b111_00000) == 0b110_00000) { // two bytes iter.next(); return (a & 0b000_11111) << 6 | cp; } if ((a & 0b11_000000) != 0b10_000000) { // second-to-last byte is invalid; return � instead iter.next(); return '�'; } cp |= (a & 0b00_111111) << 6; // >= 3 bytes iter.previous(); a = iter.peekPrevious(); if ((a & 0b1111_0000) == 0b1110_0000) { // three bytes iter.next(); iter.next(); return (a & 0b0000_1111) << 12 | cp; } if ((a & 0b11_000000) != 0b10_000000) { // third-to-last byte is invalid; return � instead iter.next(); iter.next(); return '�'; } cp |= (a & 0b00_111111) << 12; // >= 4 bytes iter.previous(); a = iter.peekPrevious(); if ((a & 0b11111_000) == 0b11110_000) { // four bytes iter.next(); iter.next(); iter.next(); return (a & 0b00000_111) << 18 | cp; } // only invalid possibilities are left; return � instead iter.next(); iter.next(); iter.next(); return '�'; } public long getIndex() { return offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/Utf8EncodingByteIterator.java000066400000000000000000000170521361511066400334010ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.iteration; import java.util.NoSuchElementException; import org.wildfly.common.Assert; import org.wildfly.common.bytes.ByteStringBuilder; /** */ final class Utf8EncodingByteIterator extends ByteIterator { private final CodePointIterator iter; private final boolean escapeNul; // state 0 = between code points // state 1 = after byte 1 of 2 // state 2 = after byte 1 of 3 // state 3 = after byte 2 of 3 // state 4 = after byte 1 of 4 // state 5 = after byte 2 of 4 // state 6 = after byte 3 of 4 private int st; private int cp; private long offset; Utf8EncodingByteIterator(final CodePointIterator iter, final boolean escapeNul) { this.iter = iter; this.escapeNul = escapeNul; cp = - 1; } public boolean hasNext() { return st != 0 || iter.hasNext(); } public boolean hasPrevious() { return st != 0 || iter.hasPrevious(); } public int next() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); offset++; switch (st) { case 0: { int cp = iter.next(); if (cp == 0 && ! escapeNul || cp < 0x80) { return cp; } else if (cp < 0x800) { this.cp = cp; st = 1; return 0b110_00000 | cp >> 6; } else if (cp < 0x10000) { this.cp = cp; st = 2; return 0b1110_0000 | cp >> 12; } else if (cp < 0x110000) { this.cp = cp; st = 4; return 0b11110_000 | cp >> 18; } else { this.cp = '�'; st = 2; return 0b1110_0000 | '�' >> 12; } } case 1: case 3: case 6: { st = 0; return 0b10_000000 | cp & 0x3f; } case 2: { st = 3; return 0b10_000000 | cp >> 6 & 0x3f; } case 4: { st = 5; return 0b10_000000 | cp >> 12 & 0x3f; } case 5: { st = 6; return 0b10_000000 | cp >> 6 & 0x3f; } default: { throw Assert.impossibleSwitchCase(st); } } } public int peekNext() throws NoSuchElementException { if (! hasNext()) throw new NoSuchElementException(); switch (st) { case 0: { int cp = iter.peekNext(); if (cp < 0x80) { return cp; } else if (cp < 0x800) { return 0b110_00000 | cp >> 6; } else if (cp < 0x10000) { return 0b1110_0000 | cp >> 12; } else if (cp < 0x110000) { return 0b11110_000 | cp >> 18; } else { return 0b1110_0000 | '�' >> 12; } } case 1: case 3: case 6: { return 0b10_000000 | cp & 0x3f; } case 2: case 5: { return 0b10_000000 | cp >> 6 & 0x3f; } case 4: { return 0b10_000000 | cp >> 12 & 0x3f; } default: { throw Assert.impossibleSwitchCase(st); } } } public int previous() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); offset--; switch (st) { case 0: { int cp = iter.previous(); if (cp == 0 && ! escapeNul || cp < 0x80) { return cp; } else if (cp < 0x800) { this.cp = cp; st = 1; return 0b10_000000 | cp & 0x3f; } else if (cp < 0x10000) { this.cp = cp; st = 3; return 0b10_000000 | cp & 0x3f; } else if (cp < 0x110000) { this.cp = cp; st = 6; return 0b10_000000 | cp & 0x3f; } else { this.cp = '�'; st = 3; return 0b10_000000 | '�' & 0x3f; } } case 1: { st = 0; return 0b110_00000 | cp >> 6; } case 2: { st = 0; return 0b1110_0000 | cp >> 12; } case 3: { st = 2; return 0b10_000000 | cp >> 6 & 0x3f; } case 4: { st = 0; return 0b11110_000 | cp >> 18; } case 5: { st = 4; return 0b10_000000 | cp >> 12 & 0x3f; } case 6: { st = 5; return 0b10_000000 | cp >> 6 & 0x3f; } default: { throw Assert.impossibleSwitchCase(st); } } } public int peekPrevious() throws NoSuchElementException { if (! hasPrevious()) throw new NoSuchElementException(); switch (st) { case 0: { int cp = iter.peekPrevious(); if (cp == 0 && ! escapeNul || cp < 0x80) { return cp; } else if (cp < 0x800) { return 0b10_000000 | cp & 0x3f; } else if (cp < 0x10000) { return 0b10_000000 | cp & 0x3f; } else if (cp < 0x110000) { return 0b10_000000 | cp & 0x3f; } else { return 0b10_000000 | '�' & 0x3f; } } case 1: { return 0b110_00000 | cp >> 6; } case 2: { return 0b1110_0000 | cp >> 12; } case 3: case 6: { return 0b10_000000 | cp >> 6 & 0x3f; } case 4: { return 0b11110_000 | cp >> 18; } case 5: { return 0b10_000000 | cp >> 12 & 0x3f; } default: { throw Assert.impossibleSwitchCase(st); } } } public ByteStringBuilder appendTo(final ByteStringBuilder builder) { if (st == 0) { // this is faster final int oldLen = builder.length(); builder.appendUtf8(iter); offset += builder.length() - oldLen; } else { super.appendTo(builder); } return builder; } public long getIndex() { return offset; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/iteration/package-info.java000066400000000000000000000014231361511066400310650ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes related to iteration. */ package org.wildfly.common.iteration; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/000077500000000000000000000000001361511066400246305ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/ExtendedLock.java000066400000000000000000000027161361511066400300520ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import java.util.concurrent.locks.Lock; /** * A thread-owned lock which exposes additional informational methods. */ public interface ExtendedLock extends Lock { /** * Determine if this lock is held. * * @return {@code true} if this lock is held, {@code false} otherwise */ boolean isLocked(); /** * Determine if this lock is held by the current thread. * * @return {@code true} if this lock is held by the current thread, {@code false} otherwise */ boolean isHeldByCurrentThread(); /** * Query if this lock instance tends to be "fair". * * @return {@code true} if the lock instance tends towards fairness, {@code false} otherwise */ boolean isFair(); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/ExtendedReentrantLock.java000066400000000000000000000020131361511066400317230ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import java.util.concurrent.locks.ReentrantLock; /** */ @SuppressWarnings("serial") class ExtendedReentrantLock extends ReentrantLock implements ExtendedLock { ExtendedReentrantLock(final boolean fair) { super(fair); } ExtendedReentrantLock() { super(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/JDKSpecific.java000066400000000000000000000031571361511066400275570ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import sun.misc.Unsafe; /** */ final class JDKSpecific { private JDKSpecific() {} static final Unsafe unsafe; static { unsafe = AccessController.doPrivileged(new PrivilegedAction() { public Unsafe run() { try { final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return (Unsafe) field.get(null); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } } }); } static void onSpinWait() { // n/a } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/Locks.java000066400000000000000000000032341361511066400265500ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import org.wildfly.common.annotation.NotNull; /** * A utility class to create {@code ExtendedLock} objects. */ public final class Locks { private Locks() {} /** * Create a standard reentrant {@code ExtendedLock} with the default fairness policy. * * @return a reentrant {@code ExtendedLock} */ public static @NotNull ExtendedLock reentrantLock() { return new ExtendedReentrantLock(); } /** * Create a standard reentrant {@code ExtendedLock} with the given fairness policy. * * @param fair the fairness policy * @return a reentrant {@code ExtendedLock} */ public static @NotNull ExtendedLock reentrantLock(boolean fair) { return new ExtendedReentrantLock(fair); } /** * Create a spin lock. * * @return the spin lock * @see SpinLock */ public static @NotNull ExtendedLock spinLock() { return new SpinLock(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/SpinLock.java000066400000000000000000000137571361511066400272320ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import static org.wildfly.common.lock.JDKSpecific.unsafe; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import org.wildfly.common.Assert; import org.wildfly.common.cpu.ProcessorInfo; /** * A spin lock. Such locks are designed to only be held for a very short time - for example, long enough to compare and * swap two fields. The lock may degrade to yielding the thread after a certain number of spins if it is held for too long. *

* Spin locks do not support conditions, and they do not support timed waiting. Normally only the uninterruptible {@code lock}, * {@code tryLock}, and {@code unlock} methods should be used to control the lock. */ public class SpinLock implements ExtendedLock { private static final long ownerOffset; private static final int spinLimit; static { try { ownerOffset = unsafe.objectFieldOffset(SpinLock.class.getDeclaredField("owner")); } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } spinLimit = AccessController.doPrivileged( (PrivilegedAction) () -> Integer.valueOf( System.getProperty("jboss.spin-lock.limit", ProcessorInfo.availableProcessors() == 1 ? "0" : "5000") ) ).intValue(); } @SuppressWarnings("unused") private volatile Thread owner; private int level; /** * Construct a new instance. */ public SpinLock() {} /** * Determine if this spin lock is held. Useful for assertions. * * @return {@code true} if the lock is held by any thread, {@code false} otherwise */ public boolean isLocked() { return owner != null; } /** * Determine if this spin lock is held by the calling thread. Useful for assertions. * * @return {@code true} if the lock is held by the calling thread, {@code false} otherwise */ public boolean isHeldByCurrentThread() { return owner == Thread.currentThread(); } /** * Determine if this lock is fair. * * @return {@code true}; the lock is fair */ public boolean isFair() { return true; } /** * Acquire the lock by spinning until it is held. */ public void lock() { Thread owner; int spins = 0; for (;;) { owner = this.owner; if (owner == Thread.currentThread()) { level++; return; } else if (owner == null && unsafe.compareAndSwapObject(this, ownerOffset, null, Thread.currentThread())) { level = 1; return; } else if (spins >= spinLimit) { Thread.yield(); } else { JDKSpecific.onSpinWait(); spins++; } } } /** * Acquire the lock by spinning until it is held or the thread is interrupted. * * @throws InterruptedException if the thread is interrupted before the lock can be acquired */ public void lockInterruptibly() throws InterruptedException { Thread owner; int spins = 0; for (;;) { if (Thread.interrupted()) throw new InterruptedException(); owner = this.owner; if (owner == Thread.currentThread()) { level++; return; } else if (owner == null && unsafe.compareAndSwapObject(this, ownerOffset, null, Thread.currentThread())) { level = 1; return; } else if (spins >= spinLimit) { Thread.yield(); } else { JDKSpecific.onSpinWait(); spins++; } } } /** * Try to acquire the lock, returning immediately whether or not the lock was acquired. * * @return {@code true} if the lock was acquired, {@code false} otherwise */ public boolean tryLock() { Thread owner = this.owner; if (owner == Thread.currentThread()) { level++; return true; } else if (owner == null && unsafe.compareAndSwapObject(this, ownerOffset, null, Thread.currentThread())) { level = 1; return true; } else { return false; } } /** * Release the lock. * * @throws IllegalMonitorStateException if the lock is not held by the current thread */ public void unlock() { Thread owner = this.owner; if (owner == Thread.currentThread()) { if (--level == 0) this.owner = null; } else { throw new IllegalMonitorStateException(); } } /** * Unsupported. * * @param time ignored * @param unit ignored * @return nothing * @throws UnsupportedOperationException always */ public boolean tryLock(final long time, final TimeUnit unit) throws UnsupportedOperationException { throw Assert.unsupported(); } /** * Unsupported. * * @return nothing * @throws UnsupportedOperationException always */ public Condition newCondition() throws UnsupportedOperationException { throw Assert.unsupported(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/Substitutions.java000066400000000000000000000023761361511066400304020ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; final class Substitutions { @TargetClass(JDKSpecific.class) static final class Target_JDKSpecific { @Substitute static void onSpinWait() { Target_PauseNode.pause(); } } @TargetClass(className = "org.graalvm.compiler.nodes.PauseNode") static final class Target_PauseNode { @Alias public static native void pause(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/lock/package-info.java000066400000000000000000000001231361511066400300130ustar00rootroot00000000000000/** * Classes which provide basic lock types. */ package org.wildfly.common.lock;wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/math/000077500000000000000000000000001361511066400246315ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/math/HashMath.java000066400000000000000000000130251361511066400271720ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.math; import org.wildfly.common.Assert; /** * Routines which are useful for hashcode computation, among other things. * * @author David M. Lloyd */ public final class HashMath { private static final int PRESELECTED_PRIME = 1299827; private HashMath() { } /** * Round the given value up to the next positive power of two. * * @param value the value (must not be negative and must be less than or equal to {@code 2^31}) * @return the rounded power of two value */ public static int roundToPowerOfTwo(int value) { Assert.checkMinimumParameter("value", 0, value); Assert.checkMaximumParameter("value", 0x4000_0000, value); return value <= 1 ? value : Integer.highestOneBit(value - 1) << 1; } /** * A hash function which combines an accumulated hash with a next hash such that {@code f(f(k, p2, b), p1, a) ≠ₙ f(f(k, p1, a), p2, b)}. * This function is suitable for object chains whose order affects the overall equality of the hash code. *

* The exact algorithm is not specified and is therefore subject to change and should not be relied upon for hash * codes that persist outside of the JVM process. * * @param accumulatedHash the accumulated hash code of the previous stage * @param prime a prime multiplier * @param nextHash the hash code of the next single item * @return the new accumulated hash code */ public static int multiHashOrdered(int accumulatedHash, int prime, int nextHash) { return multiplyWrap(accumulatedHash, prime) + nextHash; } /** * A hash function which combines an accumulated hash with a next hash such that {@code f(f(k, p2, b), p1, a) = f(f(k, p1, a), p2, b)}. * This function is suitable for object chains whose order does not affect the overall equality of the hash code. *

* The exact algorithm is not specified and is therefore subject to change and should not be relied upon for hash * codes that persist outside of the JVM process. * * @param accumulatedHash the accumulated hash code of the previous stage * @param prime a prime multiplier * @param nextHash the hash code of the next single item * @return the new accumulated hash code */ public static int multiHashUnordered(int accumulatedHash, int prime, int nextHash) { return multiplyWrap(nextHash, prime) + accumulatedHash; } /** * A hash function which combines an accumulated hash with a next hash such that {@code f(f(k, b), a) ≠ₙ f(f(k, a), b)}. * This function is suitable for object chains whose order affects the overall equality of the hash code. *

* The exact algorithm is not specified and is therefore subject to change and should not be relied upon for hash * codes that persist outside of the JVM process. * * @param accumulatedHash the accumulated hash code of the previous stage * @param nextHash the hash code of the next single item * @return the new accumulated hash code */ public static int multiHashOrdered(int accumulatedHash, int nextHash) { return multiHashOrdered(accumulatedHash, PRESELECTED_PRIME, nextHash); } /** * A hash function which combines an accumulated hash with a next hash such that {@code f(f(k, b), a) = f(f(k, a), b)}. * This function is suitable for object chains whose order does not affect the overall equality of the hash code. *

* The exact algorithm is not specified and is therefore subject to change and should not be relied upon for hash * codes that persist outside of the JVM process. * * @param accumulatedHash the accumulated hash code of the previous stage * @param nextHash the hash code of the next single item * @return the new accumulated hash code */ public static int multiHashUnordered(int accumulatedHash, int nextHash) { return multiHashUnordered(accumulatedHash, PRESELECTED_PRIME, nextHash); } /** * Multiply two unsigned integers together. If the result overflows a 32-bit number, XOR the overflowed bits back into the result. * This operation is commutative, i.e. if we designate the {@code ⨰} symbol to represent this operation, then {@code a ⨰ b = b ⨰ a}. * This operation is not associative, i.e. {@code (a ⨰ b) ⨰ c ≠ₙ a ⨰ (b ⨰ c)} (the symbol {@code ≠ₙ} meaning "not necessarily equal to"), * therefore this operation is suitable for ordered combinatorial hash functions. * * @param a the first number to multiply * @param b the second number to multiply * @return the wrapped multiply result */ public static int multiplyWrap(int a, int b) { long r1 = (long) a * b; return (int) r1 ^ (int) (r1 >>> 32); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/math/package-info.java000066400000000000000000000015671361511066400300310ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes which perform various common mathematical functions. * * @author David M. Lloyd */ package org.wildfly.common.math; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/000077500000000000000000000000001361511066400244665ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/CidrAddress.java000066400000000000000000000362611361511066400275300ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import static java.lang.Integer.signum; import static java.lang.Math.min; import java.io.Serializable; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; import org.wildfly.common.math.HashMath; /** * A Classless Inter-Domain Routing address. This is the combination of an IP address and a netmask. * * @author David M. Lloyd */ public final class CidrAddress implements Serializable, Comparable { private static final long serialVersionUID = - 6548529324373774149L; /** * The CIDR address representing all IPv4 addresses. */ public static final CidrAddress INET4_ANY_CIDR = new CidrAddress(Inet.INET4_ANY, 0); /** * The CIDR address representing all IPv6 addresses. */ public static final CidrAddress INET6_ANY_CIDR = new CidrAddress(Inet.INET6_ANY, 0); private final InetAddress networkAddress; private final byte[] cachedBytes; private final int netmaskBits; private Inet4Address broadcast; private String toString; private int hashCode; private CidrAddress(final InetAddress networkAddress, final int netmaskBits) { this.networkAddress = networkAddress; cachedBytes = networkAddress.getAddress(); this.netmaskBits = netmaskBits; } /** * Create a new CIDR address. * * @param networkAddress the network address (must not be {@code null}) * @param netmaskBits the netmask bits (0-32 for IPv4, or 0-128 for IPv6) * @return the CIDR address (not {@code null}) */ public static CidrAddress create(InetAddress networkAddress, int netmaskBits) { Assert.checkNotNullParam("networkAddress", networkAddress); Assert.checkMinimumParameter("netmaskBits", 0, netmaskBits); int scopeId = Inet.getScopeId(networkAddress); if (networkAddress instanceof Inet4Address) { Assert.checkMaximumParameter("netmaskBits", 32, netmaskBits); if (netmaskBits == 0) { return INET4_ANY_CIDR; } } else if (networkAddress instanceof Inet6Address) { Assert.checkMaximumParameter("netmaskBits", 128, netmaskBits); if (netmaskBits == 0 && scopeId == 0) { return INET6_ANY_CIDR; } } else { throw Assert.unreachableCode(); } final byte[] bytes = networkAddress.getAddress(); maskBits0(bytes, netmaskBits); String name = Inet.toOptimalString(bytes); try { if (bytes.length == 4) { return new CidrAddress(InetAddress.getByAddress(name, bytes), netmaskBits); } else { return new CidrAddress(Inet6Address.getByAddress(name, bytes, scopeId), netmaskBits); } } catch (UnknownHostException e) { throw Assert.unreachableCode(); } } /** * Create a new CIDR address. * * @param addressBytes the network address bytes (must not be {@code null}, must be 4 bytes for IPv4 or 16 bytes for IPv6) * @param netmaskBits the netmask bits (0-32 for IPv4, or 0-128 for IPv6) * @return the CIDR address (not {@code null}) */ public static CidrAddress create(byte[] addressBytes, int netmaskBits) { return create(addressBytes, netmaskBits, true); } static CidrAddress create(byte[] addressBytes, int netmaskBits, boolean clone) { Assert.checkNotNullParam("networkAddress", addressBytes); Assert.checkMinimumParameter("netmaskBits", 0, netmaskBits); final int length = addressBytes.length; if (length == 4) { Assert.checkMaximumParameter("netmaskBits", 32, netmaskBits); if (netmaskBits == 0) { return INET4_ANY_CIDR; } } else if (length == 16) { Assert.checkMaximumParameter("netmaskBits", 128, netmaskBits); if (netmaskBits == 0) { return INET6_ANY_CIDR; } } else { throw CommonMessages.msg.invalidAddressBytes(length); } final byte[] bytes = clone ? addressBytes.clone() : addressBytes; maskBits0(bytes, netmaskBits); String name = Inet.toOptimalString(bytes); try { return new CidrAddress(InetAddress.getByAddress(name, bytes), netmaskBits); } catch (UnknownHostException e) { throw Assert.unreachableCode(); } } /** * Determine if this CIDR address matches the given address. * * @param address the address to test * @return {@code true} if the address matches, {@code false} otherwise */ public boolean matches(InetAddress address) { Assert.checkNotNullParam("address", address); if (address instanceof Inet4Address) { return matches((Inet4Address) address); } else if (address instanceof Inet6Address) { return matches((Inet6Address) address); } else { throw Assert.unreachableCode(); } } /** * Determine if this CIDR address matches the given address bytes. * * @param bytes the address bytes to test * @return {@code true} if the address bytes match, {@code false} otherwise */ public boolean matches(byte[] bytes) { return matches(bytes, 0); } /** * Determine if this CIDR address matches the given address bytes. * * @param bytes the address bytes to test * @param scopeId the scope ID, or 0 to match no scope * @return {@code true} if the address bytes match, {@code false} otherwise */ public boolean matches(byte[] bytes, int scopeId) { Assert.checkNotNullParam("bytes", bytes); return cachedBytes.length == bytes.length && (getScopeId() == 0 || getScopeId() == scopeId) && bitsMatch(cachedBytes, bytes, netmaskBits); } /** * Determine if this CIDR address matches the given address. * * @param address the address to test * @return {@code true} if the address matches, {@code false} otherwise */ public boolean matches(Inet4Address address) { Assert.checkNotNullParam("address", address); return networkAddress instanceof Inet4Address && bitsMatch(cachedBytes, address.getAddress(), netmaskBits); } /** * Determine if this CIDR address matches the given address. * * @param address the address to test * @return {@code true} if the address matches, {@code false} otherwise */ public boolean matches(Inet6Address address) { Assert.checkNotNullParam("address", address); return networkAddress instanceof Inet6Address && bitsMatch(cachedBytes, address.getAddress(), netmaskBits) && (getScopeId() == 0 || getScopeId() == address.getScopeId()); } /** * Determine if this CIDR address matches the given CIDR address. This will be true only when the given CIDR * block is wholly enclosed by this one. * * @param address the address to test * @return {@code true} if the given block is enclosed by this one, {@code false} otherwise */ public boolean matches(CidrAddress address) { Assert.checkNotNullParam("address", address); return netmaskBits <= address.netmaskBits && matches(address.cachedBytes) && (getScopeId() == 0 || getScopeId() == address.getScopeId()); } /** * Get the network address. The returned address has a resolved name consisting of the most compact valid string * representation of the network of this CIDR address. * * @return the network address (not {@code null}) */ public InetAddress getNetworkAddress() { return networkAddress; } /** * Get the broadcast address for this CIDR block. If the block has no broadcast address (either because it is IPv6 * or it is too small) then {@code null} is returned. * * @return the broadcast address for this CIDR block, or {@code null} if there is none */ public Inet4Address getBroadcastAddress() { final Inet4Address broadcast = this.broadcast; if (broadcast == null) { final int netmaskBits = this.netmaskBits; if (netmaskBits >= 31) { // definitely IPv6 or too small return null; } // still maybe IPv6 final byte[] cachedBytes = this.cachedBytes; if (cachedBytes.length == 4) { // calculate if (netmaskBits == 0) { return this.broadcast = Inet.INET4_BROADCAST; } else { final byte[] bytes = maskBits1(cachedBytes.clone(), netmaskBits); try { return this.broadcast = (Inet4Address) InetAddress.getByAddress(Inet.toOptimalString(bytes), bytes); } catch (UnknownHostException e) { throw Assert.unreachableCode(); } } } return null; } return broadcast; } /** * Get the netmask bits. This will be in the range 0-32 for IPv4 addresses, and 0-128 for IPv6 addresses. * * @return the netmask bits */ public int getNetmaskBits() { return netmaskBits; } /** * Get the match address scope ID (if it is an IPv6 address). * * @return the scope ID, or 0 if there is none or the address is an IPv4 address */ public int getScopeId() { return Inet.getScopeId(getNetworkAddress()); } public int compareTo(final CidrAddress other) { Assert.checkNotNullParam("other", other); if (this == other) return 0; return compareAddressBytesTo(other.cachedBytes, other.netmaskBits, other.getScopeId()); } public int compareAddressBytesTo(final byte[] otherBytes, final int otherNetmaskBits, final int scopeId) { Assert.checkNotNullParam("bytes", otherBytes); final int otherLength = otherBytes.length; if (otherLength != 4 && otherLength != 16) { throw CommonMessages.msg.invalidAddressBytes(otherLength); } // IPv4 before IPv6 final byte[] cachedBytes = this.cachedBytes; int res = signum(cachedBytes.length - otherLength); if (res != 0) return res; res = signum(scopeId - getScopeId()); if (res != 0) return res; // sorted numerically with long matches coming later final int netmaskBits = this.netmaskBits; int commonPrefix = min(netmaskBits, otherNetmaskBits); // compare byte-wise as far as we can int i = 0; while (commonPrefix >= 8) { res = signum((cachedBytes[i] & 0xff) - (otherBytes[i] & 0xff)); if (res != 0) return res; i++; commonPrefix -= 8; } while (commonPrefix > 0) { final int bit = 1 << commonPrefix; res = signum((cachedBytes[i] & bit) - (otherBytes[i] & bit)); if (res != 0) return res; commonPrefix--; } // common prefix is a match; now the shortest mask wins return signum(netmaskBits - otherNetmaskBits); } public boolean equals(final Object obj) { return obj instanceof CidrAddress && equals((CidrAddress) obj); } public boolean equals(final CidrAddress obj) { return obj == this || obj != null && netmaskBits == obj.netmaskBits && Arrays.equals(cachedBytes, obj.cachedBytes); } public int hashCode() { int hashCode = this.hashCode; if (hashCode == 0) { hashCode = HashMath.multiHashOrdered(netmaskBits, Arrays.hashCode(cachedBytes)); if (hashCode == 0) { hashCode = 1; } this.hashCode = hashCode; } return hashCode; } public String toString() { final String toString = this.toString; if (toString == null) { final int scopeId = getScopeId(); if (scopeId == 0) { return this.toString = String.format("%s/%d", Inet.toOptimalString(cachedBytes), Integer.valueOf(netmaskBits)); } else { return this.toString = String.format("%s%%%d/%d", Inet.toOptimalString(cachedBytes), Integer.valueOf(scopeId), Integer.valueOf(netmaskBits)); } } return toString; } Object writeReplace() { return new Ser(cachedBytes, netmaskBits); } static final class Ser implements Serializable { private static final long serialVersionUID = 6367919693596329038L; final byte[] b; final int m; Ser(final byte[] b, final int m) { this.b = b; this.m = m; } Object readResolve() { return create(b, m, false); } } private static boolean bitsMatch(byte[] address, byte[] test, int bits) { final int length = address.length; assert length == test.length; // bytes are in big-endian form. int i = 0; while (bits >= 8 && i < length) { if (address[i] != test[i]) { return false; } i ++; bits -= 8; } if (bits > 0) { assert bits < 8; int mask = 0xff << 8 - bits; if ((address[i] & 0xff & mask) != (test[i] & 0xff & mask)) { return false; } } return true; } private static byte[] maskBits0(byte[] address, int bits) { final int length = address.length; // bytes are in big-endian form. int i = 0; while (bits >= 8 && i < length) { i ++; bits -= 8; } if (bits > 0) { assert bits < 8; int mask = 0xff << 8 - bits; address[i++] &= mask; } while (i < length) { address[i++] = 0; } return address; } private static byte[] maskBits1(byte[] address, int bits) { final int length = address.length; // bytes are in big-endian form. int i = 0; while (bits >= 8 && i < length) { i ++; bits -= 8; } if (bits > 0) { assert bits < 8; int mask = 0xff >>> 8 - bits; address[i++] |= mask; } while (i < length) { address[i++] = (byte) 0xff; } return address; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/CidrAddressTable.java000066400000000000000000000265071361511066400305020ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import java.net.Inet4Address; import java.net.InetAddress; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.atomic.AtomicReference; import org.wildfly.common.Assert; /** * A table for mapping IP addresses to objects using {@link CidrAddress} instances for matching. * * @author David M. Lloyd */ public final class CidrAddressTable implements Iterable> { @SuppressWarnings("rawtypes") private static final Mapping[] NO_MAPPINGS = new Mapping[0]; private final AtomicReference[]> mappingsRef; public CidrAddressTable() { mappingsRef = new AtomicReference<>(empty()); } private CidrAddressTable(Mapping[] mappings) { mappingsRef = new AtomicReference<>(mappings); } public T getOrDefault(InetAddress address, T defVal) { Assert.checkNotNullParam("address", address); final Mapping mapping = doGet(mappingsRef.get(), address.getAddress(), address instanceof Inet4Address ? 32 : 128, Inet.getScopeId(address)); return mapping == null ? defVal : mapping.value; } public T get(InetAddress address) { return getOrDefault(address, null); } public T put(CidrAddress block, T value) { Assert.checkNotNullParam("block", block); Assert.checkNotNullParam("value", value); return doPut(block, null, value, true, true); } public T putIfAbsent(CidrAddress block, T value) { Assert.checkNotNullParam("block", block); Assert.checkNotNullParam("value", value); return doPut(block, null, value, true, false); } public T replaceExact(CidrAddress block, T value) { Assert.checkNotNullParam("block", block); Assert.checkNotNullParam("value", value); return doPut(block, null, value, false, true); } public boolean replaceExact(CidrAddress block, T expect, T update) { Assert.checkNotNullParam("block", block); Assert.checkNotNullParam("expect", expect); Assert.checkNotNullParam("update", update); return doPut(block, expect, update, false, true) == expect; } public T removeExact(CidrAddress block) { Assert.checkNotNullParam("block", block); return doPut(block, null, null, false, true); } public boolean removeExact(CidrAddress block, T expect) { Assert.checkNotNullParam("block", block); return doPut(block, expect, null, false, true) == expect; } private T doPut(final CidrAddress block, final T expect, final T update, final boolean putIfAbsent, final boolean putIfPresent) { assert putIfAbsent || putIfPresent; final AtomicReference[]> mappingsRef = this.mappingsRef; final byte[] bytes = block.getNetworkAddress().getAddress(); Mapping[] oldVal, newVal; int idx; T existing; boolean matchesExpected; do { oldVal = mappingsRef.get(); idx = doFind(oldVal, bytes, block.getNetmaskBits(), block.getScopeId()); if (idx < 0) { if (! putIfAbsent) { return null; } existing = null; } else { existing = oldVal[idx].value; } if (expect != null) { matchesExpected = Objects.equals(expect, existing); if (! matchesExpected) { return existing; } } else { matchesExpected = false; } if (idx >= 0 && ! putIfPresent) { return existing; } // now construct the new mapping final int oldLen = oldVal.length; if (update == null) { assert idx >= 0; // removal if (oldLen == 1) { newVal = empty(); } else { final Mapping removing = oldVal[idx]; newVal = Arrays.copyOf(oldVal, oldLen - 1); System.arraycopy(oldVal, idx + 1, newVal, idx, oldLen - idx - 1); // now reparent any children that I was a parent of with my old parent for (int i = 0; i < oldLen - 1; i ++) { if (newVal[i].parent == removing) { newVal[i] = newVal[i].withNewParent(removing.parent); } } } } else if (idx >= 0) { // replace newVal = oldVal.clone(); final Mapping oldMapping = oldVal[idx]; final Mapping newMapping = new Mapping<>(block, update, oldVal[idx].parent); newVal[idx] = newMapping; // now reparent any child to me for (int i = 0; i < oldLen; i ++) { if (i != idx && newVal[i].parent == oldMapping) { newVal[i] = newVal[i].withNewParent(newMapping); } } } else { // add newVal = Arrays.copyOf(oldVal, oldLen + 1); final Mapping newMappingParent = doGet(oldVal, bytes, block.getNetmaskBits(), block.getScopeId()); final Mapping newMapping = new Mapping<>(block, update, newMappingParent); newVal[-idx - 1] = newMapping; System.arraycopy(oldVal, -idx - 1, newVal, -idx, oldLen + idx + 1); // now reparent any children who have a parent of my (possibly null) parent but match me for (int i = 0; i <= oldLen; i++) { if (newVal[i] != newMapping && newVal[i].parent == newMappingParent && block.matches(newVal[i].range)) { newVal[i] = newVal[i].withNewParent(newMapping); } } } } while (! mappingsRef.compareAndSet(oldVal, newVal)); return matchesExpected ? expect : existing; } @SuppressWarnings("unchecked") private static Mapping[] empty() { return NO_MAPPINGS; } public void clear() { mappingsRef.set(empty()); } public int size() { return mappingsRef.get().length; } public boolean isEmpty() { return size() == 0; } public CidrAddressTable clone() { return new CidrAddressTable<>(mappingsRef.get()); } public Iterator> iterator() { final Mapping[] mappings = mappingsRef.get(); return new Iterator>() { int idx; public boolean hasNext() { return idx < mappings.length; } public Mapping next() { if (! hasNext()) throw new NoSuchElementException(); return mappings[idx++]; } }; } public Spliterator> spliterator() { final Mapping[] mappings = mappingsRef.get(); return Spliterators.spliterator(mappings, Spliterator.IMMUTABLE | Spliterator.ORDERED); } public String toString() { StringBuilder b = new StringBuilder(); final Mapping[] mappings = mappingsRef.get(); b.append(mappings.length).append(" mappings"); for (final Mapping mapping : mappings) { b.append(System.lineSeparator()).append('\t').append(mapping.range); if (mapping.parent != null) { b.append(" (parent ").append(mapping.parent.range).append(')'); } b.append(" -> ").append(mapping.value); } return b.toString(); } private int doFind(Mapping[] table, byte[] bytes, int maskBits, final int scopeId) { int low = 0; int high = table.length - 1; while (low <= high) { // bisect the range int mid = low + high >>> 1; // compare the mapping at this location Mapping mapping = table[mid]; int cmp = mapping.range.compareAddressBytesTo(bytes, maskBits, scopeId); if (cmp < 0) { // move to the latter half low = mid + 1; } else if (cmp > 0) { // move to the former half high = mid - 1; } else { // exact match is the best case return mid; } } // return the point we would insert at (plus one, negated) return -(low + 1); } private Mapping doGet(Mapping[] table, byte[] bytes, final int netmaskBits, final int scopeId) { int idx = doFind(table, bytes, netmaskBits, scopeId); if (idx >= 0) { // exact match assert table[idx].range.matches(bytes, scopeId); return table[idx]; } // check immediate predecessor if there is one int pre = -idx - 2; if (pre >= 0) { if (table[pre].range.matches(bytes, scopeId)) { return table[pre]; } // try parent Mapping parent = table[pre].parent; while (parent != null) { if (parent.range.matches(bytes, scopeId)) { return parent; } parent = parent.parent; } } return null; } /** * A single mapping in the table. * * @param the value type */ public static final class Mapping { final CidrAddress range; final T value; final Mapping parent; Mapping(final CidrAddress range, final T value, final Mapping parent) { this.range = range; this.value = value; this.parent = parent; } Mapping withNewParent(Mapping newParent) { return new Mapping(range, value, newParent); } /** * Get the address range of this entry. * * @return the address range of this entry (not {@code null}) */ public CidrAddress getRange() { return range; } /** * Get the stored value of this entry. * * @return the stored value of this entry */ public T getValue() { return value; } /** * Get the parent of this entry, if any. * * @return the parent of this entry, or {@code null} if there is no parent */ public Mapping getParent() { return parent; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/GetHostInfoAction.java000066400000000000000000000060331361511066400306620ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import java.net.UnknownHostException; import java.security.PrivilegedAction; import java.util.regex.Pattern; /** */ final class GetHostInfoAction implements PrivilegedAction { GetHostInfoAction() { } public String[] run() { // allow host name to be overridden String qualifiedHostName = System.getProperty("jboss.qualified.host.name"); String providedHostName = System.getProperty("jboss.host.name"); String providedNodeName = System.getProperty("jboss.node.name"); if (qualifiedHostName == null) { // if host name is specified, don't pick a qualified host name that isn't related to it qualifiedHostName = providedHostName; if (qualifiedHostName == null) { // POSIX-like OSes including Mac should have this set qualifiedHostName = System.getenv("HOSTNAME"); } if (qualifiedHostName == null) { // Certain versions of Windows qualifiedHostName = System.getenv("COMPUTERNAME"); } if (qualifiedHostName == null) { try { qualifiedHostName = HostName.getLocalHost().getHostName(); } catch (UnknownHostException e) { qualifiedHostName = null; } } if (qualifiedHostName != null && Pattern.compile("^\\d+\\.\\d+\\.\\d+\\.\\d+$|:").matcher(qualifiedHostName).find()) { // IP address is not acceptable qualifiedHostName = null; } if (qualifiedHostName == null) { // Give up qualifiedHostName = "unknown-host.unknown-domain"; } else { qualifiedHostName = qualifiedHostName.trim().toLowerCase(); } } if (providedHostName == null) { // Use the host part of the qualified host name final int idx = qualifiedHostName.indexOf('.'); providedHostName = idx == - 1 ? qualifiedHostName : qualifiedHostName.substring(0, idx); } if (providedNodeName == null) { providedNodeName = providedHostName; } return new String[] { providedHostName, qualifiedHostName, providedNodeName }; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/HostName.java000066400000000000000000000067121361511066400270550ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import static java.security.AccessController.doPrivileged; import java.net.InetAddress; import java.net.UnknownHostException; import org.wildfly.common.Assert; /** * Methods for getting the system host name. The host name is detected from the environment, but may be overridden by * use of the {@code jboss.host.name} and/or {@code jboss.qualified.host.name} system properties. * * @author David M. Lloyd */ public final class HostName { private static final Object lock = new Object(); private static volatile String hostName; private static volatile String qualifiedHostName; private static volatile String nodeName; static { String[] names = doPrivileged(new GetHostInfoAction()); hostName = names[0]; qualifiedHostName = names[1]; nodeName = names[2]; } private HostName() { } static InetAddress getLocalHost() throws UnknownHostException { InetAddress addr; try { addr = InetAddress.getLocalHost(); } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404 addr = InetAddress.getByName(null); } return addr; } /** * Get the detected host name. * * @return the detected host name */ public static String getHostName() { return hostName; } /** * Get the detected qualified host name. * * @return the detected qualified host name */ public static String getQualifiedHostName() { return qualifiedHostName; } /** * Get the node name. * * @return the node name */ public static String getNodeName() { return nodeName; } /** * Set the host name. The qualified host name is set directly from the given value; the unqualified host name * is then re-derived from that value. The node name is not changed by this method. * * @param qualifiedHostName the host name */ public static void setQualifiedHostName(final String qualifiedHostName) { Assert.checkNotNullParam("qualifiedHostName", qualifiedHostName); synchronized (lock) { HostName.qualifiedHostName = qualifiedHostName; // Use the host part of the qualified host name final int idx = qualifiedHostName.indexOf('.'); HostName.hostName = idx == -1 ? qualifiedHostName : qualifiedHostName.substring(0, idx); } } /** * Set the node name. * * @param nodeName the node name */ public static void setNodeName(final String nodeName) { Assert.checkNotNullParam("nodeName", nodeName); HostName.nodeName = nodeName; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/Inet.java000066400000000000000000001254111361511066400262340ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import static java.security.AccessController.doPrivileged; import java.lang.reflect.Array; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.security.PrivilegedAction; import java.util.Enumeration; import java.util.regex.Pattern; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; /** * Utilities relating to Internet protocol (a.k.a. "INET" or "IP") address manipulation. * * @author David M. Lloyd */ public final class Inet { private Inet() {} /** * The "any" address for IPv4. */ public static final Inet4Address INET4_ANY = getInet4Address(0, 0, 0, 0); /** * The traditional loopback address for IPv4. */ public static final Inet4Address INET4_LOOPBACK = getInet4Address(127, 0, 0, 1); /** * The broadcast-all address for IPv4. */ public static final Inet4Address INET4_BROADCAST = getInet4Address(255, 255, 255, 255); /** * The "any" address for IPv6. */ public static final Inet6Address INET6_ANY = getInet6Address(0, 0, 0, 0, 0, 0, 0, 0); /** * The loopback address for IPv6. */ public static final Inet6Address INET6_LOOPBACK = getInet6Address(0, 0, 0, 0, 0, 0, 0, 1); /** * Get the optimal string representation of an IP address. For IPv6 addresses, this representation will be * more compact that the default. * * @param inetAddress the address (must not be {@code null}) * @return the string representation (not {@code null}) */ public static String toOptimalString(InetAddress inetAddress) { Assert.checkNotNullParam("inetAddress", inetAddress); return inetAddress instanceof Inet6Address ? toOptimalStringV6(inetAddress.getAddress()) : inetAddress.getHostAddress(); } /** * Get the optimal string representation of the bytes of an IP address. * * @param addressBytes the address bytes (must not be {@code null}) * @return the string representation (not {@code null}) */ public static String toOptimalString(byte[] addressBytes) { Assert.checkNotNullParam("addressBytes", addressBytes); if (addressBytes.length == 4) { return (addressBytes[0] & 0xff) + "." + (addressBytes[1] & 0xff) + "." + (addressBytes[2] & 0xff) + "." + (addressBytes[3] & 0xff); } else if (addressBytes.length == 16) { return toOptimalStringV6(addressBytes); } else { throw CommonMessages.msg.invalidAddressBytes(addressBytes.length); } } /** * Get a string representation of the given address which is suitable for use as the host component of a URL. * * @param inetAddress the address (must not be {@code null}) * @param useHostNameIfPresent {@code true} to preserve the host name string in the address, {@code false} to always give * an IP address string * @return the string representation (not {@code null}) */ public static String toURLString(InetAddress inetAddress, boolean useHostNameIfPresent) { Assert.checkNotNullParam("inetAddress", inetAddress); if (useHostNameIfPresent) { final String hostName = getHostNameIfResolved(inetAddress); if (hostName != null) { if (inetAddress instanceof Inet6Address && isInet6Address(hostName)) { return "[" + hostName + "]"; } else { // return it even if it's an IP address or whatever return hostName; } } } if (inetAddress instanceof Inet6Address) { return "[" + toOptimalString(inetAddress) + "]"; } else { return toOptimalString(inetAddress); } } /** * Get a string representation of the given address bytes which is suitable for use as the host component of a URL. * * @param addressBytes the address bytes (must not be {@code null}) * @return the string representation (not {@code null}) */ public static String toURLString(byte[] addressBytes) { Assert.checkNotNullParam("addressBytes", addressBytes); if (addressBytes.length == 4) { return (addressBytes[0] & 0xff) + "." + (addressBytes[1] & 0xff) + "." + (addressBytes[2] & 0xff) + "." + (addressBytes[3] & 0xff); } else if (addressBytes.length == 16) { return "[" + toOptimalStringV6(addressBytes) + "]"; } else { throw CommonMessages.msg.invalidAddressBytes(addressBytes.length); } } /** * Get the IPv6 equivalent of the given address. If the address is IPv4 then it is returned as a compatibility * address. * * @param inetAddress the address to convert (must not be {@code null}) * @return the converted address (not {@code null}) */ public static Inet6Address toInet6Address(InetAddress inetAddress) { if (inetAddress instanceof Inet6Address) { return (Inet6Address) inetAddress; } else { assert inetAddress instanceof Inet4Address; final byte[] addr = new byte[16]; addr[10] = addr[11] = (byte) 0xff; System.arraycopy(inetAddress.getAddress(), 0, addr, 12, 4); // get unresolved host name try { return Inet6Address.getByAddress(getHostNameIfResolved(inetAddress), addr, 0); } catch (UnknownHostException e) { // not possible throw new IllegalStateException(e); } } } /** * Get the host name of the given address, if it is resolved. Otherwise, return {@code null}. * * @param inetAddress the address to check (must not be {@code null}) * @return the host name, or {@code null} if the address has no host name and is unresolved */ public static String getHostNameIfResolved(InetAddress inetAddress) { Assert.checkNotNullParam("inetAddress", inetAddress); return getHostNameIfResolved(new InetSocketAddress(inetAddress, 0)); } /** * Get the host name of the given address, if it is resolved. Otherwise, return {@code null}. * * @param socketAddress the socket address to check (must not be {@code null}) * @return the host name, or {@code null} if the address has no host name and is unresolved */ public static String getHostNameIfResolved(InetSocketAddress socketAddress) { Assert.checkNotNullParam("socketAddress", socketAddress); final String hostString = socketAddress.getHostString(); final String toString = socketAddress.toString(); final int slash = toString.lastIndexOf('/'); if (slash == 0) { // it might be unresolved or it might explicitly be "" return hostString.isEmpty() ? "" : null; } return hostString; } /** * Get a resolved socket address from the given URI. * * @param uri the URI (must not be {@code null}) * @param defaultPort the default port to use if none is given (must be in the range {@code 1 ≤ n ≤ 65535} * @param addressType the class of the {@code InetAddress} to search for (must not be {@code null}) * @return the socket address, or {@code null} if the URI does not have a host component * @throws UnknownHostException if address resolution failed */ public static InetSocketAddress getResolved(URI uri, int defaultPort, Class addressType) throws UnknownHostException { Assert.checkNotNullParam("uri", uri); Assert.checkMinimumParameter("defaultPort", 1, defaultPort); Assert.checkMaximumParameter("defaultPort", 65535, defaultPort); Assert.checkNotNullParam("addressType", addressType); final InetAddress resolved = getResolvedInetAddress(uri, addressType); if (resolved == null) { return null; } final int uriPort = uri.getPort(); return uriPort != - 1 ? new InetSocketAddress(resolved, uriPort) : new InetSocketAddress(resolved, defaultPort); } /** * Get the resolved socket address from the given URI. * * @param uri the URI (must not be {@code null}) * @param defaultPort the default port to use if none is given (must be in the range {@code 1 ≤ n ≤ 65535} * @return the socket address, or {@code null} if the URI does not have a host component * @throws UnknownHostException if address resolution failed */ public static InetSocketAddress getResolved(URI uri, int defaultPort) throws UnknownHostException { return getResolved(uri, defaultPort, InetAddress.class); } /** * Get an Internet address for a URI destination, resolving the host name if necessary. * * @param uri the destination URI * @param the type of the {@code InetAddress} to search for * @return the address, or {@code null} if no authority is present in the URI * @throws UnknownHostException if the URI host was existent but could not be resolved to a valid address */ public static T getResolvedInetAddress(URI uri, Class addressType) throws UnknownHostException { final String uriHost = uri.getHost(); if (uriHost == null) { return null; } final int length = uriHost.length(); if (length == 0) { return null; } return getAddressByNameAndType(uriHost, addressType); } /** * Get an Internet address for a URI destination, resolving the host name if necessary. * * @param uri the destination URI * @return the address, or {@code null} if no authority is present in the URI * @throws UnknownHostException if the URI host was existent but could not be resolved to a valid address */ public static InetAddress getResolvedInetAddress(URI uri) throws UnknownHostException { return getResolvedInetAddress(uri, InetAddress.class); } /** * Get a copy of the given socket address, but with a resolved address component. * * @param address the (possibly unresolved) address (must not be {@code null}) * @return the resolved address (not {@code null}) * @throws UnknownHostException if address resolution failed */ public static InetSocketAddress getResolved(InetSocketAddress address) throws UnknownHostException { return getResolved(address, InetAddress.class); } /** * Get a copy of the given socket address, but with a resolved address component of the given type. * * @param address the (possibly unresolved) address (must not be {@code null}) * @param addressType the class of the {@code InetAddress} to search for (must not be {@code null}) * @return the resolved address (not {@code null}) * @throws UnknownHostException if address resolution failed, or if no addresses of the given type were found, or * if the given address was already resolved but is not of the given address type */ public static InetSocketAddress getResolved(InetSocketAddress address, Class addressType) throws UnknownHostException { Assert.checkNotNullParam("address", address); Assert.checkNotNullParam("addressType", addressType); if (! address.isUnresolved()) { if (! addressType.isInstance(address.getAddress())) { // the address part does not match throw new UnknownHostException(address.getHostString()); } return address; } return new InetSocketAddress(getAddressByNameAndType(address.getHostString(), addressType), address.getPort()); } /** * Resolve the given host name, returning the first answer with the given address type. * * @param hostName the host name to resolve (must not be {@code null}) * @param addressType the class of the {@code InetAddress} to search for (must not be {@code null}) * @param the type of the {@code InetAddress} to search for * @return the resolved address (not {@code null}) * @throws UnknownHostException if address resolution failed or if no addresses of the given type were found */ public static T getAddressByNameAndType(String hostName, Class addressType) throws UnknownHostException { Assert.checkNotNullParam("hostName", hostName); Assert.checkNotNullParam("addressType", addressType); if (addressType == InetAddress.class) { return addressType.cast(InetAddress.getByName(hostName)); } for (InetAddress inetAddress : InetAddress.getAllByName(hostName)) { if (addressType.isInstance(inetAddress)) { return addressType.cast(inetAddress); } } // no i18n here because this is a "standard" exception throw new UnknownHostException(hostName); } /** * Resolve the given host name, returning all answers with the given address type. * * @param hostName the host name to resolve (must not be {@code null}) * @param addressType the class of the {@code InetAddress} to search for (must not be {@code null}) * @param the type of the {@code InetAddress} to search for * @return the resolved addresses (not {@code null}) * @throws UnknownHostException if address resolution failed or if no addresses of the given type were found */ @SuppressWarnings("unchecked") public static T[] getAllAddressesByNameAndType(String hostName, Class addressType) throws UnknownHostException { Assert.checkNotNullParam("hostName", hostName); Assert.checkNotNullParam("addressType", addressType); if (addressType == InetAddress.class) { // safe because T == InetAddress return (T[]) InetAddress.getAllByName(hostName); } final InetAddress[] addresses = InetAddress.getAllByName(hostName); final int length = addresses.length; int count = 0; for (InetAddress inetAddress : addresses) { if (addressType.isInstance(inetAddress)) { count ++; } } if (count == 0) { // no i18n here because this is a "standard" exception throw new UnknownHostException(hostName); } final T[] newArray = (T[]) Array.newInstance(addressType, count); if (count == length) { //noinspection SuspiciousSystemArraycopy System.arraycopy(addresses, 0, newArray, 0, length); } else { int idx = 0; for (InetAddress inetAddress : addresses) { if (addressType.isInstance(inetAddress)) { newArray[idx] = addressType.cast(inetAddress); } } } return newArray; } /** * Get an IPv4 address from four integer segments. Each segment must be between 0 and 255. * * @param s1 the first segment * @param s2 the second segment * @param s3 the third segment * @param s4 the fourth segment * @return the address (not {@code null}) */ public static Inet4Address getInet4Address(int s1, int s2, int s3, int s4) { byte[] bytes = new byte[4]; Assert.checkMinimumParameter("s1", 0, s1); Assert.checkMaximumParameter("s1", 255, s1); Assert.checkMinimumParameter("s2", 0, s2); Assert.checkMaximumParameter("s2", 255, s2); Assert.checkMinimumParameter("s3", 0, s3); Assert.checkMaximumParameter("s3", 255, s3); Assert.checkMinimumParameter("s4", 0, s4); Assert.checkMaximumParameter("s4", 255, s4); bytes[0] = (byte) s1; bytes[1] = (byte) s2; bytes[2] = (byte) s3; bytes[3] = (byte) s4; try { return (Inet4Address) InetAddress.getByAddress(s1 + "." + s2 + "." + s3 + "." + s4, bytes); } catch (UnknownHostException e) { // not possible throw new IllegalStateException(e); } } /** * Get an IPv6 address from eight integer segments. Each segment must be between 0 and 65535 ({@code 0xffff}). * * @param s1 the first segment * @param s2 the second segment * @param s3 the third segment * @param s4 the fourth segment * @param s5 the fifth segment * @param s6 the sixth segment * @param s7 the seventh segment * @param s8 the eighth segment * @return the address (not {@code null}) */ public static Inet6Address getInet6Address(int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8) { byte[] bytes = new byte[16]; Assert.checkMinimumParameter("s1", 0, s1); Assert.checkMaximumParameter("s1", 0xffff, s1); Assert.checkMinimumParameter("s2", 0, s2); Assert.checkMaximumParameter("s2", 0xffff, s2); Assert.checkMinimumParameter("s3", 0, s3); Assert.checkMaximumParameter("s3", 0xffff, s3); Assert.checkMinimumParameter("s4", 0, s4); Assert.checkMaximumParameter("s4", 0xffff, s4); Assert.checkMinimumParameter("s5", 0, s5); Assert.checkMaximumParameter("s5", 0xffff, s5); Assert.checkMinimumParameter("s6", 0, s6); Assert.checkMaximumParameter("s6", 0xffff, s6); Assert.checkMinimumParameter("s7", 0, s7); Assert.checkMaximumParameter("s7", 0xffff, s7); Assert.checkMinimumParameter("s8", 0, s8); Assert.checkMaximumParameter("s8", 0xffff, s8); bytes[0] = (byte) (s1 >> 8); bytes[1] = (byte) s1; bytes[2] = (byte) (s2 >> 8); bytes[3] = (byte) s2; bytes[4] = (byte) (s3 >> 8); bytes[5] = (byte) s3; bytes[6] = (byte) (s4 >> 8); bytes[7] = (byte) s4; bytes[8] = (byte) (s5 >> 8); bytes[9] = (byte) s5; bytes[10] = (byte) (s6 >> 8); bytes[11] = (byte) s6; bytes[12] = (byte) (s7 >> 8); bytes[13] = (byte) s7; bytes[14] = (byte) (s8 >> 8); bytes[15] = (byte) s8; try { return Inet6Address.getByAddress(toOptimalStringV6(bytes), bytes, 0); } catch (UnknownHostException e) { // not possible throw new IllegalStateException(e); } } /** * Checks whether given String is a valid IPv6 address. * * @param address address textual representation * @return {@code true} if {@code address} is a valid IPv6 address, {@code false} otherwise */ public static boolean isInet6Address(String address) { return parseInet6AddressToBytes(address) != null; } /** * Parse an IPv6 address into an {@code Inet6Address} object. * * @param address the address to parse * @return the parsed address, or {@code null} if the address is not valid */ public static Inet6Address parseInet6Address(String address) { return parseInet6Address(address, null); } /** * Parse an IPv6 address into an {@code Inet6Address} object. * * @param address the address to parse (must not be {@code null}) * @param hostName the host name to use in the resultant object, or {@code null} to use the string representation of * the address * @return the parsed address, or {@code null} if the address is not valid */ public static Inet6Address parseInet6Address(String address, String hostName) { final byte[] bytes = parseInet6AddressToBytes(address); if (bytes == null) { return null; } int scopeId = 0; Inet6Address inetAddress; try { inetAddress = Inet6Address.getByAddress(hostName == null ? toOptimalStringV6(bytes) : hostName, bytes, 0); } catch (UnknownHostException e) { // not possible throw new IllegalStateException(e); } final int pctIdx = address.indexOf('%'); if (pctIdx != -1) { scopeId = getScopeId(address.substring(pctIdx + 1), inetAddress); if (scopeId == 0) { // address not valid after all... return null; } try { inetAddress = Inet6Address.getByAddress(hostName == null ? toOptimalStringV6(bytes) : hostName, bytes, scopeId); } catch (UnknownHostException e) { // not possible throw new IllegalStateException(e); } } return inetAddress; } /** * Parse an IPv6 address into an {@code Inet6Address} object, throwing an exception on failure. * * @param address the address to parse * @return the parsed address (not {@code null}) * @throws IllegalArgumentException if the address is not valid */ public static Inet6Address parseInet6AddressOrFail(String address) { final Inet6Address result = parseInet6Address(address, null); if (result == null) throw CommonMessages.msg.invalidAddress(address); return result; } /** * Parse an IPv6 address into an {@code Inet6Address} object. * * @param address the address to parse (must not be {@code null}) * @param hostName the host name to use in the resultant object, or {@code null} to use the string representation of * the address * @return the parsed address (not {@code null}) * @throws IllegalArgumentException if the address is not valid */ public static Inet6Address parseInet6AddressOrFail(String address, String hostName) { final Inet6Address result = parseInet6Address(address, hostName); if (result == null) throw CommonMessages.msg.invalidAddress(address); return result; } /** * Checks whether given String is a valid IPv4 address. * * @param address address textual representation * @return {@code true} if {@code address} is a valid IPv4 address, {@code false} otherwise */ public static boolean isInet4Address(String address) { return parseInet4AddressToBytes(address) != null; } /** * Parse an IPv4 address into an {@code Inet4Address} object. * * @param address the address to parse * @return the parsed address, or {@code null} if the address is not valid */ public static Inet4Address parseInet4Address(String address) { return parseInet4Address(address, null); } /** * Parse an IPv4 address into an {@code Inet4Address} object. * * @param address the address to parse * @param hostName the host name to use in the resultant object, or {@code null} to use the string representation of * the address * @return the parsed address, or {@code null} if the address is not valid */ public static Inet4Address parseInet4Address(String address, String hostName) { final byte[] bytes = parseInet4AddressToBytes(address); if (bytes == null) { return null; } try { return (Inet4Address) Inet4Address.getByAddress(hostName == null ? toOptimalString(bytes) : hostName, bytes); } catch (UnknownHostException e) { // not possible throw new IllegalStateException(e); } } /** * Parse an IPv4 address into an {@code Inet4Address} object, throwing an exception on failure. * * @param address the address to parse * @return the parsed address (not {@code null}) * @throws IllegalArgumentException if the address is not valid */ public static Inet4Address parseInet4AddressOrFail(String address) { final Inet4Address result = parseInet4Address(address, null); if (result == null) throw CommonMessages.msg.invalidAddress(address); return result; } /** * Parse an IPv4 address into an {@code Inet4Address} object. * * @param address the address to parse (must not be {@code null}) * @param hostName the host name to use in the resultant object, or {@code null} to use the string representation of * the address * @return the parsed address (not {@code null}) * @throws IllegalArgumentException if the address is not valid */ public static Inet4Address parseInet4AddressOrFail(String address, String hostName) { final Inet4Address result = parseInet4Address(address, hostName); if (result == null) throw CommonMessages.msg.invalidAddress(address); return result; } /** * Parse an IP address into an {@code InetAddress} object. * * @param address the address to parse * @return the parsed address, or {@code null} if the address is not valid */ public static InetAddress parseInetAddress(String address) { return parseInetAddress(address, null); } /** * Parse an IP address into an {@code InetAddress} object. * * @param address the address to parse * @param hostName the host name to use in the resultant object, or {@code null} to use the string representation of * the address * @return the parsed address, or {@code null} if the address is not valid */ public static InetAddress parseInetAddress(String address, String hostName) { // simple heuristic if (address.indexOf(':') != -1) { return parseInet6Address(address, hostName); } else { return parseInet4Address(address, hostName); } } /** * Parse an IP address into an {@code InetAddress} object, throwing an exception on failure. * * @param address the address to parse * @return the parsed address (not {@code null}) * @throws IllegalArgumentException if the address is not valid */ public static InetAddress parseInetAddressOrFail(String address) { final InetAddress result = parseInetAddress(address, null); if (result == null) throw CommonMessages.msg.invalidAddress(address); return result; } /** * Parse an IP address into an {@code InetAddress} object. * * @param address the address to parse (must not be {@code null}) * @param hostName the host name to use in the resultant object, or {@code null} to use the string representation of * the address * @return the parsed address (not {@code null}) * @throws IllegalArgumentException if the address is not valid */ public static InetAddress parseInetAddressOrFail(String address, String hostName) { final InetAddress result = parseInetAddress(address, hostName); if (result == null) throw CommonMessages.msg.invalidAddress(address); return result; } /** * Parse a CIDR address into a {@code CidrAddress} object. * * @param address the address to parse * @return the parsed address, or {@code null} if the address is not valid */ public static CidrAddress parseCidrAddress(String address) { final int idx = address.indexOf('/'); if (idx == -1) { return null; } int mask; try { mask = Integer.parseInt(address.substring(idx + 1)); } catch (NumberFormatException e) { return null; } final byte[] addressBytes = parseInetAddressToBytes(address.substring(0, idx)); if (addressBytes == null) { return null; } try { return CidrAddress.create(addressBytes, mask, false); } catch (IllegalArgumentException e) { return null; } } /** * Converts IPv6 address from textual representation to bytes. *

* If given string doesn't represent valid IPv6 address, the method returns {@code null}. * * @param address address textual representation * @return byte array representing the address, or {@code null} if the address is not valid */ public static byte[] parseInet6AddressToBytes(String address) { if (address == null || address.isEmpty()) { return null; } // remove brackets if present if (address.startsWith("[") && address.endsWith("]")) { address = address.substring(1, address.length() - 1); } final int pctIdx = address.indexOf('%'); if (pctIdx != -1) { address = address.substring(0, pctIdx); } String[] segments = address.split(":", 10); // there can be minimum of 2 and maximum of 8 colons, which makes 3 respectively 9 segments if (segments.length > 9 || segments.length < 3) { return null; } // if the first segment is empty, the second one must be too - "::

" if (segments[0].length() == 0 && segments[1].length() != 0) { return null; } // if the last segment is empty, the segment before it must be too - "
::" if (segments[segments.length - 1].length() == 0 && segments[segments.length - 2].length() != 0) { return null; } // validate segments for (int i = 0; i < segments.length; i++) { for (int charIdx = 0; charIdx < segments[i].length(); charIdx++) { char c = segments[i].charAt(charIdx); if (c == '.' && i != segments.length - 1) { return null; // "." is allowed in the last segment only } else if (c != '.' && c != ':' && Character.digit(c, 16) == -1) { return null; // not ".", ":" or a digit } } } // look for an empty segment - "::" int emptyIndex = -1; for (int i = 0; i < segments.length - 1; i++) { if (segments[i].length() == 0) { if (emptyIndex > 0) { return null; // more than one occurrence of "::", invalid address } else if (emptyIndex != 0) { // don't rewrite skipIndex=0, when address starts with "::" emptyIndex = i; } } } boolean containsIPv4 = segments[segments.length - 1].contains("."); int totalSegments = containsIPv4 ? 7 : 8; // if the last segment contains IPv4 notation ("::ffff:192.0.0.1"), the address only has 7 segments if (emptyIndex == -1 && segments.length != totalSegments) { return null; // no substitution but incorrect number of segments } int skipIndex; int skippedSegments; boolean isDefaultRoute = segments.length == 3 && segments[0].isEmpty() && segments[1].isEmpty() && segments[2].isEmpty(); // is address just "::"? if (isDefaultRoute) { skipIndex = 0; skippedSegments = 8; } else if (segments[0].isEmpty() || segments[segments.length - 1].isEmpty()) { // "::" is at the beginning or end of the address skipIndex = emptyIndex; skippedSegments = totalSegments - segments.length + 2; } else if (emptyIndex > -1) { // "::" somewhere in the middle skipIndex = emptyIndex; skippedSegments = totalSegments - segments.length + 1; } else { // no substitution skipIndex = 0; skippedSegments = 0; } ByteBuffer bytes = ByteBuffer.allocate(16); try { // convert segments before "::" for (int i = 0; i < skipIndex; i++) { bytes.putShort(parseHexadecimal(segments[i])); } // fill "0" characters into expanded segments for (int i = skipIndex; i < skipIndex + skippedSegments; i++) { bytes.putShort((short) 0); } // convert segments after "::" for (int i = skipIndex + skippedSegments; i < totalSegments; i++) { int segmentIdx = segments.length - (totalSegments - i); if (containsIPv4 && i == totalSegments - 1) { // we are at the last segment and it contains IPv4 address String[] ipV4Segments = segments[segmentIdx].split("\\."); if (ipV4Segments.length != 4) { return null; // incorrect number of segments in IPv4 } for (int idxV4 = 0; idxV4 < 4; idxV4++) { bytes.put(parseDecimal(ipV4Segments[idxV4])); } } else { bytes.putShort(parseHexadecimal(segments[segmentIdx])); } } return bytes.array(); } catch (NumberFormatException e) { return null; } } /** * Converts IPv4 address from textual representation to bytes. *

* If given string doesn't represent valid IPv4 address, the method returns {@code null}. *

* This only supports decimal notation. * * @param address address textual representation * @return byte array representing the address, or {@code null} if the address is not valid */ public static byte[] parseInet4AddressToBytes(String address) { String[] segments = address.split("\\.", 5); if (segments.length != 4) { return null; // require 4 segments } // validate segments for (int i = 0; i < segments.length; i++) { if (segments[i].length() < 1) { return null; // empty segment } for (int cidx = 0; cidx < segments[i].length(); cidx++) { if (Character.digit(segments[i].charAt(cidx), 10) < 0) { return null; // not a digit } } } byte[] bytes = new byte[4]; try { for (int i = 0; i < segments.length; i++) { bytes[i] = parseDecimal(segments[i]); } return bytes; } catch (NumberFormatException e) { return null; } } /** * Converts an IP address from textual representation to bytes. *

* If given string doesn't represent valid IP address, the method returns {@code null}. * * @param address address textual representation * @return byte array representing the address, or {@code null} if the address is not valid */ public static byte[] parseInetAddressToBytes(String address) { // simple heuristic if (address.indexOf(':') != -1) { return parseInet6AddressToBytes(address); } else { return parseInet4AddressToBytes(address); } } /** * Get the scope ID of the given address (if it is an IPv6 address). * * @return the scope ID, or 0 if there is none or the address is an IPv4 address */ public static int getScopeId(InetAddress address) { return address instanceof Inet6Address ? ((Inet6Address) address).getScopeId() : 0; } private static final Pattern NUMERIC = Pattern.compile("\\d+"); /** * Attempt to get the scope ID of the given string. If the string is numeric then the number is parsed * and returned as-is. If the scope is a string, then a search for the matching network interface will occur. * * @param scopeName the scope number or name as a string (must not be {@code null}) * @return the scope ID, or 0 if no matching scope could be found */ public static int getScopeId(String scopeName) { return getScopeId(scopeName, null); } /** * Attempt to get the scope ID of the given string. If the string is numeric then the number is parsed * and returned as-is. If the scope is a string, then a search for the matching network interface will occur. * * @param scopeName the scope number or name as a string (must not be {@code null}) * @param compareWith the address to compare with, to ensure that the wrong local scope is not selected (may be {@code null}) * @return the scope ID, or 0 if no matching scope could be found */ public static int getScopeId(String scopeName, InetAddress compareWith) { Assert.checkNotNullParam("scopeName", scopeName); if (NUMERIC.matcher(scopeName).matches()) try { return Integer.parseInt(scopeName); } catch (NumberFormatException ignored) { return 0; } final NetworkInterface ni = findInterfaceWithScopeId(scopeName); if (ni == null) return 0; return getScopeId(ni, compareWith); } public static NetworkInterface findInterfaceWithScopeId(String scopeName) { final Enumeration enumeration; try { enumeration = NetworkInterface.getNetworkInterfaces(); } catch (SocketException ignored) { return null; } while (enumeration.hasMoreElements()) { final NetworkInterface net = enumeration.nextElement(); if (net.getName().equals(scopeName)) { return net; } } return null; } public static int getScopeId(NetworkInterface networkInterface) { return getScopeId(networkInterface, null); } public static int getScopeId(NetworkInterface networkInterface, InetAddress compareWith) { Assert.checkNotNullParam("networkInterface", networkInterface); Inet6Address cw6 = compareWith instanceof Inet6Address ? (Inet6Address) compareWith : null; Inet6Address address = doPrivileged((PrivilegedAction) () -> { final Enumeration addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { final InetAddress a = addresses.nextElement(); if (a instanceof Inet6Address) { final Inet6Address a6 = (Inet6Address) a; if (cw6 == null || a6.isLinkLocalAddress() == cw6.isLinkLocalAddress() && a6.isSiteLocalAddress() == cw6.isSiteLocalAddress() ) { return a6; } } } return null; }); return address == null ? 0 : address.getScopeId(); } /** * Extract a base URI from the given scheme and socket address. The address is not resolved. * * @param scheme the URI scheme * @param socketAddress the host socket address * @param defaultPort the protocol default port, or -1 if there is none * @return the URI instance * @throws URISyntaxException if the URI failed to be constructed for some reason */ public static URI getURIFromAddress(String scheme, InetSocketAddress socketAddress, int defaultPort) throws URISyntaxException { String host = getHostNameIfResolved(socketAddress); if (isInet6Address(host)) { host = '[' + host + ']'; } final int port = socketAddress.getPort(); return new URI(scheme, null, host, port == defaultPort ? -1 : port, null, null, null); } private static byte parseDecimal(String number) { int i = Integer.parseInt(number); if (i < 0 || i > 255) { throw new NumberFormatException(); } return (byte) i; } private static short parseHexadecimal(String hexNumber) { int i = Integer.parseInt(hexNumber, 16); if (i > 0xffff) { throw new NumberFormatException(); } return (short) i; } private static String toOptimalStringV6(final byte[] bytes) { final int[] segments = new int[8]; for (int i = 0; i < 8; i ++) { segments[i] = (bytes[i << 1] & 0xff) << 8 | bytes[(i << 1) + 1] & 0xff; } // now loop through the segments and add them as optimally as possible final StringBuilder b = new StringBuilder(); for (int i = 0; i < 8; i ++) { if (segments[i] == 0) { if (i == 7) { b.append('0'); } else { // possible to collapse it i++; if (segments[i] == 0) { // yup b.append(':').append(':'); for (i++; i < 8; i++) { if (segments[i] == 0xffff && b.length() == 2) { b.append("ffff"); if (i == 5) { // it's an IPv4 compat address. b.append(':').append(bytes[12] & 0xff).append('.').append(bytes[13] & 0xff).append('.').append(bytes[14] & 0xff).append('.').append(bytes[15] & 0xff); i = 8; } else if (i == 4 && segments[5] == 0) { // it's a SIIT address. b.append(":0:").append(bytes[12] & 0xff).append('.').append(bytes[13] & 0xff).append('.').append(bytes[14] & 0xff).append('.').append(bytes[15] & 0xff); i = 8; } else { // finally break and do the rest normally for (i++; i < 8; i++) { b.append(':').append(Integer.toHexString(segments[i])); } } } else if (segments[i] != 0) { // finally break and do the rest normally b.append(Integer.toHexString(segments[i])); for (i++; i < 8; i++) { b.append(':').append(Integer.toHexString(segments[i])); } } } } else { // no, just a single 0 in isolation doesn't get collapsed if (i > 1) b.append(':'); b.append('0').append(':').append(Integer.toHexString(segments[i])); } } } else { if (i > 0) b.append(':'); b.append(Integer.toHexString(segments[i])); } } return b.toString(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/Substitutions.java000066400000000000000000000116351361511066400302360ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import org.graalvm.nativeimage.StackValue; import org.graalvm.nativeimage.c.CContext; import org.graalvm.nativeimage.c.function.CFunction; import org.graalvm.nativeimage.c.type.CCharPointer; import org.graalvm.nativeimage.c.type.CTypeConversion; import org.graalvm.word.UnsignedWord; import org.graalvm.word.WordFactory; /** */ final class Substitutions { @TargetClass(className = "org.wildfly.common.net.GetHostInfoAction") static final class Target_org_wildfly_common_net_GetHostInfoAction { @Substitute public String[] run() { // still allow host name to be overridden String qualifiedHostName = System.getProperty("jboss.qualified.host.name"); String providedHostName = System.getProperty("jboss.host.name"); String providedNodeName = System.getProperty("jboss.node.name"); if (qualifiedHostName == null) { // if host name is specified, don't pick a qualified host name that isn't related to it qualifiedHostName = providedHostName; if (qualifiedHostName == null) { // query the operating system CCharPointer nameBuf = StackValue.get(ProcessSubstitutions.SIZE); // should be more than enough int res = NativeInfo.gethostname(nameBuf, WordFactory.unsigned(ProcessSubstitutions.SIZE)); if (res != -1 && res > 0) { if (res == ProcessSubstitutions.SIZE) { // null-terminate a really long name nameBuf.write(ProcessSubstitutions.SIZE - 1, (byte) 0); } qualifiedHostName = CTypeConversion.toJavaString(nameBuf); } } if (qualifiedHostName == null) { // POSIX-like OSes including Mac should have this set qualifiedHostName = System.getenv("HOSTNAME"); } if (qualifiedHostName == null) { // Certain versions of Windows qualifiedHostName = System.getenv("COMPUTERNAME"); } if (qualifiedHostName == null) { try { qualifiedHostName = HostName.getLocalHost().getHostName(); } catch (UnknownHostException e) { qualifiedHostName = null; } } if (qualifiedHostName != null && (Inet.isInet4Address(qualifiedHostName) || Inet.isInet6Address(qualifiedHostName))) { // IP address is not acceptable qualifiedHostName = null; } if (qualifiedHostName == null) { // Give up qualifiedHostName = "unknown-host.unknown-domain"; } else { qualifiedHostName = qualifiedHostName.trim().toLowerCase(); } } if (providedHostName == null) { // Use the host part of the qualified host name final int idx = qualifiedHostName.indexOf('.'); providedHostName = idx == - 1 ? qualifiedHostName : qualifiedHostName.substring(0, idx); } if (providedNodeName == null) { providedNodeName = providedHostName; } return new String[] { providedHostName, qualifiedHostName, providedNodeName }; } } @CContext(NativeInfoDirectives.class) static final class NativeInfo { @CFunction static native int gethostname(CCharPointer nameBuf, UnsignedWord /* size_t */ len); } static final class NativeInfoDirectives implements CContext.Directives { public List getHeaderFiles() { return Collections.singletonList(""); } } static final class ProcessSubstitutions { static final int SIZE = 512; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/URIs.java000066400000000000000000000032201361511066400261500ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import java.net.URI; /** * URI-specific utilities. */ public final class URIs { private URIs() {} /** * Get the user name information from a URI, if any. * * @param uri the URI * @return the user name, or {@code null} if the URI did not contain a recoverable user name */ public static String getUserFromURI(URI uri) { String userInfo = uri.getUserInfo(); if (userInfo == null && "domain".equals(uri.getScheme())) { final String ssp = uri.getSchemeSpecificPart(); final int at = ssp.lastIndexOf('@'); if (at == -1) { return null; } userInfo = ssp.substring(0, at); } if (userInfo != null) { final int colon = userInfo.indexOf(':'); if (colon != -1) { userInfo = userInfo.substring(0, colon); } } return userInfo; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/net/package-info.java000066400000000000000000000015661361511066400276650ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Utilities relating abstractly to network-related activities. * * @author David M. Lloyd */ package org.wildfly.common.net; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/os/000077500000000000000000000000001361511066400243215ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/os/GetProcessInfoAction.java000066400000000000000000000104461361511066400312210ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; import static java.lang.Math.max; import java.io.File; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.security.PrivilegedAction; /** */ final class GetProcessInfoAction implements PrivilegedAction { GetProcessInfoAction() { } public Object[] run() { long pid = - 1L; String processName = ""; final RuntimeMXBean runtime; try { runtime = ManagementFactory.getPlatformMXBean(RuntimeMXBean.class); } catch (Exception ignored) { return new Object[] { Long.valueOf(pid), processName }; } // TODO: on Java 9, use ProcessHandle.current().pid() // Process ID final String name = runtime.getName(); if (name != null) { final int idx = name.indexOf('@'); if (idx != - 1) try { pid = Long.parseLong(name.substring(0, idx)); } catch (NumberFormatException ignored) { } } // TODO: on Java 9, maybe ProcessHandle.current().info().commandLine() or .command() instead // Process name processName = System.getProperty("jboss.process.name"); if (processName == null) { final String classPath = System.getProperty("java.class.path"); final String commandLine = System.getProperty("sun.java.command"); if (commandLine != null) { if (classPath != null && commandLine.startsWith(classPath)) { // OK probably a JAR launch final int sepIdx = classPath.lastIndexOf(File.separatorChar); if (sepIdx > 0) { processName = classPath.substring(sepIdx + 1); } else { processName = classPath; } } else { // probably a class name // it might be a class name followed by args, like org.foo.Bar -baz -zap int firstSpace = commandLine.indexOf(' '); final String className; if (firstSpace > 0) { className = commandLine.substring(0, firstSpace); } else { className = commandLine; } // no args now int lastDot = className.lastIndexOf('.', firstSpace); if (lastDot > 0) { processName = className.substring(lastDot + 1); if (processName.equalsIgnoreCase("jar") || processName.equalsIgnoreCase("ȷar")) { // oops, I guess it was a JAR name... let's just take a guess then int secondLastDot = className.lastIndexOf('.', lastDot - 1); int sepIdx = className.lastIndexOf(File.separatorChar); int lastSep = secondLastDot == - 1 ? sepIdx : sepIdx == - 1 ? secondLastDot : max(sepIdx, secondLastDot); if (lastSep > 0) { processName = className.substring(lastSep + 1); } else { processName = className; } } } else { processName = className; } } } } if (processName == null) { processName = ""; } return new Object[] { Long.valueOf(pid), processName }; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/os/Process.java000066400000000000000000000034551361511066400266110ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; import static java.security.AccessController.doPrivileged; /** * Utilities for getting information about the current process. * * @author David M. Lloyd */ public final class Process { private static final long processId; private static final String processName; static { Object[] array = doPrivileged(new GetProcessInfoAction()); processId = ((Long) array[0]).longValue(); processName = (String) array[1]; } private Process() { } /** * Get the name of this process. If the process name is not known, then "<unknown>" is returned. * * @return the process name (not {@code null}) */ public static String getProcessName() { return processName; } /** * Get the ID of this process. This is the operating system specific PID. If the PID cannot be determined, * -1 is returned. * * @return the ID of this process, or -1 if it cannot be determined */ public static long getProcessId() { return processId; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/os/ProcessRedirect.java000066400000000000000000000034511361511066400302670ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; import java.io.File; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Locale; /** * Process redirections that work on all JDK versions. */ public final class ProcessRedirect { private ProcessRedirect() {} /** * Get the "discard" process redirection target. * * @return the discarding redirection target */ public static ProcessBuilder.Redirect discard() { return ProcessBuilder.Redirect.to(new File(isWindows() ? "NUL" : "/dev/null")); } private static boolean isWindows() { final SecurityManager sm = System.getSecurityManager(); return (sm == null ? getOsName() : getOsNamePrivileged()).toLowerCase(Locale.ROOT).contains("windows"); } private static String getOsNamePrivileged() { return AccessController.doPrivileged(new PrivilegedAction() { public String run() { return getOsName(); } }); } private static String getOsName() { return System.getProperty("os.name", "unknown"); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/os/Substitutions.java000066400000000000000000000035651361511066400300740ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; import java.io.File; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import org.graalvm.nativeimage.ProcessProperties; final class Substitutions { @TargetClass(className = "org.wildfly.common.os.GetProcessInfoAction") static final class Target_org_wildfly_common_os_GetProcessInfoAction { @Substitute public Object[] run() { return new Object[] { Long.valueOf(ProcessProperties.getProcessID() & 0xffff_ffffL), ProcessUtils.getProcessName() }; } } static final class ProcessUtils { static String getProcessName() { String name = System.getProperty("jboss.process.name"); if (name == null) { String exeName = ProcessProperties.getExecutableName(); if (! exeName.isEmpty()) { int idx = exeName.lastIndexOf(File.separatorChar); name = idx == -1 ? exeName : idx == exeName.length() - 1 ? null : exeName.substring(idx + 1); } } if (name == null) { name = ""; } return name; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/os/package-info.java000066400000000000000000000015661361511066400275200ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Utilities related to the operating system and current process. * * @author David M. Lloyd */ package org.wildfly.common.os; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/package-info.java000066400000000000000000000017771361511066400271030ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Common classes for a variety of purposes. Use {@link org.wildfly.common.Assert Assert} for common checks and * assertions. Use {@link org.wildfly.common.Factory Factory} as a generalized factory type. * * @author David M. Lloyd */ package org.wildfly.common;wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/000077500000000000000000000000001361511066400244545ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/CleanerReference.java000066400000000000000000000034471361511066400305170ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * A special version of {@link PhantomReference} that is strongly retained until it is reaped by the collection thread. * * @author David M. Lloyd */ public class CleanerReference extends PhantomReference { private static final Set> set = Collections.newSetFromMap(new ConcurrentHashMap, Boolean>()); /** * Construct a new instance with a reaper. * * @param referent the referent * @param attachment the attachment * @param reaper the reaper to use */ public CleanerReference(final T referent, final A attachment, final Reaper reaper) { super(referent, attachment, reaper); set.add(this); } void clean() { set.remove(this); } public final int hashCode() { return super.hashCode(); } public final boolean equals(final Object obj) { return super.equals(obj); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/Log.java000066400000000000000000000025621361511066400260450ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * @author David M. Lloyd */ @MessageLogger(projectCode = "COM", length = 5) interface Log { Log log = Logger.getMessageLogger(Log.class, "org.wildfly.common.ref"); // 3000-3099 reserved for reference queue logging @LogMessage(level = Logger.Level.DEBUG) @Message(id = 3000, value = "Reaping a reference failed") void reapFailed(@Cause Throwable cause); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/PhantomReference.java000066400000000000000000000045621361511066400305530ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import java.lang.ref.ReferenceQueue; /** * A reapable phantom reference with an attachment. If a {@link Reaper} is given, then it will be used to asynchronously * clean up the referent. * * @param the reference value type * @param the attachment type * * @see java.lang.ref.PhantomReference * * @author David M. Lloyd */ public class PhantomReference extends java.lang.ref.PhantomReference implements Reference, Reapable { private final A attachment; private final Reaper reaper; /** * Construct a new instance with an explicit reference queue. * * @param referent the referent * @param attachment the attachment * @param q the reference queue to use */ public PhantomReference(final T referent, final A attachment, final ReferenceQueue q) { super(referent, q); this.attachment = attachment; reaper = null; } /** * Construct a new instance with a reaper. * * @param referent the referent * @param attachment the attachment * @param reaper the reaper to use */ public PhantomReference(final T referent, final A attachment, final Reaper reaper) { super(referent, References.ReaperThread.REAPER_QUEUE); this.reaper = reaper; this.attachment = attachment; } public A getAttachment() { return attachment; } public Type getType() { return Type.PHANTOM; } public Reaper getReaper() { return reaper; } public String toString() { return "phantom reference"; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/Reapable.java000066400000000000000000000021561361511066400270360ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; /** * A reference which is reapable (can be automatically collected). * * @param the reference type * @param the reference attachment type * * @apiviz.exclude * * @author David M. Lloyd */ interface Reapable { /** * Get the associated reaper. * * @return the reaper */ Reaper getReaper(); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/Reaper.java000066400000000000000000000021431361511066400265350ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; /** * A cleaner for a dead object. * * @param the reference type * @param the reference attachment type * * @author David M. Lloyd */ public interface Reaper { /** * Perform the cleanup action for a reference. * * @param reference the reference */ void reap(Reference reference); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/Reference.java000066400000000000000000000100531361511066400272140ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import java.util.EnumSet; /** * An enhanced reference type with a type-safe attachment. * * @param the reference value type * @param the attachment type * * @see java.lang.ref.Reference * * @author David M. Lloyd */ public interface Reference { /** * Get the value, or {@code null} if the reference has been cleared. * * @return the value */ T get(); /** * Get the attachment, if any. * * @return the attachment */ A getAttachment(); /** * Clear the reference. */ void clear(); /** * Get the type of the reference. * * @return the type */ Type getType(); /** * A reference type. * * @apiviz.exclude */ enum Type { /** * A strong reference. */ STRONG, /** * A weak reference. */ WEAK, /** * A phantom reference. */ PHANTOM, /** * A soft reference. */ SOFT, /** * A {@code null} reference. */ NULL, ; private static final int fullSize = values().length; /** * Determine whether the given set is fully populated (or "full"), meaning it contains all possible values. * * @param set the set * * @return {@code true} if the set is full, {@code false} otherwise */ public static boolean isFull(final EnumSet set) { return set != null && set.size() == fullSize; } /** * Determine whether this instance is equal to one of the given instances. * * @param v1 the first instance * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final Type v1) { return this == v1; } /** * Determine whether this instance is equal to one of the given instances. * * @param v1 the first instance * @param v2 the second instance * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final Type v1, final Type v2) { return this == v1 || this == v2; } /** * Determine whether this instance is equal to one of the given instances. * * @param v1 the first instance * @param v2 the second instance * @param v3 the third instance * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final Type v1, final Type v2, final Type v3) { return this == v1 || this == v2 || this == v3; } /** * Determine whether this instance is equal to one of the given instances. * * @param values the possible values * * @return {@code true} if one of the instances matches this one, {@code false} otherwise */ public boolean in(final Type... values) { if (values != null) for (Type value : values) { if (this == value) return true; } return false; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/References.java000066400000000000000000000171471361511066400274120ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import static java.security.AccessController.doPrivileged; import java.lang.ref.ReferenceQueue; import java.security.PrivilegedAction; import java.util.concurrent.atomic.AtomicInteger; import org.wildfly.common.Assert; /** * A set of utility methods for reference types. */ public final class References { private References() { } private static final Reference NULL = new Reference() { public Object get() { return null; } public Object getAttachment() { return null; } public void clear() { } public Type getType() { return Type.NULL; } public String toString() { return "NULL reference"; } }; static final class ReaperThread extends Thread { static final ReferenceQueue REAPER_QUEUE = new ReferenceQueue(); static { final AtomicInteger cnt = new AtomicInteger(1); final PrivilegedAction action = () -> { final ReaperThread thr = new ReaperThread(); thr.setName("Reference Reaper #" + cnt.getAndIncrement()); thr.setDaemon(true); thr.start(); return null; }; for (int i = 0; i < 3; i ++) { doPrivileged(action); } } public void run() { for (;;) try { final java.lang.ref.Reference ref = REAPER_QUEUE.remove(); if (ref instanceof CleanerReference) { ((CleanerReference) ref).clean(); } if (ref instanceof Reapable) { reap((Reapable) ref); } } catch (InterruptedException ignored) { // we consume interrupts. } catch (Throwable cause) { Log.log.reapFailed(cause); } } @SuppressWarnings({ "unchecked" }) private static void reap(final Reapable reapable) { reapable.getReaper().reap((Reference) reapable); } } /** * Create a reference of a given type with the provided value and attachment. If the reference type is * {@link Reference.Type#STRONG} or {@link Reference.Type#NULL} then the reaper argument is ignored. If * the reference type is {@link Reference.Type#NULL} then the value and attachment arguments are ignored. * * @param type the reference type * @param value the reference value * @param attachment the attachment value * @param reaper the reaper to use, if any * @param the reference value type * @param the reference attachment type * @return the reference */ public static Reference create(Reference.Type type, T value, A attachment, Reaper reaper) { Assert.checkNotNullParam("type", type); if (value == null) return getNullReference(); switch (type) { case STRONG: return new StrongReference(value, attachment); case WEAK: return new WeakReference(value, attachment, reaper); case PHANTOM: return new PhantomReference(value, attachment, reaper); case SOFT: return new SoftReference(value, attachment, reaper); case NULL: return getNullReference(); default: throw Assert.impossibleSwitchCase(type); } } /** * Create a reference of a given type with the provided value and attachment. If the reference type is * {@link Reference.Type#STRONG} or {@link Reference.Type#NULL} then the reference queue argument is ignored. If * the reference type is {@link Reference.Type#NULL} then the value and attachment arguments are ignored. * * @param type the reference type * @param value the reference value * @param attachment the attachment value * @param referenceQueue the reference queue to use, if any * @param the reference value type * @param the reference attachment type * @return the reference */ public static Reference create(Reference.Type type, T value, A attachment, ReferenceQueue referenceQueue) { Assert.checkNotNullParam("type", type); if (referenceQueue == null) return create(type, value, attachment); if (value == null) return getNullReference(); switch (type) { case STRONG: return new StrongReference(value, attachment); case WEAK: return new WeakReference(value, attachment, referenceQueue); case PHANTOM: return new PhantomReference(value, attachment, referenceQueue); case SOFT: return new SoftReference(value, attachment, referenceQueue); case NULL: return getNullReference(); default: throw Assert.impossibleSwitchCase(type); } } /** * Create a reference of a given type with the provided value and attachment. If the reference type is * {@link Reference.Type#PHANTOM} then this method will return a {@code null} reference because * such references are not constructable without a queue or reaper. If the reference type is * {@link Reference.Type#NULL} then the value and attachment arguments are ignored. * * @param type the reference type * @param value the reference value * @param attachment the attachment value * @param the reference value type * @param the reference attachment type * @return the reference */ public static Reference create(Reference.Type type, T value, A attachment) { Assert.checkNotNullParam("type", type); if (value == null) return getNullReference(); switch (type) { case STRONG: return new StrongReference(value, attachment); case WEAK: return new WeakReference(value, attachment); case PHANTOM: return getNullReference(); case SOFT: return new SoftReference(value, attachment); case NULL: return getNullReference(); default: throw Assert.impossibleSwitchCase(type); } } /** * Get a null reference. This reference type is always cleared and does not retain an attachment; as such * there is only one single instance of it. * * @param the reference value type * @param the attachment value type * @return the null reference */ @SuppressWarnings({ "unchecked" }) public static Reference getNullReference() { return (Reference) NULL; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/SoftReference.java000066400000000000000000000055101361511066400300520ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import java.lang.ref.ReferenceQueue; /** * A reapable soft reference with an attachment. If a {@link Reaper} is given, then it will be used to asynchronously * clean up the referent. * * @param the reference value type * @param the attachment type * * @see java.lang.ref.SoftReference * * @author David M. Lloyd */ public class SoftReference extends java.lang.ref.SoftReference implements Reference, Reapable { private final A attachment; private final Reaper reaper; /** * Construct a new instance. * * @param referent the referent */ public SoftReference(final T referent) { this(referent, null, (ReferenceQueue) null); } /** * Construct a new instance. * * @param referent the referent * @param attachment the attachment */ public SoftReference(final T referent, final A attachment) { this(referent, attachment, (ReferenceQueue) null); } /** * Construct a new instance with an explicit reference queue. * * @param referent the referent * @param attachment the attachment * @param q the reference queue to use */ public SoftReference(final T referent, final A attachment, final ReferenceQueue q) { super(referent, q); reaper = null; this.attachment = attachment; } /** * Construct a new instance with a reaper. * * @param referent the referent * @param attachment the attachment * @param reaper the reaper to use */ public SoftReference(final T referent, final A attachment, final Reaper reaper) { super(referent, References.ReaperThread.REAPER_QUEUE); this.reaper = reaper; this.attachment = attachment; } public Reaper getReaper() { return reaper; } public A getAttachment() { return attachment; } public Type getType() { return Type.SOFT; } public String toString() { return "soft reference to " + String.valueOf(get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/StrongReference.java000066400000000000000000000036231361511066400304160ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; /** * A strong reference with an attachment. Since strong references are always reachable, a reaper may not be used. * * @param the reference value type * @param the attachment type * * @author David M. Lloyd */ public class StrongReference implements Reference { private volatile T referent; private final A attachment; /** * Construct a new instance. * * @param referent the referent * @param attachment the attachment */ public StrongReference(final T referent, final A attachment) { this.referent = referent; this.attachment = attachment; } /** * Construct a new instance. * * @param referent the referent */ public StrongReference(final T referent) { this(referent, null); } public T get() { return referent; } public void clear() { referent = null; } public A getAttachment() { return attachment; } public Type getType() { return Type.STRONG; } public String toString() { return "strong reference to " + String.valueOf(get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/WeakReference.java000066400000000000000000000054761361511066400300410ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.ref; import java.lang.ref.ReferenceQueue; /** * A reapable weak reference with an attachment. If a {@link Reaper} is given, then it will be used to asynchronously * clean up the referent. * * @param the reference value type * @param the attachment type * * @see java.lang.ref.WeakReference * * @author David M. Lloyd */ public class WeakReference extends java.lang.ref.WeakReference implements Reference, Reapable { private final A attachment; private final Reaper reaper; /** * Construct a new instance. * * @param referent the referent */ public WeakReference(final T referent) { this(referent, null, (Reaper) null); } /** * Construct a new instance. * * @param referent the referent * @param attachment the attachment */ public WeakReference(final T referent, final A attachment) { this(referent, attachment, (Reaper) null); } /** * Construct a new instance with an explicit reference queue. * * @param referent the referent * @param attachment the attachment * @param q the reference queue to use */ public WeakReference(final T referent, final A attachment, final ReferenceQueue q) { super(referent, q); this.attachment = attachment; reaper = null; } /** * Construct a new instance with a reaper. * * @param referent the referent * @param attachment the attachment * @param reaper the reaper to use */ public WeakReference(final T referent, final A attachment, final Reaper reaper) { super(referent, References.ReaperThread.REAPER_QUEUE); this.attachment = attachment; this.reaper = reaper; } public A getAttachment() { return attachment; } public Type getType() { return Type.WEAK; } public Reaper getReaper() { return reaper; } public String toString() { return "weak reference to " + String.valueOf(get()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/ref/package-info.java000066400000000000000000000017501361511066400276460ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes which implement reference types which can be cleaned up automatically by a background thread. See * {@link org.wildfly.common.ref.Reference Reference} and its subtypes, and {@link org.wildfly.common.ref.Reaper Reaper} for more information. */ package org.wildfly.common.ref;wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/rpc/000077500000000000000000000000001361511066400244645ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/rpc/IdentityIntMap.java000066400000000000000000000153101361511066400302310ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.rpc; import java.util.Arrays; /** * An efficient identity object map whose keys are objects and whose values are {@code int}s. */ final class IdentityIntMap implements Cloneable { private int[] values; private Object[] keys; private int count; private int resizeCount; /** * Construct a new instance with the given initial capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor */ public IdentityIntMap(int initialCapacity, final float loadFactor) { if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity must be > 0"); } if (loadFactor <= 0.0f || loadFactor >= 1.0f) { throw new IllegalArgumentException("loadFactor must be > 0.0 and < 1.0"); } if (initialCapacity < 16) { initialCapacity = 16; } else { // round up final int c = Integer.highestOneBit(initialCapacity) - 1; initialCapacity = Integer.highestOneBit(initialCapacity + c); } keys = new Object[initialCapacity]; values = new int[initialCapacity]; resizeCount = (int) ((double) initialCapacity * (double) loadFactor); } /** * Clone this map. * * @return a cloned map */ @SuppressWarnings({ "unchecked" }) public IdentityIntMap clone() { try { final IdentityIntMap clone = (IdentityIntMap) super.clone(); clone.values = values.clone(); clone.keys = keys.clone(); return clone; } catch (CloneNotSupportedException e) { throw new IllegalStateException(); } } /** * Construct a new instance with the given load factor and an initial capacity of 64. * * @param loadFactor the load factor */ public IdentityIntMap(final float loadFactor) { this(64, loadFactor); } /** * Construct a new instance with the given initial capacity and a load factor of {@code 0.5}. * * @param initialCapacity the initial capacity */ public IdentityIntMap(final int initialCapacity) { this(initialCapacity, 0.5f); } /** * Construct a new instance with an initial capacity of 64 and a load factor of {@code 0.5}. */ public IdentityIntMap() { this(0.5f); } /** * Get a value from the map. * * @param key the key * @param defVal the value to return if the key is not found * @return the map value at the given key, or the value of {@code defVal} if it's not found */ public int get(T key, int defVal) { final Object[] keys = this.keys; final int mask = keys.length - 1; int hc = System.identityHashCode(key) & mask; Object v; for (;;) { v = keys[hc]; if (v == key) { return values[hc]; } if (v == null) { // not found return defVal; } hc = (hc + 1) & mask; } } /** * Put a value into the map. Any previous mapping is discarded silently. * * @param key the key * @param value the value to store */ public void put(T key, int value) { final Object[] keys = this.keys; final int mask = keys.length - 1; final int[] values = this.values; Object v; int hc = System.identityHashCode(key) & mask; for (int idx = hc;; idx = hc++ & mask) { v = keys[idx]; if (v == null) { keys[idx] = key; values[idx] = value; if (++count > resizeCount) { resize(); } return; } if (v == key) { values[idx] = value; return; } } } private void resize() { final Object[] oldKeys = keys; final int oldsize = oldKeys.length; final int[] oldValues = values; if (oldsize >= 0x40000000) { throw new IllegalStateException("Table full"); } final int newsize = oldsize << 1; final int mask = newsize - 1; final Object[] newKeys = new Object[newsize]; final int[] newValues = new int[newsize]; keys = newKeys; values = newValues; if ((resizeCount <<= 1) == 0) { resizeCount = Integer.MAX_VALUE; } for (int oi = 0; oi < oldsize; oi ++) { final Object key = oldKeys[oi]; if (key != null) { int ni = System.identityHashCode(key) & mask; for (;;) { final Object v = newKeys[ni]; if (v == null) { // found newKeys[ni] = key; newValues[ni] = oldValues[oi]; break; } ni = (ni + 1) & mask; } } } } public void clear() { Arrays.fill(keys, null); count = 0; } /** * Get a string summary representation of this map. * * @return a string representation */ public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Map length = ").append(keys.length).append(", count = ").append(count).append(", resize count = ").append(resizeCount).append('\n'); for (int i = 0; i < keys.length; i ++) { builder.append('[').append(i).append("] = "); if (keys[i] != null) { final int hc = System.identityHashCode(keys[i]); builder.append("{ ").append(keys[i]).append(" (hash ").append(hc).append(", modulus ").append(hc % keys.length).append(") => ").append(values[i]).append(" }"); } else { builder.append("(blank)"); } builder.append('\n'); } return builder.toString(); } }wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/rpc/RemoteExceptionCause.java000066400000000000000000000674221361511066400314350ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.rpc; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; import org.wildfly.common.Assert; import org.wildfly.common._private.CommonMessages; /** * A remote exception cause. Instances of this class are intended to aid with diagnostics and are not intended to be * directly thrown. They may be added to other exception types as a cause or suppressed throwable. * * @author David M. Lloyd */ public final class RemoteExceptionCause extends Throwable { private static final long serialVersionUID = 7849011228540958997L; private static final ClassValue>> fieldGetterValue = new ClassValue>>() { protected Function> computeValue(final Class type) { final Field[] fields = type.getFields(); final int length = fields.length; int i, j; for (i = 0, j = 0; i < length; i ++) { if ((fields[i].getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) == Modifier.PUBLIC) { fields[j ++] = fields[i]; } } final int finalLength = j; final Field[] finalFields; if (j < i) { finalFields = Arrays.copyOf(fields, j); } else { finalFields = fields; } if (finalLength == 0) { return t -> Collections.emptyMap(); } else if (finalLength == 1) { final Field field = finalFields[0]; return t -> { try { return Collections.singletonMap(field.getName(), String.valueOf(field.get(t))); } catch (IllegalAccessException e) { // impossible throw new IllegalStateException(e); } }; } return t -> { Map map = new TreeMap<>(); for (Field field : finalFields) { try { map.put(field.getName(), String.valueOf(field.get(t))); } catch (IllegalAccessException e) { // impossible throw new IllegalStateException(e); } } return Collections.unmodifiableMap(map); }; } }; private static final StackTraceElement[] EMPTY_STACK = new StackTraceElement[0]; private final String exceptionClassName; private final Map fields; private transient String toString; RemoteExceptionCause(final String msg, final RemoteExceptionCause cause, final String exceptionClassName, final Map fields, boolean cloneFields) { super(msg); if (cause != null) { initCause(cause); } Assert.checkNotNullParam("exceptionClassName", exceptionClassName); this.exceptionClassName = exceptionClassName; if (cloneFields) { final Iterator> iterator = fields.entrySet().iterator(); if (! iterator.hasNext()) { this.fields = Collections.emptyMap(); } else { final Map.Entry e1 = iterator.next(); final String name1 = e1.getKey(); final String value1 = e1.getValue(); if (name1 == null || value1 == null) { throw CommonMessages.msg.cannotContainNullFieldNameOrValue(); } if (! iterator.hasNext()) { this.fields = Collections.singletonMap(name1, value1); } else { Map map = new TreeMap<>(); map.put(name1, value1); do { final Map.Entry next = iterator.next(); map.put(next.getKey(), next.getValue()); } while (iterator.hasNext()); this.fields = Collections.unmodifiableMap(map); } } } else { this.fields = fields; } } /** * Constructs a new {@code RemoteExceptionCause} instance with an initial message. No * cause is specified. * * @param msg the message * @param exceptionClassName the name of the exception's class (must not be {@code null}) */ public RemoteExceptionCause(final String msg, final String exceptionClassName) { this(msg, null, exceptionClassName, Collections.emptyMap(), false); } /** * Constructs a new {@code RemoteExceptionCause} instance with an initial message and cause. * * @param msg the message * @param cause the cause * @param exceptionClassName the name of the exception's class (must not be {@code null}) */ public RemoteExceptionCause(final String msg, final RemoteExceptionCause cause, final String exceptionClassName) { this(msg, cause, exceptionClassName, Collections.emptyMap(), false); } /** * Constructs a new {@code RemoteExceptionCause} instance with an initial message. No * cause is specified. * * @param msg the message * @param exceptionClassName the name of the exception's class (must not be {@code null}) * @param fields the public fields of the remote exception (must not be {@code null}) */ public RemoteExceptionCause(final String msg, final String exceptionClassName, final Map fields) { this(msg, null, exceptionClassName, fields, true); } /** * Constructs a new {@code RemoteExceptionCause} instance with an initial message and cause. * * @param msg the message * @param cause the cause * @param exceptionClassName the name of the exception's class (must not be {@code null}) * @param fields the public fields of the remote exception (must not be {@code null}) */ public RemoteExceptionCause(final String msg, final RemoteExceptionCause cause, final String exceptionClassName, final Map fields) { this(msg, cause, exceptionClassName, fields, true); } /** * Get a remote exception cause for the given {@link Throwable}. All of the cause and suppressed exceptions will * also be converted. * * @param t the throwable, or {@code null} * @return the remote exception cause, or {@code null} if {@code null} was passed in */ public static RemoteExceptionCause of(Throwable t) { return of(t, new IdentityHashMap<>()); } private static RemoteExceptionCause of(Throwable t, IdentityHashMap seen) { if (t == null) return null; if (t instanceof RemoteExceptionCause) { return (RemoteExceptionCause) t; } else { final RemoteExceptionCause existing = seen.get(t); if (existing != null) { return existing; } final RemoteExceptionCause e = new RemoteExceptionCause(t.getMessage(), t.getClass().getName(), fieldGetterValue.get(t.getClass()).apply(t)); e.setStackTrace(t.getStackTrace()); seen.put(t, e); final Throwable cause = t.getCause(); if (cause != null) e.initCause(of(cause, seen)); for (Throwable throwable : t.getSuppressed()) { e.addSuppressed(of(throwable, seen)); } return e; } } /** * Convert this remote exception cause to a plain throwable for sending to peers which use serialization and do not * have this class present. Note that this does not recursively apply; normally, a serialization framework will * handle the recursive application of this operation through object resolution. * * @return the throwable (not {@code null}) */ public Throwable toPlainThrowable() { final Throwable throwable = new Throwable(toString(), getCause()); throwable.setStackTrace(getStackTrace()); for (Throwable s : getSuppressed()) { throwable.addSuppressed(s); } return throwable; } /** * Get the original exception class name. * * @return the original exception class name (not {@code null}) */ public String getExceptionClassName() { return exceptionClassName; } /** * Get the field names of the remote exception. * * @return the field names of the remote exception */ public Set getFieldNames() { return fields.keySet(); } /** * Get the string value of the given field name. * * @param fieldName the name of the field (must not be {@code null}) * @return the string value of the given field name */ public String getFieldValue(String fieldName) { Assert.checkNotNullParam("fieldName", fieldName); return fields.get(fieldName); } /** * Get a string representation of this exception. The representation will return an indication of the fact that * this was a remote exception, the remote exception type, and optionally details of the exception content, followed * by the exception message. * * @return the string representation of the exception */ public String toString() { final String toString = this.toString; if (toString == null) { final String message = getMessage(); StringBuilder b = new StringBuilder(); b.append(message == null ? CommonMessages.msg.remoteException(exceptionClassName) : CommonMessages.msg.remoteException(exceptionClassName, message)); Iterator> iterator = fields.entrySet().iterator(); if (iterator.hasNext()) { b.append("\n\tPublic fields:"); do { final Map.Entry entry = iterator.next(); b.append('\n').append('\t').append('\t').append(entry.getKey()).append('=').append(entry.getValue()); } while (iterator.hasNext()); } return this.toString = b.toString(); } return toString; } // Format: // class name // null | message // stack trace // count ( field-name field-value )* // null | caused-by // count suppressed* // Add new data to the end; old versions must ignore extra data private static final int ST_NULL = 0; private static final int ST_NEW_STRING = 1; // utf8 data follows private static final int ST_NEW_STACK_ELEMENT_V8 = 2; // string string string int private static final int ST_NEW_STACK_ELEMENT_V9 = 3; // string string string string string string int private static final int ST_NEW_EXCEPTION_CAUSE = 4; // recurse private static final int ST_INT8 = 5; // one byte private static final int ST_INT16 = 6; // two bytes private static final int ST_INT32 = 7; // four bytes private static final int ST_INT_MINI = 0x20; // low 5 bits == signed value private static final int ST_BACKREF_FAR = 0x40; // low 6 bits + next byte are distance private static final int ST_BACKREF_NEAR = 0x80; // low 7 bits are distance /** * Write this remote exception cause to the given stream, without using serialization. * * @param output the output stream (must not be {@code null}) * @throws IOException if an error occurs writing the data */ public void writeToStream(DataOutput output) throws IOException { Assert.checkNotNullParam("output", output); writeToStream(output, new IdentityIntMap(), new HashMap(), 0); } private static int readPackedInt(DataInput is) throws IOException { final int b = is.readUnsignedByte(); if ((b & 0xE0) == ST_INT_MINI) { // sign-extend it return b << 27 >> 27; } else if (b == ST_INT8) { return is.readByte(); } else if (b == ST_INT16) { return is.readShort(); } else if (b == ST_INT32) { return is.readInt(); } else { throw CommonMessages.msg.corruptedStream(); } } private static void writePackedInt(DataOutput os, int val) throws IOException { if (-0x10 <= val && val < 0x10) { os.write(ST_INT_MINI | val & 0b01_1111); } else if (-0x80 <= val && val < 0x80) { os.write(ST_INT8); os.write(val); } else if (-0x8000 <= val && val < 0x8000) { os.write(ST_INT16); os.writeShort(val); } else { os.write(ST_INT32); os.writeInt(val); } } private int writeToStream(DataOutput output, IdentityIntMap seen, HashMap stringCache, int cnt) throws IOException { // register in cycle map seen.put(this, cnt++); // write the header byte output.writeByte(ST_NEW_EXCEPTION_CAUSE); // first write class name cnt = writeString(output, exceptionClassName, seen, stringCache, cnt); // null or message cnt = writeString(output, getMessage(), seen, stringCache, cnt); // stack trace cnt = writeStackTrace(output, getStackTrace(), seen, stringCache, cnt); // fields cnt = writeFields(output, fields, seen, stringCache, cnt); // caused-by cnt = writeThrowable(output, getCause(), seen, stringCache, cnt); // suppressed final Throwable[] suppressed = getSuppressed(); writePackedInt(output, suppressed.length); for (final Throwable t : suppressed) { cnt = writeThrowable(output, t, seen, stringCache, cnt); } return cnt; } private int writeFields(final DataOutput output, final Map fields, final IdentityIntMap seen, final HashMap stringCache, int cnt) throws IOException { writePackedInt(output, fields.size()); for (Map.Entry entry : fields.entrySet()) { cnt = writeString(output, entry.getKey(), seen, stringCache, cnt); cnt = writeString(output, entry.getValue(), seen, stringCache, cnt); } return cnt; } private int writeStackTrace(final DataOutput output, final StackTraceElement[] stackTrace, final IdentityIntMap seen, final HashMap stringCache, int cnt) throws IOException { // don't bother recording in seen because stack traces are always copied final int length = stackTrace.length; writePackedInt(output, length); for (StackTraceElement element : stackTrace) { cnt = writeStackElement(output, element, seen, stringCache, cnt); } return cnt; } private int writeStackElement(final DataOutput output, final StackTraceElement element, final IdentityIntMap seen, final HashMap stringCache, int cnt) throws IOException { final int idx = seen.get(element, - 1); final int distance = cnt - idx; if (idx == -1 || distance > (1 << 14) - 1) { output.write(ST_NEW_STACK_ELEMENT_V8); cnt = writeString(output, element.getClassName(), seen, stringCache, cnt); cnt = writeString(output, element.getMethodName(), seen, stringCache, cnt); cnt = writeString(output, element.getFileName(), seen, stringCache, cnt); writePackedInt(output, element.getLineNumber()); seen.put(element, cnt++); return cnt; } else { if (distance < 127) { output.writeByte(ST_BACKREF_NEAR | distance); } else { assert distance <= 0x3fff; output.writeByte(ST_BACKREF_FAR | distance >> 8); output.writeByte(distance); } return cnt; } } private int writeThrowable(final DataOutput output, final Throwable throwable, final IdentityIntMap seen, final HashMap stringCache, final int cnt) throws IOException { if (throwable == null) { output.write(ST_NULL); return cnt; } else { final int idx = seen.get(throwable, - 1); final int distance = cnt - idx; if (idx == - 1 || distance >= 0x4000) { RemoteExceptionCause nested; if (throwable instanceof RemoteExceptionCause) { nested = (RemoteExceptionCause) throwable; } else { seen.put(throwable, cnt); // do not increment yet nested = of(throwable); } return nested.writeToStream(output, seen, stringCache, cnt); // this will increment it } else { if (distance < 127) { output.writeByte(ST_BACKREF_NEAR | distance); } else { assert distance <= 0x3fff; output.writeByte(ST_BACKREF_FAR | distance >> 8); output.writeByte(distance); } return cnt; } } } private int writeString(final DataOutput output, String string, final IdentityIntMap seen, final HashMap stringCache, final int cnt) throws IOException { if (string == null) { output.write(ST_NULL); return cnt; } // make sure we never duplicate a string string = stringCache.computeIfAbsent(string, Function.identity()); final int idx = seen.get(string, - 1); final int distance = cnt - idx; if (idx == -1 || distance > (1 << 14) - 1) { seen.put(string, cnt); output.write(ST_NEW_STRING); output.writeUTF(string); return cnt + 1; } else { if (distance < 127) { output.writeByte(ST_BACKREF_NEAR | distance); } else { assert distance <= 0x3fff; output.writeByte(ST_BACKREF_FAR | distance >> 8); output.writeByte(distance); } return cnt; } } public static RemoteExceptionCause readFromStream(DataInput input) throws IOException { return readObject(input, RemoteExceptionCause.class, new ArrayList<>(), false); } private static T readObject(DataInput input, Class expect, ArrayList cache, final boolean allowNull) throws IOException { final int b = input.readUnsignedByte(); if (b == ST_NULL) { if (! allowNull) { throw CommonMessages.msg.corruptedStream(); } return null; } else if (b == ST_NEW_STRING) { if (expect != String.class) { throw CommonMessages.msg.corruptedStream(); } final String str = input.readUTF(); cache.add(str); return expect.cast(str); } else if (b == ST_NEW_EXCEPTION_CAUSE) { if (expect != RemoteExceptionCause.class) { throw CommonMessages.msg.corruptedStream(); } final int idx = cache.size(); cache.add(null); String exClassName = readObject(input, String.class, cache, false); String exMessage = readObject(input, String.class, cache, true); int length = readPackedInt(input); StackTraceElement[] stackTrace; if (length == 0) { stackTrace = EMPTY_STACK; } else { stackTrace = new StackTraceElement[length]; for (int i = 0; i < length; i++) { stackTrace[i] = readObject(input, StackTraceElement.class, cache, false); } } Map fields; length = readPackedInt(input); if (length == 0) { fields = Collections.emptyMap(); } else if (length == 1) { fields = Collections.singletonMap(readObject(input, String.class, cache, false), readObject(input, String.class, cache, false)); } else { fields = new HashMap<>(length); for (int i = 0; i < length; i++) { fields.put(readObject(input, String.class, cache, false), readObject(input, String.class, cache, false)); } } final RemoteExceptionCause result = new RemoteExceptionCause(exMessage, null, exClassName, fields, false); cache.set(idx, result); RemoteExceptionCause causedBy = readObject(input, RemoteExceptionCause.class, cache, true); result.initCause(causedBy); length = readPackedInt(input); result.setStackTrace(stackTrace); for (int i = 0; i < length; i++) { // this can't actually be null because we passed {@code false} in to allowNull //noinspection ConstantConditions result.addSuppressed(readObject(input, RemoteExceptionCause.class, cache, false)); } return expect.cast(result); } else if (b == ST_NEW_STACK_ELEMENT_V8) { if (expect != StackTraceElement.class) { throw CommonMessages.msg.corruptedStream(); } // this can't actually be null because we passed {@code false} in to allowNull //noinspection ConstantConditions final StackTraceElement element = new StackTraceElement( readObject(input, String.class, cache, false), readObject(input, String.class, cache, false), readObject(input, String.class, cache, true), readPackedInt(input) ); cache.add(element); return expect.cast(element); } else if (b == ST_NEW_STACK_ELEMENT_V9) { if (expect != StackTraceElement.class) { throw CommonMessages.msg.corruptedStream(); } // discard CL name, module name, and module version readObject(input, String.class, cache, true); readObject(input, String.class, cache, true); readObject(input, String.class, cache, true); // this can't actually be null because we passed {@code false} in to allowNull //noinspection ConstantConditions final StackTraceElement element = new StackTraceElement( readObject(input, String.class, cache, false), readObject(input, String.class, cache, false), readObject(input, String.class, cache, true), readPackedInt(input) ); cache.add(element); return expect.cast(element); } else if ((b & ST_BACKREF_NEAR) != 0) { int idx = b & 0x7f; if (idx > cache.size()) { throw CommonMessages.msg.corruptedStream(); } Object obj = cache.get(cache.size() - idx); if (expect.isInstance(obj)) { return expect.cast(obj); } else { throw CommonMessages.msg.corruptedStream(); } } else if ((b & ST_BACKREF_FAR) != 0) { final int b2 = input.readUnsignedByte(); int idx = (b & 0x3f) << 8 | b2; if (idx > cache.size()) { throw CommonMessages.msg.corruptedStream(); } Object obj = cache.get(cache.size() - idx); if (expect.isInstance(obj)) { return expect.cast(obj); } else { throw CommonMessages.msg.corruptedStream(); } } else { throw CommonMessages.msg.corruptedStream(); } } private static final String[] NO_STRINGS = new String[0]; private static final RemoteExceptionCause[] NO_REMOTE_EXCEPTION_CAUSES = new RemoteExceptionCause[0]; Object writeReplace() { final Throwable[] origSuppressed = getSuppressed(); final int length = origSuppressed.length; final RemoteExceptionCause[] suppressed; if (length == 0) { suppressed = NO_REMOTE_EXCEPTION_CAUSES; } else { suppressed = new RemoteExceptionCause[length]; for (int i = 0; i < length; i ++) { suppressed[i] = of(origSuppressed[i]); } } String[] fieldArray; final int size = fields.size(); if (size == 0) { fieldArray = NO_STRINGS; } else { fieldArray = new String[size << 1]; int i = 0; for (Map.Entry entry : fields.entrySet()) { fieldArray[i++] = entry.getKey(); fieldArray[i++] = entry.getValue(); } } return new Serialized(getMessage(), exceptionClassName, of(getCause()), suppressed, getStackTrace(), fieldArray); } public RemoteExceptionCause getCause() { return (RemoteExceptionCause) super.getCause(); } static final class Serialized implements Serializable { private static final long serialVersionUID = - 2201431870774913071L; // small field names serialize smaller final String m; final String cn; final RemoteExceptionCause c; final RemoteExceptionCause[] s; final StackTraceElement[] st; final String[] f; Serialized(final String m, final String cn, final RemoteExceptionCause c, final RemoteExceptionCause[] s, final StackTraceElement[] st, final String[] f) { this.m = m; this.cn = cn; this.c = c; this.s = s; this.st = st; this.f = f; } Object readResolve() { final Map fields; if (f == null) { fields = Collections.emptyMap(); } else { final int fl = f.length; if ((fl & 1) != 0) { throw CommonMessages.msg.invalidOddFields(); } else if (fl == 0) { fields = Collections.emptyMap(); } else if (fl == 2) { fields = Collections.singletonMap(f[0], f[1]); } else { final TreeMap map = new TreeMap<>(); for (int i = 0; i < fl; i += 2) { map.put(f[i], f[i + 1]); } fields = Collections.unmodifiableMap(map); } } final RemoteExceptionCause ex = new RemoteExceptionCause(m, c, cn, fields, false); ex.setStackTrace(st); final RemoteExceptionCause[] suppressed = s; if (suppressed != null) for (RemoteExceptionCause c : suppressed) { ex.addSuppressed(c); } return ex; } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/rpc/package-info.java000066400000000000000000000015671361511066400276640ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes which are commonly useful for simple RPC applications. * * @author David M. Lloyd */ package org.wildfly.common.rpc; wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/000077500000000000000000000000001361511066400255205ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/ContextClassLoaderSelector.java000066400000000000000000000017541361511066400336340ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.selector; /** * @author David M. Lloyd */ @Deprecated class ContextClassLoaderSelector extends Selector { public ClassLoader get() { return Thread.currentThread().getContextClassLoader(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/DefaultSelector.java000066400000000000000000000026541361511066400314570ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.selector; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.wildfly.common.context.Contextual; /** * An annotation indicating the default selector implementation class to use for a class. * * @author David M. Lloyd * * @deprecated Use {@link Contextual} instead. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Deprecated public @interface DefaultSelector { /** * The selector implementation class to use. * * @return the selector implementation class */ Class> value(); } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/GlobalSelector.java000066400000000000000000000026521361511066400312710ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.selector; import org.wildfly.common.Assert; import org.wildfly.common.context.Contextual; /** * A selector which always returns one global instance. * * @author David M. Lloyd * * @deprecated Use {@link Contextual} instead. */ @Deprecated public final class GlobalSelector extends Selector { private final T instance; /** * Construct a new instance. * * @param instance the constant instance to always return from this selector */ public GlobalSelector(final T instance) { Assert.checkNotNullParam("instance", instance); this.instance = instance; } public T get() { return instance; } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/Selector.java000066400000000000000000000234631361511066400301530ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.selector; import java.lang.reflect.InvocationTargetException; import java.security.PrivilegedAction; import java.util.concurrent.atomic.AtomicReference; import org.wildfly.common.Assert; import org.wildfly.common.context.Contextual; /** * A selector for an object which is obtainable via static context. * * @author David M. Lloyd * * @deprecated Use {@link Contextual} instead. */ @Deprecated public abstract class Selector { private static final Selector NULL = new Selector() { public Object get() { return null; } }; private static final ClassValue> selVal = new ClassValue>() { protected Holder computeValue(final Class type) { return doCompute(type); } private Holder doCompute(final Class type) { Selector selector = null; try { final DefaultSelector defaultSelector = type.getAnnotation(DefaultSelector.class); if (defaultSelector != null) { final Class> selectorType = defaultSelector.value(); selector = (Selector) selectorType.getConstructor().newInstance(); } } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException ignored) { } final Holder holder = new Holder<>(type); holder.set(selector); return holder; } }; protected Selector() { } /** * Get the currently relevant object, or {@code null} if there is none. * * @return the currently relevant object */ public abstract T get(); /** * Get the {@code null} selector. This selector always returns {@code null}. * * @param the selectable class' type * @return the {@code null} selector */ @SuppressWarnings("unchecked") public static Selector nullSelector() { return (Selector) NULL; } /** * Get the selector for a given class. Never returns {@code null}. If there is a selector set, the caller must * have the {@code get} {@link SelectorPermission} for the class. * * @param clazz the class * @param the class type * @return the selector for the given type (not {@code null}) */ @SuppressWarnings("unchecked") public static Selector selectorFor(Class clazz) { Assert.checkNotNullParam("clazz", clazz); final Holder holder = (Holder) selVal.get(clazz); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(holder.getGetPermission()); } final Selector sel = holder.get(); return sel == null ? Selector.nullSelector() : sel; } /** * Set the selector for a given class. If there is no selector set, the caller must have the {@code set} {@link SelectorPermission} for that class. * If there is one set, the caller must have the {@code change} {@link SelectorPermission}. If there is a selector * set, and it is identical to the proposed selector, this method returns without taking any action. * * @param clazz the class * @param selector the selector to set for the class * @param the class type */ @SuppressWarnings("unchecked") public static void setSelectorFor(Class clazz, Selector selector) { Assert.checkNotNullParam("clazz", clazz); final Holder holder = (Holder) selVal.get(clazz); Selector oldValue; boolean set = false, change = false; for (;;) { oldValue = holder.get(); if (oldValue == selector) { return; } if (oldValue == null) { if (! set) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(holder.getSetPermission()); } set = true; } if (holder.compareAndSet(null, selector)) { return; } } else { if (! change) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(holder.getChangePermission()); } change = true; } if (holder.compareAndSet(oldValue, selector)) { return; } } } } /** * Get an efficient, unchecked selector getter for a given class. The caller must have the {@code get} * {@link SelectorPermission} for the class. * * @param clazz the class * @param the class type * @return the unchecked selector getter */ @SuppressWarnings("unchecked") public static Getter selectorGetterFor(Class clazz) { Assert.checkNotNullParam("clazz", clazz); final Holder holder = (Holder) selVal.get(clazz); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(holder.getGetPermission()); } return new Getter<>(holder); } /** * Get a privileged action which returns the getter for a selector. * * @param clazz the class * @param the class type * @return the getter privileged action */ public static PrivilegedAction> selectorGetterActionFor(final Class clazz) { Assert.checkNotNullParam("clazz", clazz); return () -> selectorGetterFor(clazz); } /** * Get the {@code get} permission for the given class. The permission is cached. * * @param clazz the class to get the permission for * @return the selector permission for the class */ public static SelectorPermission getGetPermissionFor(Class clazz) { Assert.checkNotNullParam("clazz", clazz); return selVal.get(clazz).getGetPermission(); } /** * Get the {@code set} permission for the given class. The permission is cached. * * @param clazz the class to get the permission for * @return the selector permission for the class */ public static SelectorPermission getSetPermissionFor(Class clazz) { Assert.checkNotNullParam("clazz", clazz); return selVal.get(clazz).getSetPermission(); } /** * Get the {@code change} permission for the given class. The permission is cached. * * @param clazz the class to get the permission for * @return the selector permission for the class */ public static SelectorPermission getChangePermissionFor(Class clazz) { Assert.checkNotNullParam("clazz", clazz); return selVal.get(clazz).getChangePermission(); } /** * An efficient, unchecked getter for a selector for a given class. * * @param the selectable class' type */ public static final class Getter { private final Holder holder; Getter(final Holder holder) { this.holder = holder; } /** * Get the selector for this getter. No permission checks are performed. * * @return the selector */ public Selector getSelector() { final Selector sel = holder.get(); return sel == null ? Selector.nullSelector() : sel; } } @SuppressWarnings("serial") static final class Holder extends AtomicReference> { private final Class clazz; private final SelectorPermission getPermission; private final SelectorPermission setPermission; private final SelectorPermission changePermission; private final AtomicReference lockRef = new AtomicReference<>(); Holder(final Class clazz) { Assert.assertNotNull(clazz); this.clazz = clazz; getPermission = new SelectorPermission(clazz.getName(), "get"); setPermission = new SelectorPermission(clazz.getName(), "set"); changePermission = new SelectorPermission(clazz.getName(), "change"); } Class getClazz() { return clazz; } SelectorPermission getGetPermission() { return getPermission; } SelectorPermission getSetPermission() { return setPermission; } SelectorPermission getChangePermission() { return changePermission; } void lock(Object key) { Assert.assertNotNull(key); if (! lockRef.compareAndSet(null, key)) { throw new SecurityException("Selector is locked"); } } void unlock(Object key) { Assert.assertNotNull(key); if (! lockRef.compareAndSet(key, null)) { throw new SecurityException("Selector could not be unlocked"); } } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/SelectorPermission.java000066400000000000000000000070101361511066400322120ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.selector; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.security.BasicPermission; import java.security.Permission; import org.wildfly.common.Assert; /** * Permission to access a specific selector. * * @author David M. Lloyd */ public final class SelectorPermission extends BasicPermission { private static final long serialVersionUID = -7156787601824624014L; private static final int ACTION_GET = 1; private static final int ACTION_SET = 2; private static final int ACTION_CHANGE = 4; private final int actions; public SelectorPermission(final String name, final String actions) { super(name); Assert.checkNotNullParam("name", name); Assert.checkNotNullParam("actions", actions); final String[] actionArray = actions.split("\\s*,\\s*"); int q = 0; for (String action : actionArray) { if (action.equalsIgnoreCase("get")) { q |= ACTION_GET; } else if (action.equalsIgnoreCase("set")) { q |= ACTION_SET; } else if (action.equalsIgnoreCase("change")) { q |= ACTION_CHANGE; } else if (action.equals("*")) { q |= ACTION_GET | ACTION_SET | ACTION_CHANGE; break; } } this.actions = q; } public String getActions() { // few enough final int maskedActions = actions & 0b111; switch (maskedActions) { case 0b000: return ""; case 0b001: return "get"; case 0b010: return "set"; case 0b011: return "get,set"; case 0b100: return "change"; case 0b101: return "get,change"; case 0b110: return "set,change"; case 0b111: return "get,set,change"; default: throw Assert.impossibleSwitchCase(maskedActions); } } public boolean implies(final Permission p) { return p instanceof SelectorPermission && implies((SelectorPermission) p); } public boolean implies(final SelectorPermission p) { return p != null && (p.actions & actions) == p.actions && super.implies(p); } public boolean equals(final Object p) { return p instanceof SelectorPermission && equals((SelectorPermission) p); } public boolean equals(final SelectorPermission p) { return p != null && (p.actions == actions) && super.equals(p); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); final int actions = this.actions; if ((actions & 0b111) != actions) { throw new InvalidObjectException("Invalid permission actions"); } } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/ThreadLocalSelector.java000066400000000000000000000027571361511066400322610ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.selector; import org.wildfly.common.Assert; import org.wildfly.common.context.Contextual; /** * A thread local selector implementation. * * @author David M. Lloyd * * @deprecated Use {@link Contextual} instead. */ @Deprecated public final class ThreadLocalSelector extends Selector { private final ThreadLocal threadLocal; /** * Construct a new instance. * * @param threadLocal the thread-local to use to store the selector's value */ public ThreadLocalSelector(final ThreadLocal threadLocal) { Assert.checkNotNullParam("threadLocal", threadLocal); this.threadLocal = threadLocal; } public T get() { return threadLocal.get(); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/selector/package-info.java000066400000000000000000000016031361511066400307070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author David M. Lloyd * * @deprecated Use {@link org.wildfly.common.context.Contextual} instead. */ package org.wildfly.common.selector;wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/string/000077500000000000000000000000001361511066400252065ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/string/CompositeCharSequence.java000066400000000000000000000106351361511066400323070ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.string; import java.io.Serializable; import java.nio.CharBuffer; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * A {@link CharSequence} composed of other character sequences. * All methods delegate to one or more of the underlying character sequences, using relative indexes. * @author Paul Ferraro */ public class CompositeCharSequence implements CharSequence, Serializable { private static final long serialVersionUID = 4975968165050531721L; private final List sequences; private transient int hashCode = 0; /** * Constructs a new composite character sequence. * @param sequences an array of character sequences. */ public CompositeCharSequence(CharSequence... sequences) { this(Arrays.asList(sequences)); } /** * Constructs a new composite character sequence. * @param sequences a list of character sequences. */ public CompositeCharSequence(List sequences) { this.sequences = sequences; } @Override public int length() { int length = 0; for (CharSequence sequence : this.sequences) { length += sequence.length(); } return length; } @Override public char charAt(int index) { int relativeIndex = index; for (CharSequence sequence : this.sequences) { if (relativeIndex < sequence.length()) { return sequence.charAt(relativeIndex); } relativeIndex -= sequence.length(); } throw new IndexOutOfBoundsException(); } @Override public CharSequence subSequence(int start, int end) { if ((start < 0) || (start > end) || (end > this.length())) { throw new IndexOutOfBoundsException(); } if (start == end) return ""; List result = null; int relativeStart = start; int relativeEnd = end; for (CharSequence sequence : this.sequences) { if ((relativeStart < sequence.length()) && (relativeEnd > 0)) { CharSequence subSequence = sequence.subSequence(Math.max(relativeStart, 0), Math.min(relativeEnd, sequence.length())); if (result == null) { // If subsequence falls within a single sequence if ((relativeStart >= 0) && (relativeEnd <= sequence.length())) { return subSequence; } result = new LinkedList<>(); } result.add(subSequence); } relativeStart -= sequence.length(); relativeEnd -= sequence.length(); } return new CompositeCharSequence(result); } @Override public int hashCode() { int result = this.hashCode; if (result == 0) { for (int i = 0; i < this.length(); ++i) { result = 31 * result + this.charAt(i); } this.hashCode = result; } return result; } @Override public boolean equals(Object object) { if (!(object instanceof CharSequence)) return false; CharSequence sequence = (CharSequence) object; int length = sequence.length(); if (this.length() != length) return false; for (int i = 0; i < length; ++i) { if (this.charAt(i) != sequence.charAt(i)) return false; } return true; } @Override public String toString() { CharBuffer buffer = CharBuffer.allocate(this.length()); for (CharSequence sequence : this.sequences) { buffer.put(CharBuffer.wrap(sequence)); } return String.valueOf(buffer.array()); } } wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/string/package-info.java000066400000000000000000000015621361511066400304010ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes which perform various common string functions. * * @author Paul Ferraro */ package org.wildfly.common.string; wildfly-common-1.5.3.Final/src/main/java11/000077500000000000000000000000001361511066400203115ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java11/org/000077500000000000000000000000001361511066400211005ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java11/org/wildfly/000077500000000000000000000000001361511066400225525ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java11/org/wildfly/common/000077500000000000000000000000001361511066400240425ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java11/org/wildfly/common/archive/000077500000000000000000000000001361511066400254635ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java11/org/wildfly/common/archive/JDKSpecific.java000066400000000000000000000022271361511066400304070ustar00rootroot00000000000000package org.wildfly.common.archive; import static java.lang.Math.min; import java.io.IOException; import java.nio.ByteBuffer; import java.util.zip.DataFormatException; import java.util.zip.Inflater; /** */ final class JDKSpecific { private JDKSpecific() {} static ByteBuffer inflate(final Inflater inflater, final ByteBuffer[] bufs, long offset, final int compSize, final int uncompSize) throws DataFormatException, IOException { int cnt = 0; byte[] out = new byte[uncompSize]; int op = 0; while (cnt < compSize) { int rem = compSize - cnt; final ByteBuffer buf = bufs[Archive.bufIdx(offset + cnt)].duplicate(); buf.position(Archive.bufOffs(offset + cnt)); buf.limit(min(buf.capacity(), buf.position() + rem)); cnt += buf.remaining(); inflater.setInput(buf); do { op += inflater.inflate(out, op, uncompSize - op); } while (! inflater.needsInput()); } if (! inflater.finished()) { throw new IOException("Corrupted compression stream"); } return ByteBuffer.wrap(out); } } wildfly-common-1.5.3.Final/src/main/java9/000077500000000000000000000000001361511066400202405ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/000077500000000000000000000000001361511066400210275ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/000077500000000000000000000000001361511066400225015ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/000077500000000000000000000000001361511066400237715ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/cpu/000077500000000000000000000000001361511066400245605ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/cpu/ProcessorInfo.java000066400000000000000000000017641361511066400302260ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.cpu; /** * Provides general information about the processors on this host (Java 9 version). */ public class ProcessorInfo { private ProcessorInfo() { } public static int availableProcessors() { return Runtime.getRuntime().availableProcessors(); } } wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/lock/000077500000000000000000000000001361511066400247215ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/lock/JDKSpecific.java000066400000000000000000000031751361511066400276500ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import sun.misc.Unsafe; /** */ final class JDKSpecific { private JDKSpecific() {} static final Unsafe unsafe; static { unsafe = AccessController.doPrivileged(new PrivilegedAction() { public Unsafe run() { try { final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return (Unsafe) field.get(null); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } } }); } static void onSpinWait() { Thread.onSpinWait(); } } wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/lock/Substitutions.java000066400000000000000000000016771361511066400304760ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.lock; final class Substitutions { static final class Target_JDKSpecific { static void onSpinWait() { } } static final class Target_PauseNode { public static native void pause(); } } wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/os/000077500000000000000000000000001361511066400244125ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/os/GetProcessInfoAction.java000066400000000000000000000072071361511066400313130ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; import static java.lang.Math.max; import java.io.File; import java.security.PrivilegedAction; /** */ final class GetProcessInfoAction implements PrivilegedAction { GetProcessInfoAction() { } public Object[] run() { final ProcessHandle processHandle = ProcessHandle.current(); final long pid = processHandle.pid(); String processName = System.getProperty("jboss.process.name"); if (processName == null) { final String classPath = System.getProperty("java.class.path"); final String commandLine = System.getProperty("sun.java.command"); if (commandLine != null) { if (classPath != null && commandLine.startsWith(classPath)) { // OK probably a JAR launch final int sepIdx = classPath.lastIndexOf(File.separatorChar); if (sepIdx > 0) { processName = classPath.substring(sepIdx + 1); } else { processName = classPath; } } else { // probably a class name // it might be a class name followed by args, like org.foo.Bar -baz -zap int firstSpace = commandLine.indexOf(' '); final String className; if (firstSpace > 0) { className = commandLine.substring(0, firstSpace); } else { className = commandLine; } // no args now int lastDot = className.lastIndexOf('.', firstSpace); if (lastDot > 0) { processName = className.substring(lastDot + 1); if (processName.equalsIgnoreCase("jar") || processName.equalsIgnoreCase("ȷar")) { // oops, I guess it was a JAR name... let's just take a guess then int secondLastDot = className.lastIndexOf('.', lastDot - 1); int sepIdx = className.lastIndexOf(File.separatorChar); int lastSep = secondLastDot == - 1 ? sepIdx : sepIdx == - 1 ? secondLastDot : max(sepIdx, secondLastDot); if (lastSep > 0) { processName = className.substring(lastSep + 1); } else { processName = className; } } } else { processName = className; } } } } if (processName == null) { processName = processHandle.info().command().orElse(null); } if (processName == null) { processName = ""; } return new Object[] { Long.valueOf(pid), processName }; } } wildfly-common-1.5.3.Final/src/main/java9/org/wildfly/common/os/ProcessRedirect.java000066400000000000000000000016311361511066400303560ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; public final class ProcessRedirect { private ProcessRedirect() {} public static ProcessBuilder.Redirect discard() { return ProcessBuilder.Redirect.DISCARD; } } wildfly-common-1.5.3.Final/src/test/000077500000000000000000000000001361511066400172615ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/000077500000000000000000000000001361511066400202025ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/000077500000000000000000000000001361511066400207715ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/000077500000000000000000000000001361511066400224435ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/000077500000000000000000000000001361511066400237335ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/archive/000077500000000000000000000000001361511066400253545ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/archive/ArchiveIndexTest.java000066400000000000000000000030401361511066400314250ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.archive; import static org.junit.Assert.*; import org.junit.Test; /** * */ public class ArchiveIndexTest { private void doIndexTest(Index index) { // simple get/put index.put(4, 1234); assertEquals(1234, index.get(4)); index.put(0, 5555); assertEquals(5555, index.get(0)); assertEquals(-1, index.get(3)); // check linear probing index.put(4, 2345); assertEquals(1234, index.get(4)); assertEquals(2345, index.get(5)); assertEquals(-1, index.get(6)); } @Test public void testTinyIndex() { doIndexTest(new TinyIndex(130)); } @Test public void testLargeIndex() { doIndexTest(new LargeIndex(112)); } @Test public void testHugeIndex() { doIndexTest(new HugeIndex(112)); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/archive/ArchiveTest.java000066400000000000000000000077141361511066400304510ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.archive; import static org.junit.Assert.*; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import org.junit.Test; /** * */ public class ArchiveTest { public static final String SIMPLE_CONTENT_1 = "This is a string that is meant to be long but easy to compress, which can be read back in a single line."; private static final String TEST_CONTENT_NAME = "test/content/file.text"; @Test public void testReadContentStored() throws IOException { doReadContent(ZipEntry.STORED); } @Test public void testReadContentDeflated() throws IOException { doReadContent(ZipEntry.DEFLATED); } private void doReadContent(int method) throws IOException { final Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(Attributes.Name.SPECIFICATION_TITLE.toString(), "Test JAR"); final byte[] contentBytes; try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (OutputStreamWriter osw = new OutputStreamWriter(baos, StandardCharsets.UTF_8)) { try (BufferedWriter writer = new BufferedWriter(osw)) { for (int i = 0; i < 50; i ++) { writer.write(SIMPLE_CONTENT_1); writer.newLine(); } } } contentBytes = baos.toByteArray(); } final ByteArrayOutputStream os = new ByteArrayOutputStream(); try (JarOutputStream jos = new JarOutputStream(os, manifest)) { final JarEntry jarEntry = new JarEntry(TEST_CONTENT_NAME); jarEntry.setSize(contentBytes.length); if (method == ZipEntry.STORED) { jarEntry.setCompressedSize(contentBytes.length); final CRC32 crc32 = new CRC32(); crc32.update(contentBytes); jarEntry.setCrc(crc32.getValue()); } jarEntry.setMethod(method); jos.putNextEntry(jarEntry); jos.write(contentBytes); jos.closeEntry(); } final byte[] bytes = os.toByteArray(); final Archive archive = Archive.open(ByteBuffer.wrap(bytes)); assertEquals(-1, archive.getEntryHandle("non/existent/file/")); assertEquals(-1, archive.getEntryHandle("")); final long handle = archive.getEntryHandle(TEST_CONTENT_NAME); assertNotEquals(-1, handle); assertEquals(contentBytes.length, archive.getUncompressedSize(handle)); assertTrue(contentBytes.length >= archive.getCompressedSize(handle)); final ByteBuffer contentsBuf = archive.getEntryContents(handle); assertNotNull(contentsBuf); // verify the buffer view final byte[] compareBytes = new byte[contentBytes.length]; contentsBuf.get(compareBytes); assertEquals(0, contentsBuf.remaining()); assertArrayEquals(contentBytes, compareBytes); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/codec/000077500000000000000000000000001361511066400250105ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/codec/Base32Test.java000066400000000000000000000260161361511066400275370ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; /** * Tests for Base32 encoding and decoding. * * @author Farah Juma */ public class Base32Test { public Base32Test() { } @Test public void testEncodeEmpty() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncode6Padding() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("f").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("MY======", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("f").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("MY", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncode4Padding() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("fo").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("MZXQ====", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("fo").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("MZXQ", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncode3Padding() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("foo").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("MZXW6===", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("foo").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("MZXW6", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncode1Padding() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("foob").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("MZXW6YQ=", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("foob").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("MZXW6YQ", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeNoPadding() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("fooba").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("MZXW6YTB", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("fooba").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("MZXW6YTB", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeMoreThan5Characters() { // With the padding characters included CodePointIterator ci = CodePointIterator.ofString("foobarfoobarfoobar").asLatin1().base32Encode(); String encoded = ci.drainToString(); assertEquals("MZXW6YTBOJTG633CMFZGM33PMJQXE===", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); // Without the padding characters ci = CodePointIterator.ofString("foobarfoobarfoobar").asLatin1().base32Encode(Base32Alphabet.STANDARD, false); encoded = ci.drainToString(); assertEquals("MZXW6YTBOJTG633CMFZGM33PMJQXE", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } private void verifyBackwardIterationOfEncodedCharacters(CodePointIterator ci, String encoded) { int encodedSize = encoded.length(); for (int i = encodedSize - 1; i >= 0; i--) { assertTrue(ci.hasPrevious()); assertEquals(encoded.charAt(i), ci.previous()); } } @Test public void testDecodeEmpty() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecode6Padding() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("MY======").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("f", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("MY").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("f", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecode4Padding() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("MZXQ====").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("fo", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("MZXQ").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("fo", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecode3Padding() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("MZXW6===").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("foo", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("MZXW6").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("foo", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecode1Padding() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("MZXW6YQ=").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("foob", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("MZXW6YQ").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("foob", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeNoPadding() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("MZXW6YTB").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("fooba", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("MZXW6YTB").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("fooba", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeMoreThan5Characters() throws Exception { // With the padding characters included ByteIterator bi = CodePointIterator.ofString("MZXW6YTBOJTG633CMFZGM33PMJQXE===").base32Decode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("foobarfoobarfoobar", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); // Without the padding characters bi = CodePointIterator.ofString("MZXW6YTBOJTG633CMFZGM33PMJQXE").base32Decode(Base32Alphabet.STANDARD, false); decoded = bi.asUtf8String().drainToString(); assertEquals("foobarfoobarfoobar", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test(expected=DecodeException.class) public void testDecodeInvalidCharacter() throws Exception { CodePointIterator.ofString("MZXW6YTBOá").base32Decode().drain(); } @Test(expected=DecodeException.class) public void testDecodeInvalidPadding() throws Exception { CodePointIterator.ofString("M====").base32Decode().drain(); } private void verifyBackwardIterationOfDecodedBytes(ByteIterator bi, String decoded) { int decodedSize = decoded.length(); for (int i = decodedSize - 1; i >= 0; i--) { assertTrue(bi.hasPrevious()); assertEquals(decoded.charAt(i), bi.previous()); } } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/codec/Base64Test.java000066400000000000000000000250301361511066400275370ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.charset.StandardCharsets; import org.junit.Assert; import org.junit.Test; import org.wildfly.common.bytes.ByteStringBuilder; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; /** * Tests of encoding/decoding Base64 B (standard alphabet) * implemented in org.wildfly.security.util.Base64 * * @author Jan Kalina */ @SuppressWarnings("SpellCheckingInspection") public class Base64Test { public Base64Test() { } /* * Standard Base64 alphabet encoding * (Expected values by http://www.freeformatter.com/base64-encoder.html) */ @Test public void testEncodeBlank() { assertEquals("", ByteIterator.EMPTY.base64Encode().drainToString()); } @Test public void testEncodeWithoutPadding() { assertEquals("YWJj", CodePointIterator.ofString("abc").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeWith1Padding() { assertEquals("YWI=", CodePointIterator.ofString("ab").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeWith2Padding() { assertEquals("YWJjZA==", CodePointIterator.ofString("abcd").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeWithTurnedOffPadding() { assertEquals("YWJjZA", CodePointIterator.ofString("abcd").asLatin1().base64Encode(Base64Alphabet.STANDARD, false).drainToString()); } @Test public void testEncodeBinary() { assertEquals("AAEjRWeJq83v", ByteIterator.ofBytes((byte)0x00,(byte)0x01,(byte)0x23,(byte)0x45,(byte)0x67,(byte)0x89,(byte)0xAB,(byte)0xCD,(byte)0xEF).base64Encode().drainToString()); } @Test public void testEncodeRfc1() { assertEquals("Zg==", CodePointIterator.ofString("f").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeRfc2() { assertEquals("Zm8=", CodePointIterator.ofString("fo").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeRfc3() { assertEquals("Zm9v", CodePointIterator.ofString("foo").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeRfc4() { assertEquals("Zm9vYg==", CodePointIterator.ofString("foob").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeRfc5() { assertEquals("Zm9vYmE=", CodePointIterator.ofString("fooba").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeRfc6() { assertEquals("Zm9vYmFy", CodePointIterator.ofString("foobar").asLatin1().base64Encode().drainToString()); } @Test public void testEncodeAgainstPrecomputedValue() throws Exception { final byte[] input = "Testing input of base64 function".getBytes("UTF-8"); final String output = CodePointIterator.ofString("Testing input of base64 function").asLatin1().base64Encode().drainToString(); Assert.assertEquals("VGVzdGluZyBpbnB1dCBvZiBiYXNlNjQgZnVuY3Rpb24=", output); Assert.assertArrayEquals(input, CodePointIterator.ofString(output).base64Decode().drain()); } @Test public void testEncodeByteStartingWithOne() { ByteStringBuilder bsb = new ByteStringBuilder(); bsb.append((byte)0x00); bsb.append((byte)0xB8); assertEquals("ALg=", bsb.iterate().base64Encode().drainToString()); } @Test public void testEncodeMoreBinaryBytes() { ByteStringBuilder bsb = new ByteStringBuilder(); bsb.append((byte)0xD0); bsb.append((byte)0xB8); bsb.append((byte)0xE4); bsb.append((byte)0xBD); bsb.append((byte)0xA0); bsb.append((byte)0xF0); bsb.append((byte)0x9F); bsb.append((byte)0x82); bsb.append((byte)0xA1); bsb.append((byte)0x31); bsb.append((byte)0xE2); bsb.append((byte)0x81); bsb.append((byte)0x84); bsb.append((byte)0x32); bsb.append((byte)0x20); bsb.append((byte)0xCC); bsb.append((byte)0x81); assertEquals("0LjkvaDwn4KhMeKBhDIgzIE=", bsb.iterate().base64Encode().drainToString()); } /* * Standard Base64 alphabet decoding * (Expected values by http://www.freeformatter.com/base64-encoder.html) */ @Test public void testDecodeBlank() throws Exception { Assert.assertArrayEquals(new byte[]{}, CodePointIterator.EMPTY.base64Decode(Base64Alphabet.STANDARD, false).drain()); } @Test public void testDecodeWithoutPadding() throws Exception { assertEquals("abc", CodePointIterator.ofString("YWJj").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeWith1Padding() throws Exception { assertEquals("ab", CodePointIterator.ofString("YWI=").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeWith2Padding() throws Exception { assertEquals("abcd", CodePointIterator.ofString("YWJjZA==").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeBinary() throws Exception { byte[] out = CodePointIterator.ofString("AAEjRWeJq83v").base64Decode(Base64Alphabet.STANDARD, false).drain(); Assert.assertArrayEquals(new byte[]{(byte)0x00,(byte)0x01,(byte)0x23,(byte)0x45,(byte)0x67,(byte)0x89,(byte)0xAB,(byte)0xCD,(byte)0xEF}, out); } @Test public void testDecodeRfc1() throws Exception { assertEquals("f", CodePointIterator.ofString("Zg==").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeRfc2() throws Exception { assertEquals("fo", CodePointIterator.ofString("Zm8=").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeRfc3() throws Exception { assertEquals("foo", CodePointIterator.ofString("Zm9v").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeRfc4() throws Exception { assertEquals("foob", CodePointIterator.ofString("Zm9vYg==").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeRfc5() throws Exception { assertEquals("fooba", CodePointIterator.ofString("Zm9vYmE=").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testDecodeRfc6() throws Exception { assertEquals("foobar", CodePointIterator.ofString("Zm9vYmFy").base64Decode(Base64Alphabet.STANDARD, false).asUtf8String().drainToString()); } @Test public void testUtf8Transcode() { final String str = "abc123xyz987ä³€¼‘’“”"; final byte[] bytes = str.getBytes(StandardCharsets.UTF_8); assertArrayEquals(bytes, CodePointIterator.ofString(str).asUtf8().drain()); assertEquals(str, ByteIterator.ofBytes(bytes).asUtf8String().drainToString()); assertEquals(str, CodePointIterator.ofString(str).asUtf8().asUtf8String().drainToString()); } /* * Decoding of invalid input */ @Test(expected=IllegalArgumentException.class) public void testInvalidInputDecodePadding1() throws Exception { CodePointIterator.ofString("=").base64Decode(Base64Alphabet.STANDARD, false).drain(); } @Test(expected=IllegalArgumentException.class) public void testInvalidInputDecodePadding2() throws Exception { CodePointIterator.ofString("==").base64Decode(Base64Alphabet.STANDARD, false).drain(); } @Test(expected=IllegalArgumentException.class) public void testInvalidInputDecodePadding3() throws Exception { CodePointIterator.ofString("===").base64Decode(Base64Alphabet.STANDARD, false).drain(); } @Test(expected=IllegalArgumentException.class) public void testInvalidInputDecodeNonAlphabeticChar() throws Exception { CodePointIterator.ofString("áááááááááááá").base64Decode(Base64Alphabet.STANDARD, false).drain(); } public void testInvalidInputDecodeTooMuchPadding() throws Exception { final CodePointIterator r = CodePointIterator.ofString("YWI=="); r.base64Decode(Base64Alphabet.STANDARD, false).drain(); assertTrue(r.hasNext()); assertEquals('=', r.next()); assertFalse(r.hasNext()); } /* * General Base64 tests */ /** * Tests if encoding/decoding works properly. * (data length) % 3 == 0 */ @Test public void testEncodeDecodeToByteStringBuilderMod0() throws Exception { doEncodeDecodeTest(generateSequence(255)); } /** * Tests if encoding/decoding works properly. * (data length) % 3 == 1 */ @Test public void testEncodeDecodeToByteStringBuilderMod1() throws Exception { doEncodeDecodeTest(generateSequence(256)); } /** * Tests if encoding/decoding works properly. * (data length) % 3 == 2 */ @Test public void testEncodeDecodeToByteStringBuilderMod2() throws Exception { doEncodeDecodeTest(generateSequence(257)); } private void doEncodeDecodeTest(byte[] inputData) throws Exception { byte[] outputData = ByteIterator.ofBytes(inputData).base64Encode().base64Decode().drain(); assertArrayEquals("Encode-Decode test failed, results are not the same.", inputData, outputData); } private byte[] generateSequence(final int len) { byte[] data = new byte[len]; for (int i = 0; i < len ; i++) { data[i] = (byte)i; } return data; } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/codec/HexTest.java000066400000000000000000000200111361511066400272310ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.codec; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Assert; import org.junit.Test; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; /** * Tests for Hex encoding and decoding. The expected results for these test cases have been * taken from the examples in RFC 4648. * * @author Farah Juma */ public class HexTest { public HexTest() { } @Test public void testEncodeEmpty() { CodePointIterator ci = CodePointIterator.ofString("").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeRfcExample1() { CodePointIterator ci = CodePointIterator.ofString("f").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("66", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeRfcExample2() { CodePointIterator ci = CodePointIterator.ofString("fo").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("666f", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeRfcExample3() { CodePointIterator ci = CodePointIterator.ofString("foo").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("666f6f", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeRfcExample4() { CodePointIterator ci = CodePointIterator.ofString("foob").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("666f6f62", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeRfcExample5() { CodePointIterator ci = CodePointIterator.ofString("fooba").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("666f6f6261", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeRfcExample6() { CodePointIterator ci = CodePointIterator.ofString("foobar").asLatin1().hexEncode(); String encoded = ci.drainToString(); assertEquals("666f6f626172", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeUpperCase() { CodePointIterator ci = ByteIterator.ofBytes((byte) 0x1d, (byte) 0x34, (byte) 0xaf, (byte) 0xbc, (byte) 0x9e, (byte) 0x89).hexEncode(true); String encoded = ci.drainToString(); assertEquals("1D34AFBC9E89", encoded); verifyBackwardIterationOfEncodedCharacters(ci, encoded); } @Test public void testEncodeWithFormatting() { Assert.assertEquals("66:6F:6F:62:61:72", CodePointIterator.ofString("foobar").asLatin1().hexEncode(true).drainToString(':', 2)); Assert.assertEquals("0x66 0x6F 0x6F 0x62 0x61 0x72", CodePointIterator.ofString("foobar").asLatin1().hexEncode(true).drainToString("0x", ' ', 2)); Assert.assertEquals("666F6F6261\n72666F6F62\n6172666F6F\n626172", CodePointIterator.ofString("foobarfoobarfoobar").asLatin1().hexEncode(true).drainToString('\n', 10)); } private void verifyBackwardIterationOfEncodedCharacters(CodePointIterator ci, String encoded) { int encodedSize = encoded.length(); for (int i = encodedSize - 1; i >= 0; i--) { assertTrue(ci.hasPrevious()); Assert.assertEquals(encoded.charAt(i), ci.previous()); } } @Test public void testDecodeEmpty() throws Exception { ByteIterator bi = CodePointIterator.ofString("").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeRfcExample1() throws Exception { ByteIterator bi = CodePointIterator.ofString("66").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("f", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeRfcExample2() throws Exception { ByteIterator bi = CodePointIterator.ofString("666f").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("fo", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeRfcExample3() throws Exception { ByteIterator bi = CodePointIterator.ofString("666f6f").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("foo", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeRfcExample4() throws Exception { ByteIterator bi = CodePointIterator.ofString("666f6f62").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("foob", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeRfcExample5() throws Exception { ByteIterator bi = CodePointIterator.ofString("666f6f6261").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("fooba", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeRfcExample6() throws Exception { ByteIterator bi = CodePointIterator.ofString("666f6f626172").hexDecode(); String decoded = bi.asUtf8String().drainToString(); assertEquals("foobar", decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test public void testDecodeUpperCase() throws Exception { ByteIterator bi = CodePointIterator.ofString("1D34AFBC9E89").hexDecode(); byte[] decoded = bi.drain(); assertArrayEquals(new byte[]{(byte) 0x1d, (byte) 0x34, (byte) 0xaf, (byte) 0xbc, (byte) 0x9e, (byte) 0x89}, decoded); verifyBackwardIterationOfDecodedBytes(bi, decoded); } @Test(expected=DecodeException.class) public void testDecodeInvalidCharacter() throws Exception { CodePointIterator.ofString("6h666f6f626172g").hexDecode().drain(); } @Test(expected=DecodeException.class) public void testDecodeInvalidLength() throws Exception { CodePointIterator.ofChars(new char[]{'1', 'F', 'A'}).hexDecode().drain(); } private void verifyBackwardIterationOfDecodedBytes(ByteIterator bi, String decoded) { int decodedSize = decoded.length(); for (int i = decodedSize - 1; i >= 0; i--) { assertTrue(bi.hasPrevious()); Assert.assertEquals(decoded.charAt(i), bi.previous()); } } private void verifyBackwardIterationOfDecodedBytes(ByteIterator bi, byte[] decoded) { int decodedSize = decoded.length; for (int i = decodedSize - 1; i >= 0; i--) { assertTrue(bi.hasPrevious()); assertEquals(decoded[i], (byte) bi.previous()); } } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/context/000077500000000000000000000000001361511066400254175ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/context/ContextPermissionTestCase.java000066400000000000000000000135101361511066400334130ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.context; import java.security.Permission; import java.security.PermissionCollection; import java.util.Enumeration; import org.junit.Test; import org.junit.Assert; /** * @author David M. Lloyd */ public class ContextPermissionTestCase { @Test public void testActions() { final ContextPermission allBlah = new ContextPermission("blah", "*"); final ContextPermission allBaz = new ContextPermission("baz", "*"); Assert.assertFalse(allBaz.implies(allBlah)); Assert.assertFalse(allBlah.implies(allBaz)); Assert.assertFalse(allBaz.equals(allBlah)); Assert.assertFalse(allBlah.equals(allBaz)); final ContextPermission justGetBlah = new ContextPermission("blah", "get,getGlobalDefault,getThreadDefault"); Assert.assertTrue(allBlah.implies(justGetBlah)); Assert.assertFalse(justGetBlah.implies(allBlah)); Assert.assertFalse(allBlah.equals(justGetBlah)); Assert.assertFalse(justGetBlah.equals(allBlah)); Assert.assertFalse(allBaz.implies(justGetBlah)); final ContextPermission justSetBlah = new ContextPermission("blah", "setGlobalDefault,setThreadDefault"); Assert.assertTrue(allBlah.implies(justSetBlah)); Assert.assertFalse(justSetBlah.implies(allBlah)); Assert.assertFalse(justSetBlah.implies(justGetBlah)); Assert.assertFalse(justGetBlah.implies(justSetBlah)); final ContextPermission justGetAndSetBlah = justGetBlah.withActions(justSetBlah.getActions()); Assert.assertTrue(allBlah.implies(justGetAndSetBlah)); Assert.assertTrue(justGetAndSetBlah.implies(justGetBlah)); Assert.assertTrue(justGetAndSetBlah.implies(justSetBlah)); } @Test public void testNames() { final ContextPermission allAll = new ContextPermission("*", "*"); final ContextPermission getAll = new ContextPermission("*", "get,getGlobalDefault,getThreadDefault"); final ContextPermission allBlah = new ContextPermission("blah", "*"); final ContextPermission allBaz = new ContextPermission("baz", "*"); final ContextPermission justGetBlah = new ContextPermission("blah", "get,getGlobalDefault,getThreadDefault"); final ContextPermission justSetBlah = new ContextPermission("blah", "setGlobalDefault,setThreadDefault"); final ContextPermission justGetAndSetBlah = justGetBlah.withActions(justSetBlah.getActions()); Assert.assertTrue(allAll.implies(allAll)); Assert.assertTrue(allAll.implies(getAll)); Assert.assertTrue(allAll.implies(allBlah)); Assert.assertTrue(allAll.implies(allBaz)); Assert.assertTrue(allAll.implies(justGetBlah)); Assert.assertTrue(allAll.implies(justSetBlah)); Assert.assertTrue(allAll.implies(justGetAndSetBlah)); Assert.assertTrue(getAll.implies(getAll)); Assert.assertTrue(getAll.implies(justGetBlah)); Assert.assertFalse(allBlah.implies(allAll)); Assert.assertFalse(getAll.implies(allAll)); Assert.assertFalse(getAll.implies(allBaz)); Assert.assertFalse(allBlah.implies(getAll)); } @Test public void testCollection() { final PermissionCollection collection = new ContextPermission("*", "*").newPermissionCollection(); Assert.assertFalse(collection.implies(new ContextPermission("blah", "get"))); collection.add(new ContextPermission("blah", "get")); Assert.assertTrue(collection.implies(new ContextPermission("blah", "get"))); Assert.assertFalse(collection.implies(new ContextPermission("blah", "*"))); Assert.assertFalse(collection.implies(new ContextPermission("*", "get"))); collection.add(new ContextPermission("blah", "getGlobalDefault")); Assert.assertTrue(collection.implies(new ContextPermission("blah", "get"))); Assert.assertTrue(collection.implies(new ContextPermission("blah", "getGlobalDefault"))); Assert.assertFalse(collection.implies(new ContextPermission("blah", "*"))); Assert.assertFalse(collection.implies(new ContextPermission("*", "get"))); Enumeration elements; elements = collection.elements(); Assert.assertTrue(elements.hasMoreElements()); Assert.assertEquals(new ContextPermission("blah", "get,getGlobalDefault"), elements.nextElement()); Assert.assertFalse(elements.hasMoreElements()); collection.add(new ContextPermission("*", "get")); elements = collection.elements(); Assert.assertTrue(elements.hasMoreElements()); Assert.assertEquals(new ContextPermission("*", "get"), elements.nextElement()); Assert.assertTrue(elements.hasMoreElements()); Assert.assertEquals(new ContextPermission("blah", "getGlobalDefault"), elements.nextElement()); Assert.assertFalse(elements.hasMoreElements()); collection.add(new ContextPermission("*", "*")); elements = collection.elements(); Assert.assertTrue(elements.hasMoreElements()); Assert.assertEquals(new ContextPermission("*", "*"), elements.nextElement()); Assert.assertFalse(elements.hasMoreElements()); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/expression/000077500000000000000000000000001361511066400261325ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/expression/ExpressionTestCase.java000066400000000000000000000442021361511066400325720ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.wildfly.common.Assert; /** * @author David M. Lloyd */ public class ExpressionTestCase { @Test public void testEmpty() throws Exception { final Expression expression = Expression.compile(""); assertEquals("Should expand to empty string", "", expression.evaluate((c, b) -> { fail("No expressions should be found"); })); } @Test public void testLiteral() throws Exception { final String expected = "this is a literal"; final Expression expression = Expression.compile(expected); assertEquals(expected, expression.evaluate((c, b) -> { fail("No expressions should be found"); })); } @Test public void testExpr1() throws Exception { final Expression expression = Expression.compile("${foo.bar}"); assertEquals("Should expand to empty string", "", expression.evaluate((c, b) -> { assertEquals("foo.bar", c.getKey()); })); } @Test public void testExpr1a() throws Exception { final Expression expression = Expression.compile("${foo.bar}"); assertEquals("fuzz", expression.evaluate((c, b) -> { assertEquals("foo.bar", c.getKey()); b.append("fuzz"); })); } @Test public void testNoTrim1() throws Exception { final Expression expression1 = Expression.compile(" ${foo.bar} "); assertEquals("", expression1.evaluate((c, b) -> {})); final Expression expression2 = Expression.compile(" ${foo.bar} ", Expression.Flag.NO_TRIM); assertEquals(" ", expression2.evaluate((c, b) -> {})); } @Test public void testNoTrim2() throws Exception { final Expression expression1 = Expression.compile(" this is a literal "); assertEquals("this is a literal", expression1.evaluate((c, b) -> {})); final Expression expression2 = Expression.compile(" this is a literal ", Expression.Flag.NO_TRIM); assertEquals(" this is a literal ", expression2.evaluate((c, b) -> {})); } @Test public void testExpr2() throws Exception { final Expression expression = Expression.compile("foo${foo.bar}bar"); assertEquals("foobazbar", expression.evaluate((c, b) -> { assertEquals("foo.bar", c.getKey()); b.append("baz"); })); } @Test public void testExpr3() throws Exception { final Expression expression = Expression.compile("foo${foo.bar}"); assertEquals("foobaz", expression.evaluate((c, b) -> { assertEquals("foo.bar", c.getKey()); b.append("baz"); })); } @Test public void testExpr4() throws Exception { final Expression expression = Expression.compile("${foo.bar}bar"); assertEquals("bazbar", expression.evaluate((c, b) -> { assertEquals("foo.bar", c.getKey()); b.append("baz"); })); } @Test public void testRecurseKey1() throws Exception { final Expression expression = Expression.compile("${${foo}.bar}bar"); assertEquals("bazbar", expression.evaluate((c, b) -> { final String key = c.getKey(); switch (key) { case "foo": b.append("bzz"); return; case "bzz.bar": b.append("baz"); return; default: throw Assert.impossibleSwitchCase(key); } })); } @Test public void testRecurseDefault1() throws Exception { final Expression expression = Expression.compile("${foo:${bar}}bar"); assertEquals("bazbar", expression.evaluate((c, b) -> { final String key = c.getKey(); switch (key) { case "foo": c.expandDefault(); return; case "bar": b.append("baz"); return; default: throw Assert.impossibleSwitchCase(key); } })); } @Test public void testGeneralExpansion1() throws Exception { final Expression expression = Expression.compile("foo${{zip}}${bar}", Expression.Flag.GENERAL_EXPANSION); assertEquals("foobazrab", expression.evaluate((c, b) -> { final String key = c.getKey(); switch (key) { case "zip": b.append("baz"); return; case "bar": b.append("rab"); return; default: throw Assert.impossibleSwitchCase(key); } })); } @Test public void testPoint1() throws Exception { final Expression expression = Expression.compile("${${foo}}", Expression.Flag.NO_RECURSE_KEY); expression.evaluate((c, b) -> { assertEquals("${foo}", c.getKey()); }); } @Test public void testPoint2() throws Exception { try { final Expression expression = Expression.compile("$"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint3() throws Exception { final Expression expression = Expression.compile("$", Expression.Flag.LENIENT_SYNTAX); assertEquals("$", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); final Expression expression2 = Expression.compile("foo$", Expression.Flag.LENIENT_SYNTAX); assertEquals("foo$", expression2.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint3_1() throws Exception { final Expression expression = Expression.compile("$$"); assertEquals("$", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); final Expression expression2 = Expression.compile("foo$$"); assertEquals("foo$", expression2.evaluate((c, b) -> { fail("unexpected expansion"); })); } // no testPoint4 @Test public void testPoint5() throws Exception { try { Expression.compile("${expr"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint6() throws Exception { final Expression expression = Expression.compile("${expr", Expression.Flag.LENIENT_SYNTAX); assertEquals("result", expression.evaluate((c, b) -> { assertEquals("expr", c.getKey()); b.append("result"); })); } @Test public void testPoint7() throws Exception { final Expression expression = Expression.compile("${expr::baz}", Expression.Flag.DOUBLE_COLON); assertEquals("result", expression.evaluate((c, b) -> { assertEquals("expr::baz", c.getKey()); b.append("result"); })); } @Test public void testPoint8() throws Exception { final Expression expression = Expression.compile("${expr::baz}"); assertEquals(":baz", expression.evaluate((c, b) -> { assertEquals("expr", c.getKey()); c.expandDefault(); })); } @Test public void testPoint9() throws Exception { try { Expression.compile("${expr:foo"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint10() throws Exception { final Expression expression = Expression.compile("${expr:foo", Expression.Flag.LENIENT_SYNTAX); assertEquals("foo", expression.evaluate((c, b) -> { assertEquals("expr", c.getKey()); c.expandDefault(); })); } @Test public void testPoint11() throws Exception { final Expression expression = Expression.compile("${expr:foo}bar"); assertEquals("foobar", expression.evaluate((c, b) -> { assertEquals("expr", c.getKey()); c.expandDefault(); })); } @Test public void testPoint12() throws Exception { final Expression expression = Expression.compile("${expr}bar"); assertEquals("foobar", expression.evaluate((c, b) -> { assertEquals("expr", c.getKey()); b.append("foo"); })); } @Test public void testPoint13() throws Exception { final Expression expression = Expression.compile("foo$$bar", Expression.Flag.MINI_EXPRS); assertEquals("foorizbar", expression.evaluate((c, b) -> { assertEquals("$", c.getKey()); b.append("riz"); })); } @Test public void testPoint14() throws Exception { final Expression expression = Expression.compile("foo$$bar"); assertEquals("foo$bar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint15() throws Exception { final Expression expression = Expression.compile("foo$}bar", Expression.Flag.MINI_EXPRS); assertEquals("foorizbar", expression.evaluate((c, b) -> { assertEquals("}", c.getKey()); b.append("riz"); })); } @Test public void testPoint16() throws Exception { final Expression expression = Expression.compile("foo${bar$}baz", Expression.Flag.LENIENT_SYNTAX); assertEquals("foorizbaz", expression.evaluate((c, b) -> { assertEquals("bar$", c.getKey()); b.append("riz"); })); } @Test public void testPoint17() throws Exception { try { Expression.compile("foo${bar$}baz"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint18() throws Exception { final Expression expression = Expression.compile("foo$}bar", Expression.Flag.LENIENT_SYNTAX); assertEquals("foo$}bar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint19() throws Exception { try { Expression.compile("foobar$}baz"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint20() throws Exception { final Expression expression = Expression.compile("foo$:baz", Expression.Flag.MINI_EXPRS); assertEquals("foobarbaz", expression.evaluate((c, b) -> { assertEquals(":", c.getKey()); b.append("bar"); })); } @Test public void testPoint21() throws Exception { final Expression expression = Expression.compile("${foo$:bar}", Expression.Flag.LENIENT_SYNTAX); assertEquals("baz", expression.evaluate((c, b) -> { assertEquals("foo$", c.getKey()); assertEquals("bar", c.getExpandedDefault()); b.append("baz"); })); } @Test public void testPoint22() throws Exception { try { Expression.compile("${foo$:bar}"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint23() throws Exception { final Expression expression = Expression.compile("foo$:bar", Expression.Flag.LENIENT_SYNTAX); assertEquals("foo$:bar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint24() throws Exception { try { Expression.compile("foo$:bar"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint25() throws Exception { final Expression expression = Expression.compile("foo$xbar", Expression.Flag.MINI_EXPRS); assertEquals("foobazbar", expression.evaluate((c, b) -> { assertEquals("x", c.getKey()); b.append("baz"); })); } @Test public void testPoint26() throws Exception { final Expression expression = Expression.compile("foo$xbar", Expression.Flag.LENIENT_SYNTAX); assertEquals("foo$xbar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint27() throws Exception { try { Expression.compile("foo$xbar"); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint28() throws Exception { final Expression expression = Expression.compile("${foo:bar}"); assertEquals("bar", expression.evaluate((c, b) -> { assertEquals("foo", c.getKey()); assertEquals("bar", c.getExpandedDefault()); c.expandDefault(); })); } @Test public void testPoint29() throws Exception { final Expression expression = Expression.compile("foo:bar"); assertEquals("foo:bar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint1_2() throws Exception { final Expression expression = Expression.compile("{${foo{bar}}}"); assertEquals("{xxx}", expression.evaluate((c, b) -> { assertEquals("foo{bar}", c.getKey()); b.append("xxx"); })); } @Test public void testPoint1_3() throws Exception { // also TP 30, 31 final Expression expression = Expression.compile("{${foo{bar}}}", Expression.Flag.NO_SMART_BRACES); assertEquals("{xxx}}", expression.evaluate((c, b) -> { assertEquals("foo{bar", c.getKey()); b.append("xxx"); })); } // no tp 32 @Test public void testPoint33() throws Exception { final Expression expression = Expression.compile("foo\\", Expression.Flag.LENIENT_SYNTAX, Expression.Flag.ESCAPES); assertEquals("foo\\", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint34() throws Exception { try { Expression.compile("foo\\", Expression.Flag.ESCAPES); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint35() throws Exception { final Expression expression = Expression.compile("foo\\nbar", Expression.Flag.ESCAPES); assertEquals("foo\nbar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint36() throws Exception { final Expression expression = Expression.compile("foo\\rbar", Expression.Flag.ESCAPES); assertEquals("foo\rbar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint37() throws Exception { final Expression expression = Expression.compile("foo\\tbar", Expression.Flag.ESCAPES); assertEquals("foo\tbar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint38() throws Exception { final Expression expression = Expression.compile("foo\\bbar", Expression.Flag.ESCAPES); assertEquals("foo\bbar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint39() throws Exception { final Expression expression = Expression.compile("foo\\fbar", Expression.Flag.ESCAPES); assertEquals("foo\fbar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint40() throws Exception { final Expression expression = Expression.compile("foo\\?bar", Expression.Flag.ESCAPES, Expression.Flag.LENIENT_SYNTAX); assertEquals("foo?bar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint41() throws Exception { try { Expression.compile("foo\\?bar", Expression.Flag.ESCAPES); fail("expected exception"); } catch (IllegalArgumentException e) { // OK } } @Test public void testPoint42() throws Exception { final Expression expression = Expression.compile("foo\\?bar"); assertEquals("foo\\?bar", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint43() throws Exception { // also tp 44 final Expression expression = Expression.compile("plain-content"); assertEquals("plain-content", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint45() throws Exception { final Expression expression = Expression.compile("W:\\\\workspace\\\\some-path\\\\xxxxyyyy", Expression.Flag.ESCAPES); assertEquals("W:\\workspace\\some-path\\xxxxyyyy", expression.evaluate((c, b) -> { fail("unexpected expansion"); })); } @Test public void testPoint46() throws Exception { // an empty default value is valid final Expression expression = Expression.compile("${foo.bar:}"); assertEquals("Should expand to empty string", "", expression.evaluate((c, b) -> { assertTrue(c.hasDefault()); assertEquals("", c.getExpandedDefault()); })); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/math/000077500000000000000000000000001361511066400246645ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/math/HashMathTestCase.java000066400000000000000000000071031361511066400306610ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.math; import static org.junit.Assert.*; import static org.wildfly.common.math.HashMath.*; import org.junit.Test; public class HashMathTestCase { @Test public void testPowerOfTwo() { assertEquals(0, roundToPowerOfTwo(0)); assertEquals(1, roundToPowerOfTwo(1)); assertEquals(4, roundToPowerOfTwo(3)); assertEquals(4, roundToPowerOfTwo(4)); assertEquals(8, roundToPowerOfTwo(5)); assertEquals(8, roundToPowerOfTwo(7)); assertEquals(8, roundToPowerOfTwo(8)); assertEquals(128, roundToPowerOfTwo(128)); assertEquals(256, roundToPowerOfTwo(129)); assertEquals(256, roundToPowerOfTwo(200)); assertEquals(256, roundToPowerOfTwo(255)); assertEquals(256, roundToPowerOfTwo(256)); assertEquals(0x2000_0000, roundToPowerOfTwo(0x2000_0000)); assertEquals(0x4000_0000, roundToPowerOfTwo(0x2000_0001)); assertEquals(0x4000_0000, roundToPowerOfTwo(0x3FFF_FFFF)); assertEquals(0x4000_0000, roundToPowerOfTwo(0x4000_0000)); } @Test public void testOrderedCommutative() { final int ab = multiHashOrdered(multiHashOrdered(1234, 65537, 13), 16633, 5342); final int ba = multiHashOrdered(multiHashOrdered(1234, 16633, 5342), 65537, 13); assertNotEquals(ab, ba); final int cd = multiHashOrdered(multiHashOrdered(0, 65537, 13), 16633, 5342); final int dc = multiHashOrdered(multiHashOrdered(0, 16633, 5342), 65537, 13); assertNotEquals(cd, dc); final int ef = multiHashOrdered(multiHashOrdered(0xf948_1829, 65537, 13), 16633, 5342); final int fe = multiHashOrdered(multiHashOrdered(0xf948_1829, 16633, 5342), 65537, 13); assertNotEquals(ef, fe); final int gh = multiHashOrdered(multiHashOrdered(0xf948_1829, 65537, 13), 16633, 0); final int hg = multiHashOrdered(multiHashOrdered(0xf948_1829, 16633, 0), 65537, 13); assertNotEquals(gh, hg); } @Test public void testUnorderedCommutative() { final int ab = multiHashUnordered(multiHashUnordered(1234, 65537, 13), 16633, 5342); final int ba = multiHashUnordered(multiHashUnordered(1234, 16633, 5342), 65537, 13); assertEquals(ab, ba); final int cd = multiHashUnordered(multiHashUnordered(0, 65537, 13), 16633, 5342); final int dc = multiHashUnordered(multiHashUnordered(0, 16633, 5342), 65537, 13); assertEquals(cd, dc); final int ef = multiHashUnordered(multiHashUnordered(0xf948_1829, 65537, 13), 16633, 5342); final int fe = multiHashUnordered(multiHashUnordered(0xf948_1829, 16633, 5342), 65537, 13); assertEquals(ef, fe); final int gh = multiHashUnordered(multiHashUnordered(0xf948_1829, 65537, 13), 16633, 0); final int hg = multiHashUnordered(multiHashUnordered(0xf948_1829, 16633, 0), 65537, 13); assertEquals(gh, hg); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/net/000077500000000000000000000000001361511066400245215ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/net/CidrAddressTableTest.java000066400000000000000000000253421361511066400313710ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import static org.junit.Assert.*; import org.junit.Test; public class CidrAddressTableTest { @Test public void testEmpty() { CidrAddressTable table = new CidrAddressTable<>(); assertTrue(table.isEmpty()); } @Test public void testSingle4() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet4Address("10.4.5.9"), 16), "meow"); assertEquals("meow", table.get(Inet.parseInet4Address("10.4.5.9"))); assertEquals("woof", table.getOrDefault(Inet.parseInet4Address("11.4.5.9"), "woof")); } @Test public void testDouble4() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet4Address("10.4.5.9"), 16), "meow"); table.put(CidrAddress.create(Inet.parseInet4Address("11.4.5.9"), 16), "nyan"); assertEquals("meow", table.get(Inet.parseInet4Address("10.4.5.9"))); assertEquals("nyan", table.get(Inet.parseInet4Address("11.4.5.9"))); assertEquals("woof", table.getOrDefault(Inet.parseInet4Address("12.4.5.9"), "woof")); } @Test public void testBig4() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet4Address("0.0.0.0"), 0), "the big block"); table.put(CidrAddress.create(Inet.parseInet4Address("8.8.8.8"), 32), "one DNS server"); table.put(CidrAddress.create(Inet.parseInet4Address("12.4.0.0"), 16), "twelve-four"); table.put(CidrAddress.create(Inet.parseInet4Address("127.0.0.0"), 8), "local stuff"); table.put(CidrAddress.create(Inet.parseInet4Address("10.0.0.0"), 8), "big private"); table.put(CidrAddress.create(Inet.parseInet4Address("10.0.0.0"), 12), "big private sub-block (1)"); table.put(CidrAddress.create(Inet.parseInet4Address("10.16.0.0"), 12), "big private sub-block (2)"); table.put(CidrAddress.create(Inet.parseInet4Address("192.168.1.0"), 24), "little private"); assertEquals("big private sub-block (1)", table.get(Inet.parseInet4Address("10.4.5.9"))); assertEquals("big private", table.get(Inet.parseInet4Address("10.33.5.9"))); assertEquals("the big block", table.get(Inet.parseInet4Address("11.4.5.9"))); assertEquals("the big block", table.get(Inet.parseInet4Address("8.8.8.9"))); assertEquals("the big block", table.get(Inet.parseInet4Address("8.8.8.7"))); assertEquals("one DNS server", table.get(Inet.parseInet4Address("8.8.8.8"))); assertEquals("little private", table.get(Inet.parseInet4Address("192.168.1.34"))); assertEquals("local stuff", table.get(Inet.parseInet4Address("127.0.0.1"))); assertEquals(8, table.size()); } @Test public void testVaryLengths4() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet4Address("10.4.5.9"), 16), "meow"); table.put(CidrAddress.create(Inet.parseInet4Address("10.4.5.9"), 17), "nyan"); assertEquals("meow", table.get(Inet.parseInet4Address("10.4.255.9"))); assertEquals("nyan", table.get(Inet.parseInet4Address("10.4.5.9"))); assertEquals("woof", table.getOrDefault(Inet.parseInet4Address("12.4.5.9"), "woof")); } @Test public void testRemove4() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet4Address("10.4.5.9"), 16), "meow"); table.put(CidrAddress.create(Inet.parseInet4Address("11.4.5.9"), 16), "nyan"); assertEquals("meow", table.removeExact(CidrAddress.create(Inet.parseInet4Address("10.4.0.0"), 16))); assertEquals(1, table.size()); assertEquals(null, table.removeExact(CidrAddress.create(Inet.parseInet4Address("10.4.0.0"), 16))); assertEquals(null, table.removeExact(CidrAddress.create(Inet.parseInet4Address("11.5.4.0"), 16))); assertFalse(table.removeExact(CidrAddress.create(Inet.parseInet4Address("11.4.0.0"), 16), "meow")); assertEquals(1, table.size()); assertTrue(table.removeExact(CidrAddress.create(Inet.parseInet4Address("11.4.0.0"), 16), "nyan")); assertTrue(table.isEmpty()); } @Test public void testReplace4() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet4Address("10.4.5.9"), 16), "meow"); table.put(CidrAddress.create(Inet.parseInet4Address("11.4.5.9"), 16), "nyan"); assertEquals("meow", table.replaceExact(CidrAddress.create(Inet.parseInet4Address("10.4.0.0"), 16), "purr")); assertEquals("purr", table.get(Inet.parseInet4Address("10.4.99.255"))); assertEquals(2, table.size()); assertFalse(table.replaceExact(CidrAddress.create(Inet.parseInet4Address("11.4.0.0"), 16), "meow", "purr")); assertTrue(table.replaceExact(CidrAddress.create(Inet.parseInet4Address("11.4.0.0"), 16), "nyan", "hiss")); assertEquals("hiss", table.get(Inet.parseInet4Address("11.4.100.200"))); } @Test public void testSingle6() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet6Address("1000::"), 16), "meow"); assertEquals("meow", table.get(Inet.parseInet6Address("1000:2000:3000::"))); assertEquals("woof", table.getOrDefault(Inet.parseInet6Address("1001:2000:3000::"), "woof")); } @Test public void testDouble6() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet6Address("1000::4.5.9.4"), 16), "meow"); table.put(CidrAddress.create(Inet.parseInet6Address("1100::3.4.5.9"), 16), "nyan"); assertEquals("meow", table.get(Inet.parseInet6Address("1000::ffff:44.55.69.99"))); assertEquals("nyan", table.get(Inet.parseInet6Address("1100:1::1:1100"))); assertEquals("woof", table.getOrDefault(Inet.parseInet6Address("1111:1::4ae4"), "woof")); } @Test public void testBig6() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet6Address("::"), 0), "the big block"); table.put(CidrAddress.create(Inet.parseInet6Address("::ffff:8.8.8.8"), 128), "one DNS server"); table.put(CidrAddress.create(Inet.parseInet6Address("12:4::"), 32), "twelve-four"); table.put(CidrAddress.create(Inet.parseInet6Address("ff01::"), 32), "local stuff"); table.put(CidrAddress.create(Inet.parseInet6Address("1010:1010:1010::"), 48), "big private sub-block (2)"); table.put(CidrAddress.create(Inet.parseInet6Address("1010::"), 16), "big private"); table.put(CidrAddress.create(Inet.parseInet6Address("1010:1010::"), 32), "big private sub-block (1)"); table.put(CidrAddress.create(Inet.parseInet6Address("4592:f092:33f2:6655::"), 64), "little private"); assertEquals("big private sub-block (1)", table.get(Inet.parseInet6Address("1010:1010:2993:9938:ff0f::"))); assertEquals("big private", table.get(Inet.parseInet6Address("1010:1011:2993:9938:ff0f::"))); assertEquals("the big block", table.get(Inet.parseInet6Address("9999::"))); assertEquals("the big block", table.get(Inet.parseInet6Address("ff02:20ff::"))); assertEquals("the big block", table.get(Inet.parseInet6Address("::ffff:8.8.8.7"))); assertEquals("one DNS server", table.get(Inet.parseInet6Address("::ffff:8.8.8.8"))); assertEquals("little private", table.get(Inet.parseInet6Address("4592:f092:33f2:6655:1234:4929:2929:1110"))); assertEquals("local stuff", table.get(Inet.parseInet6Address("ff01::1"))); assertEquals(8, table.size()); } @Test public void testVaryLengths6() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet6Address("fe3f:ff44::"), 32), "meow"); table.put(CidrAddress.create(Inet.parseInet6Address("fe3f:ff44::"), 33), "nyan"); assertEquals("meow", table.get(Inet.parseInet6Address("fe3f:ff44:8000::"))); assertEquals("nyan", table.get(Inet.parseInet6Address("fe3f:ff44:0000::"))); assertEquals("woof", table.getOrDefault(Inet.parseInet6Address("fe3f:ff45::"), "woof")); } @Test public void testRemove6() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet6Address("ee55:7711:6543:ab3d::"), 32), "meow"); table.put(CidrAddress.create(Inet.parseInet6Address("ee56:7722:73ec:01ee::"), 32), "nyan"); assertEquals("meow", table.removeExact(CidrAddress.create(Inet.parseInet6Address("ee55:7711::"), 32))); assertEquals(1, table.size()); assertEquals(null, table.removeExact(CidrAddress.create(Inet.parseInet6Address("ee55:7711::"), 32))); assertEquals(null, table.removeExact(CidrAddress.create(Inet.parseInet6Address("ee56::"), 16))); assertFalse(table.removeExact(CidrAddress.create(Inet.parseInet6Address("ee55:7711::"), 32), "meow")); assertEquals(1, table.size()); assertTrue(table.removeExact(CidrAddress.create(Inet.parseInet6Address("ee56:7722::"), 32), "nyan")); assertTrue(table.isEmpty()); } @Test public void testReplace6() { CidrAddressTable table = new CidrAddressTable<>(); table.put(CidrAddress.create(Inet.parseInet6Address("5e:4ffe::"), 32), "meow"); table.put(CidrAddress.create(Inet.parseInet6Address("5e:4fff::"), 32), "nyan"); assertEquals("meow", table.replaceExact(CidrAddress.create(Inet.parseInet6Address("5e:4ffe:f55f::"), 32), "purr")); assertEquals("purr", table.get(Inet.parseInet6Address("5e:4ffe:6011:222::44ee"))); assertEquals(2, table.size()); assertFalse(table.replaceExact(CidrAddress.create(Inet.parseInet6Address("5e:4ffe::"), 32), "meow", "purr")); assertTrue(table.replaceExact(CidrAddress.create(Inet.parseInet6Address("5e:4fff::"), 32), "nyan", "hiss")); assertEquals("hiss", table.get(Inet.parseInet6Address("5e:4fff:6:a::5:e"))); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/net/CidrAddressTest.java000066400000000000000000000246551361511066400304270ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import static org.junit.Assert.*; import org.junit.Test; public class CidrAddressTest { @Test public void testBasic4() { CidrAddress cidrAddress = CidrAddress.create(Inet.getInet4Address(127, 0, 0, 1), 32); assertEquals("127.0.0.1/32", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(127, 0, 0, 1), 8); assertEquals("127.0.0.0/8", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 0); assertEquals("0.0.0.0/0", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 1); assertEquals("128.0.0.0/1", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 2); assertEquals("192.0.0.0/2", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 3); assertEquals("224.0.0.0/3", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 4); assertEquals("240.0.0.0/4", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 5); assertEquals("248.0.0.0/5", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 6); assertEquals("252.0.0.0/6", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 7); assertEquals("254.0.0.0/7", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 8); assertEquals("255.0.0.0/8", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 9); assertEquals("255.128.0.0/9", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 10); assertEquals("255.192.0.0/10", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 11); assertEquals("255.224.0.0/11", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 12); assertEquals("255.240.0.0/12", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 13); assertEquals("255.248.0.0/13", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 14); assertEquals("255.252.0.0/14", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 15); assertEquals("255.254.0.0/15", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 16); assertEquals("255.255.0.0/16", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 17); assertEquals("255.255.128.0/17", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 18); assertEquals("255.255.192.0/18", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 19); assertEquals("255.255.224.0/19", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 20); assertEquals("255.255.240.0/20", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 21); assertEquals("255.255.248.0/21", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 22); assertEquals("255.255.252.0/22", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 23); assertEquals("255.255.254.0/23", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 24); assertEquals("255.255.255.0/24", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 25); assertEquals("255.255.255.128/25", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 26); assertEquals("255.255.255.192/26", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 27); assertEquals("255.255.255.224/27", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 28); assertEquals("255.255.255.240/28", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 29); assertEquals("255.255.255.248/29", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 30); assertEquals("255.255.255.252/30", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 31); assertEquals("255.255.255.254/31", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.getInet4Address(255, 255, 255, 255), 32); assertEquals("255.255.255.255/32", cidrAddress.toString()); } @Test public void testBasic6() { CidrAddress cidrAddress = CidrAddress.create(Inet.parseInet6Address("::1"), 128); assertEquals("::1/128", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("::1"), 0); assertEquals("::/0", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("ffff:ee55::5:34de:ffff"), 32); assertEquals("ffff:ee55::/32", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("ffff:ee55::5:34de:ffff"), 30); assertEquals("ffff:ee54::/30", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("ffff:ee55::5:34de:ffff"), 20); assertEquals("ffff:e000::/20", cidrAddress.toString()); } @Test public void testBasic6Scoped() { CidrAddress cidrAddress = CidrAddress.create(Inet.parseInet6Address("::1%1"), 128); assertEquals("::1%1/128", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("::1%1"), 0); assertEquals("::%1/0", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("ffff:ee55::5:34de:ffff%1"), 32); assertEquals("ffff:ee55::%1/32", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("ffff:ee55::5:34de:ffff%1"), 30); assertEquals("ffff:ee54::%1/30", cidrAddress.toString()); cidrAddress = CidrAddress.create(Inet.parseInet6Address("ffff:ee55::5:34de:ffff%1"), 20); assertEquals("ffff:e000::%1/20", cidrAddress.toString()); } @Test public void testMatch4() { CidrAddress cidrAddress = CidrAddress.create(Inet.parseInet4Address("10.10.20.20"), 16); assertEquals("10.10.0.0/16", cidrAddress.toString()); assertTrue(cidrAddress.matches(Inet.parseInet4Address("10.10.0.0"))); assertTrue(cidrAddress.matches(Inet.parseInet4Address("10.10.10.10"))); assertTrue(cidrAddress.matches(Inet.parseInet4Address("10.10.255.255"))); assertFalse(cidrAddress.matches(Inet.parseInet4Address("10.11.255.255"))); assertFalse(cidrAddress.matches(Inet.parseInet4Address("0.0.20.20"))); } @Test public void testMatch6() { CidrAddress cidrAddress = CidrAddress.create(Inet.parseInet6Address("fed:f00d::3456:feed"), 32); assertEquals("fed:f00d::/32", cidrAddress.toString()); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:0f:beef::"))); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:0f:beef::%1"))); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:c0ff:ee::"))); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:beef:0f:f00d::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:beef:0f:f00d::%1"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed::%1"))); } @Test public void testMatch6Scoped() { CidrAddress cidrAddress = CidrAddress.create(Inet.parseInet6Address("fed:f00d::3456:feed%1"), 32); assertEquals("fed:f00d::%1/32", cidrAddress.toString()); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:0f:beef::%1"))); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:c0ff:ee::%1"))); assertTrue(cidrAddress.matches(Inet.parseInet6Address("fed:f00d::%1"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:0f:beef::%2"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:c0ff:ee::%2"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:f00d::%2"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:0f:beef::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:f00d:c0ff:ee::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:f00d::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:beef:0f:f00d::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed:beef:0f:f00d::%1"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed::"))); assertFalse(cidrAddress.matches(Inet.parseInet6Address("fed::%1"))); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/net/InetTest.java000066400000000000000000000146101361511066400271250ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.net; import static org.junit.Assert.*; import static org.wildfly.common.net.Inet.*; import java.net.InetAddress; import java.net.UnknownHostException; import org.junit.Test; /** * @author David M. Lloyd */ public class InetTest { @Test public void testRepresentation1() throws Exception { assertEquals("::1", toOptimalString(InetAddress.getByName("0:0::1"))); assertEquals("::", toOptimalString(InetAddress.getByName("0:0:0:0:0:0:0:0"))); assertEquals("1::", toOptimalString(InetAddress.getByName("1:0:0:0:0:0:0:0"))); assertEquals("1:1::1:1", toOptimalString(InetAddress.getByName("1:1:0:0:0:0:1:1"))); assertEquals("1:1::1:1", toOptimalString(getInet6Address(1, 1, 0, 0, 0, 0, 1, 1))); assertEquals("1:2:3:4:5:6:7:8", toOptimalString(InetAddress.getByName("1:2:3:4:5:6:7:8"))); assertEquals("9:a:b:cc:dd:0:eee:ffff", toOptimalString(InetAddress.getByName("0009:000A:000B:00CC:00DD:0000:0EEE:FFFF"))); assertEquals("1:2:3:0:5:6:7:8", toOptimalString(InetAddress.getByName("1:2:3:0:5:6:7:8"))); assertEquals("1:0:3:0:5:6:7:8", toOptimalString(InetAddress.getByName("1:0:3:0:5:6:7:8"))); assertEquals("1:0:3::6:7:8", toOptimalString(InetAddress.getByName("1:0:3:0:0:6:7:8"))); assertEquals("1::4:0:0:7:8", toOptimalString(InetAddress.getByName("1:0:0:4:0:0:7:8"))); assertEquals("::ffff:0:127.0.0.1", toOptimalString(InetAddress.getByName("0::ffff:0:127.0.0.1"))); assertEquals("::ffff:127.0.0.1", toOptimalString(toInet6Address(getInet4Address(127,0,0,1)))); } @Test public void testUnresolved() throws Exception { assertEquals("foo bar", getHostNameIfResolved(InetAddress.getByAddress("foo bar", new byte[]{ 127, 0, 0, 1}))); assertEquals("", getHostNameIfResolved(InetAddress.getByAddress("", new byte[]{ 127, 0, 0, 1}))); assertNull(getHostNameIfResolved(InetAddress.getByAddress(new byte[]{ 127, 0, 0, 1}))); } @Test public void testInet6AddressToBytes() throws Exception { checkAddressToBytes("::"); checkAddressToBytes("::1"); checkAddressToBytes("::7:8"); checkAddressToBytes("1::"); checkAddressToBytes("1:2::"); checkAddressToBytes("1:2::7:8"); checkAddressToBytes("1:2:3:4:5::7:8"); checkAddressToBytes("1:2:3:4:5:6:7:8"); checkAddressToBytes("ff1:ff2:ff3:ff4:ff5:ff6:ff7:ff8"); checkAddressToBytes("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); checkAddressToBytes("000F:00EF:0DEF:CDEF::"); assertArrayEquals(bytes(0, 0, 0, 0, 0, 0xffff, 0x0a00, 1), parseInet6AddressToBytes("::ffff:10.0.0.1")); assertArrayEquals(bytes(0, 0, 0, 0, 0, 0, 0x7f00, 1), parseInet6AddressToBytes("::127.0.0.1")); assertArrayEquals(bytes(0, 0, 0, 0, 0, 0, 0x7f00, 1), parseInet6AddressToBytes("0:0:0:0:0:0:127.0.0.1")); assertNull(parseInet6AddressToBytes("1:2:3:4:5:6:7")); assertNull(parseInet6AddressToBytes("1:2:3:4:5:6:7:8:9")); assertNull(parseInet6AddressToBytes("1:2:3:4:5:6:7:1.1.1.1")); assertNull(parseInet6AddressToBytes("1:2:3:4:5:1.1.1.1")); assertNull(parseInet6AddressToBytes("1:2::5::8")); assertNull(parseInet6AddressToBytes("1:2:::8")); assertNull(parseInet6AddressToBytes("1:2:::10000")); assertNull(parseInet6AddressToBytes("1:2:::x")); assertNull(parseInet6AddressToBytes("::1.2.3")); assertNull(parseInet6AddressToBytes("::1.2.3.4.5")); assertNull(parseInet6AddressToBytes("::1.2.3.256")); } @Test public void testInet4AddressToBytes() throws UnknownHostException { assertArrayEquals(bytes(1, 2, 3, 4), parseInet4AddressToBytes("1.2.3.4")); assertArrayEquals(bytes(1, 0, 0, 10), parseInet4AddressToBytes("1.0.0.010")); // octal numbers not supported assertArrayEquals(bytes(255, 255, 255, 255), parseInet4AddressToBytes("255.255.255.255")); assertNull(parseInet4AddressToBytes(".1.1.1")); assertNull(parseInet4AddressToBytes("1..1.1")); assertNull(parseInet4AddressToBytes("1.1.1.")); assertNull(parseInet4AddressToBytes("1.1.1.1.1")); assertNull(parseInet4AddressToBytes("1.1.1.256")); // higher than 256 numbers not supported assertNull(parseInet4AddressToBytes("1.1.1.0256")); // octal numbers not supported assertNull(parseInet4AddressToBytes("1.1.1.0xf")); // hexadecimal numbers not supported assertNull(parseInet4AddressToBytes("1.1.1")); // short notation not supported assertNull(parseInet4AddressToBytes("1.1")); assertNull(parseInet4AddressToBytes("1")); } private void checkAddressToBytes(String ipv6) throws UnknownHostException { byte[] bytes = parseInet6AddressToBytes(ipv6); assertNotNull(bytes); assertArrayEquals(InetAddress.getByName(ipv6).getAddress(), bytes); } private byte[] bytes(int s1, int s2, int s3, int s4) { return new byte[] {(byte) s1, (byte) s2, (byte) s3, (byte) s4}; } private byte[] bytes(int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8) { byte[] bytes = new byte[16]; bytes[0] = (byte) (s1 >> 8); bytes[1] = (byte) s1; bytes[2] = (byte) (s2 >> 8); bytes[3] = (byte) s2; bytes[4] = (byte) (s3 >> 8); bytes[5] = (byte) s3; bytes[6] = (byte) (s4 >> 8); bytes[7] = (byte) s4; bytes[8] = (byte) (s5 >> 8); bytes[9] = (byte) s5; bytes[10] = (byte) (s6 >> 8); bytes[11] = (byte) s6; bytes[12] = (byte) (s7 >> 8); bytes[13] = (byte) s7; bytes[14] = (byte) (s8 >> 8); bytes[15] = (byte) s8; return bytes; } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/os/000077500000000000000000000000001361511066400243545ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/os/ProcessTest.java000066400000000000000000000021141361511066400274730ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.os; import org.junit.Test; /** * @author David M. Lloyd */ public class ProcessTest { public ProcessTest() { } @Test public void printProcessInfo() { System.out.println("Process ID: " + Process.getProcessId()); System.out.println("Process name: " + Process.getProcessName()); } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/rpc/000077500000000000000000000000001361511066400245175ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/rpc/TestRemoteExceptionCause.java000066400000000000000000000205061361511066400323200ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.common.rpc; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.sql.SQLException; import java.util.function.Supplier; import javax.transaction.xa.XAException; import org.junit.Test; import org.wildfly.common.function.ExceptionBiConsumer; public class TestRemoteExceptionCause { @Test public void className() throws Exception { Throwable t = new XAException(XAException.XAER_RMERR); RemoteExceptionCause cause = RemoteExceptionCause.of(t); assertEquals(XAException.class.getName(), cause.getExceptionClassName()); assertEquals(TestRemoteExceptionCause.class.getName(), cause.getStackTrace()[0].getClassName()); assertNull(cause.getMessage()); } @Test public void message() throws Exception { final String message = "This one has a message"; Throwable t = new NullPointerException(message); RemoteExceptionCause cause = RemoteExceptionCause.of(t); assertEquals(message, cause.getMessage()); assertTrue(cause.toString().endsWith(": " + message)); t = new IllegalStateException(); cause = RemoteExceptionCause.of(t); assertNull(cause.getMessage()); assertFalse(cause.toString().contains(":")); } @Test public void fields() throws Exception { Throwable t = new XAException(XAException.XAER_RMERR); RemoteExceptionCause cause = RemoteExceptionCause.of(t); assertEquals(1, cause.getFieldNames().size()); assertTrue(cause.getFieldNames().contains("errorCode")); assertEquals("-3", cause.getFieldValue("errorCode")); t = new IllegalArgumentException("foo bar baz"); cause = RemoteExceptionCause.of(t); assertEquals(0, cause.getFieldNames().size()); t = new SQLException("reason", "bad state", 12345); cause = RemoteExceptionCause.of(t); assertEquals(0, cause.getFieldNames().size()); } @Test public void cause() throws Exception { Throwable t = new IllegalStateException("outer", new NullPointerException("inner")); RemoteExceptionCause cause = RemoteExceptionCause.of(t); assertEquals(IllegalStateException.class.getName(), cause.getExceptionClassName()); assertEquals("outer", cause.getMessage()); assertNotNull(cause.getCause()); assertEquals(NullPointerException.class.getName(), cause.getCause().getExceptionClassName()); assertEquals("inner", cause.getCause().getMessage()); assertNull(cause.getCause().getCause()); } @Test public void loop() throws Exception { Throwable t1 = new IllegalStateException(); Throwable t2 = new NullPointerException(); Throwable t3 = new IllegalArgumentException(); t1.initCause(t2); t2.initCause(t3); t3.initCause(t1); RemoteExceptionCause cause = RemoteExceptionCause.of(t1); assertEquals(IllegalStateException.class.getName(), cause.getExceptionClassName()); assertEquals(NullPointerException.class.getName(), cause.getCause().getExceptionClassName()); assertEquals(IllegalArgumentException.class.getName(), cause.getCause().getCause().getExceptionClassName()); assertSame(cause, cause.getCause().getCause().getCause()); } private void doSerialTest(Supplier supplier, ExceptionBiConsumer resultHandler) throws Exception { final Throwable throwable = supplier.get(); RemoteExceptionCause cause = RemoteExceptionCause.of(throwable); final ByteArrayOutputStream os = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(os); cause.writeToStream(dos); dos.flush(); final ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); final DataInputStream dis = new DataInputStream(is); resultHandler.accept(throwable, RemoteExceptionCause.readFromStream(dis)); } @Test public void serial0() throws Exception { doSerialTest(() -> new SQLException("reason", "sql-state", 12345), (t, c) -> { assertEquals(t.getClass().getName(), c.getExceptionClassName()); assertStackTraceArrayEquals(t, c); }); } @Test public void serial1() throws Exception { doSerialTest(() -> { Throwable t = new XAException(XAException.XAER_RMERR); t.initCause(new NullPointerException("Null pointer!")); return t; }, (t, c) -> { assertEquals(t.getClass().getName(), c.getExceptionClassName()); assertEquals(t.getCause().getClass().getName(), c.getCause().getExceptionClassName()); assertStackTraceArrayEquals(t, c); assertStackTraceArrayEquals(t.getCause(), c.getCause()); }); } @Test public void serial2() throws Exception { // cause loop doSerialTest(() -> { Throwable t1 = new IllegalStateException(); Throwable t2 = new NullPointerException(); Throwable t3 = new IllegalArgumentException(); t1.initCause(t2); t2.initCause(t3); t3.initCause(t1); return t1; }, (t, c) -> { assertEquals(t.getClass().getName(), c.getExceptionClassName()); assertEquals(t.getCause().getClass().getName(), c.getCause().getExceptionClassName()); assertEquals(t.getCause().getCause().getClass().getName(), c.getCause().getCause().getExceptionClassName()); assertSame(c.getCause().getCause().getCause(), c); assertStackTraceArrayEquals(t, c); assertStackTraceArrayEquals(t.getCause(), c.getCause()); }); } @Test public void serial3() throws Exception { // suppressed loop doSerialTest(() -> { Throwable t1 = new IllegalStateException(); Throwable t2 = new NullPointerException(); Throwable t3 = new IllegalArgumentException(); t1.addSuppressed(t2); t2.addSuppressed(t3); t3.addSuppressed(t1); return t1; }, (t, c) -> { assertEquals(t.getClass().getName(), c.getExceptionClassName()); assertEquals(t.getSuppressed()[0].getClass().getName(), ((RemoteExceptionCause) c.getSuppressed()[0]).getExceptionClassName()); assertEquals(t.getSuppressed()[0].getSuppressed()[0].getClass().getName(), ((RemoteExceptionCause) c.getSuppressed()[0].getSuppressed()[0]).getExceptionClassName()); assertSame(c.getSuppressed()[0].getSuppressed()[0].getSuppressed()[0], c); assertStackTraceArrayEquals(t, c); }); } static void assertStackTraceArrayEquals(Throwable t1, Throwable t2) { if (t1 == t2) return; assertNotNull("t1", t1); assertNotNull("t2", t2); final StackTraceElement[] s1 = t1.getStackTrace(); final StackTraceElement[] s2 = t2.getStackTrace(); if (s1 == s2) return; final int length = s1.length; assertEquals("Stack trace lengths differ", length, s2.length); for (int i = 0; i < length; i ++) { assertEquals("Class name difference at index " + i, s1[i].getClassName(), s2[i].getClassName()); assertEquals("Method name difference at index " + i, s1[i].getMethodName(), s2[i].getMethodName()); assertEquals("File name difference at index " + i, s1[i].getFileName(), s2[i].getFileName()); assertEquals("Line number difference at index " + i, s1[i].getLineNumber(), s2[i].getLineNumber()); } } } wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/string/000077500000000000000000000000001361511066400252415ustar00rootroot00000000000000CompositeCharSequenceTestCase.java000066400000000000000000000055011361511066400337130ustar00rootroot00000000000000wildfly-common-1.5.3.Final/src/test/java/org/wildfly/common/stringpackage org.wildfly.common.string; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.stream.IntStream; import org.junit.Test; import org.wildfly.common.string.CompositeCharSequence; /** * Unit test for {@link CompositeCharSequence}. * @author Paul Ferraro */ public class CompositeCharSequenceTestCase { private final CharSequence sequence = new CompositeCharSequence("01", "23", "45"); @Test public void length() { assertEquals(6, this.sequence.length()); } @Test public void string() { assertEquals("012345", this.sequence.toString()); } @Test public void charAt() { for (int i = -1; i < 7; ++i) { try { char result = this.sequence.charAt(i); if ((i < 0) || (i >= 6)) { fail(String.format("charAt(%d) returned '%s', but IndexOutOfBoundsException was expected", i, result)); } assertEquals('0' + i, result); } catch (IndexOutOfBoundsException e) { if ((i >= 0) && (i < 6)) { fail(String.format("Unexpected IndexOutOfBoundsException during charAt(%d)", i)); } } } } @Test public void subSequence() { for (int i = -1; i < 7; ++i) { for (int j = -1; j <= 7; ++j) { try { CharSequence result = this.sequence.subSequence(i, j); if ((i < 0) || (i > j) || (j > 6)) { fail(String.format("subSequence(%d, %d) returned '%s', but IndexOutOfBoundsException was expected", i, j, result.toString())); } StringBuilder expected = new StringBuilder(j - i); IntStream.range(i, j).forEach(value -> expected.append((char) ('0' + value))); assertEquals(expected.toString(), result.toString()); } catch (IndexOutOfBoundsException e) { if ((i >= 0) && (j <= 6) && (i <= j)) { fail(String.format("Unexpected IndexOutOfBoundsException during subSequence(%d, %d)", i, j)); } } } } } @Test public void equals() { assertTrue(this.sequence.equals("012345")); assertTrue(this.sequence.equals(new CompositeCharSequence("012", "345"))); assertTrue(this.sequence.equals(new CompositeCharSequence("012345"))); } @Test public void hash() { int hashCode = this.sequence.hashCode(); assertEquals("012345".hashCode(), hashCode); assertEquals(new CompositeCharSequence("012", "345").hashCode(), hashCode); assertEquals(new CompositeCharSequence("012345").hashCode(), hashCode); } }