file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
1
// We define the operation of splitting // a binary number n into two numbers // a(n), b(n) as follows. Let 0 ≤ i1 < i2 < // . . . < ik be the indices of the bits (with // the least significant bit having index 0) in // n that are 1. Then the indices of the bits // of a(n) that are 1 are i1, i3, i5, . . . and the // indices of the bits of b(n) that are 1 are // i2, i4, i6, . . . // For example, if n is 110110101 in binary // then, again in binary, we have a = // 010010001 and b = 100100100. // Input // Each test case consists of a single integer // n between 1 and 231 − 1 written in standard decimal (base 10) format on a single line. Input is // terminated by a line containing ‘0’ which should not be processed. // Output // The output for each test case consists of a single line, containing the integers a(n) and b(n) separated // by a single space. Both a(n) and b(n) should be written in decimal format. // Sample Input // 6 // 7 // 13 // 0 // Sample Output // 2 4 // 5 2 // 9 4 /** * Created by kdn251 on 2/10/17. */ import java.util.*; import java.io.*; public class SplittingNumbers { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while((line = br.readLine()) != null) { //read number int number = Integer.parseInt(line); //terminate if number is zero if(number == 0) break; //intialize variables int count = 0; int a = 0; int b = 0; while(number > 0) { //get lowest set bit int currentBit = number ^ (number & (number - 1)); //if count is even or a with current bit if(count % 2 == 0) { a |= currentBit; } //if count is odd or b with current bit else { b |= currentBit; } //increment count count++; //clear lowest set bit for next iteration number &= (number - 1); } //print a and b System.out.println(a + " " + b); } } }
kdn251/interviews
uva/SplittingNumbers.java
2
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/CoordIJK.java
3
package com.macro.mall.search.domain; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.Setting; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; /** * 搜索商品的信息 * Created by macro on 2018/6/19. */ @Data @EqualsAndHashCode @Document(indexName = "pms") @Setting(shards = 1,replicas = 0) public class EsProduct implements Serializable { private static final long serialVersionUID = -1L; @Id private Long id; @Field(type = FieldType.Keyword) private String productSn; private Long brandId; @Field(type = FieldType.Keyword) private String brandName; private Long productCategoryId; @Field(type = FieldType.Keyword) private String productCategoryName; private String pic; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String name; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String subTitle; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String keywords; private BigDecimal price; private Integer sale; private Integer newStatus; private Integer recommandStatus; private Integer stock; private Integer promotionType; private Integer sort; @Field(type = FieldType.Nested, fielddata = true) private List<EsProductAttributeValue> attrValueList; }
macrozheng/mall
mall-search/src/main/java/com/macro/mall/search/domain/EsProduct.java
4
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import java.lang.ref.WeakReference; import java.util.Locale; import java.util.ServiceConfigurationError; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.CheckForNull; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Jesse Wilson */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault final class Platform { private static final Logger logger = Logger.getLogger(Platform.class.getName()); private static final PatternCompiler patternCompiler = loadPatternCompiler(); private Platform() {} static CharMatcher precomputeCharMatcher(CharMatcher matcher) { return matcher.precomputedInternal(); } static <T extends Enum<T>> Optional<T> getEnumIfPresent(Class<T> enumClass, String value) { WeakReference<? extends Enum<?>> ref = Enums.getEnumConstants(enumClass).get(value); /* * We use `fromNullable` instead of `of` because `WeakReference.get()` has a nullable return * type. * * In practice, we are very unlikely to see `null`: The `WeakReference` to the enum constant * won't be cleared as long as the enum constant is referenced somewhere, and the enum constant * is referenced somewhere for as long as the enum class is loaded. *Maybe in theory* the enum * class could be unloaded after the above call to `getEnumConstants` but before we call * `get()`, but that is vanishingly unlikely. */ return ref == null ? Optional.absent() : Optional.fromNullable(enumClass.cast(ref.get())); } static String formatCompact4Digits(double value) { return String.format(Locale.ROOT, "%.4g", value); } static boolean stringIsNullOrEmpty(@CheckForNull String string) { return string == null || string.isEmpty(); } /** * Returns the string if it is not null, or an empty string otherwise. * * @param string the string to test and possibly return * @return {@code string} if it is not null; {@code ""} otherwise */ static String nullToEmpty(@CheckForNull String string) { return (string == null) ? "" : string; } /** * Returns the string if it is not empty, or a null string otherwise. * * @param string the string to test and possibly return * @return {@code string} if it is not empty; {@code null} otherwise */ @CheckForNull static String emptyToNull(@CheckForNull String string) { return stringIsNullOrEmpty(string) ? null : string; } static CommonPattern compilePattern(String pattern) { Preconditions.checkNotNull(pattern); return patternCompiler.compile(pattern); } static boolean patternCompilerIsPcreLike() { return patternCompiler.isPcreLike(); } private static PatternCompiler loadPatternCompiler() { return new JdkPatternCompiler(); } private static void logPatternCompilerError(ServiceConfigurationError e) { logger.log(Level.WARNING, "Error loading regex compiler, falling back to next option", e); } private static final class JdkPatternCompiler implements PatternCompiler { @Override public CommonPattern compile(String pattern) { return new JdkPattern(Pattern.compile(pattern)); } @Override public boolean isPcreLike() { return true; } } }
google/guava
guava/src/com/google/common/base/Platform.java
5
// Companion Code to the paper "Generative Forests" by R. Nock and M. Guillame-Bert. import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Algorithm *****/ class SplitDetails implements Debuggable { // records the split details of a split // important for split_observations, since some observations can have unknown values and thus this // needs to be computed & recorded ONCE int index_feature; int index_split; int[][] split_observations; SplitDetails(int index_f, int index_s, int[][] split_o) { index_feature = index_f; index_split = index_s; split_observations = split_o; } } public class Algorithm implements Debuggable { public static String LEAF_CHOICE_RANDOMIZED_WITH_NON_ZERO_EMPIRICAL_MEASURE = "LEAF_CHOICE_RANDOMIZED_WITH_NON_ZERO_EMPIRICAL_MEASURE", LEAF_CHOICE_HEAVIEST_LEAF_AMONG_TREES = "LEAF_CHOICE_HEAVIEST_LEAF_AMONG_TREES"; // different ways of picking a leaf public static String[] LEAF_CHOICE = { LEAF_CHOICE_RANDOMIZED_WITH_NON_ZERO_EMPIRICAL_MEASURE, LEAF_CHOICE_HEAVIEST_LEAF_AMONG_TREES }; public static double MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING = 1.0; // boosting can "peel off" support with zero empirical card: this requires minimum local card at // new leaf public static double MINIMUM_P_R_FOR_BOOSTING = EPS2; // minimum estimated weight of empirical measure to allow a split for EOGT public static int MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION = 1000; // if the total number of tests to be done is larger than this, does random picking of tests for // this number of iterations (else is exhaustive) public static int STEPS_TO_COMPUTE_DENSITY_ESTIMATION = 100; // interval to save density estimation values public static void CHECK_LEAF_CHOICE_VALID(String s) { int i = 0; do { if (LEAF_CHOICE[i].equals(s)) return; else i++; } while (i < LEAF_CHOICE.length); Dataset.perror("Algorithm.class :: no such choice as " + s + " for leaf choice"); } Dataset myDS; GenerativeModelBasedOnEnsembleOfTrees geot; // parameters for learning int nb_iterations, initial_number_of_trees; boolean nb_trees_increase_allowed; String how_to_choose_leaf, splitting_method; public static String[] DENSITY_ESTIMATION_OUTPUT_TYPE = {"LIKELIHOODS", "LOG_LIKELIHOODS"}; public static int INDEX_DENSITY_ESTIMATION_OUTPUT_TYPE = 0; // type of output for density estimation Vector<Vector<Double>> density_estimation_outputs_likelihoods; Vector<Vector<Double>> density_estimation_outputs_log_likelihoods; Algorithm( Dataset ds, int name, int nb_iterations, int initial_number_of_trees, String split_m, boolean generative_forest) { this(ds, name); if (generative_forest) geot.generative_forest(); else geot.ensemble_of_generative_trees(); this.nb_iterations = nb_iterations; this.initial_number_of_trees = initial_number_of_trees; this.how_to_choose_leaf = Algorithm.LEAF_CHOICE_HEAVIEST_LEAF_AMONG_TREES; splitting_method = split_m; nb_trees_increase_allowed = false; } Algorithm(Dataset ds, int n) { myDS = ds; geot = new GenerativeModelBasedOnEnsembleOfTrees(ds, n); } public GenerativeModelBasedOnEnsembleOfTrees learn_geot() { if (nb_trees_increase_allowed) Dataset.perror("NOT YET"); if (geot.generative_forest) System.out.print(" [GF] "); else if (geot.ensemble_of_generative_trees) System.out.print("[EOGT] "); geot.init(initial_number_of_trees); HashSet<MeasuredSupportAtTupleOfNodes> tuples_of_leaves_with_positive_measure_geot = new HashSet<>(); if (splitting_method.equals(Wrapper.BOOSTING)) tuples_of_leaves_with_positive_measure_geot.add( new MeasuredSupportAtTupleOfNodes(geot, false, true, -1)); int i; Node leaf; boolean ok; Vector<Double> current_likelihood; Vector<Double> current_log_likelihood; double[][] avs = new double[2][]; // [0][] = likelihood; [1][] = loglikelihood avs[0] = new double[2]; avs[1] = new double[2]; if ((geot.generative_forest) && (myDS.myDomain.myW.density_estimation)) { density_estimation_outputs_likelihoods = new Vector<>(); density_estimation_outputs_log_likelihoods = new Vector<>(); } for (i = 0; i < nb_iterations; i++) { leaf = null; ok = true; leaf = choose_leaf(how_to_choose_leaf); if (leaf == null) { Dataset.warning(" no splittable leaf found "); ok = false; } if (ok) { if (geot.generative_forest) ok = split_generative_forest(leaf, tuples_of_leaves_with_positive_measure_geot); else if (geot.ensemble_of_generative_trees) ok = split_ensemble_of_generative_trees(leaf, tuples_of_leaves_with_positive_measure_geot); else Dataset.perror("Algorithm.class :: no such option available yet"); } if (!ok) { System.out.print("X "); break; } else System.out.print("."); if (i % 10 == 0) System.out.print(myDS.myDomain.memString()); leaf.myTree.checkConsistency(); if ((i % Algorithm.STEPS_TO_COMPUTE_DENSITY_ESTIMATION == 0) && (geot.generative_forest) && (myDS.myDomain.myW.density_estimation)) { current_likelihood = new Vector<>(); current_log_likelihood = new Vector<>(); avs = geot.expected_density_estimation_output(); current_likelihood.addElement(new Double(i)); current_likelihood.addElement(new Double(avs[0][0])); current_likelihood.addElement(new Double(avs[0][1])); density_estimation_outputs_likelihoods.addElement(current_likelihood); current_log_likelihood.addElement(new Double(i)); current_log_likelihood.addElement(new Double(avs[1][0])); current_log_likelihood.addElement(new Double(avs[1][1])); density_estimation_outputs_log_likelihoods.addElement(current_log_likelihood); } } System.out.print(" [soft_probs] "); geot.compute_probabilities_soft(); return geot; } Node choose_leaf(String how_to_choose_leaf) { Algorithm.CHECK_LEAF_CHOICE_VALID(how_to_choose_leaf); // a leaf has a handle to its tree so can pick a leaf regardless of the tree if (geot.trees == null) Dataset.perror("Algorithm.class :: no tree to choose a leaf from"); int i, j, meas = -1; Node n, ret = null; boolean firstleaf = true; Iterator it; if (how_to_choose_leaf.equals(Algorithm.LEAF_CHOICE_HEAVIEST_LEAF_AMONG_TREES)) { for (i = 0; i < geot.trees.size(); i++) { it = geot.trees.elementAt(i).leaves.iterator(); while (it.hasNext()) { n = (Node) it.next(); if ((n.observations_in_node) && (n.has_feature_tests()) && ((firstleaf) || (n.observation_indexes_in_node.length > meas))) { firstleaf = false; ret = n; meas = n.observation_indexes_in_node.length; } } } } return ret; } public boolean split_generative_forest(Node leaf, HashSet<MeasuredSupportAtTupleOfNodes> tol) { if (!leaf.is_leaf) Dataset.perror("Algorithm.class :: " + leaf + " is not a leaf"); FeatureTest[][] all_feature_tests = new FeatureTest[leaf.node_support.dim()][]; // x = feature index, y = split index boolean[] splittable_feature = new boolean[leaf.node_support.dim()]; boolean at_least_one_splittable_feature = false; SplitDetails sd = null; int i, nb_total_splits = 0, j, index_f = -1, index_s = -1; Vector<FeatureTest> dumft; for (i = 0; i < leaf.node_support.dim(); i++) { dumft = FeatureTest.ALL_FEATURE_TESTS(leaf.node_support.feature(i), myDS); if (dumft != null) { at_least_one_splittable_feature = true; splittable_feature[i] = true; all_feature_tests[i] = new FeatureTest[dumft.size()]; for (j = 0; j < dumft.size(); j++) all_feature_tests[i][j] = dumft.elementAt(j); nb_total_splits += all_feature_tests[i].length; } else { splittable_feature[i] = false; all_feature_tests[i] = new FeatureTest[0]; } } if (!at_least_one_splittable_feature) Dataset.perror("Algorithm.class :: no splittable feature for node " + leaf); if (splitting_method.equals(Wrapper.BOOSTING)) { if (Wrapper.FAST_SPLITTING) sd = split_top_down_boosting_generative_forest_fast( leaf, splittable_feature, all_feature_tests, tol); else sd = split_top_down_boosting_generative_forest( leaf, splittable_feature, all_feature_tests, tol); } else Dataset.perror("Algorithm.class :: no such split choice as " + splitting_method); if (sd == null) return false; index_f = sd.index_feature; index_s = sd.index_split; int[][] new_split_observations = sd.split_observations; // feature found at index index_f, split_index to be used at all_feature_tests[index_f][index_s] // node update if ((leaf.is_leaf) || (leaf.node_feature_test != all_feature_tests[index_f][index_s]) || (leaf.node_feature_split_index != index_f)) Dataset.perror( "Algorithm.class :: leaf should have been updated (" + leaf.is_leaf + ") (" + leaf.node_feature_test + " vs " + all_feature_tests[index_f][index_s] + ") (" + leaf.node_feature_split_index + " vs " + index_s + ")"); // create two new nodes Feature[] new_features = leaf.node_feature_test.split_feature( myDS, leaf.node_support.feature(leaf.node_feature_split_index), true, true); Support[] new_supports = leaf.node_support.split_support(leaf.node_feature_split_index, new_features); Node new_left_leaf = new Node( leaf.myTree, leaf.myTree.number_nodes, leaf.depth + 1, new_split_observations[0], new_supports[0]); Node new_right_leaf = new Node( leaf.myTree, leaf.myTree.number_nodes + 1, leaf.depth + 1, new_split_observations[1], new_supports[1]); if (new_split_observations[0].length + new_split_observations[1].length != leaf.observation_indexes_in_node.length) Dataset.perror("Algorithm.class :: error in splitting supports, mismatch in #examples"); leaf.p_left = (double) new_split_observations[0].length / ((double) leaf.observation_indexes_in_node.length); leaf.p_right = (double) new_split_observations[1].length / ((double) leaf.observation_indexes_in_node.length); if (splitting_method.equals(Wrapper.BOOSTING)) { // unmarking the elements in tol Iterator it = tol.iterator(); MeasuredSupportAtTupleOfNodes ms; while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if (ms.marked_for_update) ms.unmark_for_update(new_left_leaf, new_right_leaf); } } // update tree's statistics leaf.myTree.statistics_number_of_nodes_for_each_feature[index_f]++; // link nodes leaf.left_child = new_left_leaf; leaf.right_child = new_right_leaf; leaf.left_child.p_reach = leaf.p_reach * leaf.p_left; leaf.right_child.p_reach = leaf.p_reach * leaf.p_right; // update tree leaves & size leaf.myTree.number_nodes += 2; boolean test_remove = leaf.myTree.remove_leaf_from_tree_structure(leaf); // leaf.myTree.leaves.remove(leaf); if (!test_remove) Dataset.perror("Algorithm.class :: Leaf " + leaf.name + " not found in tree's leaves"); if (leaf.depth > leaf.myTree.depth) Dataset.perror( "Algorithm.class :: Leaf " + leaf.name + " at depth " + leaf.depth + " > leaf.myTree depth = " + leaf.myTree.depth); if (leaf.depth == leaf.myTree.depth) leaf.myTree.depth++; leaf.myTree.add_leaf_to_tree_structure(new_left_leaf); leaf.myTree.add_leaf_to_tree_structure(new_right_leaf); return true; } public boolean split_ensemble_of_generative_trees( Node leaf, HashSet<MeasuredSupportAtTupleOfNodes> tol) { if (!leaf.is_leaf) Dataset.perror("Algorithm.class :: " + leaf + " is not a leaf"); FeatureTest[][] all_feature_tests = new FeatureTest[leaf.node_support.dim()][]; // x = feature index, y = split index boolean[] splittable_feature = new boolean[leaf.node_support.dim()]; boolean at_least_one_splittable_feature = false; SplitDetails sd = null; int i, nb_total_splits = 0, j, index_f = -1, index_s = -1; Vector<FeatureTest> dumft; for (i = 0; i < leaf.node_support.dim(); i++) { dumft = FeatureTest.ALL_FEATURE_TESTS(leaf.node_support.feature(i), myDS); if (dumft != null) { at_least_one_splittable_feature = true; splittable_feature[i] = true; all_feature_tests[i] = new FeatureTest[dumft.size()]; for (j = 0; j < dumft.size(); j++) all_feature_tests[i][j] = dumft.elementAt(j); nb_total_splits += all_feature_tests[i].length; } else { splittable_feature[i] = false; all_feature_tests[i] = new FeatureTest[0]; } } if (!at_least_one_splittable_feature) Dataset.perror("Algorithm.class :: no splittable feature for node " + leaf); if (splitting_method.equals(Wrapper.BOOSTING)) { sd = split_top_down_boosting_ensemble_of_generative_trees_fast( leaf, splittable_feature, all_feature_tests, tol); } else Dataset.perror("Algorithm.class :: no such split choice as " + splitting_method); if (sd == null) return false; index_f = sd.index_feature; index_s = sd.index_split; int[][] new_split_observations = sd.split_observations; // feature found at index index_f, split_index to be used at all_feature_tests[index_f][index_s] // node update if ((leaf.is_leaf) || (leaf.node_feature_test != all_feature_tests[index_f][index_s]) || (leaf.node_feature_split_index != index_f)) Dataset.perror( "Algorithm.class :: leaf should have been updated (" + leaf.is_leaf + ") (" + leaf.node_feature_test + " vs " + all_feature_tests[index_f][index_s] + ") (" + leaf.node_feature_split_index + " vs " + index_s + ")"); // create two new nodes Feature[] new_features = leaf.node_feature_test.split_feature( myDS, leaf.node_support.feature(leaf.node_feature_split_index), true, true); Support[] new_supports = leaf.node_support.split_support(leaf.node_feature_split_index, new_features); Node new_left_leaf = new Node( leaf.myTree, leaf.myTree.number_nodes, leaf.depth + 1, new_split_observations[0], new_supports[0]); Node new_right_leaf = new Node( leaf.myTree, leaf.myTree.number_nodes + 1, leaf.depth + 1, new_split_observations[1], new_supports[1]); if (new_split_observations[0].length + new_split_observations[1].length != leaf.observation_indexes_in_node.length) Dataset.perror("Algorithm.class :: error in splitting supports, mismatch in #examples"); leaf.p_left = (double) new_split_observations[0].length / ((double) leaf.observation_indexes_in_node.length); leaf.p_right = (double) new_split_observations[1].length / ((double) leaf.observation_indexes_in_node.length); if (splitting_method.equals(Wrapper.BOOSTING)) { // unmarking the elements in tol Iterator it = tol.iterator(); MeasuredSupportAtTupleOfNodes ms; while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if (ms.marked_for_update) ms.unmark_for_update(new_left_leaf, new_right_leaf); } } // update tree's statistics leaf.myTree.statistics_number_of_nodes_for_each_feature[index_f]++; // link nodes leaf.left_child = new_left_leaf; leaf.right_child = new_right_leaf; leaf.left_child.p_reach = leaf.p_reach * leaf.p_left; leaf.right_child.p_reach = leaf.p_reach * leaf.p_right; // update tree leaves & size leaf.myTree.number_nodes += 2; boolean test_remove = leaf.myTree.remove_leaf_from_tree_structure(leaf); // leaf.myTree.leaves.remove(leaf); if (!test_remove) Dataset.perror("Algorithm.class :: Leaf " + leaf.name + " not found in tree's leaves"); if (leaf.depth > leaf.myTree.depth) Dataset.perror( "Algorithm.class :: Leaf " + leaf.name + " at depth " + leaf.depth + " > leaf.myTree depth = " + leaf.myTree.depth); if (leaf.depth == leaf.myTree.depth) leaf.myTree.depth++; leaf.myTree.add_leaf_to_tree_structure(new_left_leaf); leaf.myTree.add_leaf_to_tree_structure(new_right_leaf); return true; } public HashSet<String> filter_for_leaf( Hashtable<String, MeasuredSupportAtTupleOfNodes> all_measured_supports_at_intersection, Node leaf) { // returns a subset of keys of all_measured_supports_at_intersection having leaf in them HashSet<String> ret = new HashSet<>(); Vector<Node> all_nodes; boolean tree_done; int i; for (i = 0; i < geot.trees.size(); i++) { all_nodes = new Vector<>(); tree_done = false; } return ret; } public SplitDetails split_top_down_boosting_generative_forest( Node leaf, boolean[] splittable_feature, FeatureTest[][] all_feature_tests, HashSet<MeasuredSupportAtTupleOfNodes> tol) { HashSet<MeasuredSupportAtTupleOfNodes> subset_with_leaf = new HashSet<>(); HashSet<MeasuredSupportAtTupleOfNodes> new_candidates_after_split; HashSet<MeasuredSupportAtTupleOfNodes> best_candidates_for_left_after_split = null; HashSet<MeasuredSupportAtTupleOfNodes> best_candidates_for_right_after_split = null; Iterator it = tol.iterator(); MeasuredSupportAtTupleOfNodes ms; int number_obs_tot = 0, i, j, k, index_f = -1, index_s = -1, number_left_obs, number_right_obs, iter = 0, index_try; double cur_Bayes, p_ccstar, opt_Bayes = -1.0; boolean found, at_least_one; while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if (ms.tree_nodes_support_contains_node(leaf)) { subset_with_leaf.add(ms); number_obs_tot += ms.generative_support.local_empirical_measure.observations_indexes.length; } } if (number_obs_tot != leaf.observation_indexes_in_node.length) Dataset.perror( "Algorithm.class :: mismatch between the total #observations (" + number_obs_tot + ") and leaf weight (" + leaf.observation_indexes_in_node.length + ")"); if (subset_with_leaf.size() == 0) Dataset.perror( "Algorithm.class :: no subsets of MeasuredSupportAtTupleOfNodes with leaf " + leaf); // speed up Vector<Integer[]> couple_feature_index_feature_test_index = new Vector<>(); for (i = 0; i < splittable_feature.length; i++) if (splittable_feature[i]) for (j = 0; j < all_feature_tests[i].length; j++) couple_feature_index_feature_test_index.addElement( new Integer[] {new Integer(i), new Integer(j)}); List<Integer> shuffled_indexes = new ArrayList<>(); for (i = 0; i < couple_feature_index_feature_test_index.size(); i++) shuffled_indexes.add(i); Collections.shuffle(shuffled_indexes); int max_number_tries = (couple_feature_index_feature_test_index.size() > Algorithm.MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION) ? Algorithm.MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION : couple_feature_index_feature_test_index.size(), dumi; // works regardless of the option chosen found = false; for (k = 0; k < max_number_tries; k++) { index_try = shuffled_indexes.get(shuffled_indexes.size() - 1).intValue(); i = couple_feature_index_feature_test_index.elementAt(index_try)[0].intValue(); j = couple_feature_index_feature_test_index.elementAt(index_try)[1].intValue(); dumi = shuffled_indexes.remove(shuffled_indexes.size() - 1); iter++; new_candidates_after_split = new HashSet<>(); cur_Bayes = 0.0; // computes all split_top_down_boosting_statistics & current Bayes entropy (HL in (7)) number_left_obs = number_right_obs = 0; it = subset_with_leaf.iterator(); at_least_one = false; while (it.hasNext()) { at_least_one = true; ms = (MeasuredSupportAtTupleOfNodes) it.next(); ms.split_top_down_boosting_statistics = ms.split_for_boosting_computations(all_feature_tests[i][j], i); if ((ms.split_top_down_boosting_statistics[0] != null) && (ms.split_top_down_boosting_statistics[0] .generative_support .local_empirical_measure .observations_indexes != null)) number_left_obs += ms.split_top_down_boosting_statistics[0] .generative_support .local_empirical_measure .observations_indexes .length; if ((ms.split_top_down_boosting_statistics[1] != null) && (ms.split_top_down_boosting_statistics[1] .generative_support .local_empirical_measure .observations_indexes != null)) number_right_obs += ms.split_top_down_boosting_statistics[1] .generative_support .local_empirical_measure .observations_indexes .length; p_ccstar = (Statistics.PRIOR * ((double) ms.generative_support.local_empirical_measure.observations_indexes.length) / ((double) myDS.observations_from_file.size())) + ((1.0 - Statistics.PRIOR) * ms.generative_support.support.weight_uniform_distribution); cur_Bayes += (p_ccstar * Statistics.MU_BAYES_GENERATIVE_FOREST( ms.split_top_down_boosting_statistics, 1.0)); } // Bayes entropy improvement ? if ((at_least_one) && (number_left_obs >= Algorithm.MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING) && (number_right_obs >= Algorithm.MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING) && ((!found) || (cur_Bayes < opt_Bayes))) { index_f = i; index_s = j; opt_Bayes = cur_Bayes; found = true; best_candidates_for_left_after_split = new HashSet<>(); best_candidates_for_right_after_split = new HashSet<>(); it = subset_with_leaf.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if (ms.split_top_down_boosting_statistics[0] != null) best_candidates_for_left_after_split.add(ms.split_top_down_boosting_statistics[0]); if (ms.split_top_down_boosting_statistics[1] != null) best_candidates_for_right_after_split.add(ms.split_top_down_boosting_statistics[1]); } } } // update leaf if ((index_f == -1) || (index_s == -1)) return null; leaf.node_feature_test = all_feature_tests[index_f][index_s]; leaf.node_feature_split_index = index_f; leaf.is_leaf = false; // splits observations using split details // collects all observations already assigned from subset Vector<Integer> left_obs = new Vector<>(); Vector<Integer> right_obs = new Vector<>(); if (best_candidates_for_left_after_split.size() > 0) { it = best_candidates_for_left_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) for (i = 0; i < ms.generative_support.local_empirical_measure.observations_indexes.length; i++) left_obs.addElement( new Integer(ms.generative_support.local_empirical_measure.observations_indexes[i])); } } if (best_candidates_for_right_after_split.size() > 0) { it = best_candidates_for_right_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) for (i = 0; i < ms.generative_support.local_empirical_measure.observations_indexes.length; i++) right_obs.addElement( new Integer(ms.generative_support.local_empirical_measure.observations_indexes[i])); } } Vector<Integer> all_leaf_obs = new Vector<>(); int[] alo; for (i = 0; i < leaf.observation_indexes_in_node.length; i++) all_leaf_obs.addElement(new Integer(leaf.observation_indexes_in_node[i])); int[][] new_split_observations = new int[2][]; new_split_observations[0] = new int[left_obs.size()]; new_split_observations[1] = new int[right_obs.size()]; for (i = 0; i < left_obs.size(); i++) new_split_observations[0][i] = left_obs.elementAt(i).intValue(); for (i = 0; i < right_obs.size(); i++) new_split_observations[1][i] = right_obs.elementAt(i).intValue(); // remove subset_with_leaf from tol it = subset_with_leaf.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); found = tol.remove(ms); if (!found) Dataset.perror( "Algorithm.class :: subset of support " + ms + " should be in the set of all"); } // update tol: add all elements in best_candidates_for_left_after_split & // best_candidates_for_right_after_split WITH >0 MEASURE, remove from tol all elements in // subset; if (best_candidates_for_left_after_split.size() > 0) { it = best_candidates_for_left_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) { ms.marked_for_update = true; ms.marked_for_update_index_tree = leaf.myTree.name; ms.marked_for_update_which_child = MeasuredSupportAtTupleOfNodes.LEFT_CHILD; tol.add(ms); } } } if (best_candidates_for_right_after_split.size() > 0) { it = best_candidates_for_right_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) { ms.marked_for_update = true; ms.marked_for_update_index_tree = leaf.myTree.name; ms.marked_for_update_which_child = MeasuredSupportAtTupleOfNodes.RIGHT_CHILD; tol.add(ms); } } } return new SplitDetails(index_f, index_s, new_split_observations); } public SplitDetails split_top_down_boosting_generative_forest_fast( Node leaf, boolean[] splittable_feature, FeatureTest[][] all_feature_tests, HashSet<MeasuredSupportAtTupleOfNodes> tol) { // tol contains all current tuple of leaves whose intersection support has >0 empirical measure // fast method which does not record where observations with missing values go (to match the // argument used to compute Bayes risk during testing all splits and that for the split // selected) HashSet<MeasuredSupportAtTupleOfNodes> subset_with_leaf = new HashSet<>(); HashSet<MeasuredSupportAtTupleOfNodes> new_candidates_after_split; HashSet<MeasuredSupportAtTupleOfNodes> best_candidates_for_left_after_split = null; HashSet<MeasuredSupportAtTupleOfNodes> best_candidates_for_right_after_split = null; Iterator it = tol.iterator(); MeasuredSupportAtTupleOfNodes ms; int number_obs_tot = 0, i, j, k, index_f = -1, index_s = -1, number_left_obs, number_right_obs, iter = 0, index_try; double cur_Bayes, p_ccstar, opt_Bayes = -1.0; boolean found, at_least_one; double[] rapid_split_stats = new double[4]; while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if (ms.tree_nodes_support_contains_node(leaf)) { subset_with_leaf.add(ms); number_obs_tot += ms.generative_support.local_empirical_measure.observations_indexes.length; } } if (number_obs_tot != leaf.observation_indexes_in_node.length) Dataset.perror( "Algorithm.class :: mismatch between the total #observations (" + number_obs_tot + ") and leaf weight (" + leaf.observation_indexes_in_node.length + ")"); if (subset_with_leaf.size() == 0) Dataset.perror( "Algorithm.class :: no subsets of MeasuredSupportAtTupleOfNodes with leaf " + leaf); // speed up Vector<Integer[]> couple_feature_index_feature_test_index = new Vector<>(); for (i = 0; i < splittable_feature.length; i++) if (splittable_feature[i]) for (j = 0; j < all_feature_tests[i].length; j++) couple_feature_index_feature_test_index.addElement( new Integer[] {new Integer(i), new Integer(j)}); List<Integer> shuffled_indexes = new ArrayList<>(); for (i = 0; i < couple_feature_index_feature_test_index.size(); i++) shuffled_indexes.add(i); Collections.shuffle(shuffled_indexes); int max_number_tries = (couple_feature_index_feature_test_index.size() > Algorithm.MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION) ? Algorithm.MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION : couple_feature_index_feature_test_index.size(), dumi; // works regardless of the option chosen found = false; for (k = 0; k < max_number_tries; k++) { index_try = shuffled_indexes.get(shuffled_indexes.size() - 1).intValue(); i = couple_feature_index_feature_test_index.elementAt(index_try)[0].intValue(); j = couple_feature_index_feature_test_index.elementAt(index_try)[1].intValue(); dumi = shuffled_indexes.remove(shuffled_indexes.size() - 1); iter++; new_candidates_after_split = new HashSet<>(); cur_Bayes = 0.0; // computes all split_top_down_boosting_statistics & current Bayes entropy (HL in (7)) number_left_obs = number_right_obs = 0; it = subset_with_leaf.iterator(); at_least_one = false; while (it.hasNext()) { at_least_one = true; ms = (MeasuredSupportAtTupleOfNodes) it.next(); rapid_split_stats = ms.rapid_split_statistics(all_feature_tests[i][j], i); number_left_obs += rapid_split_stats[0]; number_right_obs += rapid_split_stats[1]; p_ccstar = (Statistics.PRIOR * ((double) ms.generative_support.local_empirical_measure.observations_indexes.length) / ((double) myDS.observations_from_file.size())) + ((1.0 - Statistics.PRIOR) * ms.generative_support.support.weight_uniform_distribution); cur_Bayes += (p_ccstar * Statistics.MU_BAYES_GENERATIVE_FOREST_SIMPLE( rapid_split_stats[0], rapid_split_stats[1], rapid_split_stats[2], rapid_split_stats[3], myDS.observations_from_file.size(), 1.0)); } // Bayes entropy improvement ? if ((at_least_one) && (number_left_obs >= Algorithm.MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING) && (number_right_obs >= Algorithm.MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING) && ((!found) || (cur_Bayes < opt_Bayes))) { // index_f = i; index_s = j; opt_Bayes = cur_Bayes; found = true; } } // update leaf if ((index_f == -1) || (index_s == -1)) return null; // compute best_candidates_for_left_after_split, best_candidates_for_right_after_split : SPEED // UP it = subset_with_leaf.iterator(); best_candidates_for_left_after_split = new HashSet<>(); best_candidates_for_right_after_split = new HashSet<>(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); ms.split_top_down_boosting_statistics = ms.split_for_boosting_computations(all_feature_tests[index_f][index_s], index_f); if (ms.split_top_down_boosting_statistics[0] != null) best_candidates_for_left_after_split.add(ms.split_top_down_boosting_statistics[0]); if (ms.split_top_down_boosting_statistics[1] != null) best_candidates_for_right_after_split.add(ms.split_top_down_boosting_statistics[1]); } // end of SPEED UP leaf.node_feature_test = all_feature_tests[index_f][index_s]; leaf.node_feature_split_index = index_f; leaf.is_leaf = false; // splits observations using split details // collects all observations already assigned from subset Vector<Integer> left_obs = new Vector<>(); Vector<Integer> right_obs = new Vector<>(); if (best_candidates_for_left_after_split.size() > 0) { it = best_candidates_for_left_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) for (i = 0; i < ms.generative_support.local_empirical_measure.observations_indexes.length; i++) left_obs.addElement( new Integer(ms.generative_support.local_empirical_measure.observations_indexes[i])); } } if (best_candidates_for_right_after_split.size() > 0) { it = best_candidates_for_right_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) for (i = 0; i < ms.generative_support.local_empirical_measure.observations_indexes.length; i++) right_obs.addElement( new Integer(ms.generative_support.local_empirical_measure.observations_indexes[i])); } } Vector<Integer> all_leaf_obs = new Vector<>(); int[] alo; for (i = 0; i < leaf.observation_indexes_in_node.length; i++) all_leaf_obs.addElement(new Integer(leaf.observation_indexes_in_node[i])); int[][] new_split_observations = new int[2][]; new_split_observations[0] = new int[left_obs.size()]; new_split_observations[1] = new int[right_obs.size()]; for (i = 0; i < left_obs.size(); i++) new_split_observations[0][i] = left_obs.elementAt(i).intValue(); for (i = 0; i < right_obs.size(); i++) new_split_observations[1][i] = right_obs.elementAt(i).intValue(); // remove subset_with_leaf from tol it = subset_with_leaf.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); found = tol.remove(ms); if (!found) Dataset.perror( "Algorithm.class :: subset of support " + ms + " should be in the set of all"); } // update tol: add all elements in best_candidates_for_left_after_split & // best_candidates_for_right_after_split WITH >0 MEASURE, remove from tol all elements in // subset; if (best_candidates_for_left_after_split.size() > 0) { it = best_candidates_for_left_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) { ms.marked_for_update = true; ms.marked_for_update_index_tree = leaf.myTree.name; ms.marked_for_update_which_child = MeasuredSupportAtTupleOfNodes.LEFT_CHILD; tol.add(ms); } } } if (best_candidates_for_right_after_split.size() > 0) { it = best_candidates_for_right_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) { ms.marked_for_update = true; ms.marked_for_update_index_tree = leaf.myTree.name; ms.marked_for_update_which_child = MeasuredSupportAtTupleOfNodes.RIGHT_CHILD; tol.add(ms); } } } return new SplitDetails(index_f, index_s, new_split_observations); } public SplitDetails split_top_down_boosting_ensemble_of_generative_trees_fast( Node leaf, boolean[] splittable_feature, FeatureTest[][] all_feature_tests, HashSet<MeasuredSupportAtTupleOfNodes> tol) { // tol contains all current tuple of leaves whose intersection support has >0 empirical measure HashSet<MeasuredSupportAtTupleOfNodes> subset_with_leaf = new HashSet<>(); HashSet<MeasuredSupportAtTupleOfNodes> new_candidates_after_split; HashSet<MeasuredSupportAtTupleOfNodes> best_candidates_for_left_after_split = null; HashSet<MeasuredSupportAtTupleOfNodes> best_candidates_for_right_after_split = null; Iterator it = tol.iterator(); MeasuredSupportAtTupleOfNodes ms; int number_obs_tot = 0, i, j, k, l, index_f = -1, number_left_obs, number_right_obs, index_s = -1, iter = 0, index_try; double cur_Bayes, p_ccstar, opt_Bayes = -1.0, p_R, p_R_left, p_R_right, vol0, vol1, p0, p1, u_left, u_right; boolean found, at_least_one; Support[] split_support; double[] rapid_split_stats = new double[4]; while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if (ms.tree_nodes_support_contains_node(leaf)) { subset_with_leaf.add(ms); number_obs_tot += ms.generative_support.local_empirical_measure.observations_indexes.length; } } if (number_obs_tot != leaf.observation_indexes_in_node.length) Dataset.perror( "Algorithm.class :: mismatch between the total #observations (" + number_obs_tot + ") and leaf weight (" + leaf.observation_indexes_in_node.length + ")"); if (subset_with_leaf.size() == 0) Dataset.perror( "Algorithm.class :: no subsets of MeasuredSupportAtTupleOfNodes with leaf " + leaf); // speed up Vector<Integer[]> couple_feature_index_feature_test_index = new Vector<>(); for (i = 0; i < splittable_feature.length; i++) if (splittable_feature[i]) for (j = 0; j < all_feature_tests[i].length; j++) couple_feature_index_feature_test_index.addElement( new Integer[] {new Integer(i), new Integer(j)}); List<Integer> shuffled_indexes = new ArrayList<>(); for (i = 0; i < couple_feature_index_feature_test_index.size(); i++) shuffled_indexes.add(i); Collections.shuffle(shuffled_indexes); int max_number_tries = (couple_feature_index_feature_test_index.size() > Algorithm.MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION) ? Algorithm.MAXIMAL_NUMBER_OF_SPLIT_TESTS_TRIES_PER_BOOSTING_ITERATION : couple_feature_index_feature_test_index.size(), dumi; // works regardless of the option chosen found = false; for (k = 0; k < max_number_tries; k++) { index_try = shuffled_indexes.get(shuffled_indexes.size() - 1).intValue(); i = couple_feature_index_feature_test_index.elementAt(index_try)[0].intValue(); j = couple_feature_index_feature_test_index.elementAt(index_try)[1].intValue(); dumi = shuffled_indexes.remove(shuffled_indexes.size() - 1); iter++; new_candidates_after_split = new HashSet<>(); cur_Bayes = 0.0; // computes all split_top_down_boosting_statistics & current Bayes entropy (HL in (7)) number_left_obs = number_right_obs = 0; it = subset_with_leaf.iterator(); at_least_one = false; while (it.hasNext()) { at_least_one = true; ms = (MeasuredSupportAtTupleOfNodes) it.next(); rapid_split_stats = ms.rapid_split_statistics(all_feature_tests[i][j], i); number_left_obs += rapid_split_stats[0]; number_right_obs += rapid_split_stats[ 1]; // "cheating" on cardinals just to make sure supports not empty (not used in // ranking splits) l = Statistics.R.nextInt( ms.tree_nodes_support .size()); // very fast approx. should take into account all trees BUT this eases // distributed training p_R = (ms.tree_nodes_support.elementAt(l).p_reach / ms.tree_nodes_support.elementAt(l).node_support.volume) * ms.generative_support.support.volume; split_support = Support.SPLIT_SUPPORT(myDS, ms.generative_support.support, all_feature_tests[i][j], i); if (split_support[0] != null) vol0 = (double) split_support[0].volume; else vol0 = 0.0; if (split_support[1] != null) vol1 = (double) split_support[1].volume; else vol1 = 0.0; p0 = vol0 / (vol0 + vol1); p1 = vol1 / (vol0 + vol1); p_R_left = p_R * p0; p_R_right = p_R * p1; u_left = ms.generative_support.support.weight_uniform_distribution * p0; u_right = ms.generative_support.support.weight_uniform_distribution * p1; p_ccstar = (Statistics.PRIOR * p_R) + ((1.0 - Statistics.PRIOR) * ms.generative_support.support.weight_uniform_distribution); cur_Bayes += (p_ccstar * Statistics.MU_BAYES_ENSEMBLE_OF_GENERATIVE_TREES( myDS, p_R, p_R_left, p_R_right, u_left, u_right, 1.0)); } // Bayes entropy improvement ? if ((at_least_one) && (number_left_obs >= Algorithm.MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING) && (number_right_obs >= Algorithm.MINIMUM_EMPIRICAL_CARD_AT_NEW_LEAF_FOR_BOOSTING) && ((!found) || (cur_Bayes < opt_Bayes))) { index_f = i; index_s = j; opt_Bayes = cur_Bayes; found = true; } } // update leaf if ((index_f == -1) || (index_s == -1)) return null; // compute best_candidates_for_left_after_split, best_candidates_for_right_after_split : SPEED // UP it = subset_with_leaf.iterator(); best_candidates_for_left_after_split = new HashSet<>(); best_candidates_for_right_after_split = new HashSet<>(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); ms.split_top_down_boosting_statistics = ms.split_for_boosting_computations(all_feature_tests[index_f][index_s], index_f); if (ms.split_top_down_boosting_statistics[0] != null) best_candidates_for_left_after_split.add(ms.split_top_down_boosting_statistics[0]); if (ms.split_top_down_boosting_statistics[1] != null) best_candidates_for_right_after_split.add(ms.split_top_down_boosting_statistics[1]); } // end of SPEED UP leaf.node_feature_test = all_feature_tests[index_f][index_s]; leaf.node_feature_split_index = index_f; leaf.is_leaf = false; // splits observations using split details // collects all observations already assigned from subset Vector<Integer> left_obs = new Vector<>(); Vector<Integer> right_obs = new Vector<>(); if (best_candidates_for_left_after_split.size() > 0) { it = best_candidates_for_left_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) for (i = 0; i < ms.generative_support.local_empirical_measure.observations_indexes.length; i++) left_obs.addElement( new Integer(ms.generative_support.local_empirical_measure.observations_indexes[i])); } } if (best_candidates_for_right_after_split.size() > 0) { it = best_candidates_for_right_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) for (i = 0; i < ms.generative_support.local_empirical_measure.observations_indexes.length; i++) right_obs.addElement( new Integer(ms.generative_support.local_empirical_measure.observations_indexes[i])); } } Vector<Integer> all_leaf_obs = new Vector<>(); int[] alo; for (i = 0; i < leaf.observation_indexes_in_node.length; i++) all_leaf_obs.addElement(new Integer(leaf.observation_indexes_in_node[i])); int[][] new_split_observations = new int[2][]; new_split_observations[0] = new int[left_obs.size()]; new_split_observations[1] = new int[right_obs.size()]; for (i = 0; i < left_obs.size(); i++) new_split_observations[0][i] = left_obs.elementAt(i).intValue(); for (i = 0; i < right_obs.size(); i++) new_split_observations[1][i] = right_obs.elementAt(i).intValue(); // remove subset_with_leaf from tol it = subset_with_leaf.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); found = tol.remove(ms); if (!found) Dataset.perror( "Algorithm.class :: subset of support " + ms + " should be in the set of all"); } // update tol: add all elements in best_candidates_for_left_after_split & // best_candidates_for_right_after_split WITH >0 MEASURE, remove from tol all elements in // subset; if (best_candidates_for_left_after_split.size() > 0) { it = best_candidates_for_left_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) { ms.marked_for_update = true; ms.marked_for_update_index_tree = leaf.myTree.name; ms.marked_for_update_which_child = MeasuredSupportAtTupleOfNodes.LEFT_CHILD; tol.add(ms); } } } if (best_candidates_for_right_after_split.size() > 0) { it = best_candidates_for_right_after_split.iterator(); while (it.hasNext()) { ms = (MeasuredSupportAtTupleOfNodes) it.next(); if ((ms.generative_support.local_empirical_measure.observations_indexes != null) && (ms.generative_support.local_empirical_measure.observations_indexes.length > 0)) { ms.marked_for_update = true; ms.marked_for_update_index_tree = leaf.myTree.name; ms.marked_for_update_which_child = MeasuredSupportAtTupleOfNodes.RIGHT_CHILD; tol.add(ms); } } } return new SplitDetails(index_f, index_s, new_split_observations); } }
google-research/google-research
generative_forests/src/Algorithm.java
6
package mindustry.content; import arc.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.struct.*; import arc.util.*; import mindustry.entities.*; import mindustry.entities.abilities.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; import mindustry.world.blocks.units.UnitAssembler.*; import static arc.graphics.g2d.Draw.rect; import static arc.graphics.g2d.Draw.*; import static arc.graphics.g2d.Lines.*; import static arc.math.Angles.*; import static mindustry.Vars.*; public class Fx{ public static final Rand rand = new Rand(); public static final Vec2 v = new Vec2(); public static final Effect none = new Effect(0, 0f, e -> {}), blockCrash = new Effect(90f, e -> { if(!(e.data instanceof Block block)) return; alpha(e.fin() + 0.5f); float offset = Mathf.lerp(0f, 180f, e.fout()); color(0f, 0f, 0f, 0.44f); rect(block.fullIcon, e.x - offset * 4f, e.y, (float)block.size * 8f, (float)block.size * 8f); color(Color.white); rect(block.fullIcon, e.x + offset, e.y + offset * 5f, (float)block.size * 8f, (float)block.size * 8f); }), trailFade = new Effect(400f, e -> { if(!(e.data instanceof Trail trail)) return; //lifetime is how many frames it takes to fade out the trail e.lifetime = trail.length * 1.4f; if(!state.isPaused()){ trail.shorten(); } trail.drawCap(e.color, e.rotation); trail.draw(e.color, e.rotation); }), unitSpawn = new Effect(30f, e -> { if(!(e.data instanceof UnitType unit)) return; TextureRegion region = unit.fullIcon; float scl = (1f + e.fout() * 2f) * region.scl(); alpha(e.fout()); mixcol(Color.white, e.fin()); rect(region, e.x, e.y, 180f); reset(); alpha(e.fin()); rect(region, e.x, e.y, region.width * scl, region.height * scl, e.rotation - 90); }), unitCapKill = new Effect(80f, e -> { color(Color.scarlet); alpha(e.fout(Interp.pow4Out)); float size = 10f + e.fout(Interp.pow10In) * 25f; Draw.rect(Icon.warning.getRegion(), e.x, e.y, size, size); }), unitEnvKill = new Effect(80f, e -> { color(Color.scarlet); alpha(e.fout(Interp.pow4Out)); float size = 10f + e.fout(Interp.pow10In) * 25f; Draw.rect(Icon.cancel.getRegion(), e.x, e.y, size, size); }), unitControl = new Effect(30f, e -> { if(!(e.data instanceof Unit select)) return; boolean block = select instanceof BlockUnitc; mixcol(Pal.accent, 1f); alpha(e.fout()); rect(block ? ((BlockUnitc)select).tile().block.fullIcon : select.type.fullIcon, select.x, select.y, block ? 0f : select.rotation - 90f); alpha(1f); Lines.stroke(e.fslope()); Lines.square(select.x, select.y, e.fout() * select.hitSize * 2f, 45); Lines.stroke(e.fslope() * 2f); Lines.square(select.x, select.y, e.fout() * select.hitSize * 3f, 45f); reset(); }), unitDespawn = new Effect(100f, e -> { if(!(e.data instanceof Unit select) || select.type == null) return; float scl = e.fout(Interp.pow2Out); float p = Draw.scl; Draw.scl *= scl; mixcol(Pal.accent, 1f); rect(select.type.fullIcon, select.x, select.y, select.rotation - 90f); reset(); Draw.scl = p; }), unitSpirit = new Effect(17f, e -> { if(!(e.data instanceof Position to)) return; color(Pal.accent); Tmp.v1.set(e.x, e.y).interpolate(Tmp.v2.set(to), e.fin(), Interp.pow2In); float x = Tmp.v1.x, y = Tmp.v1.y; float size = 2.5f * e.fin(); Fill.square(x, y, 1.5f * size, 45f); Tmp.v1.set(e.x, e.y).interpolate(Tmp.v2.set(to), e.fin(), Interp.pow5In); x = Tmp.v1.x; y = Tmp.v1.y; Fill.square(x, y, size, 45f); }), itemTransfer = new Effect(12f, e -> { if(!(e.data instanceof Position to)) return; Tmp.v1.set(e.x, e.y).interpolate(Tmp.v2.set(to), e.fin(), Interp.pow3) .add(Tmp.v2.sub(e.x, e.y).nor().rotate90(1).scl(Mathf.randomSeedRange(e.id, 1f) * e.fslope() * 10f)); float x = Tmp.v1.x, y = Tmp.v1.y; float size = 1f; color(Pal.accent); Fill.circle(x, y, e.fslope() * 3f * size); color(e.color); Fill.circle(x, y, e.fslope() * 1.5f * size); }), pointBeam = new Effect(25f, 300f, e -> { if(!(e.data instanceof Position pos)) return; Draw.color(e.color, e.fout()); Lines.stroke(1.5f); Lines.line(e.x, e.y, pos.getX(), pos.getY()); Drawf.light(e.x, e.y, pos.getX(), pos.getY(), 20f, e.color, 0.6f * e.fout()); }), pointHit = new Effect(8f, e -> { color(Color.white, e.color, e.fin()); stroke(e.fout() + 0.2f); Lines.circle(e.x, e.y, e.fin() * 6f); }), lightning = new Effect(10f, 500f, e -> { if(!(e.data instanceof Seq)) return; Seq<Vec2> lines = e.data(); stroke(3f * e.fout()); color(e.color, Color.white, e.fin()); for(int i = 0; i < lines.size - 1; i++){ Vec2 cur = lines.get(i); Vec2 next = lines.get(i + 1); Lines.line(cur.x, cur.y, next.x, next.y, false); } for(Vec2 p : lines){ Fill.circle(p.x, p.y, Lines.getStroke() / 2f); } }), coreBuildShockwave = new Effect(120, 500f, e -> { e.lifetime = e.rotation; color(Pal.command); stroke(e.fout(Interp.pow5Out) * 4f); Lines.circle(e.x, e.y, e.fin() * e.rotation * 2f); }), coreBuildBlock = new Effect(80f, e -> { if(!(e.data instanceof Block block)) return; mixcol(Pal.accent, 1f); alpha(e.fout()); rect(block.fullIcon, e.x, e.y); }).layer(Layer.turret - 5f), pointShockwave = new Effect(20, e -> { color(e.color); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, e.finpow() * e.rotation); randLenVectors(e.id + 1, 8, 1f + 23f * e.finpow(), (x, y) -> lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f)); }), moveCommand = new Effect(20, e -> { color(Pal.command); stroke(e.fout() * 5f); Lines.circle(e.x, e.y, 6f + e.fin() * 2f); }).layer(Layer.overlayUI), attackCommand = new Effect(20, e -> { color(Pal.remove); stroke(e.fout() * 5f); poly(e.x, e.y, 4, 7f + e.fin() * 2f); }).layer(Layer.overlayUI), commandSend = new Effect(28, e -> { color(Pal.command); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 4f + e.finpow() * e.rotation); }), upgradeCore = new Effect(120f, e -> { if(!(e.data instanceof Block block)) return; mixcol(Tmp.c1.set(Color.white).lerp(Pal.accent, e.fin()), 1f); alpha(e.fout()); rect(block.fullIcon, e.x, e.y); }).layer(Layer.turret - 5f), upgradeCoreBloom = new Effect(80f, e -> { color(Pal.accent); stroke(4f * e.fout()); Lines.square(e.x, e.y, tilesize / 2f * e.rotation + 2f); }), placeBlock = new Effect(16, e -> { color(Pal.accent); stroke(3f - e.fin() * 2f); Lines.square(e.x, e.y, tilesize / 2f * e.rotation + e.fin() * 3f); }), coreLaunchConstruct = new Effect(35, e -> { color(Pal.accent); stroke(4f - e.fin() * 3f); Lines.square(e.x, e.y, tilesize / 2f * e.rotation * 1.2f + e.fin() * 5f); randLenVectors(e.id, 5 + (int)(e.rotation * 5), e.rotation * 3f + (tilesize * e.rotation) * e.finpow() * 1.5f, (x, y) -> { Lines.lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * (4f + e.rotation)); }); }), tapBlock = new Effect(12, e -> { color(Pal.accent); stroke(3f - e.fin() * 2f); Lines.circle(e.x, e.y, 4f + (tilesize / 1.5f * e.rotation) * e.fin()); }), breakBlock = new Effect(12, e -> { color(Pal.remove); stroke(3f - e.fin() * 2f); Lines.square(e.x, e.y, tilesize / 2f * e.rotation + e.fin() * 3f); randLenVectors(e.id, 3 + (int)(e.rotation * 3), e.rotation * 2f + (tilesize * e.rotation) * e.finpow(), (x, y) -> { Fill.square(e.x + x, e.y + y, 1f + e.fout() * (3f + e.rotation)); }); }), payloadDeposit = new Effect(30f, e -> { if(!(e.data instanceof YeetData data)) return; Tmp.v1.set(e.x, e.y).lerp(data.target, e.finpow()); float x = Tmp.v1.x, y = Tmp.v1.y; scl(e.fout(Interp.pow3Out) * 1.05f); if(data.item instanceof Block block){ Drawf.squareShadow(x, y, block.size * tilesize * 1.85f, 1f); }else if(data.item instanceof UnitType unit){ unit.drawSoftShadow(e.x, e.y, e.rotation, 1f); } mixcol(Pal.accent, e.fin()); rect(data.item.fullIcon, x, y, data.item instanceof Block ? 0f : e.rotation - 90f); }).layer(Layer.flyingUnitLow - 5f), select = new Effect(23, e -> { color(Pal.accent); stroke(e.fout() * 3f); Lines.circle(e.x, e.y, 3f + e.fin() * 14f); }), smoke = new Effect(100, e -> { color(Color.gray, Pal.darkishGray, e.fin()); Fill.circle(e.x, e.y, (7f - e.fin() * 7f)/2f); }), fallSmoke = new Effect(110, e -> { color(Color.gray, Color.darkGray, e.rotation); Fill.circle(e.x, e.y, e.fout() * 3.5f); }), unitWreck = new Effect(200f, e -> { if(!(e.data instanceof TextureRegion reg)) return; Draw.mixcol(Pal.rubble, 1f); float vel = e.fin(Interp.pow5Out) * 2f * Mathf.randomSeed(e.id, 1f); float totalRot = Mathf.randomSeed(e.id + 1, 10f); Tmp.v1.trns(Mathf.randomSeed(e.id + 2, 360f), vel); Draw.z(Mathf.lerp(Layer.flyingUnitLow, Layer.debris, e.fin())); Draw.alpha(e.fout(Interp.pow5Out)); Draw.rect(reg, e.x + Tmp.v1.x, e.y + Tmp.v1.y, e.rotation - 90 + totalRot * e.fin(Interp.pow5Out)); }), rocketSmoke = new Effect(120, e -> { color(Color.gray); alpha(Mathf.clamp(e.fout()*1.6f - Interp.pow3In.apply(e.rotation)*1.2f)); Fill.circle(e.x, e.y, (1f + 6f * e.rotation) - e.fin()*2f); }), rocketSmokeLarge = new Effect(220, e -> { color(Color.gray); alpha(Mathf.clamp(e.fout()*1.6f - Interp.pow3In.apply(e.rotation)*1.2f)); Fill.circle(e.x, e.y, (1f + 6f * e.rotation * 1.3f) - e.fin()*2f); }), magmasmoke = new Effect(110, e -> { color(Color.gray); Fill.circle(e.x, e.y, e.fslope() * 6f); }), spawn = new Effect(30, e -> { stroke(2f * e.fout()); color(Pal.accent); Lines.poly(e.x, e.y, 4, 5f + e.fin() * 12f); }), unitAssemble = new Effect(70, e -> { if(!(e.data instanceof UnitType type)) return; alpha(e.fout()); mixcol(Pal.accent, e.fout()); rect(type.fullIcon, e.x, e.y, e.rotation); }).layer(Layer.flyingUnit + 5f), padlaunch = new Effect(10, e -> { stroke(4f * e.fout()); color(Pal.accent); Lines.poly(e.x, e.y, 4, 5f + e.fin() * 60f); }), breakProp = new Effect(23, e -> { float scl = Math.max(e.rotation, 1); color(Tmp.c1.set(e.color).mul(1.1f)); randLenVectors(e.id, 6, 19f * e.finpow() * scl, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3.5f * scl + 0.3f); }); }).layer(Layer.debris), unitDrop = new Effect(30, e -> { color(Pal.lightishGray); randLenVectors(e.id, 9, 3 + 20f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.4f); }); }).layer(Layer.debris), unitLand = new Effect(30, e -> { color(Tmp.c1.set(e.color).mul(1.1f)); //TODO doesn't respect rotation / size randLenVectors(e.id, 6, 17f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.3f); }); }).layer(Layer.debris), unitDust = new Effect(30, e -> { color(Tmp.c1.set(e.color).mul(1.3f)); randLenVectors(e.id, 3, 8f * e.finpow(), e.rotation, 30f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3f + 0.3f); }); }).layer(Layer.debris), unitLandSmall = new Effect(30, e -> { color(Tmp.c1.set(e.color).mul(1.1f)); randLenVectors(e.id, (int)(6 * e.rotation), 12f * e.finpow() * e.rotation, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3f + 0.1f); }); }).layer(Layer.debris), unitPickup = new Effect(18, e -> { color(Pal.lightishGray); stroke(e.fin() * 2f); Lines.poly(e.x, e.y, 4, 13f * e.fout()); }).layer(Layer.debris), crawlDust = new Effect(35, e -> { color(Tmp.c1.set(e.color).mul(1.6f)); randLenVectors(e.id, 2, 10f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fslope() * 4f + 0.3f); }); }).layer(Layer.debris), landShock = new Effect(12, e -> { color(Pal.lancerLaser); stroke(e.fout() * 3f); Lines.poly(e.x, e.y, 12, 20f * e.fout()); }).layer(Layer.debris), pickup = new Effect(18, e -> { color(Pal.lightishGray); stroke(e.fout() * 2f); Lines.spikes(e.x, e.y, 1f + e.fin() * 6f, e.fout() * 4f, 6); }), sparkExplosion = new Effect(30f, 160f, e -> { color(e.color); stroke(e.fout() * 3f); float circleRad = 6f + e.finpow() * e.rotation; Lines.circle(e.x, e.y, circleRad); rand.setSeed(e.id); for(int i = 0; i < 16; i++){ float angle = rand.random(360f); float lenRand = rand.random(0.5f, 1f); Lines.lineAngle(e.x, e.y, angle, e.foutpow() * e.rotation * 0.8f * rand.random(1f, 0.6f) + 2f, e.finpow() * e.rotation * 1.2f * lenRand + 6f); } }), titanExplosion = new Effect(30f, 160f, e -> { color(e.color); stroke(e.fout() * 3f); float circleRad = 6f + e.finpow() * 60f; Lines.circle(e.x, e.y, circleRad); rand.setSeed(e.id); for(int i = 0; i < 16; i++){ float angle = rand.random(360f); float lenRand = rand.random(0.5f, 1f); Lines.lineAngle(e.x, e.y, angle, e.foutpow() * 50f * rand.random(1f, 0.6f) + 2f, e.finpow() * 70f * lenRand + 6f); } }), titanSmoke = new Effect(300f, 300f, b -> { float intensity = 3f; color(b.color, 0.7f); for(int i = 0; i < 4; i++){ rand.setSeed(b.id*2 + i); float lenScl = rand.random(0.5f, 1f); int fi = i; b.scaled(b.lifetime * lenScl, e -> { randLenVectors(e.id + fi - 1, e.fin(Interp.pow10Out), (int)(2.9f * intensity), 22f * intensity, (x, y, in, out) -> { float fout = e.fout(Interp.pow5Out) * rand.random(0.5f, 1f); float rad = fout * ((2f + intensity) * 2.35f); Fill.circle(e.x + x, e.y + y, rad); Drawf.light(e.x + x, e.y + y, rad * 2.5f, b.color, 0.5f); }); }); } }), missileTrailSmoke = new Effect(180f, 300f, b -> { float intensity = 2f; color(b.color, 0.7f); for(int i = 0; i < 4; i++){ rand.setSeed(b.id*2 + i); float lenScl = rand.random(0.5f, 1f); int fi = i; b.scaled(b.lifetime * lenScl, e -> { randLenVectors(e.id + fi - 1, e.fin(Interp.pow10Out), (int)(2.9f * intensity), 13f * intensity, (x, y, in, out) -> { float fout = e.fout(Interp.pow5Out) * rand.random(0.5f, 1f); float rad = fout * ((2f + intensity) * 2.35f); Fill.circle(e.x + x, e.y + y, rad); Drawf.light(e.x + x, e.y + y, rad * 2.5f, b.color, 0.5f); }); }); } }).layer(Layer.bullet - 1f), neoplasmSplat = new Effect(400f, 300f, b -> { float intensity = 3f; color(Pal.neoplasm1); for(int i = 0; i < 4; i++){ rand.setSeed(b.id*2 + i); float lenScl = rand.random(0.5f, 1f); int fi = i; b.scaled(b.lifetime * lenScl, e -> { randLenVectors(e.id + fi - 1, e.fin(Interp.pow10Out), (int)(5f * intensity), 22f * intensity, (x, y, in, out) -> { float fout = e.fout(Interp.pow5Out) * rand.random(0.5f, 1f); float rad = fout * ((2f + intensity) * 1.35f); Fill.circle(e.x + x, e.y + y, rad); Drawf.light(e.x + x, e.y + y, rad * 2.5f, b.color, 0.5f); }); }); } }).layer(Layer.bullet - 2f), scatheExplosion = new Effect(60f, 160f, e -> { color(e.color); stroke(e.fout() * 5f); float circleRad = 6f + e.finpow() * 60f; Lines.circle(e.x, e.y, circleRad); rand.setSeed(e.id); for(int i = 0; i < 16; i++){ float angle = rand.random(360f); float lenRand = rand.random(0.5f, 1f); Tmp.v1.trns(angle, circleRad); for(int s : Mathf.signs){ Drawf.tri(e.x + Tmp.v1.x, e.y + Tmp.v1.y, e.foutpow() * 40f, e.fout() * 30f * lenRand + 6f, angle + 90f + s * 90f); } } }), scatheLight = new Effect(60f, 160f, e -> { float circleRad = 6f + e.finpow() * 60f; color(e.color, e.foutpow()); Fill.circle(e.x, e.y, circleRad); }).layer(Layer.bullet + 2f), scatheSlash = new Effect(40f, 160f, e -> { Draw.color(e.color); for(int s : Mathf.signs){ Drawf.tri(e.x, e.y, e.fout() * 25f, e.foutpow() * 66f + 6f, e.rotation + s * 90f); } }), dynamicSpikes = new Effect(40f, 100f, e -> { color(e.color); stroke(e.fout() * 2f); float circleRad = 4f + e.finpow() * e.rotation; Lines.circle(e.x, e.y, circleRad); for(int i = 0; i < 4; i++){ Drawf.tri(e.x, e.y, 6f, e.rotation * 1.5f * e.fout(), i*90); } color(); for(int i = 0; i < 4; i++){ Drawf.tri(e.x, e.y, 3f, e.rotation * 1.45f / 3f * e.fout(), i*90); } Drawf.light(e.x, e.y, circleRad * 1.6f, Pal.heal, e.fout()); }), greenBomb = new Effect(40f, 100f, e -> { color(Pal.heal); stroke(e.fout() * 2f); float circleRad = 4f + e.finpow() * 65f; Lines.circle(e.x, e.y, circleRad); color(Pal.heal); for(int i = 0; i < 4; i++){ Drawf.tri(e.x, e.y, 6f, 100f * e.fout(), i*90); } color(); for(int i = 0; i < 4; i++){ Drawf.tri(e.x, e.y, 3f, 35f * e.fout(), i*90); } Drawf.light(e.x, e.y, circleRad * 1.6f, Pal.heal, e.fout()); }), greenLaserCharge = new Effect(80f, 100f, e -> { color(Pal.heal); stroke(e.fin() * 2f); Lines.circle(e.x, e.y, 4f + e.fout() * 100f); Fill.circle(e.x, e.y, e.fin() * 20); randLenVectors(e.id, 20, 40f * e.fout(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fin() * 5f); Drawf.light(e.x + x, e.y + y, e.fin() * 15f, Pal.heal, 0.7f); }); color(); Fill.circle(e.x, e.y, e.fin() * 10); Drawf.light(e.x, e.y, e.fin() * 20f, Pal.heal, 0.7f); }).followParent(true).rotWithParent(true), greenLaserChargeSmall = new Effect(40f, 100f, e -> { color(Pal.heal); stroke(e.fin() * 2f); Lines.circle(e.x, e.y, e.fout() * 50f); }).followParent(true).rotWithParent(true), greenCloud = new Effect(80f, e -> { color(Pal.heal); randLenVectors(e.id, e.fin(), 7, 9f, (x, y, fin, fout) -> { Fill.circle(e.x + x, e.y + y, 5f * fout); }); }), healWaveDynamic = new Effect(22, e -> { color(Pal.heal); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 4f + e.finpow() * e.rotation); }), healWave = new Effect(22, e -> { color(Pal.heal); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 4f + e.finpow() * 60f); }), heal = new Effect(11, e -> { color(Pal.heal); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 2f + e.finpow() * 7f); }), dynamicWave = new Effect(22, e -> { color(e.color, 0.7f); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 4f + e.finpow() * e.rotation); }), shieldWave = new Effect(22, e -> { color(e.color, 0.7f); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 4f + e.finpow() * 60f); }), shieldApply = new Effect(11, e -> { color(e.color, 0.7f); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 2f + e.finpow() * 7f); }), disperseTrail = new Effect(13, e -> { color(Color.white, e.color, e.fin()); stroke(0.6f + e.fout() * 1.7f); rand.setSeed(e.id); for(int i = 0; i < 2; i++){ float rot = e.rotation + rand.range(15f) + 180f; v.trns(rot, rand.random(e.fin() * 27f)); lineAngle(e.x + v.x, e.y + v.y, rot, e.fout() * rand.random(2f, 7f) + 1.5f); } }), hitBulletSmall = new Effect(14, e -> { color(Color.white, Pal.lightOrange, e.fin()); e.scaled(7f, s -> { stroke(0.5f + s.fout()); Lines.circle(e.x, e.y, s.fin() * 5f); }); stroke(0.5f + e.fout()); randLenVectors(e.id, 5, e.fin() * 15f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 3 + 1f); }); Drawf.light(e.x, e.y, 20f, Pal.lightOrange, 0.6f * e.fout()); }), hitBulletColor = new Effect(14, e -> { color(Color.white, e.color, e.fin()); e.scaled(7f, s -> { stroke(0.5f + s.fout()); Lines.circle(e.x, e.y, s.fin() * 5f); }); stroke(0.5f + e.fout()); randLenVectors(e.id, 5, e.fin() * 15f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 3 + 1f); }); Drawf.light(e.x, e.y, 20f, e.color, 0.6f * e.fout()); }), hitSquaresColor = new Effect(14, e -> { color(Color.white, e.color, e.fin()); e.scaled(7f, s -> { stroke(0.5f + s.fout()); Lines.circle(e.x, e.y, s.fin() * 5f); }); stroke(0.5f + e.fout()); randLenVectors(e.id, 5, e.fin() * 17f, (x, y) -> { float ang = Mathf.angle(x, y); Fill.square(e.x + x, e.y + y, e.fout() * 3.2f, ang); }); Drawf.light(e.x, e.y, 20f, e.color, 0.6f * e.fout()); }), hitFuse = new Effect(14, e -> { color(Color.white, Pal.surge, e.fin()); e.scaled(7f, s -> { stroke(0.5f + s.fout()); Lines.circle(e.x, e.y, s.fin() * 7f); }); stroke(0.5f + e.fout()); randLenVectors(e.id, 6, e.fin() * 15f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 3 + 1f); }); }), hitBulletBig = new Effect(13, e -> { color(Color.white, Pal.lightOrange, e.fin()); stroke(0.5f + e.fout() * 1.5f); randLenVectors(e.id, 8, e.finpow() * 30f, e.rotation, 50f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1.5f); }); }), hitFlameSmall = new Effect(14, e -> { color(Pal.lightFlame, Pal.darkFlame, e.fin()); stroke(0.5f + e.fout()); randLenVectors(e.id, 2, 1f + e.fin() * 15f, e.rotation, 50f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 3 + 1f); }); }), hitFlamePlasma = new Effect(14, e -> { color(Color.white, Pal.heal, e.fin()); stroke(0.5f + e.fout()); randLenVectors(e.id, 2, 1f + e.fin() * 15f, e.rotation, 50f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 3 + 1f); }); }), hitLiquid = new Effect(16, e -> { color(e.color); randLenVectors(e.id, 5, 1f + e.fin() * 15f, e.rotation, 60f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 2f); }); }), hitLaserBlast = new Effect(12, e -> { color(e.color); stroke(e.fout() * 1.5f); randLenVectors(e.id, 8, e.finpow() * 17f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1f); }); }), hitEmpSpark = new Effect(40, e -> { color(Pal.heal); stroke(e.fout() * 1.6f); randLenVectors(e.id, 18, e.finpow() * 27f, e.rotation, 360f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 6 + 1f); }); }), hitLancer = new Effect(12, e -> { color(Color.white); stroke(e.fout() * 1.5f); randLenVectors(e.id, 8, e.finpow() * 17f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1f); }); }), hitBeam = new Effect(12, e -> { color(e.color); stroke(e.fout() * 2f); randLenVectors(e.id, 6, e.finpow() * 18f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1f); }); }), hitFlameBeam = new Effect(19, e -> { color(e.color); randLenVectors(e.id, 7, e.finpow() * 11f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 2 + 0.5f); }); }), hitMeltdown = new Effect(12, e -> { color(Pal.meltdownHit); stroke(e.fout() * 2f); randLenVectors(e.id, 6, e.finpow() * 18f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1f); }); }), hitMeltHeal = new Effect(12, e -> { color(Pal.heal); stroke(e.fout() * 2f); randLenVectors(e.id, 6, e.finpow() * 18f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1f); }); }), instBomb = new Effect(15f, 100f, e -> { color(Pal.bulletYellowBack); stroke(e.fout() * 4f); Lines.circle(e.x, e.y, 4f + e.finpow() * 20f); for(int i = 0; i < 4; i++){ Drawf.tri(e.x, e.y, 6f, 80f * e.fout(), i*90 + 45); } color(); for(int i = 0; i < 4; i++){ Drawf.tri(e.x, e.y, 3f, 30f * e.fout(), i*90 + 45); } Drawf.light(e.x, e.y, 150f, Pal.bulletYellowBack, 0.9f * e.fout()); }), instTrail = new Effect(30, e -> { for(int i = 0; i < 2; i++){ color(i == 0 ? Pal.bulletYellowBack : Pal.bulletYellow); float m = i == 0 ? 1f : 0.5f; float rot = e.rotation + 180f; float w = 15f * e.fout() * m; Drawf.tri(e.x, e.y, w, (30f + Mathf.randomSeedRange(e.id, 15f)) * m, rot); Drawf.tri(e.x, e.y, w, 10f * m, rot + 180f); } Drawf.light(e.x, e.y, 60f, Pal.bulletYellowBack, 0.6f * e.fout()); }), instShoot = new Effect(24f, e -> { e.scaled(10f, b -> { color(Color.white, Pal.bulletYellowBack, b.fin()); stroke(b.fout() * 3f + 0.2f); Lines.circle(b.x, b.y, b.fin() * 50f); }); color(Pal.bulletYellowBack); for(int i : Mathf.signs){ Drawf.tri(e.x, e.y, 13f * e.fout(), 85f, e.rotation + 90f * i); Drawf.tri(e.x, e.y, 13f * e.fout(), 50f, e.rotation + 20f * i); } Drawf.light(e.x, e.y, 180f, Pal.bulletYellowBack, 0.9f * e.fout()); }), instHit = new Effect(20f, 200f, e -> { color(Pal.bulletYellowBack); for(int i = 0; i < 2; i++){ color(i == 0 ? Pal.bulletYellowBack : Pal.bulletYellow); float m = i == 0 ? 1f : 0.5f; for(int j = 0; j < 5; j++){ float rot = e.rotation + Mathf.randomSeedRange(e.id + j, 50f); float w = 23f * e.fout() * m; Drawf.tri(e.x, e.y, w, (80f + Mathf.randomSeedRange(e.id + j, 40f)) * m, rot); Drawf.tri(e.x, e.y, w, 20f * m, rot + 180f); } } e.scaled(10f, c -> { color(Pal.bulletYellow); stroke(c.fout() * 2f + 0.2f); Lines.circle(e.x, e.y, c.fin() * 30f); }); e.scaled(12f, c -> { color(Pal.bulletYellowBack); randLenVectors(e.id, 25, 5f + e.fin() * 80f, e.rotation, 60f, (x, y) -> { Fill.square(e.x + x, e.y + y, c.fout() * 3f, 45f); }); }); }), hitLaser = new Effect(8, e -> { color(Color.white, Pal.heal, e.fin()); stroke(0.5f + e.fout()); Lines.circle(e.x, e.y, e.fin() * 5f); Drawf.light(e.x, e.y, 23f, Pal.heal, e.fout() * 0.7f); }), hitLaserColor = new Effect(8, e -> { color(Color.white, e.color, e.fin()); stroke(0.5f + e.fout()); Lines.circle(e.x, e.y, e.fin() * 5f); Drawf.light(e.x, e.y, 23f, e.color, e.fout() * 0.7f); }), despawn = new Effect(12, e -> { color(Pal.lighterOrange, Color.gray, e.fin()); stroke(e.fout()); randLenVectors(e.id, 7, e.fin() * 7f, e.rotation, 40f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 2 + 1f); }); }), airBubble = new Effect(100f, e -> { randLenVectors(e.id, 1, e.fin() * 12f, (x, y) -> { rect(renderer.bubbles[Math.min((int)(renderer.bubbles.length * Mathf.curveMargin(e.fin(), 0.11f, 0.06f)), renderer.bubbles.length - 1)], e.x + x, e.y + y); }); }).layer(Layer.flyingUnitLow + 1), flakExplosion = new Effect(20, e -> { color(Pal.bulletYellow); e.scaled(6, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 10f); }); color(Color.gray); randLenVectors(e.id, 5, 2f + 23f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3f + 0.5f); }); color(Pal.lighterOrange); stroke(e.fout()); randLenVectors(e.id + 1, 4, 1f + 23f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); Drawf.light(e.x, e.y, 50f, Pal.lighterOrange, 0.8f * e.fout()); }), plasticExplosion = new Effect(24, e -> { color(Pal.plastaniumFront); e.scaled(7, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 24f); }); color(Color.gray); randLenVectors(e.id, 7, 2f + 28f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.5f); }); color(Pal.plastaniumBack); stroke(e.fout()); randLenVectors(e.id + 1, 4, 1f + 25f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); Drawf.light(e.x, e.y, 50f, Pal.plastaniumBack, 0.8f * e.fout()); }), plasticExplosionFlak = new Effect(28, e -> { color(Pal.plastaniumFront); e.scaled(7, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 34f); }); color(Color.gray); randLenVectors(e.id, 7, 2f + 30f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.5f); }); color(Pal.plastaniumBack); stroke(e.fout()); randLenVectors(e.id + 1, 4, 1f + 30f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); }), blastExplosion = new Effect(22, e -> { color(Pal.missileYellow); e.scaled(6, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 15f); }); color(Color.gray); randLenVectors(e.id, 5, 2f + 23f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.5f); }); color(Pal.missileYellowBack); stroke(e.fout()); randLenVectors(e.id + 1, 4, 1f + 23f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); Drawf.light(e.x, e.y, 45f, Pal.missileYellowBack, 0.8f * e.fout()); }), sapExplosion = new Effect(25, e -> { color(Pal.sapBullet); e.scaled(6, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 80f); }); color(Color.gray); randLenVectors(e.id, 9, 2f + 70 * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.5f); }); color(Pal.sapBulletBack); stroke(e.fout()); randLenVectors(e.id + 1, 8, 1f + 60f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); Drawf.light(e.x, e.y, 90f, Pal.sapBulletBack, 0.8f * e.fout()); }), massiveExplosion = new Effect(30, e -> { color(Pal.missileYellow); e.scaled(7, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 4f + i.fin() * 30f); }); color(Color.gray); randLenVectors(e.id, 8, 2f + 30f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.5f); }); color(Pal.missileYellowBack); stroke(e.fout()); randLenVectors(e.id + 1, 6, 1f + 29f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 4f); }); Drawf.light(e.x, e.y, 50f, Pal.missileYellowBack, 0.8f * e.fout()); }), artilleryTrail = new Effect(50, e -> { color(e.color); Fill.circle(e.x, e.y, e.rotation * e.fout()); }), incendTrail = new Effect(50, e -> { color(Pal.lightOrange); Fill.circle(e.x, e.y, e.rotation * e.fout()); }), missileTrail = new Effect(50, e -> { color(e.color); Fill.circle(e.x, e.y, e.rotation * e.fout()); }).layer(Layer.bullet - 0.001f), //below bullets missileTrailShort = new Effect(22, e -> { color(e.color); Fill.circle(e.x, e.y, e.rotation * e.fout()); }).layer(Layer.bullet - 0.001f), colorTrail = new Effect(50, e -> { color(e.color); Fill.circle(e.x, e.y, e.rotation * e.fout()); }), absorb = new Effect(12, e -> { color(Pal.accent); stroke(2f * e.fout()); Lines.circle(e.x, e.y, 5f * e.fout()); }), forceShrink = new Effect(20, e -> { color(e.color, e.fout()); if(renderer.animateShields){ Fill.poly(e.x, e.y, 6, e.rotation * e.fout()); }else{ stroke(1.5f); Draw.alpha(0.09f); Fill.poly(e.x, e.y, 6, e.rotation * e.fout()); Draw.alpha(1f); Lines.poly(e.x, e.y, 6, e.rotation * e.fout()); } }).layer(Layer.shields), flakExplosionBig = new Effect(30, e -> { color(Pal.bulletYellowBack); e.scaled(6, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 25f); }); color(Color.gray); randLenVectors(e.id, 6, 2f + 23f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 4f + 0.5f); }); color(Pal.bulletYellow); stroke(e.fout()); randLenVectors(e.id + 1, 4, 1f + 23f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); Drawf.light(e.x, e.y, 60f, Pal.bulletYellowBack, 0.7f * e.fout()); }), burning = new Effect(35f, e -> { color(Pal.lightFlame, Pal.darkFlame, e.fin()); randLenVectors(e.id, 3, 2f + e.fin() * 7f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.1f + e.fout() * 1.4f); }); }), fireRemove = new Effect(70f, e -> { if(Fire.regions[0] == null) return; alpha(e.fout()); rect(Fire.regions[((int)(e.rotation + e.fin() * Fire.frames)) % Fire.frames], e.x + Mathf.randomSeedRange((int)e.y, 2), e.y + Mathf.randomSeedRange((int)e.x, 2)); Drawf.light(e.x, e.y, 50f + Mathf.absin(5f, 5f), Pal.lightFlame, 0.6f * e.fout()); }), fire = new Effect(50f, e -> { color(Pal.lightFlame, Pal.darkFlame, e.fin()); randLenVectors(e.id, 2, 2f + e.fin() * 9f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fslope() * 1.5f); }); color(); Drawf.light(e.x, e.y, 20f * e.fslope(), Pal.lightFlame, 0.5f); }), fireHit = new Effect(35f, e -> { color(Pal.lightFlame, Pal.darkFlame, e.fin()); randLenVectors(e.id, 3, 2f + e.fin() * 10f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fout() * 1.6f); }); color(); }), fireSmoke = new Effect(35f, e -> { color(Color.gray); randLenVectors(e.id, 1, 2f + e.fin() * 7f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fslope() * 1.5f); }); }), //TODO needs a lot of work neoplasmHeal = new Effect(120f, e -> { color(Pal.neoplasm1, Pal.neoplasm2, e.fin()); randLenVectors(e.id, 1, e.fin() * 3f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fslope() * 2f); }); }).followParent(true).rotWithParent(true).layer(Layer.bullet - 2), steam = new Effect(35f, e -> { color(Color.lightGray); randLenVectors(e.id, 2, 2f + e.fin() * 7f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fslope() * 1.5f); }); }), ventSteam = new Effect(140f, e -> { color(e.color, Pal.vent2, e.fin()); alpha(e.fslope() * 0.78f); float length = 3f + e.finpow() * 10f; rand.setSeed(e.id); for(int i = 0; i < rand.random(3, 5); i++){ v.trns(rand.random(360f), rand.random(length)); Fill.circle(e.x + v.x, e.y + v.y, rand.random(1.2f, 3.5f) + e.fslope() * 1.1f); } }).layer(Layer.darkness - 1), drillSteam = new Effect(220f, e -> { float length = 3f + e.finpow() * 20f; rand.setSeed(e.id); for(int i = 0; i < 13; i++){ v.trns(rand.random(360f), rand.random(length)); float sizer = rand.random(1.3f, 3.7f); e.scaled(e.lifetime * rand.random(0.5f, 1f), b -> { color(Color.gray, b.fslope() * 0.93f); Fill.circle(e.x + v.x, e.y + v.y, sizer + b.fslope() * 1.2f); }); } }).startDelay(30f), fluxVapor = new Effect(140f, e -> { color(e.color); alpha(e.fout() * 0.7f); randLenVectors(e.id, 2, 3f + e.finpow() * 10f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.6f + e.fin() * 5f); }); }).layer(Layer.bullet - 1f), vapor = new Effect(110f, e -> { color(e.color); alpha(e.fout()); randLenVectors(e.id, 3, 2f + e.finpow() * 11f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.6f + e.fin() * 5f); }); }), vaporSmall = new Effect(50f, e -> { color(e.color); alpha(e.fout()); randLenVectors(e.id, 4, 2f + e.finpow() * 5f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 1f + e.fin() * 4f); }); }), fireballsmoke = new Effect(25f, e -> { color(Color.gray); randLenVectors(e.id, 1, 2f + e.fin() * 7f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fout() * 1.5f); }); }), ballfire = new Effect(25f, e -> { color(Pal.lightFlame, Pal.darkFlame, e.fin()); randLenVectors(e.id, 2, 2f + e.fin() * 7f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.2f + e.fout() * 1.5f); }); }), freezing = new Effect(40f, e -> { color(Liquids.cryofluid.color); randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 1.2f); }); }), melting = new Effect(40f, e -> { color(Liquids.slag.color, Color.white, e.fout() / 5f + Mathf.randomSeedRange(e.id, 0.12f)); randLenVectors(e.id, 2, 1f + e.fin() * 3f, (x, y) -> { Fill.circle(e.x + x, e.y + y, .2f + e.fout() * 1.2f); }); }), wet = new Effect(80f, e -> { color(Liquids.water.color); alpha(Mathf.clamp(e.fin() * 2f)); Fill.circle(e.x, e.y, e.fout()); }), muddy = new Effect(80f, e -> { color(Pal.muddy); alpha(Mathf.clamp(e.fin() * 2f)); Fill.circle(e.x, e.y, e.fout()); }), sapped = new Effect(40f, e -> { color(Pal.sap); randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fslope() * 1.1f, 45f); }); }), electrified = new Effect(40f, e -> { color(Pal.heal); randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fslope() * 1.1f, 45f); }); }), sporeSlowed = new Effect(40f, e -> { color(Pal.spore); Fill.circle(e.x, e.y, e.fslope() * 1.1f); }), oily = new Effect(42f, e -> { color(Liquids.oil.color); randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout()); }); }), overdriven = new Effect(20f, e -> { color(e.color); randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() * 2.3f + 0.5f); }); }), overclocked = new Effect(50f, e -> { color(e.color); Fill.square(e.x, e.y, e.fslope() * 2f, 45f); }), dropItem = new Effect(20f, e -> { float length = 20f * e.finpow(); float size = 7f * e.fout(); if(!(e.data instanceof Item item)) return; rect(item.fullIcon, e.x + trnsx(e.rotation, length), e.y + trnsy(e.rotation, length), size, size); }), shockwave = new Effect(10f, 80f, e -> { color(Color.white, Color.lightGray, e.fin()); stroke(e.fout() * 2f + 0.2f); Lines.circle(e.x, e.y, e.fin() * 28f); }), bigShockwave = new Effect(10f, 80f, e -> { color(Color.white, Color.lightGray, e.fin()); stroke(e.fout() * 3f); Lines.circle(e.x, e.y, e.fin() * 50f); }), spawnShockwave = new Effect(20f, 400f, e -> { color(Color.white, Color.lightGray, e.fin()); stroke(e.fout() * 3f + 0.5f); Lines.circle(e.x, e.y, e.fin() * (e.rotation + 50f)); }), explosion = new Effect(30, e -> { e.scaled(7, i -> { stroke(3f * i.fout()); Lines.circle(e.x, e.y, 3f + i.fin() * 10f); }); color(Color.gray); randLenVectors(e.id, 6, 2f + 19f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3f + 0.5f); Fill.circle(e.x + x / 2f, e.y + y / 2f, e.fout()); }); color(Pal.lighterOrange, Pal.lightOrange, Color.gray, e.fin()); stroke(1.5f * e.fout()); randLenVectors(e.id + 1, 8, 1f + 23f * e.finpow(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + e.fout() * 3f); }); }), dynamicExplosion = new Effect(30, 500f, b -> { float intensity = b.rotation; float baseLifetime = 26f + intensity * 15f; b.lifetime = 43f + intensity * 35f; color(Color.gray); //TODO awful borders with linear filtering here alpha(0.9f); for(int i = 0; i < 4; i++){ rand.setSeed(b.id*2 + i); float lenScl = rand.random(0.4f, 1f); int fi = i; b.scaled(b.lifetime * lenScl, e -> { randLenVectors(e.id + fi - 1, e.fin(Interp.pow10Out), (int)(3f * intensity), 14f * intensity, (x, y, in, out) -> { float fout = e.fout(Interp.pow5Out) * rand.random(0.5f, 1f); Fill.circle(e.x + x, e.y + y, fout * ((2f + intensity) * 1.8f)); }); }); } b.scaled(baseLifetime, e -> { e.scaled(5 + intensity * 2.5f, i -> { stroke((3.1f + intensity/5f) * i.fout()); Lines.circle(e.x, e.y, (3f + i.fin() * 14f) * intensity); Drawf.light(e.x, e.y, i.fin() * 14f * 2f * intensity, Color.white, 0.9f * e.fout()); }); color(Pal.lighterOrange, Pal.lightOrange, Color.gray, e.fin()); stroke((1.7f * e.fout()) * (1f + (intensity - 1f) / 2f)); Draw.z(Layer.effect + 0.001f); randLenVectors(e.id + 1, e.finpow() + 0.001f, (int)(9 * intensity), 40f * intensity, (x, y, in, out) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (3f + intensity)); Drawf.light(e.x + x, e.y + y, (out * 4 * (3f + intensity)) * 3.5f, Draw.getColor(), 0.8f); }); }); }), reactorExplosion = new Effect(30, 500f, b -> { float intensity = 6.8f; float baseLifetime = 25f + intensity * 11f; b.lifetime = 50f + intensity * 65f; color(Pal.reactorPurple2); alpha(0.7f); for(int i = 0; i < 4; i++){ rand.setSeed(b.id*2 + i); float lenScl = rand.random(0.4f, 1f); int fi = i; b.scaled(b.lifetime * lenScl, e -> { randLenVectors(e.id + fi - 1, e.fin(Interp.pow10Out), (int)(2.9f * intensity), 22f * intensity, (x, y, in, out) -> { float fout = e.fout(Interp.pow5Out) * rand.random(0.5f, 1f); float rad = fout * ((2f + intensity) * 2.35f); Fill.circle(e.x + x, e.y + y, rad); Drawf.light(e.x + x, e.y + y, rad * 2.5f, Pal.reactorPurple, 0.5f); }); }); } b.scaled(baseLifetime, e -> { Draw.color(); e.scaled(5 + intensity * 2f, i -> { stroke((3.1f + intensity/5f) * i.fout()); Lines.circle(e.x, e.y, (3f + i.fin() * 14f) * intensity); Drawf.light(e.x, e.y, i.fin() * 14f * 2f * intensity, Color.white, 0.9f * e.fout()); }); color(Pal.lighterOrange, Pal.reactorPurple, e.fin()); stroke((2f * e.fout())); Draw.z(Layer.effect + 0.001f); randLenVectors(e.id + 1, e.finpow() + 0.001f, (int)(8 * intensity), 28f * intensity, (x, y, in, out) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (4f + intensity)); Drawf.light(e.x + x, e.y + y, (out * 4 * (3f + intensity)) * 3.5f, Draw.getColor(), 0.8f); }); }); }), impactReactorExplosion = new Effect(30, 500f, b -> { float intensity = 8f; float baseLifetime = 25f + intensity * 15f; b.lifetime = 50f + intensity * 64f; color(Pal.lighterOrange); alpha(0.8f); for(int i = 0; i < 5; i++){ rand.setSeed(b.id*2 + i); float lenScl = rand.random(0.25f, 1f); int fi = i; b.scaled(b.lifetime * lenScl, e -> { randLenVectors(e.id + fi - 1, e.fin(Interp.pow10Out), (int)(2.8f * intensity), 25f * intensity, (x, y, in, out) -> { float fout = e.fout(Interp.pow5Out) * rand.random(0.5f, 1f); float rad = fout * ((2f + intensity) * 2.35f); Fill.circle(e.x + x, e.y + y, rad); Drawf.light(e.x + x, e.y + y, rad * 2.6f, Pal.lighterOrange, 0.7f); }); }); } b.scaled(baseLifetime, e -> { Draw.color(); e.scaled(5 + intensity * 2f, i -> { stroke((3.1f + intensity/5f) * i.fout()); Lines.circle(e.x, e.y, (3f + i.fin() * 14f) * intensity); Drawf.light(e.x, e.y, i.fin() * 14f * 2f * intensity, Color.white, 0.9f * e.fout()); }); color(Color.white, Pal.lighterOrange, e.fin()); stroke((2f * e.fout())); Draw.z(Layer.effect + 0.001f); randLenVectors(e.id + 1, e.finpow() + 0.001f, (int)(8 * intensity), 30f * intensity, (x, y, in, out) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (4f + intensity)); Drawf.light(e.x + x, e.y + y, (out * 4 * (3f + intensity)) * 3.5f, Draw.getColor(), 0.8f); }); }); }), blockExplosionSmoke = new Effect(30, e -> { color(Color.gray); randLenVectors(e.id, 6, 4f + 30f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3f); Fill.circle(e.x + x / 2f, e.y + y / 2f, e.fout()); }); }), smokePuff = new Effect(30, e -> { color(e.color); randLenVectors(e.id, 6, 4f + 30f * e.finpow(), (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 3f); Fill.circle(e.x + x / 2f, e.y + y / 2f, e.fout()); }); }), shootSmall = new Effect(8, e -> { color(Pal.lighterOrange, Pal.lightOrange, e.fin()); float w = 1f + 5 * e.fout(); Drawf.tri(e.x, e.y, w, 15f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 3f * e.fout(), e.rotation + 180f); }), shootSmallColor = new Effect(8, e -> { color(e.color, Color.gray, e.fin()); float w = 1f + 5 * e.fout(); Drawf.tri(e.x, e.y, w, 15f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 3f * e.fout(), e.rotation + 180f); }), shootHeal = new Effect(8, e -> { color(Pal.heal); float w = 1f + 5 * e.fout(); Drawf.tri(e.x, e.y, w, 17f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 4f * e.fout(), e.rotation + 180f); }), shootHealYellow = new Effect(8, e -> { color(Pal.lightTrail); float w = 1f + 5 * e.fout(); Drawf.tri(e.x, e.y, w, 17f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 4f * e.fout(), e.rotation + 180f); }), shootSmallSmoke = new Effect(20f, e -> { color(Pal.lighterOrange, Color.lightGray, Color.gray, e.fin()); randLenVectors(e.id, 5, e.finpow() * 6f, e.rotation, 20f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 1.5f); }); }), shootBig = new Effect(9, e -> { color(Pal.lighterOrange, Pal.lightOrange, e.fin()); float w = 1.2f + 7 * e.fout(); Drawf.tri(e.x, e.y, w, 25f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 4f * e.fout(), e.rotation + 180f); }), shootBig2 = new Effect(10, e -> { color(Pal.lightOrange, Color.gray, e.fin()); float w = 1.2f + 8 * e.fout(); Drawf.tri(e.x, e.y, w, 29f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 5f * e.fout(), e.rotation + 180f); }), shootBigColor = new Effect(11, e -> { color(e.color, Color.gray, e.fin()); float w = 1.2f +9 * e.fout(); Drawf.tri(e.x, e.y, w, 32f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 3f * e.fout(), e.rotation + 180f); }), shootTitan = new Effect(10, e -> { color(Pal.lightOrange, e.color, e.fin()); float w = 1.3f + 10 * e.fout(); Drawf.tri(e.x, e.y, w, 35f * e.fout(), e.rotation); Drawf.tri(e.x, e.y, w, 6f * e.fout(), e.rotation + 180f); }), shootBigSmoke = new Effect(17f, e -> { color(Pal.lighterOrange, Color.lightGray, Color.gray, e.fin()); randLenVectors(e.id, 8, e.finpow() * 19f, e.rotation, 10f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 2f + 0.2f); }); }), shootBigSmoke2 = new Effect(18f, e -> { color(Pal.lightOrange, Color.lightGray, Color.gray, e.fin()); randLenVectors(e.id, 9, e.finpow() * 23f, e.rotation, 20f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 2.4f + 0.2f); }); }), shootSmokeDisperse = new Effect(25f, e -> { color(Pal.lightOrange, Color.white, Color.gray, e.fin()); randLenVectors(e.id, 9, e.finpow() * 29f, e.rotation, 18f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 2.2f + 0.1f); }); }), shootSmokeSquare = new Effect(20f, e -> { color(Color.white, e.color, e.fin()); rand.setSeed(e.id); for(int i = 0; i < 6; i++){ float rot = e.rotation + rand.range(22f); v.trns(rot, rand.random(e.finpow() * 21f)); Fill.poly(e.x + v.x, e.y + v.y, 4, e.fout() * 2f + 0.2f, rand.random(360f)); } }), shootSmokeSquareSparse = new Effect(30f, e -> { color(Color.white, e.color, e.fin()); rand.setSeed(e.id); for(int i = 0; i < 2; i++){ float rot = e.rotation + rand.range(30f); v.trns(rot, rand.random(e.finpow() * 27f)); Fill.poly(e.x + v.x, e.y + v.y, 4, e.fout() * 3.8f + 0.2f, rand.random(360f)); } }), shootSmokeSquareBig = new Effect(32f, e -> { color(Color.white, e.color, e.fin()); rand.setSeed(e.id); for(int i = 0; i < 13; i++){ float rot = e.rotation + rand.range(26f); v.trns(rot, rand.random(e.finpow() * 30f)); Fill.poly(e.x + v.x, e.y + v.y, 4, e.fout() * 4f + 0.2f, rand.random(360f)); } }), shootSmokeTitan = new Effect(70f, e -> { rand.setSeed(e.id); for(int i = 0; i < 13; i++){ v.trns(e.rotation + rand.range(30f), rand.random(e.finpow() * 40f)); e.scaled(e.lifetime * rand.random(0.3f, 1f), b -> { color(e.color, Pal.lightishGray, b.fin()); Fill.circle(e.x + v.x, e.y + v.y, b.fout() * 3.4f + 0.3f); }); } }), shootSmokeSmite = new Effect(70f, e -> { rand.setSeed(e.id); for(int i = 0; i < 13; i++){ float a = e.rotation + rand.range(30f); v.trns(a, rand.random(e.finpow() * 50f)); e.scaled(e.lifetime * rand.random(0.3f, 1f), b -> { color(e.color); Lines.stroke(b.fout() * 3f + 0.5f); Lines.lineAngle(e.x + v.x, e.y + v.y, a, b.fout() * 8f + 0.4f); }); } }), shootSmokeMissile = new Effect(130f, 300f, e -> { color(Pal.redLight); alpha(0.5f); rand.setSeed(e.id); for(int i = 0; i < 35; i++){ v.trns(e.rotation + 180f + rand.range(21f), rand.random(e.finpow() * 90f)).add(rand.range(3f), rand.range(3f)); e.scaled(e.lifetime * rand.random(0.2f, 1f), b -> { Fill.circle(e.x + v.x, e.y + v.y, b.fout() * 9f + 0.3f); }); } }), regenParticle = new Effect(100f, e -> { color(Pal.regen); Fill.square(e.x, e.y, e.fslope() * 1.5f + 0.14f, 45f); }), regenSuppressParticle = new Effect(35f, e -> { color(e.color, Color.white, e.fin()); stroke(e.fout() * 1.4f + 0.5f); randLenVectors(e.id, 4, 17f * e.fin(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 3f + 0.5f); }); }), regenSuppressSeek = new Effect(140f, e -> { e.lifetime = Mathf.randomSeed(e.id, 120f, 200f); if(!(e.data instanceof Position to)) return; Tmp.v2.set(to).sub(e.x, e.y).nor().rotate90(1).scl(Mathf.randomSeedRange(e.id, 1f) * 50f); Tmp.bz2.set(Tmp.v1.set(e.x, e.y), Tmp.v2.add(e.x, e.y), Tmp.v3.set(to)); Tmp.bz2.valueAt(Tmp.v4, e.fout()); color(e.color); Fill.circle(Tmp.v4.x, Tmp.v4.y, e.fslope() * 2f + 0.1f); }).followParent(false).rotWithParent(false), surgeCruciSmoke = new Effect(160f, e -> { color(Pal.slagOrange); alpha(0.6f); rand.setSeed(e.id); for(int i = 0; i < 3; i++){ float len = rand.random(6f), rot = rand.range(40f) + e.rotation; e.scaled(e.lifetime * rand.random(0.3f, 1f), b -> { v.trns(rot, len * b.finpow()); Fill.circle(e.x + v.x, e.y + v.y, 2f * b.fslope() + 0.2f); }); } }), neoplasiaSmoke = new Effect(280f, e -> { color(Pal.neoplasmMid); alpha(0.6f); rand.setSeed(e.id); for(int i = 0; i < 6; i++){ float len = rand.random(10f), rot = rand.range(120f) + e.rotation; e.scaled(e.lifetime * rand.random(0.3f, 1f), b -> { v.trns(rot, len * b.finpow()); Fill.circle(e.x + v.x, e.y + v.y, 3.3f * b.fslope() + 0.2f); }); } }), heatReactorSmoke = new Effect(180f, e -> { color(Color.gray); rand.setSeed(e.id); for(int i = 0; i < 5; i++){ float len = rand.random(6f), rot = rand.range(50f) + e.rotation; e.scaled(e.lifetime * rand.random(0.3f, 1f), b -> { alpha(0.9f * b.fout()); v.trns(rot, len * b.finpow()); Fill.circle(e.x + v.x, e.y + v.y, 2.4f * b.fin() + 0.6f); }); } }), circleColorSpark = new Effect(21f, e -> { color(Color.white, e.color, e.fin()); stroke(e.fout() * 1.1f + 0.5f); randLenVectors(e.id, 9, 27f * e.fin(), 9f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 5f + 0.5f); }); }), colorSpark = new Effect(21f, e -> { color(Color.white, e.color, e.fin()); stroke(e.fout() * 1.1f + 0.5f); randLenVectors(e.id, 5, 27f * e.fin(), e.rotation, 9f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 5f + 0.5f); }); }), colorSparkBig = new Effect(25f, e -> { color(Color.white, e.color, e.fin()); stroke(e.fout() * 1.3f + 0.7f); randLenVectors(e.id, 8, 41f * e.fin(), e.rotation, 10f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 6f + 0.5f); }); }), randLifeSpark = new Effect(24f, e -> { color(Color.white, e.color, e.fin()); stroke(e.fout() * 1.5f + 0.5f); rand.setSeed(e.id); for(int i = 0; i < 15; i++){ float ang = e.rotation + rand.range(9f), len = rand.random(90f * e.finpow()); e.scaled(e.lifetime * rand.random(0.5f, 1f), p -> { v.trns(ang, len); lineAngle(e.x + v.x, e.y + v.y, ang, p.fout() * 7f + 0.5f); }); } }), shootPayloadDriver = new Effect(30f, e -> { color(Pal.accent); Lines.stroke(0.5f + 0.5f*e.fout()); float spread = 9f; rand.setSeed(e.id); for(int i = 0; i < 20; i++){ float ang = e.rotation + rand.range(17f); v.trns(ang, rand.random(e.fin() * 55f)); Lines.lineAngle(e.x + v.x + rand.range(spread), e.y + v.y + rand.range(spread), ang, e.fout() * 5f * rand.random(1f) + 1f); } }), shootSmallFlame = new Effect(32f, 80f, e -> { color(Pal.lightFlame, Pal.darkFlame, Color.gray, e.fin()); randLenVectors(e.id, 8, e.finpow() * 60f, e.rotation, 10f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.65f + e.fout() * 1.5f); }); }), shootPyraFlame = new Effect(33f, 80f, e -> { color(Pal.lightPyraFlame, Pal.darkPyraFlame, Color.gray, e.fin()); randLenVectors(e.id, 10, e.finpow() * 70f, e.rotation, 10f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.65f + e.fout() * 1.6f); }); }), shootLiquid = new Effect(15f, 80f, e -> { color(e.color); randLenVectors(e.id, 2, e.finpow() * 15f, e.rotation, 11f, (x, y) -> { Fill.circle(e.x + x, e.y + y, 0.5f + e.fout() * 2.5f); }); }), casing1 = new Effect(30f, e -> { color(Pal.lightOrange, Color.lightGray, Pal.lightishGray, e.fin()); alpha(e.fout(0.3f)); float rot = Math.abs(e.rotation) + 90f; int i = -Mathf.sign(e.rotation); float len = (2f + e.finpow() * 6f) * i; float lr = rot + e.fin() * 30f * i; Fill.rect( e.x + trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()), e.y + trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()), 1f, 2f, rot + e.fin() * 50f * i ); }).layer(Layer.bullet), casing2 = new Effect(34f, e -> { color(Pal.lightOrange, Color.lightGray, Pal.lightishGray, e.fin()); alpha(e.fout(0.5f)); float rot = Math.abs(e.rotation) + 90f; int i = -Mathf.sign(e.rotation); float len = (2f + e.finpow() * 10f) * i; float lr = rot + e.fin() * 20f * i; rect(Core.atlas.find("casing"), e.x + trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()), e.y + trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()), 2f, 3f, rot + e.fin() * 50f * i ); }).layer(Layer.bullet), casing3 = new Effect(40f, e -> { color(Pal.lightOrange, Pal.lightishGray, Pal.lightishGray, e.fin()); alpha(e.fout(0.5f)); float rot = Math.abs(e.rotation) + 90f; int i = -Mathf.sign(e.rotation); float len = (4f + e.finpow() * 9f) * i; float lr = rot + Mathf.randomSeedRange(e.id + i + 6, 20f * e.fin()) * i; rect(Core.atlas.find("casing"), e.x + trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()), e.y + trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()), 2.5f, 4f, rot + e.fin() * 50f * i ); }).layer(Layer.bullet), casing4 = new Effect(45f, e -> { color(Pal.lightOrange, Pal.lightishGray, Pal.lightishGray, e.fin()); alpha(e.fout(0.5f)); float rot = Math.abs(e.rotation) + 90f; int i = -Mathf.sign(e.rotation); float len = (4f + e.finpow() * 9f) * i; float lr = rot + Mathf.randomSeedRange(e.id + i + 6, 20f * e.fin()) * i; rect(Core.atlas.find("casing"), e.x + trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()), e.y + trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()), 3f, 6f, rot + e.fin() * 50f * i ); }).layer(Layer.bullet), casing2Double = new Effect(34f, e -> { color(Pal.lightOrange, Color.lightGray, Pal.lightishGray, e.fin()); alpha(e.fout(0.5f)); float rot = Math.abs(e.rotation) + 90f; for(int i : Mathf.signs){ float len = (2f + e.finpow() * 10f) * i; float lr = rot + e.fin() * 20f * i; rect(Core.atlas.find("casing"), e.x + trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()), e.y + trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()), 2f, 3f, rot + e.fin() * 50f * i ); } }).layer(Layer.bullet), casing3Double = new Effect(40f, e -> { color(Pal.lightOrange, Pal.lightishGray, Pal.lightishGray, e.fin()); alpha(e.fout(0.5f)); float rot = Math.abs(e.rotation) + 90f; for(int i : Mathf.signs){ float len = (4f + e.finpow() * 9f) * i; float lr = rot + Mathf.randomSeedRange(e.id + i + 6, 20f * e.fin()) * i; rect(Core.atlas.find("casing"), e.x + trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()), e.y + trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()), 2.5f, 4f, rot + e.fin() * 50f * i ); } }).layer(Layer.bullet), railShoot = new Effect(24f, e -> { e.scaled(10f, b -> { color(Color.white, Color.lightGray, b.fin()); stroke(b.fout() * 3f + 0.2f); Lines.circle(b.x, b.y, b.fin() * 50f); }); color(Pal.orangeSpark); for(int i : Mathf.signs){ Drawf.tri(e.x, e.y, 13f * e.fout(), 85f, e.rotation + 90f * i); } }), railTrail = new Effect(16f, e -> { color(Pal.orangeSpark); for(int i : Mathf.signs){ Drawf.tri(e.x, e.y, 10f * e.fout(), 24f, e.rotation + 90 + 90f * i); } Drawf.light(e.x, e.y, 60f * e.fout(), Pal.orangeSpark, 0.5f); }), railHit = new Effect(18f, 200f, e -> { color(Pal.orangeSpark); for(int i : Mathf.signs){ Drawf.tri(e.x, e.y, 10f * e.fout(), 60f, e.rotation + 140f * i); } }), lancerLaserShoot = new Effect(21f, e -> { color(Pal.lancerLaser); for(int i : Mathf.signs){ Drawf.tri(e.x, e.y, 4f * e.fout(), 29f, e.rotation + 90f * i); } }), lancerLaserShootSmoke = new Effect(26f, e -> { color(Color.white); float length = !(e.data instanceof Float) ? 70f : (Float)e.data; randLenVectors(e.id, 7, length, e.rotation, 0f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fout() * 9f); }); }), lancerLaserCharge = new Effect(38f, e -> { color(Pal.lancerLaser); randLenVectors(e.id, 14, 1f + 20f * e.fout(), e.rotation, 120f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 3f + 1f); }); }), lancerLaserChargeBegin = new Effect(60f, e -> { float margin = 1f - Mathf.curve(e.fin(), 0.9f); float fin = Math.min(margin, e.fin()); color(Pal.lancerLaser); Fill.circle(e.x, e.y, fin * 3f); color(); Fill.circle(e.x, e.y, fin * 2f); }), lightningCharge = new Effect(38f, e -> { color(Pal.lancerLaser); randLenVectors(e.id, 2, 1f + 20f * e.fout(), e.rotation, 120f, (x, y) -> { Drawf.tri(e.x + x, e.y + y, e.fslope() * 3f + 1, e.fslope() * 3f + 1, Mathf.angle(x, y)); }); }), sparkShoot = new Effect(12f, e -> { color(Color.white, e.color, e.fin()); stroke(e.fout() * 1.2f + 0.6f); randLenVectors(e.id, 7, 25f * e.finpow(), e.rotation, 3f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 5f + 0.5f); }); }), lightningShoot = new Effect(12f, e -> { color(Color.white, Pal.lancerLaser, e.fin()); stroke(e.fout() * 1.2f + 0.5f); randLenVectors(e.id, 7, 25f * e.finpow(), e.rotation, 50f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fin() * 5f + 2f); }); }), thoriumShoot = new Effect(12f, e -> { color(Color.white, Pal.thoriumPink, e.fin()); stroke(e.fout() * 1.2f + 0.5f); randLenVectors(e.id, 7, 25f * e.finpow(), e.rotation, 50f, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fin() * 5f + 2f); }); }), reactorsmoke = new Effect(17, e -> { randLenVectors(e.id, 4, e.fin() * 8f, (x, y) -> { float size = 1f + e.fout() * 5f; color(Color.lightGray, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, size/2f); }); }), redgeneratespark = new Effect(90, e -> { color(Pal.redSpark); alpha(e.fslope()); rand.setSeed(e.id); for(int i = 0; i < 2; i++){ v.trns(rand.random(360f), rand.random(e.finpow() * 9f)).add(e.x, e.y); Fill.circle(v.x, v.y, rand.random(1.4f, 2.4f)); } }).layer(Layer.bullet - 1f), turbinegenerate = new Effect(100, e -> { color(Pal.vent); alpha(e.fslope() * 0.8f); rand.setSeed(e.id); for(int i = 0; i < 3; i++){ v.trns(rand.random(360f), rand.random(e.finpow() * 14f)).add(e.x, e.y); Fill.circle(v.x, v.y, rand.random(1.4f, 3.4f)); } }).layer(Layer.bullet - 1f), generatespark = new Effect(18, e -> { randLenVectors(e.id, 5, e.fin() * 8f, (x, y) -> { color(Pal.orangeSpark, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, e.fout() * 4f /2f); }); }), fuelburn = new Effect(23, e -> { randLenVectors(e.id, 5, e.fin() * 9f, (x, y) -> { color(Color.lightGray, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, e.fout() * 2f); }); }), incinerateSlag = new Effect(34, e -> { randLenVectors(e.id, 4, e.finpow() * 5f, (x, y) -> { color(Pal.slagOrange, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, e.fout() * 1.7f); }); }), coreBurn = new Effect(23, e -> { randLenVectors(e.id, 5, e.fin() * 9f, (x, y) -> { float len = e.fout() * 4f; color(Pal.accent, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, len/2f); }); }), plasticburn = new Effect(40, e -> { randLenVectors(e.id, 5, 3f + e.fin() * 5f, (x, y) -> { color(Pal.plasticBurn, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, e.fout()); }); }), conveyorPoof = new Effect(35, e -> { color(Pal.plasticBurn, Color.gray, e.fin()); randLenVectors(e.id, 4, 3f + e.fin() * 4f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() * 1.11f); }); }), pulverize = new Effect(40, e -> { randLenVectors(e.id, 5, 3f + e.fin() * 8f, (x, y) -> { color(Pal.stoneGray); Fill.square(e.x + x, e.y + y, e.fout() * 2f + 0.5f, 45); }); }), pulverizeRed = new Effect(40, e -> { randLenVectors(e.id, 5, 3f + e.fin() * 8f, (x, y) -> { color(Pal.redDust, Pal.stoneGray, e.fin()); Fill.square(e.x + x, e.y + y, e.fout() * 2f + 0.5f, 45); }); }), pulverizeSmall = new Effect(30, e -> { randLenVectors(e.id, 3, e.fin() * 5f, (x, y) -> { color(Pal.stoneGray); Fill.square(e.x + x, e.y + y, e.fout() + 0.5f, 45); }); }), pulverizeMedium = new Effect(30, e -> { randLenVectors(e.id, 5, 3f + e.fin() * 8f, (x, y) -> { color(Pal.stoneGray); Fill.square(e.x + x, e.y + y, e.fout() + 0.5f, 45); }); }), producesmoke = new Effect(12, e -> { randLenVectors(e.id, 8, 4f + e.fin() * 18f, (x, y) -> { color(Color.white, Pal.accent, e.fin()); Fill.square(e.x + x, e.y + y, 1f + e.fout() * 3f, 45); }); }), artilleryTrailSmoke = new Effect(50, e -> { color(e.color); rand.setSeed(e.id); for(int i = 0; i < 13; i++){ float fin = e.fin() / rand.random(0.5f, 1f), fout = 1f - fin, angle = rand.random(360f), len = rand.random(0.5f, 1f); if(fin <= 1f){ Tmp.v1.trns(angle, fin * 24f * len); alpha((0.5f - Math.abs(fin - 0.5f)) * 2f); Fill.circle(e.x + Tmp.v1.x, e.y + Tmp.v1.y, 0.5f + fout * 4f); } } }), smokeCloud = new Effect(70, e -> { randLenVectors(e.id, e.fin(), 30, 30f, (x, y, fin, fout) -> { color(Color.gray); alpha((0.5f - Math.abs(fin - 0.5f)) * 2f); Fill.circle(e.x + x, e.y + y, 0.5f + fout * 4f); }); }), smeltsmoke = new Effect(15, e -> { randLenVectors(e.id, 6, 4f + e.fin() * 5f, (x, y) -> { color(Color.white, e.color, e.fin()); Fill.square(e.x + x, e.y + y, 0.5f + e.fout() * 2f, 45); }); }), coalSmeltsmoke = new Effect(40f, e -> { randLenVectors(e.id, 0.2f + e.fin(), 4, 6.3f, (x, y, fin, out) -> { color(Color.darkGray, Pal.coalBlack, e.finpowdown()); Fill.circle(e.x + x, e.y + y, out * 2f + 0.35f); }); }), formsmoke = new Effect(40, e -> { randLenVectors(e.id, 6, 5f + e.fin() * 8f, (x, y) -> { color(Pal.plasticSmoke, Color.lightGray, e.fin()); Fill.square(e.x + x, e.y + y, 0.2f + e.fout() * 2f, 45); }); }), blastsmoke = new Effect(26, e -> { randLenVectors(e.id, 12, 1f + e.fin() * 23f, (x, y) -> { float size = 2f + e.fout() * 6f; color(Color.lightGray, Color.darkGray, e.fin()); Fill.circle(e.x + x, e.y + y, size/2f); }); }), lava = new Effect(18, e -> { randLenVectors(e.id, 3, 1f + e.fin() * 10f, (x, y) -> { float size = e.fslope() * 4f; color(Color.orange, Color.gray, e.fin()); Fill.circle(e.x + x, e.y + y, size/2f); }); }), dooropen = new Effect(10, e -> { stroke(e.fout() * 1.6f); Lines.square(e.x, e.y, e.rotation * tilesize / 2f + e.fin() * 2f); }), doorclose = new Effect(10, e -> { stroke(e.fout() * 1.6f); Lines.square(e.x, e.y, e.rotation * tilesize / 2f + e.fout() * 2f); }), dooropenlarge = new Effect(10, e -> { stroke(e.fout() * 1.6f); Lines.square(e.x, e.y, tilesize + e.fin() * 2f); }), doorcloselarge = new Effect(10, e -> { stroke(e.fout() * 1.6f); Lines.square(e.x, e.y, tilesize + e.fout() * 2f); }), generate = new Effect(11, e -> { color(Color.orange, Color.yellow, e.fin()); stroke(1f); Lines.spikes(e.x, e.y, e.fin() * 5f, 2, 8); }), mineWallSmall = new Effect(50, e -> { color(e.color, Color.darkGray, e.fin()); randLenVectors(e.id, 2, e.fin() * 6f, (x, y) -> { Fill.circle(e.x + x, e.y + y, e.fout() + 0.5f); }); }), mineSmall = new Effect(30, e -> { color(e.color, Color.lightGray, e.fin()); randLenVectors(e.id, 3, e.fin() * 5f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() + 0.5f, 45); }); }), mine = new Effect(20, e -> { color(e.color, Color.lightGray, e.fin()); randLenVectors(e.id, 6, 3f + e.fin() * 6f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() * 2f, 45); }); }), mineBig = new Effect(30, e -> { color(e.color, Color.lightGray, e.fin()); randLenVectors(e.id, 6, 4f + e.fin() * 8f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() * 2f + 0.2f, 45); }); }), mineHuge = new Effect(40, e -> { color(e.color, Color.lightGray, e.fin()); randLenVectors(e.id, 8, 5f + e.fin() * 10f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() * 2f + 0.5f, 45); }); }), mineImpact = new Effect(90, e -> { color(e.color, Color.lightGray, e.fin()); randLenVectors(e.id, 12, 5f + e.finpow() * 22f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() * 2.5f + 0.5f, 45); }); }), mineImpactWave = new Effect(50f, e -> { color(e.color); stroke(e.fout() * 1.5f); randLenVectors(e.id, 12, 4f + e.finpow() * e.rotation, (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fout() * 5 + 1f); }); e.scaled(30f, b -> { Lines.stroke(5f * b.fout()); Lines.circle(e.x, e.y, b.finpow() * 28f); }); }), payloadReceive = new Effect(30, e -> { color(Color.white, Pal.accent, e.fin()); randLenVectors(e.id, 12, 7f + e.fin() * 13f, (x, y) -> { Fill.square(e.x + x, e.y + y, e.fout() * 2.1f + 0.5f, 45); }); }), teleportActivate = new Effect(50, e -> { color(e.color); e.scaled(8f, e2 -> { stroke(e2.fout() * 4f); Lines.circle(e2.x, e2.y, 4f + e2.fin() * 27f); }); stroke(e.fout() * 2f); randLenVectors(e.id, 30, 4f + 40f * e.fin(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fin() * 4f + 1f); }); }), teleport = new Effect(60, e -> { color(e.color); stroke(e.fin() * 2f); Lines.circle(e.x, e.y, 7f + e.fout() * 8f); randLenVectors(e.id, 20, 6f + 20f * e.fout(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fin() * 4f + 1f); }); }), teleportOut = new Effect(20, e -> { color(e.color); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 7f + e.fin() * 8f); randLenVectors(e.id, 20, 4f + 20f * e.fin(), (x, y) -> { lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), e.fslope() * 4f + 1f); }); }), ripple = new Effect(30, e -> { e.lifetime = 30f*e.rotation; color(Tmp.c1.set(e.color).mul(1.5f)); stroke(e.fout() * 1.4f); Lines.circle(e.x, e.y, (2f + e.fin() * 4f) * e.rotation); }).layer(Layer.debris), bubble = new Effect(20, e -> { color(Tmp.c1.set(e.color).shiftValue(0.1f)); stroke(e.fout() + 0.2f); randLenVectors(e.id, 2, e.rotation * 0.9f, (x, y) -> { Lines.circle(e.x + x, e.y + y, 1f + e.fin() * 3f); }); }), launch = new Effect(28, e -> { color(Pal.command); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, 4f + e.finpow() * 120f); }), launchPod = new Effect(50, e -> { color(Pal.engine); e.scaled(25f, f -> { stroke(f.fout() * 2f); Lines.circle(e.x, e.y, 4f + f.finpow() * 30f); }); stroke(e.fout() * 2f); randLenVectors(e.id, 24, e.finpow() * 50f, (x, y) -> { float ang = Mathf.angle(x, y); lineAngle(e.x + x, e.y + y, ang, e.fout() * 4 + 1f); }); }), healWaveMend = new Effect(40, e -> { color(e.color); stroke(e.fout() * 2f); Lines.circle(e.x, e.y, e.finpow() * e.rotation); }), overdriveWave = new Effect(50, e -> { color(e.color); stroke(e.fout()); Lines.circle(e.x, e.y, e.finpow() * e.rotation); }), healBlock = new Effect(20, e -> { color(Pal.heal); stroke(2f * e.fout() + 0.5f); Lines.square(e.x, e.y, 1f + (e.fin() * e.rotation * tilesize / 2f - 1f)); }), healBlockFull = new Effect(20, e -> { if(!(e.data instanceof Block block)) return; mixcol(e.color, 1f); alpha(e.fout()); Draw.rect(block.fullIcon, e.x, e.y); }), rotateBlock = new Effect(30, e -> { color(Pal.accent); alpha(e.fout() * 1); Fill.square(e.x, e.y, e.rotation * tilesize / 2f); }), lightBlock = new Effect(60, e -> { color(e.color); alpha(e.fout() * 1); Fill.square(e.x, e.y, e.rotation * tilesize / 2f); }), overdriveBlockFull = new Effect(60, e -> { color(e.color); alpha(e.fslope() * 0.4f); Fill.square(e.x, e.y, e.rotation * tilesize); }), shieldBreak = new Effect(40, e -> { color(e.color); stroke(3f * e.fout()); if(e.data instanceof ForceFieldAbility ab){ Lines.poly(e.x, e.y, ab.sides, e.rotation + e.fin(), ab.rotation); return; } Lines.poly(e.x, e.y, 6, e.rotation + e.fin()); }).followParent(true), arcShieldBreak = new Effect(40, e -> { Lines.stroke(3 * e.fout(), e.color); if(e.data instanceof Unit u){ ShieldArcAbility ab = (ShieldArcAbility) Structs.find(u.abilities, a -> a instanceof ShieldArcAbility); if(ab != null){ Vec2 pos = Tmp.v1.set(ab.x, ab.y).rotate(u.rotation - 90f).add(u); Lines.arc(pos.x, pos.y, ab.radius + ab.width/2, ab.angle / 360f, u.rotation + ab.angleOffset - ab.angle / 2f); Lines.arc(pos.x, pos.y, ab.radius - ab.width/2, ab.angle / 360f, u.rotation + ab.angleOffset - ab.angle / 2f); for(int i : Mathf.signs){ float px = pos.x + Angles.trnsx(u.rotation + ab.angleOffset - ab.angle / 2f * i, ab.radius + ab.width / 2), py = pos.y + Angles.trnsy(u.rotation + ab.angleOffset - ab.angle / 2f * i, ab.radius + ab.width / 2), px1 = pos.x + Angles.trnsx(u.rotation + ab.angleOffset - ab.angle / 2f * i, ab.radius - ab.width / 2), py1 = pos.y + Angles.trnsy(u.rotation + ab.angleOffset - ab.angle / 2f * i, ab.radius - ab.width / 2); Lines.line(px, py, px1, py1); } } } }).followParent(true), coreLandDust = new Effect(100f, e -> { color(e.color, e.fout(0.1f)); rand.setSeed(e.id); Tmp.v1.trns(e.rotation, e.finpow() * 90f * rand.random(0.2f, 1f)); Fill.circle(e.x + Tmp.v1.x, e.y + Tmp.v1.y, 8f * rand.random(0.6f, 1f) * e.fout(0.2f)); }).layer(Layer.groundUnit + 1f), unitShieldBreak = new Effect(35, e -> { if(!(e.data instanceof Unit unit)) return; float radius = unit.hitSize() * 1.3f; e.scaled(16f, c -> { color(e.color, 0.9f); stroke(c.fout() * 2f + 0.1f); randLenVectors(e.id, (int)(radius * 1.2f), radius/2f + c.finpow() * radius*1.25f, (x, y) -> { lineAngle(c.x + x, c.y + y, Mathf.angle(x, y), c.fout() * 5 + 1f); }); }); color(e.color, e.fout() * 0.9f); stroke(e.fout()); Lines.circle(e.x, e.y, radius); }), chainLightning = new Effect(20f, 300f, e -> { if(!(e.data instanceof Position p)) return; float tx = p.getX(), ty = p.getY(), dst = Mathf.dst(e.x, e.y, tx, ty); Tmp.v1.set(p).sub(e.x, e.y).nor(); float normx = Tmp.v1.x, normy = Tmp.v1.y; float range = 6f; int links = Mathf.ceil(dst / range); float spacing = dst / links; Lines.stroke(2.5f * e.fout()); Draw.color(Color.white, e.color, e.fin()); Lines.beginLine(); Lines.linePoint(e.x, e.y); rand.setSeed(e.id); for(int i = 0; i < links; i++){ float nx, ny; if(i == links - 1){ nx = tx; ny = ty; }else{ float len = (i + 1) * spacing; Tmp.v1.setToRandomDirection(rand).scl(range/2f); nx = e.x + normx * len + Tmp.v1.x; ny = e.y + normy * len + Tmp.v1.y; } Lines.linePoint(nx, ny); } Lines.endLine(); }).followParent(false).rotWithParent(false), chainEmp = new Effect(30f, 300f, e -> { if(!(e.data instanceof Position p)) return; float tx = p.getX(), ty = p.getY(), dst = Mathf.dst(e.x, e.y, tx, ty); Tmp.v1.set(p).sub(e.x, e.y).nor(); float normx = Tmp.v1.x, normy = Tmp.v1.y; float range = 6f; int links = Mathf.ceil(dst / range); float spacing = dst / links; Lines.stroke(4f * e.fout()); Draw.color(Color.white, e.color, e.fin()); Lines.beginLine(); Lines.linePoint(e.x, e.y); rand.setSeed(e.id); for(int i = 0; i < links; i++){ float nx, ny; if(i == links - 1){ nx = tx; ny = ty; }else{ float len = (i + 1) * spacing; Tmp.v1.setToRandomDirection(rand).scl(range/2f); nx = e.x + normx * len + Tmp.v1.x; ny = e.y + normy * len + Tmp.v1.y; } Lines.linePoint(nx, ny); } Lines.endLine(); }).followParent(false).rotWithParent(false), legDestroy = new Effect(90f, 100f, e -> { if(!(e.data instanceof LegDestroyData data)) return; rand.setSeed(e.id); e.lifetime = rand.random(70f, 130f); Tmp.v1.trns(rand.random(360f), rand.random(data.region.width / 8f) * e.finpow()); float ox = Tmp.v1.x, oy = Tmp.v1.y; alpha(e.foutpowdown()); stroke(data.region.height * scl); line(data.region, data.a.x + ox, data.a.y + oy, data.b.x + ox, data.b.y + oy, false); }).layer(Layer.groundUnit + 5f), debugLine = new Effect(90f, 1000000000000f, e -> { if(!(e.data instanceof Vec2[] vec)) return; Draw.color(e.color); Lines.stroke(2f); if(vec.length == 2){ Lines.line(vec[0].x, vec[0].y, vec[1].x, vec[1].y); }else{ Lines.beginLine(); for(Vec2 v : vec) Lines.linePoint(v.x, v.y); Lines.endLine(); } Draw.reset(); }), debugRect = new Effect(90f, 1000000000000f, e -> { if(!(e.data instanceof Rect rect)) return; Draw.color(e.color); Lines.stroke(2f); Lines.rect(rect); Draw.reset(); }); }
Anuken/Mindustry
core/src/mindustry/content/Fx.java
7
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import static android.os.Build.VERSION.SDK_INT; import java.util.concurrent.Executor; import javax.annotation.Nullable; final class Platform { static final @Nullable Executor callbackExecutor; static final Reflection reflection; static final BuiltInFactories builtInFactories; static { switch (System.getProperty("java.vm.name")) { case "Dalvik": callbackExecutor = new AndroidMainExecutor(); if (SDK_INT >= 24) { reflection = new Reflection.Android24(); builtInFactories = new BuiltInFactories.Java8(); } else { reflection = new Reflection(); builtInFactories = new BuiltInFactories(); } break; case "RoboVM": callbackExecutor = null; reflection = new Reflection(); builtInFactories = new BuiltInFactories(); break; default: callbackExecutor = null; reflection = new Reflection.Java8(); builtInFactories = new BuiltInFactories.Java8(); break; } } private Platform() {} }
square/retrofit
retrofit/src/main/java/retrofit2/Platform.java
8
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import org.slf4j.LoggerFactory; /** * Created by Alexis on 28-Apr-17. With Marker interface idea is to make empty interface and extend * it. Basically it is just to identify the special objects from normal objects. Like in case of * serialization , objects that need to be serialized must implement serializable interface (it is * empty interface) and down the line writeObject() method must be checking if it is an instance of * serializable or not. * * <p>Marker interface vs annotation Marker interfaces and marker annotations both have their uses, * neither of them is obsolete or always better than the other one. If you want to define a type * that does not have any new methods associated with it, a marker interface is the way to go. If * you want to mark program elements other than classes and interfaces, to allow for the possibility * of adding more information to the marker in the future, or to fit the marker into a framework * that already makes heavy use of annotation types, then a marker annotation is the correct choice */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { final var logger = LoggerFactory.getLogger(App.class); var guard = new Guard(); var thief = new Thief(); //noinspection ConstantConditions if (guard instanceof Permission) { guard.enter(); } else { logger.info("You have no permission to enter, please leave this area"); } //noinspection ConstantConditions if (thief instanceof Permission) { thief.steal(); } else { thief.doNothing(); } } }
iluwatar/java-design-patterns
marker/src/main/java/App.java
9
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow; import java.util.ArrayList; import java.util.List; /** * Driver for {@link Graph} execution. * * <p>A {@code Session} instance encapsulates the environment in which {@link Operation}s in a * {@link Graph} are executed to compute {@link Tensor Tensors}. For example: * * <pre>{@code * // Let's say graph is an instance of the Graph class * // for the computation y = 3 * x * * try (Session s = new Session(graph)) { * try (Tensor x = Tensor.create(2.0f); * Tensor y = s.runner().feed("x", x).fetch("y").run().get(0)) { * System.out.println(y.floatValue()); // Will print 6.0f * } * try (Tensor x = Tensor.create(1.1f); * Tensor y = s.runner().feed("x", x).fetch("y").run().get(0)) { * System.out.println(y.floatValue()); // Will print 3.3f * } * } * }</pre> * * <p><b>WARNING:</b>A {@code Session} owns resources that <b>must</b> be explicitly freed by * invoking {@link #close()}. * * <p>Instances of a Session are thread-safe. */ public final class Session implements AutoCloseable { /** Construct a new session with the associated {@link Graph}. */ public Session(Graph g) { this(g, null); } /** * Construct a new session with the associated {@link Graph} and configuration options. * * @param g The {@link Graph} the created Session will operate on. * @param config Configuration parameters for the session specified as a serialized <a * href="https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto">ConfigProto</a> * protocol buffer. * @throws IllegalArgumentException if the config is not a valid serialization of the ConfigProto * protocol buffer. */ public Session(Graph g, byte[] config) { graph = g; Graph.Reference r = g.ref(); try { nativeHandle = (config == null) ? allocate(r.nativeHandle()) : allocate2(r.nativeHandle(), null, config); graphRef = g.ref(); } finally { r.close(); } } /** Wrap an existing session with the associated {@link Graph}. */ Session(Graph g, long nativeHandle) { graph = g; this.nativeHandle = nativeHandle; graphRef = g.ref(); } /** * Release resources associated with the Session. * * <p>Blocks until there are no active executions ({@link Session.Runner#run()} calls). A Session * is not usable after close returns. */ @Override public void close() { graphRef.close(); synchronized (nativeHandleLock) { if (nativeHandle == 0) { return; } while (numActiveRuns > 0) { try { nativeHandleLock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Possible leak of the Session and Graph in this case? return; } } delete(nativeHandle); nativeHandle = 0; } } /** * Run {@link Operation}s and evaluate {@link Tensor Tensors}. * * <p>A Runner runs the necessary graph fragments to execute every {@link Operation} required to * evaluate the {@link Tensor Tensors} to fetch. The {@link #feed(String,int,Tensor)} call allows * callers to override the value of {@link Tensor Tensors} in the graph by substituting the * provided {@link Tensor Tensors} for the outputs of the operations provided to {@link * #feed(String,int,Tensor)}. */ public final class Runner { /** * Avoid evaluating {@code operation} and substitute {@code t} for the value it produces. * * @param operation Is either the string name of the operation, in which case this method is a * shorthand for {@code feed(operation, 0)}, or it is a string of the form * <tt>operation_name:output_index</tt> , in which case this method acts like {@code * feed(operation_name, output_index)}. These colon-separated names are commonly used in the * {@code SignatureDef} protocol buffer messages that are included in {@link * SavedModelBundle#metaGraphDef()}. */ public Runner feed(String operation, Tensor<?> t) { return feed(parseOutput(operation), t); } /** * Avoid evaluating the {@code index}-th output of {@code operation} by substituting {@code t} * for the value it produces. * * <p>Operations in a {@link Graph} can have multiple outputs, {@code index} identifies which * one {@code t} is being provided for. */ public Runner feed(String operation, int index, Tensor<?> t) { Operation op = operationByName(operation); if (op != null) { inputs.add(op.output(index)); inputTensors.add(t); } return this; } /** * Use {@code t} instead of the Tensor referred to by executing the operation referred to by * {@code operand}. */ public Runner feed(Operand<?> operand, Tensor<?> t) { inputs.add(operand.asOutput()); inputTensors.add(t); return this; } /** * Make {@link #run()} return the output of {@code operation}. * * @param operation Is either the string name of the operation, in which case this method is a * shorthand for {@code fetch(operation, 0)}, or it is a string of the form * <tt>operation_name:output_index</tt> , in which case this method acts like {@code * fetch(operation_name, output_index)}. These colon-separated names are commonly used in * the {@code SignatureDef} protocol buffer messages that are included in {@link * SavedModelBundle#metaGraphDef()}. */ public Runner fetch(String operation) { return fetch(parseOutput(operation)); } /** * Make {@link #run()} return the {@code index}-th output of {@code operation}. * * <p>Operations in a {@link Graph} can have multiple outputs, {@code index} identifies which * one to return. */ public Runner fetch(String operation, int index) { Operation op = operationByName(operation); if (op != null) { outputs.add(op.output(index)); } return this; } /** * Makes {@link #run()} return the Tensor referred to by {@code output}. */ public Runner fetch(Output<?> output) { outputs.add(output); return this; } /** * Makes {@link #run()} return the Tensor referred to by the output of {@code operand}. */ public Runner fetch(Operand<?> operand) { return fetch(operand.asOutput()); } /** * Make {@link #run()} execute {@code operation}, but not return any evaluated {@link Tensor * Tensors}. */ public Runner addTarget(String operation) { GraphOperation op = operationByName(operation); if (op != null) { targets.add(op); } return this; } /** * Make {@link #run()} execute {@code operation}, but not return any evaluated {@link Tensor * Tensors}. * * @throws IllegalArgumentException if the operation is not a {@link GraphOperation} */ public Runner addTarget(Operation operation) { if (!(operation instanceof GraphOperation)) { throw new IllegalArgumentException( "Operation of type " + operation.getClass().getName() + " is not supported in graph sessions"); } targets.add((GraphOperation) operation); return this; } /** * Make {@link #run} execute {@code operand}, but not return any evaluated {@link Tensor * Tensors}. */ public Runner addTarget(Operand<?> operand) { return addTarget(operand.asOutput().op()); } /** * (Experimental method): set options (typically for debugging) for this run. * * <p>The options are presented as a serialized <a * href="https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto">RunOptions * protocol buffer</a>. * * <p>The org.tensorflow package is free of any protocol buffer dependencies in order to remain * friendly to resource constrained systems (where something like <a * href="https://github.com/google/protobuf/tree/master/javanano#nano-version">nanoproto</a> may * be more appropriate). A cost of that is this lack of type-safety in this API function. This * choice is under review and this function may be replaced by more type-safe equivalents at any * time. */ public Runner setOptions(byte[] options) { this.runOptions = options; return this; } /** * Execute the graph fragments necessary to compute all requested fetches. * * <p><b>WARNING:</b> The caller assumes ownership of all returned {@link Tensor Tensors}, i.e., * the caller must call {@link Tensor#close} on all elements of the returned list to free up * resources. * * <p>TODO(ashankar): Reconsider the return type here. Two things in particular: (a) Make it * easier for the caller to cleanup (perhaps returning something like AutoCloseableList in * SessionTest.java), and (b) Evaluate whether the return value should be a list, or maybe a * {@code Map<Output, Tensor>}? * * <p>TODO(andrewmyers): It would also be good if whatever is returned here made it easier to * extract output tensors in a type-safe way. */ public List<Tensor<?>> run() { return runHelper(false).outputs; } /** * Execute graph fragments to compute requested fetches and return metadata about the run. * * <p>This is exactly like {@link #run()}, but in addition to the requested Tensors, also * returns metadata about the graph execution in the form of a serialized <a * href="https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto">RunMetadata * protocol buffer</a>. */ public Run runAndFetchMetadata() { return runHelper(true); } private Run runHelper(boolean wantMetadata) { long[] inputTensorHandles = new long[inputTensors.size()]; long[] inputOpHandles = new long[inputs.size()]; int[] inputOpIndices = new int[inputs.size()]; long[] outputOpHandles = new long[outputs.size()]; int[] outputOpIndices = new int[outputs.size()]; long[] targetOpHandles = new long[targets.size()]; long[] outputTensorHandles = new long[outputs.size()]; // It's okay to use Operation.getUnsafeNativeHandle() here since the safety depends on the // validity of the Graph and graphRef ensures that. int idx = 0; for (Tensor<?> t : inputTensors) { inputTensorHandles[idx++] = t.getNativeHandle(); } idx = 0; for (Output<?> o : inputs) { inputOpHandles[idx] = o.getUnsafeNativeHandle(); inputOpIndices[idx] = o.index(); idx++; } idx = 0; for (Output<?> o : outputs) { outputOpHandles[idx] = o.getUnsafeNativeHandle(); outputOpIndices[idx] = o.index(); idx++; } idx = 0; for (GraphOperation op : targets) { targetOpHandles[idx++] = op.getUnsafeNativeHandle(); } Reference runRef = new Reference(); byte[] metadata = null; try { metadata = Session.run( nativeHandle, runOptions, inputTensorHandles, inputOpHandles, inputOpIndices, outputOpHandles, outputOpIndices, targetOpHandles, wantMetadata, outputTensorHandles); } finally { runRef.close(); } List<Tensor<?>> outputs = new ArrayList<Tensor<?>>(); for (long h : outputTensorHandles) { try { outputs.add(Tensor.fromHandle(h)); } catch (Exception e) { for (Tensor<?> t : outputs) { t.close(); } outputs.clear(); throw e; } } Run ret = new Run(); ret.outputs = outputs; ret.metadata = metadata; return ret; } private class Reference implements AutoCloseable { public Reference() { synchronized (nativeHandleLock) { if (nativeHandle == 0) { throw new IllegalStateException("run() cannot be called on the Session after close()"); } ++numActiveRuns; } } @Override public void close() { synchronized (nativeHandleLock) { if (nativeHandle == 0) { return; } if (--numActiveRuns == 0) { nativeHandleLock.notifyAll(); } } } } private GraphOperation operationByName(String opName) { GraphOperation op = graph.operation(opName); if (op == null) { throw new IllegalArgumentException("No Operation named [" + opName + "] in the Graph"); } return op; } @SuppressWarnings("rawtypes") private Output<?> parseOutput(String opName) { int colon = opName.lastIndexOf(':'); if (colon == -1 || colon == opName.length() - 1) { return new Output(operationByName(opName), 0); } try { String op = opName.substring(0, colon); int index = Integer.parseInt(opName.substring(colon + 1)); return new Output(operationByName(op), index); } catch (NumberFormatException e) { return new Output(operationByName(opName), 0); } } private ArrayList<Output<?>> inputs = new ArrayList<Output<?>>(); private ArrayList<Tensor<?>> inputTensors = new ArrayList<Tensor<?>>(); private ArrayList<Output<?>> outputs = new ArrayList<Output<?>>(); private ArrayList<GraphOperation> targets = new ArrayList<GraphOperation>(); private byte[] runOptions = null; } /** Create a Runner to execute graph operations and evaluate Tensors. */ public Runner runner() { return new Runner(); } /** * Output tensors and metadata obtained when executing a session. * * <p>See {@link Runner#runAndFetchMetadata()} */ public static final class Run { /** Tensors from requested fetches. */ public List<Tensor<?>> outputs; /** * (Experimental): Metadata about the run. * * <p>A serialized <a * href="https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto">RunMetadata * protocol buffer</a>. The org.tensorflow package is free of any protocol buffer dependencies * in order to remain friendly to resource constrained systems (where something like <a * href="https://github.com/google/protobuf/tree/master/javanano#nano-version">nanoproto</a> may * be more appropriate). A cost of that is this opaque blob. This choice is under review and * this field may be replaced by more type-safe equivalents at any time. */ public byte[] metadata; } private final Graph graph; private final Graph.Reference graphRef; private final Object nativeHandleLock = new Object(); private long nativeHandle; private int numActiveRuns; // TODO(ashankar): Remove after TensorFlow 1.2 has been released with allocate2(). private static native long allocate(long graphHandle); private static native long allocate2(long graphHandle, String target, byte[] config); private static native void delete(long handle); /** * Execute a session. * * <p>The author apologizes for the ugliness of the long argument list of this method. However, * take solace in the fact that this is a private method meant to cross the JNI boundary. * * @param handle to the C API TF_Session object (Session.nativeHandle) * @param runOptions serialized representation of a RunOptions protocol buffer, or null * @param inputOpHandles (see inputOpIndices) * @param inputOpIndices (see inputTensorHandles) * @param inputTensorHandles together with inputOpHandles and inputOpIndices specifies the values * that are being "fed" (do not need to be computed) during graph execution. * inputTensorHandles[i] (which corresponds to a Tensor.nativeHandle) is considered to be the * inputOpIndices[i]-th output of the Operation inputOpHandles[i]. Thus, it is required that * inputOpHandles.length == inputOpIndices.length == inputTensorHandles.length. * @param outputOpHandles (see outputOpIndices) * @param outputOpIndices together with outputOpHandles identifies the set of values that should * be computed. The outputOpIndices[i]-th output of the Operation outputOpHandles[i], It is * required that outputOpHandles.length == outputOpIndices.length. * @param targetOpHandles is the set of Operations in the graph that are to be executed but whose * output will not be returned * @param wantRunMetadata indicates whether metadata about this execution should be returned. * @param outputTensorHandles will be filled in with handles to the outputs requested. It is * required that outputTensorHandles.length == outputOpHandles.length. * @return if wantRunMetadata is true, serialized representation of the RunMetadata protocol * buffer, false otherwise. */ private static native byte[] run( long handle, byte[] runOptions, long[] inputTensorHandles, long[] inputOpHandles, int[] inputOpIndices, long[] outputOpHandles, int[] outputOpIndices, long[] targetOpHandles, boolean wantRunMetadata, long[] outputTensorHandles); }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/Session.java
10
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Computes the neighbour H3 index from a given index. */ final class HexRing { private static final int INVALID_BASE_CELL = 127; /** Neighboring base cell ID in each IJK direction. * * For each base cell, for each direction, the neighboring base * cell ID is given. 127 indicates there is no neighbor in that direction. */ private static final int[][] baseCellNeighbors = new int[][] { { 0, 1, 5, 2, 4, 3, 8 }, // base cell 0 { 1, 7, 6, 9, 0, 3, 2 }, // base cell 1 { 2, 6, 10, 11, 0, 1, 5 }, // base cell 2 { 3, 13, 1, 7, 4, 12, 0 }, // base cell 3 { 4, INVALID_BASE_CELL, 15, 8, 3, 0, 12 }, // base cell 4 (pentagon) { 5, 2, 18, 10, 8, 0, 16 }, // base cell 5 { 6, 14, 11, 17, 1, 9, 2 }, // base cell 6 { 7, 21, 9, 19, 3, 13, 1 }, // base cell 7 { 8, 5, 22, 16, 4, 0, 15 }, // base cell 8 { 9, 19, 14, 20, 1, 7, 6 }, // base cell 9 { 10, 11, 24, 23, 5, 2, 18 }, // base cell 10 { 11, 17, 23, 25, 2, 6, 10 }, // base cell 11 { 12, 28, 13, 26, 4, 15, 3 }, // base cell 12 { 13, 26, 21, 29, 3, 12, 7 }, // base cell 13 { 14, INVALID_BASE_CELL, 17, 27, 9, 20, 6 }, // base cell 14 (pentagon) { 15, 22, 28, 31, 4, 8, 12 }, // base cell 15 { 16, 18, 33, 30, 8, 5, 22 }, // base cell 16 { 17, 11, 14, 6, 35, 25, 27 }, // base cell 17 { 18, 24, 30, 32, 5, 10, 16 }, // base cell 18 { 19, 34, 20, 36, 7, 21, 9 }, // base cell 19 { 20, 14, 19, 9, 40, 27, 36 }, // base cell 20 { 21, 38, 19, 34, 13, 29, 7 }, // base cell 21 { 22, 16, 41, 33, 15, 8, 31 }, // base cell 22 { 23, 24, 11, 10, 39, 37, 25 }, // base cell 23 { 24, INVALID_BASE_CELL, 32, 37, 10, 23, 18 }, // base cell 24 (pentagon) { 25, 23, 17, 11, 45, 39, 35 }, // base cell 25 { 26, 42, 29, 43, 12, 28, 13 }, // base cell 26 { 27, 40, 35, 46, 14, 20, 17 }, // base cell 27 { 28, 31, 42, 44, 12, 15, 26 }, // base cell 28 { 29, 43, 38, 47, 13, 26, 21 }, // base cell 29 { 30, 32, 48, 50, 16, 18, 33 }, // base cell 30 { 31, 41, 44, 53, 15, 22, 28 }, // base cell 31 { 32, 30, 24, 18, 52, 50, 37 }, // base cell 32 { 33, 30, 49, 48, 22, 16, 41 }, // base cell 33 { 34, 19, 38, 21, 54, 36, 51 }, // base cell 34 { 35, 46, 45, 56, 17, 27, 25 }, // base cell 35 { 36, 20, 34, 19, 55, 40, 54 }, // base cell 36 { 37, 39, 52, 57, 24, 23, 32 }, // base cell 37 { 38, INVALID_BASE_CELL, 34, 51, 29, 47, 21 }, // base cell 38 (pentagon) { 39, 37, 25, 23, 59, 57, 45 }, // base cell 39 { 40, 27, 36, 20, 60, 46, 55 }, // base cell 40 { 41, 49, 53, 61, 22, 33, 31 }, // base cell 41 { 42, 58, 43, 62, 28, 44, 26 }, // base cell 42 { 43, 62, 47, 64, 26, 42, 29 }, // base cell 43 { 44, 53, 58, 65, 28, 31, 42 }, // base cell 44 { 45, 39, 35, 25, 63, 59, 56 }, // base cell 45 { 46, 60, 56, 68, 27, 40, 35 }, // base cell 46 { 47, 38, 43, 29, 69, 51, 64 }, // base cell 47 { 48, 49, 30, 33, 67, 66, 50 }, // base cell 48 { 49, INVALID_BASE_CELL, 61, 66, 33, 48, 41 }, // base cell 49 (pentagon) { 50, 48, 32, 30, 70, 67, 52 }, // base cell 50 { 51, 69, 54, 71, 38, 47, 34 }, // base cell 51 { 52, 57, 70, 74, 32, 37, 50 }, // base cell 52 { 53, 61, 65, 75, 31, 41, 44 }, // base cell 53 { 54, 71, 55, 73, 34, 51, 36 }, // base cell 54 { 55, 40, 54, 36, 72, 60, 73 }, // base cell 55 { 56, 68, 63, 77, 35, 46, 45 }, // base cell 56 { 57, 59, 74, 78, 37, 39, 52 }, // base cell 57 { 58, INVALID_BASE_CELL, 62, 76, 44, 65, 42 }, // base cell 58 (pentagon) { 59, 63, 78, 79, 39, 45, 57 }, // base cell 59 { 60, 72, 68, 80, 40, 55, 46 }, // base cell 60 { 61, 53, 49, 41, 81, 75, 66 }, // base cell 61 { 62, 43, 58, 42, 82, 64, 76 }, // base cell 62 { 63, INVALID_BASE_CELL, 56, 45, 79, 59, 77 }, // base cell 63 (pentagon) { 64, 47, 62, 43, 84, 69, 82 }, // base cell 64 { 65, 58, 53, 44, 86, 76, 75 }, // base cell 65 { 66, 67, 81, 85, 49, 48, 61 }, // base cell 66 { 67, 66, 50, 48, 87, 85, 70 }, // base cell 67 { 68, 56, 60, 46, 90, 77, 80 }, // base cell 68 { 69, 51, 64, 47, 89, 71, 84 }, // base cell 69 { 70, 67, 52, 50, 83, 87, 74 }, // base cell 70 { 71, 89, 73, 91, 51, 69, 54 }, // base cell 71 { 72, INVALID_BASE_CELL, 73, 55, 80, 60, 88 }, // base cell 72 (pentagon) { 73, 91, 72, 88, 54, 71, 55 }, // base cell 73 { 74, 78, 83, 92, 52, 57, 70 }, // base cell 74 { 75, 65, 61, 53, 94, 86, 81 }, // base cell 75 { 76, 86, 82, 96, 58, 65, 62 }, // base cell 76 { 77, 63, 68, 56, 93, 79, 90 }, // base cell 77 { 78, 74, 59, 57, 95, 92, 79 }, // base cell 78 { 79, 78, 63, 59, 93, 95, 77 }, // base cell 79 { 80, 68, 72, 60, 99, 90, 88 }, // base cell 80 { 81, 85, 94, 101, 61, 66, 75 }, // base cell 81 { 82, 96, 84, 98, 62, 76, 64 }, // base cell 82 { 83, INVALID_BASE_CELL, 74, 70, 100, 87, 92 }, // base cell 83 (pentagon) { 84, 69, 82, 64, 97, 89, 98 }, // base cell 84 { 85, 87, 101, 102, 66, 67, 81 }, // base cell 85 { 86, 76, 75, 65, 104, 96, 94 }, // base cell 86 { 87, 83, 102, 100, 67, 70, 85 }, // base cell 87 { 88, 72, 91, 73, 99, 80, 105 }, // base cell 88 { 89, 97, 91, 103, 69, 84, 71 }, // base cell 89 { 90, 77, 80, 68, 106, 93, 99 }, // base cell 90 { 91, 73, 89, 71, 105, 88, 103 }, // base cell 91 { 92, 83, 78, 74, 108, 100, 95 }, // base cell 92 { 93, 79, 90, 77, 109, 95, 106 }, // base cell 93 { 94, 86, 81, 75, 107, 104, 101 }, // base cell 94 { 95, 92, 79, 78, 109, 108, 93 }, // base cell 95 { 96, 104, 98, 110, 76, 86, 82 }, // base cell 96 { 97, INVALID_BASE_CELL, 98, 84, 103, 89, 111 }, // base cell 97 (pentagon) { 98, 110, 97, 111, 82, 96, 84 }, // base cell 98 { 99, 80, 105, 88, 106, 90, 113 }, // base cell 99 { 100, 102, 83, 87, 108, 114, 92 }, // base cell 100 { 101, 102, 107, 112, 81, 85, 94 }, // base cell 101 { 102, 101, 87, 85, 114, 112, 100 }, // base cell 102 { 103, 91, 97, 89, 116, 105, 111 }, // base cell 103 { 104, 107, 110, 115, 86, 94, 96 }, // base cell 104 { 105, 88, 103, 91, 113, 99, 116 }, // base cell 105 { 106, 93, 99, 90, 117, 109, 113 }, // base cell 106 { 107, INVALID_BASE_CELL, 101, 94, 115, 104, 112 }, // base cell 107 (pentagon) { 108, 100, 95, 92, 118, 114, 109 }, // base cell 108 { 109, 108, 93, 95, 117, 118, 106 }, // base cell 109 { 110, 98, 104, 96, 119, 111, 115 }, // base cell 110 { 111, 97, 110, 98, 116, 103, 119 }, // base cell 111 { 112, 107, 102, 101, 120, 115, 114 }, // base cell 112 { 113, 99, 116, 105, 117, 106, 121 }, // base cell 113 { 114, 112, 100, 102, 118, 120, 108 }, // base cell 114 { 115, 110, 107, 104, 120, 119, 112 }, // base cell 115 { 116, 103, 119, 111, 113, 105, 121 }, // base cell 116 { 117, INVALID_BASE_CELL, 109, 118, 113, 121, 106 }, // base cell 117 (pentagon) { 118, 120, 108, 114, 117, 121, 109 }, // base cell 118 { 119, 111, 115, 110, 121, 116, 120 }, // base cell 119 { 120, 115, 114, 112, 121, 119, 118 }, // base cell 120 { 121, 116, 120, 119, 117, 113, 118 }, // base cell 121 }; /** @brief Neighboring base cell rotations in each IJK direction. * * For each base cell, for each direction, the number of 60 degree * CCW rotations to the coordinate system of the neighbor is given. * -1 indicates there is no neighbor in that direction. */ private static final int[][] baseCellNeighbor60CCWRots = new int[][] { { 0, 5, 0, 0, 1, 5, 1 }, // base cell 0 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 1 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 2 { 0, 5, 0, 0, 2, 5, 1 }, // base cell 3 { 0, -1, 1, 0, 3, 4, 2 }, // base cell 4 (pentagon) { 0, 0, 1, 0, 1, 0, 1 }, // base cell 5 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 6 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 7 { 0, 5, 0, 0, 0, 5, 1 }, // base cell 8 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 9 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 10 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 11 { 0, 5, 0, 0, 3, 5, 1 }, // base cell 12 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 13 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 14 (pentagon) { 0, 5, 0, 0, 4, 5, 1 }, // base cell 15 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 16 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 17 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 18 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 19 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 20 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 21 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 22 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 23 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 24 (pentagon) { 0, 0, 0, 3, 0, 0, 3 }, // base cell 25 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 26 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 27 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 28 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 29 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 30 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 31 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 32 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 33 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 34 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 35 { 0, 0, 0, 3, 0, 0, 3 }, // base cell 36 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 37 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 38 (pentagon) { 0, 3, 0, 0, 3, 3, 0 }, // base cell 39 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 40 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 41 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 42 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 43 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 44 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 45 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 46 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 47 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 48 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 49 (pentagon) { 0, 0, 0, 3, 0, 0, 3 }, // base cell 50 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 51 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 52 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 53 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 54 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 55 { 0, 3, 3, 3, 0, 0, 3 }, // base cell 56 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 57 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 58 (pentagon) { 0, 3, 3, 3, 3, 3, 0 }, // base cell 59 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 60 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 61 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 62 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 63 (pentagon) { 0, 0, 0, 3, 0, 0, 3 }, // base cell 64 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 65 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 66 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 67 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 68 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 69 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 70 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 71 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 72 (pentagon) { 0, 3, 3, 3, 0, 0, 3 }, // base cell 73 { 0, 3, 3, 3, 0, 0, 3 }, // base cell 74 { 0, 0, 0, 3, 0, 0, 3 }, // base cell 75 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 76 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 77 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 78 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 79 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 80 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 81 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 82 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 83 (pentagon) { 0, 0, 3, 0, 0, 3, 3 }, // base cell 84 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 85 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 86 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 87 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 88 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 89 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 90 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 91 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 92 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 93 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 94 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 95 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 96 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 97 (pentagon) { 0, 3, 3, 3, 0, 0, 3 }, // base cell 98 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 99 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 100 { 0, 3, 3, 3, 0, 0, 3 }, // base cell 101 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 102 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 103 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 104 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 105 { 0, 0, 1, 0, 3, 5, 1 }, // base cell 106 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 107 (pentagon) { 0, 5, 0, 0, 5, 5, 0 }, // base cell 108 { 0, 0, 1, 0, 4, 5, 1 }, // base cell 109 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 110 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 111 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 112 { 0, 0, 1, 0, 2, 5, 1 }, // base cell 113 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 114 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 115 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 116 { 0, -1, 1, 0, 3, 4, 2 }, // base cell 117 (pentagon) { 0, 0, 1, 0, 0, 5, 1 }, // base cell 118 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 119 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 120 { 0, 0, 1, 0, 1, 5, 1 }, // base cell 121 }; private static final int E_SUCCESS = 0; // Success (no error) private static final int E_PENTAGON = 9; // Pentagon distortion was encountered which the algorithm private static final int E_CELL_INVALID = 5; // `H3Index` cell argument was not valid private static final int E_FAILED = 1; // The operation failed but a more specific error is not available /** * Directions used for traversing a hexagonal ring counterclockwise around * {1, 0, 0} * * <pre> * _ * _/ \\_ * / \\5/ \\ * \\0/ \\4/ * / \\_/ \\ * \\1/ \\3/ * \\2/ * </pre> */ static final CoordIJK.Direction[] DIRECTIONS = new CoordIJK.Direction[] { CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }; /** * New digit when traversing along class II grids. * * Current digit -> direction -> new digit. */ private static final CoordIJK.Direction[][] NEW_DIGIT_II = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT }, { CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }, { CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT }, { CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }, { CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT } }; /** * New traversal direction when traversing along class II grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ private static final CoordIJK.Direction[][] NEW_ADJUSTMENT_II = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT } }; /** * New traversal direction when traversing along class III grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ private static final CoordIJK.Direction[][] NEW_DIGIT_III = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT }, { CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }, { CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT }, { CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }, { CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT } }; /** * New traversal direction when traversing along class III grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ private static final CoordIJK.Direction[][] NEW_ADJUSTMENT_III = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT } }; private static final CoordIJK.Direction[] NEIGHBORSETCLOCKWISE = new CoordIJK.Direction[] { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }; private static final CoordIJK.Direction[] NEIGHBORSETCOUNTERCLOCKWISE = new CoordIJK.Direction[] { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }; /** * Returns whether or not the provided H3Indexes are neighbors. * @param origin The origin H3 index. * @param destination The destination H3 index. * @return true if the indexes are neighbors, false otherwise */ public static boolean areNeighbours(long origin, long destination) { // Make sure they're hexagon indexes if (H3Index.H3_get_mode(origin) != Constants.H3_CELL_MODE) { throw new IllegalArgumentException("Invalid cell: " + origin); } if (H3Index.H3_get_mode(destination) != Constants.H3_CELL_MODE) { throw new IllegalArgumentException("Invalid cell: " + destination); } // Hexagons cannot be neighbors with themselves if (origin == destination) { return false; } final int resolution = H3Index.H3_get_resolution(origin); // Only hexagons in the same resolution can be neighbors if (resolution != H3Index.H3_get_resolution(destination)) { return false; } // H3 Indexes that share the same parent are very likely to be neighbors // Child 0 is neighbor with all of its parent's 'offspring', the other // children are neighbors with 3 of the 7 children. So a simple comparison // of origin and destination parents and then a lookup table of the children // is a super-cheap way to possibly determine they are neighbors. if (resolution > 1) { long originParent = H3.h3ToParent(origin); long destinationParent = H3.h3ToParent(destination); if (originParent == destinationParent) { int originResDigit = H3Index.H3_get_index_digit(origin, resolution); int destinationResDigit = H3Index.H3_get_index_digit(destination, resolution); if (originResDigit == CoordIJK.Direction.CENTER_DIGIT.digit() || destinationResDigit == CoordIJK.Direction.CENTER_DIGIT.digit()) { return true; } if (originResDigit >= CoordIJK.Direction.INVALID_DIGIT.digit()) { // Prevent indexing off the end of the array below throw new IllegalArgumentException(""); } if ((originResDigit == CoordIJK.Direction.K_AXES_DIGIT.digit() || destinationResDigit == CoordIJK.Direction.K_AXES_DIGIT.digit()) && H3.isPentagon(originParent)) { // If these are invalid cells, fail rather than incorrectly // reporting neighbors. For pentagon cells that are actually // neighbors across the deleted subsequence, they will fail the // optimized check below, but they will be accepted by the // gridDisk check below that. throw new IllegalArgumentException("Undefined error checking for neighbors"); } // These sets are the relevant neighbors in the clockwise // and counter-clockwise if (NEIGHBORSETCLOCKWISE[originResDigit].digit() == destinationResDigit || NEIGHBORSETCOUNTERCLOCKWISE[originResDigit].digit() == destinationResDigit) { return true; } } } // Otherwise, we have to determine the neighbor relationship the "hard" way. for (int i = 0; i < 6; i++) { long neighbor = h3NeighborInDirection(origin, DIRECTIONS[i].digit()); if (neighbor != -1) { // -1 is an expected case when trying to traverse off of // pentagons. if (destination == neighbor) { return true; } } } return false; } /** * Returns the hexagon index neighboring the origin, in the direction dir. * * Implementation note: The only reachable case where this returns -1 is if the * origin is a pentagon and the translation is in the k direction. Thus, * -1 can only be returned if origin is a pentagon. * * @param origin Origin index * @param dir Direction to move in * @return H3Index of the specified neighbor or -1 if there is no more neighbor */ static long h3NeighborInDirection(long origin, int dir) { long current = origin; int newRotations = 0; int oldBaseCell = H3Index.H3_get_base_cell(current); if (oldBaseCell < 0 || oldBaseCell >= Constants.NUM_BASE_CELLS) { // LCOV_EXCL_BR_LINE // Base cells less than zero can not be represented in an index throw new IllegalArgumentException("Invalid base cell looking for neighbor"); } int oldLeadingDigit = H3Index.h3LeadingNonZeroDigit(current); // Adjust the indexing digits and, if needed, the base cell. int r = H3Index.H3_get_resolution(current) - 1; while (true) { if (r == -1) { current = H3Index.H3_set_base_cell(current, baseCellNeighbors[oldBaseCell][dir]); newRotations = baseCellNeighbor60CCWRots[oldBaseCell][dir]; if (H3Index.H3_get_base_cell(current) == INVALID_BASE_CELL) { // Adjust for the deleted k vertex at the base cell level. // This edge actually borders a different neighbor. current = H3Index.H3_set_base_cell(current, baseCellNeighbors[oldBaseCell][CoordIJK.Direction.IK_AXES_DIGIT.digit()]); newRotations = baseCellNeighbor60CCWRots[oldBaseCell][CoordIJK.Direction.IK_AXES_DIGIT.digit()]; // perform the adjustment for the k-subsequence we're skipping // over. current = H3Index.h3Rotate60ccw(current); } break; } else { int oldDigit = H3Index.H3_get_index_digit(current, r + 1); int nextDir; if (oldDigit == CoordIJK.Direction.INVALID_DIGIT.digit()) { // Only possible on invalid input throw new IllegalArgumentException(); } else if (H3Index.isResolutionClassIII(r + 1)) { current = H3Index.H3_set_index_digit(current, r + 1, NEW_DIGIT_II[oldDigit][dir].digit()); nextDir = NEW_ADJUSTMENT_II[oldDigit][dir].digit(); } else { current = H3Index.H3_set_index_digit(current, r + 1, NEW_DIGIT_III[oldDigit][dir].digit()); nextDir = NEW_ADJUSTMENT_III[oldDigit][dir].digit(); } if (nextDir != CoordIJK.Direction.CENTER_DIGIT.digit()) { dir = nextDir; r--; } else { // No more adjustment to perform break; } } } int newBaseCell = H3Index.H3_get_base_cell(current); if (BaseCells.isBaseCellPentagon(newBaseCell)) { // force rotation out of missing k-axes sub-sequence if (H3Index.h3LeadingNonZeroDigit(current) == CoordIJK.Direction.K_AXES_DIGIT.digit()) { if (oldBaseCell != newBaseCell) { // in this case, we traversed into the deleted // k subsequence of a pentagon base cell. // We need to rotate out of that case depending // on how we got here. // check for a cw/ccw offset face; default is ccw if (BaseCells.baseCellIsCwOffset(newBaseCell, BaseCells.getBaseFaceIJK(oldBaseCell).face)) { current = H3Index.h3Rotate60cw(current); } else { // See cwOffsetPent in testGridDisk.c for why this is // unreachable. current = H3Index.h3Rotate60ccw(current); // LCOV_EXCL_LINE } } else { // In this case, we traversed into the deleted // k subsequence from within the same pentagon // base cell. if (oldLeadingDigit == CoordIJK.Direction.CENTER_DIGIT.digit()) { // Undefined: the k direction is deleted from here return -1L; } else if (oldLeadingDigit == CoordIJK.Direction.JK_AXES_DIGIT.digit()) { // Rotate out of the deleted k subsequence // We also need an additional change to the direction we're // moving in current = H3Index.h3Rotate60ccw(current); } else if (oldLeadingDigit == CoordIJK.Direction.IK_AXES_DIGIT.digit()) { // Rotate out of the deleted k subsequence // We also need an additional change to the direction we're // moving in current = H3Index.h3Rotate60cw(current); } else { // Should never occur throw new IllegalArgumentException("Undefined error looking for neighbor"); // LCOV_EXCL_LINE } } } for (int i = 0; i < newRotations; i++) { current = H3Index.h3RotatePent60ccw(current); } } else { for (int i = 0; i < newRotations; i++) { current = H3Index.h3Rotate60ccw(current); } } return current; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/HexRing.java
11
package com.thealgorithms.others; import java.util.Objects; /** * Damm algorithm is a check digit algorithm that detects all single-digit * errors and all adjacent transposition errors. It was presented by H. Michael * Damm in 2004. Essential part of the algorithm is a quasigroup of order 10 * (i.e. having a 10 × 10 Latin square as the body of its operation table) with * the special feature of being weakly totally anti-symmetric. Damm revealed * several methods to create totally anti-symmetric quasigroups of order 10 and * gave some examples in his doctoral dissertation. * * @see <a href="https://en.wikipedia.org/wiki/Damm_algorithm">Wiki. Damm * algorithm</a> */ public final class Damm { private Damm() { } /** * Weakly totally anti-symmetric quasigroup of order 10. This table is not * the only possible realisation of weak totally anti-symmetric quasigroup * but the most common one (taken from Damm doctoral dissertation). All * zeros lay on the diagonal because it simplifies the check digit * calculation. */ private static final byte[][] DAMM_TABLE = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; /** * Check input digits by Damm algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean dammCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); int checksum = 0; for (int number : numbers) { checksum = DAMM_TABLE[checksum][number]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addDammChecksum(String initialDigits) { checkInput(initialDigits); int[] numbers = toIntArray(initialDigits); int checksum = 0; for (int number : numbers) { checksum = DAMM_TABLE[checksum][number]; } return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Damm algorithm usage examples:"); var validInput = "5724"; var invalidInput = "5824"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "572"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Damm.dammCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addDammChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Damm.java
12
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import java.io.InputStream; import java.nio.ByteBuffer; /** * Abstract interface for parsing Protocol Messages. * * <p>The implementation should be stateless and thread-safe. * * <p>All methods may throw {@link InvalidProtocolBufferException}. In the event of invalid data, * like an encoding error, the cause of the thrown exception will be {@code null}. However, if an * I/O problem occurs, an exception is thrown with an {@link java.io.IOException} cause. * * @author [email protected] (Pherl Liu) */ public interface Parser<MessageType> { // NB(jh): Other parts of the protobuf API that parse messages distinguish between an I/O problem // (like failure reading bytes from a socket) and invalid data (encoding error) via the type of // thrown exception. But it would be source-incompatible to make the methods in this interface do // so since they were originally spec'ed to only throw InvalidProtocolBufferException. So callers // must inspect the cause of the exception to distinguish these two cases. /** * Parses a message of {@code MessageType} from the input. * * <p>Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling * this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF. */ public MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(CodedInputStream)}, but also parses extensions. The extensions that you * want to be able to parse must be registered in {@code extensionRegistry}. Extensions not in the * registry will be treated as unknown fields. */ public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(CodedInputStream)}, but does not throw an exception if the message is * missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(CodedInputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(CodedInputStream input, ExtensionRegistryLite)}, but does not throw an * exception if the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom( CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; // --------------------------------------------------------------- // Convenience methods. /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(ByteBuffer data) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(ByteString)}, but does not throw an exception if the message is missing * required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(ByteString data) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if * the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(byte[], int, int)}, but does not throw an exception if the message is * missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if * the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(byte[])}, but does not throw an exception if the message is missing * required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(byte[] data) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(byte[], ExtensionRegistryLite)}, but does not throw an exception if the * message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parse a message of {@code MessageType} from {@code input}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. Note that this method always reads the <i>entire</i> * input (unless it throws an exception). If you want it to stop earlier, you will need to wrap * your input in some wrapper stream that limits reading. Or, use {@link * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your message and {@link * #parseDelimitedFrom(InputStream)} to read it. * * <p>Despite usually reading the entire input, this does not close the stream. */ public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException; /** * Parses a message of {@code MessageType} from {@code input}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(InputStream)}, but does not throw an exception if the message is missing * required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)}, but does not throw an exception if * the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(InputStream)}, but does not read until EOF. Instead, the size of message * (encoded as a varint) is read first, then the message data. Use {@link * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write messages in this format. * * @return Parsed message if successful, or null if the stream is at EOF when the method starts. * Any other error (including reaching EOF during parsing) will cause an exception to be * thrown. */ public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; /** Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions. */ public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an exception if the message * is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)}, but does not throw an * exception if the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialDelimitedFrom( InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Parser.java
13
package com.genymobile.scrcpy; import android.annotation.TargetApi; import android.content.AttributionSource; import android.content.Context; import android.content.ContextWrapper; import android.os.Build; import android.os.Process; public final class FakeContext extends ContextWrapper { public static final String PACKAGE_NAME = "com.android.shell"; public static final int ROOT_UID = 0; // Like android.os.Process.ROOT_UID, but before API 29 private static final FakeContext INSTANCE = new FakeContext(); public static FakeContext get() { return INSTANCE; } private FakeContext() { super(Workarounds.getSystemContext()); } @Override public String getPackageName() { return PACKAGE_NAME; } @Override public String getOpPackageName() { return PACKAGE_NAME; } @TargetApi(Build.VERSION_CODES.S) @Override public AttributionSource getAttributionSource() { AttributionSource.Builder builder = new AttributionSource.Builder(Process.SHELL_UID); builder.setPackageName(PACKAGE_NAME); return builder.build(); } // @Override to be added on SDK upgrade for Android 14 @SuppressWarnings("unused") public int getDeviceId() { return 0; } @Override public Context getApplicationContext() { return this; } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/FakeContext.java
14
/* * Copyright (C) 2016 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; /** * The subset of the {@link java.util.regex.Pattern} API which is used by this package, and also * shared with the {@code re2j} library. For internal use only. Please refer to the {@code Pattern} * javadoc for details. */ @GwtCompatible @ElementTypesAreNonnullByDefault abstract class CommonPattern { public abstract CommonMatcher matcher(CharSequence t); public abstract String pattern(); public abstract int flags(); // Re-declare this as abstract to force subclasses to override. @Override public abstract String toString(); public static CommonPattern compile(String pattern) { return Platform.compilePattern(pattern); } public static boolean isPcreLike() { return Platform.patternCompilerIsPcreLike(); } }
google/guava
guava/src/com/google/common/base/CommonPattern.java
15
404: Not Found
brettwooldridge/HikariCP
src/main/java/module-info.java
16
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http; import java.io.Serializable; import org.springframework.util.Assert; /** * Represents an HTTP response status code. Implemented by {@link HttpStatus}, * but defined as an interface to allow for values not in that enumeration. * * @author Arjen Poutsma * @since 6.0 * @see <a href="https://www.iana.org/assignments/http-status-codes">HTTP Status Code Registry</a> * @see <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">List of HTTP status codes - Wikipedia</a> */ public sealed interface HttpStatusCode extends Serializable permits DefaultHttpStatusCode, HttpStatus { /** * Return the integer value of this status code. */ int value(); /** * Whether this status code is in the Informational class ({@code 1xx}). * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.1">RFC 2616</a> */ boolean is1xxInformational(); /** * Whether this status code is in the Successful class ({@code 2xx}). * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.2">RFC 2616</a> */ boolean is2xxSuccessful(); /** * Whether this status code is in the Redirection class ({@code 3xx}). * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.3">RFC 2616</a> */ boolean is3xxRedirection(); /** * Whether this status code is in the Client Error class ({@code 4xx}). * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.4">RFC 2616</a> */ boolean is4xxClientError(); /** * Whether this status code is in the Server Error class ({@code 5xx}). * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.5">RFC 2616</a> */ boolean is5xxServerError(); /** * Whether this status code is in the Client or Server Error class * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.4">RFC 2616</a> * @see <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-10.3">RFC 2616</a> * ({@code 4xx} or {@code 5xx}). * @see #is4xxClientError() * @see #is5xxServerError() */ boolean isError(); /** * Whether this {@code HttpStatusCode} shares the same integer {@link #value() value} as the other status code. * <p>Useful for comparisons that take deprecated aliases into account or compare arbitrary implementations * of {@code HttpStatusCode} (e.g. in place of {@link HttpStatus#equals(Object) HttpStatus enum equality}). * @param other the other {@code HttpStatusCode} to compare * @return true if the two {@code HttpStatusCode} objects share the same integer {@code value()}, false otherwise * @since 6.0.5 */ default boolean isSameCodeAs(HttpStatusCode other) { return value() == other.value(); } /** * Return an {@code HttpStatusCode} object for the given integer value. * @param code the status code as integer * @return the corresponding {@code HttpStatusCode} * @throws IllegalArgumentException if {@code code} is not a three-digit * positive number */ static HttpStatusCode valueOf(int code) { Assert.isTrue(code >= 100 && code <= 999, () -> "Status code '" + code + "' should be a three-digit positive integer"); HttpStatus status = HttpStatus.resolve(code); if (status != null) { return status; } else { return new DefaultHttpStatusCode(code); } } }
spring-projects/spring-framework
spring-web/src/main/java/org/springframework/http/HttpStatusCode.java
17
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; /** * <p>A RocksEnv is an interface used by the rocksdb implementation to access * operating system functionality like the filesystem etc.</p> * * <p>All Env implementations are safe for concurrent access from * multiple threads without any external synchronization.</p> */ public class RocksEnv extends Env { /** * <p>Package-private constructor that uses the specified native handle * to construct a RocksEnv.</p> * * <p>Note that the ownership of the input handle * belongs to the caller, and the newly created RocksEnv will not take * the ownership of the input handle. As a result, calling * {@code dispose()} of the created RocksEnv will be no-op.</p> */ RocksEnv(final long handle) { super(handle); } @Override protected native final void disposeInternal(final long handle); }
facebook/rocksdb
java/src/main/java/org/rocksdb/RocksEnv.java
18
/* ### * IP: GHIDRA * * 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 ghidra.pty; import java.io.IOException; /** * A pseudo-terminal * * <p> * A pseudo-terminal is essentially a two way pipe where one end acts as the parent, and the other * acts as the child. The process opening the pseudo-terminal is given a handle to both ends. The * child end is generally given to a subprocess, possibly designating the pty as the controlling tty * of a new session. This scheme is how, for example, an SSH daemon starts a new login shell. The * shell is given the child end, and the parent end is presented to the SSH client. * * <p> * This is more powerful than controlling a process via standard in and standard out. 1) Some * programs detect whether or not stdin/out/err refer to the controlling tty. For example, a program * should avoid prompting for passwords unless stdin is the controlling tty. Using a pty can provide * a controlling tty that is not necessarily controlled by a user. 2) Terminals have other * properties and can, e.g., send signals to the foreground process group (job) by sending special * characters. Normal characters are passed to the child, but special characters may be interpreted * by the terminal's <em>line discipline</em>. A rather common case is to send Ctrl-C (character * 003). Using stdin, the subprocess simply reads 003. With a properly-configured pty and session, * the subprocess is interrupted (sent SIGINT) instead. * * <p> * This class opens a pseudo-terminal and presents both ends as individual handles. The parent end * simply provides an input and output stream. These are typical byte-oriented streams, except that * the data passes through the pty, subject to interpretation by the OS kernel. On Linux, this means * the pty will apply the configured line discipline. Consult the host OS documentation for special * character sequences. * * <p> * The child end also provides the input and output streams, but it is uncommon to use them from the * same process. More likely, subprocess is launched in a new session, configuring the child as the * controlling terminal. Thus, the child handle provides methods for obtaining the child pty file * name and/or spawning a new session. Once spawned, the parent end is used to control the session. * * <p> * Example: * * <pre> * Pty pty = factory.openpty(); * pty.getChild().session("bash"); * * PrintWriter writer = new PrintWriter(pty.getParent().getOutputStream()); * writer.println("echo test"); * BufferedReader reader = * new BufferedReader(new InputStreamReader(pty.getParent().getInputStream())); * System.out.println(reader.readLine()); * System.out.println(reader.readLine()); * * pty.close(); * </pre> */ public interface Pty extends AutoCloseable { /** * Get a handle to the parent side of the pty * * @return the parent handle */ PtyParent getParent(); /** * Get a handle to the child side of the pty * * @return the child handle */ PtyChild getChild(); /** * Closes both ends of the pty * * <p> * This only closes this process's handles to the pty. For the parent end, this should be the * only process with a handle. The child end may be opened by any number of other processes. * More than likely, however, those processes will terminate once the parent end is closed, * since reads or writes on the child will produce EOF or an error. * * @throws IOException if an I/O error occurs */ @Override void close() throws IOException; }
NationalSecurityAgency/ghidra
Ghidra/Framework/Pty/src/main/java/ghidra/pty/Pty.java
19
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import java.util.List; /** * Router. (SPI, Prototype, ThreadSafe) * <p> * <a href="http://en.wikipedia.org/wiki/Routing">Routing</a> * * @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory) * @see org.apache.dubbo.rpc.cluster.Directory#list(Invocation) */ public interface Router extends Comparable<Router> { int DEFAULT_PRIORITY = Integer.MAX_VALUE; /** * Get the router url. * * @return url */ URL getUrl(); /** * Filter invokers with current routing rule and only return the invokers that comply with the rule. * * @param invokers invoker list * @param url refer url * @param invocation invocation * @return routed invokers * @throws RpcException */ <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException; /** * Notify the router the invoker list. Invoker list may change from time to time. This method gives the router a * chance to prepare before {@link Router#route(List, URL, Invocation)} gets called. * * @param invokers invoker list * @param <T> invoker's type */ default <T> void notify(List<Invoker<T>> invokers) { } /** * To decide whether this router need to execute every time an RPC comes or should only execute when addresses or * rule change. * * @return true if the router need to execute every time. */ boolean isRuntime(); /** * To decide whether this router should take effect when none of the invoker can match the router rule, which * means the {@link #route(List, URL, Invocation)} would be empty. Most of time, most router implementation would * default this value to false. * * @return true to execute if none of invokers matches the current router */ boolean isForce(); /** * Router's priority, used to sort routers. * * @return router's priority */ int getPriority(); @Override default int compareTo(Router o) { if (o == null) { throw new IllegalArgumentException(); } return Integer.compare(this.getPriority(), o.getPriority()); } }
apache/dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java
20
package com.macro.mall.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CmsHelpExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CmsHelpExample() { oredCriteria = new ArrayList<>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andCategoryIdIsNull() { addCriterion("category_id is null"); return (Criteria) this; } public Criteria andCategoryIdIsNotNull() { addCriterion("category_id is not null"); return (Criteria) this; } public Criteria andCategoryIdEqualTo(Long value) { addCriterion("category_id =", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotEqualTo(Long value) { addCriterion("category_id <>", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThan(Long value) { addCriterion("category_id >", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThanOrEqualTo(Long value) { addCriterion("category_id >=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThan(Long value) { addCriterion("category_id <", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThanOrEqualTo(Long value) { addCriterion("category_id <=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdIn(List<Long> values) { addCriterion("category_id in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotIn(List<Long> values) { addCriterion("category_id not in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdBetween(Long value1, Long value2) { addCriterion("category_id between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotBetween(Long value1, Long value2) { addCriterion("category_id not between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andIconIsNull() { addCriterion("icon is null"); return (Criteria) this; } public Criteria andIconIsNotNull() { addCriterion("icon is not null"); return (Criteria) this; } public Criteria andIconEqualTo(String value) { addCriterion("icon =", value, "icon"); return (Criteria) this; } public Criteria andIconNotEqualTo(String value) { addCriterion("icon <>", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThan(String value) { addCriterion("icon >", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThanOrEqualTo(String value) { addCriterion("icon >=", value, "icon"); return (Criteria) this; } public Criteria andIconLessThan(String value) { addCriterion("icon <", value, "icon"); return (Criteria) this; } public Criteria andIconLessThanOrEqualTo(String value) { addCriterion("icon <=", value, "icon"); return (Criteria) this; } public Criteria andIconLike(String value) { addCriterion("icon like", value, "icon"); return (Criteria) this; } public Criteria andIconNotLike(String value) { addCriterion("icon not like", value, "icon"); return (Criteria) this; } public Criteria andIconIn(List<String> values) { addCriterion("icon in", values, "icon"); return (Criteria) this; } public Criteria andIconNotIn(List<String> values) { addCriterion("icon not in", values, "icon"); return (Criteria) this; } public Criteria andIconBetween(String value1, String value2) { addCriterion("icon between", value1, value2, "icon"); return (Criteria) this; } public Criteria andIconNotBetween(String value1, String value2) { addCriterion("icon not between", value1, value2, "icon"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andShowStatusIsNull() { addCriterion("show_status is null"); return (Criteria) this; } public Criteria andShowStatusIsNotNull() { addCriterion("show_status is not null"); return (Criteria) this; } public Criteria andShowStatusEqualTo(Integer value) { addCriterion("show_status =", value, "showStatus"); return (Criteria) this; } public Criteria andShowStatusNotEqualTo(Integer value) { addCriterion("show_status <>", value, "showStatus"); return (Criteria) this; } public Criteria andShowStatusGreaterThan(Integer value) { addCriterion("show_status >", value, "showStatus"); return (Criteria) this; } public Criteria andShowStatusGreaterThanOrEqualTo(Integer value) { addCriterion("show_status >=", value, "showStatus"); return (Criteria) this; } public Criteria andShowStatusLessThan(Integer value) { addCriterion("show_status <", value, "showStatus"); return (Criteria) this; } public Criteria andShowStatusLessThanOrEqualTo(Integer value) { addCriterion("show_status <=", value, "showStatus"); return (Criteria) this; } public Criteria andShowStatusIn(List<Integer> values) { addCriterion("show_status in", values, "showStatus"); return (Criteria) this; } public Criteria andShowStatusNotIn(List<Integer> values) { addCriterion("show_status not in", values, "showStatus"); return (Criteria) this; } public Criteria andShowStatusBetween(Integer value1, Integer value2) { addCriterion("show_status between", value1, value2, "showStatus"); return (Criteria) this; } public Criteria andShowStatusNotBetween(Integer value1, Integer value2) { addCriterion("show_status not between", value1, value2, "showStatus"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andReadCountIsNull() { addCriterion("read_count is null"); return (Criteria) this; } public Criteria andReadCountIsNotNull() { addCriterion("read_count is not null"); return (Criteria) this; } public Criteria andReadCountEqualTo(Integer value) { addCriterion("read_count =", value, "readCount"); return (Criteria) this; } public Criteria andReadCountNotEqualTo(Integer value) { addCriterion("read_count <>", value, "readCount"); return (Criteria) this; } public Criteria andReadCountGreaterThan(Integer value) { addCriterion("read_count >", value, "readCount"); return (Criteria) this; } public Criteria andReadCountGreaterThanOrEqualTo(Integer value) { addCriterion("read_count >=", value, "readCount"); return (Criteria) this; } public Criteria andReadCountLessThan(Integer value) { addCriterion("read_count <", value, "readCount"); return (Criteria) this; } public Criteria andReadCountLessThanOrEqualTo(Integer value) { addCriterion("read_count <=", value, "readCount"); return (Criteria) this; } public Criteria andReadCountIn(List<Integer> values) { addCriterion("read_count in", values, "readCount"); return (Criteria) this; } public Criteria andReadCountNotIn(List<Integer> values) { addCriterion("read_count not in", values, "readCount"); return (Criteria) this; } public Criteria andReadCountBetween(Integer value1, Integer value2) { addCriterion("read_count between", value1, value2, "readCount"); return (Criteria) this; } public Criteria andReadCountNotBetween(Integer value1, Integer value2) { addCriterion("read_count not between", value1, value2, "readCount"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/CmsHelpExample.java
21
package restx.demo; import com.google.common.base.Optional; import restx.server.WebServer; import restx.server.Jetty11WebServer; /** * This class can be used to run the app. * * Alternatively, you can deploy the app as a war in a regular container like tomcat or jetty. * * Reading the port from system env PORT makes it compatible with heroku. */ public class AppServer { public static final String WEB_INF_LOCATION = "src/main/webapp/WEB-INF/web.xml"; public static final String WEB_APP_LOCATION = "src/main/webapp"; public static void main(String[] args) throws Exception { int port = Integer.valueOf(Optional.fromNullable(System.getenv("PORT")).or("8080")); WebServer server = new Jetty11WebServer(WEB_INF_LOCATION, WEB_APP_LOCATION, port, "0.0.0.0"); /* * load mode from system property if defined, or default to dev * be careful with that setting, if you use this class to launch your server in production, make sure to launch * it with -Drestx.mode=prod or change the default here */ System.setProperty("restx.mode", System.getProperty("restx.mode", "dev")); System.setProperty("restx.app.package", "restx.demo"); server.startAndAwait(); } }
eugenp/tutorials
web-modules/restx/src/main/java/restx/demo/AppServer.java
22
/* * Copyright 2020 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.InjectAccessors; import com.oracle.svm.core.annotate.TargetClass; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Collection; @TargetClass(NetUtil.class) final class NetUtilSubstitutions { private NetUtilSubstitutions() { } @Alias @InjectAccessors(NetUtilLocalhost4Accessor.class) public static Inet4Address LOCALHOST4; @Alias @InjectAccessors(NetUtilLocalhost6Accessor.class) public static Inet6Address LOCALHOST6; @Alias @InjectAccessors(NetUtilLocalhostAccessor.class) public static InetAddress LOCALHOST; @Alias @InjectAccessors(NetUtilNetworkInterfacesAccessor.class) public static Collection<NetworkInterface> NETWORK_INTERFACES; private static final class NetUtilLocalhost4Accessor { static Inet4Address get() { // using https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom return NetUtilLocalhost4LazyHolder.LOCALHOST4; } static void set(Inet4Address ignored) { // a no-op setter to avoid exceptions when NetUtil is initialized at run-time } } private static final class NetUtilLocalhost4LazyHolder { private static final Inet4Address LOCALHOST4 = NetUtilInitializations.createLocalhost4(); } private static final class NetUtilLocalhost6Accessor { static Inet6Address get() { // using https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom return NetUtilLocalhost6LazyHolder.LOCALHOST6; } static void set(Inet6Address ignored) { // a no-op setter to avoid exceptions when NetUtil is initialized at run-time } } private static final class NetUtilLocalhost6LazyHolder { private static final Inet6Address LOCALHOST6 = NetUtilInitializations.createLocalhost6(); } private static final class NetUtilLocalhostAccessor { static InetAddress get() { // using https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom return NetUtilLocalhostLazyHolder.LOCALHOST; } static void set(InetAddress ignored) { // a no-op setter to avoid exceptions when NetUtil is initialized at run-time } } private static final class NetUtilLocalhostLazyHolder { private static final InetAddress LOCALHOST = NetUtilInitializations .determineLoopback(NetUtilNetworkInterfacesLazyHolder.NETWORK_INTERFACES, NetUtilLocalhost4LazyHolder.LOCALHOST4, NetUtilLocalhost6LazyHolder.LOCALHOST6) .address(); } private static final class NetUtilNetworkInterfacesAccessor { static Collection<NetworkInterface> get() { // using https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom return NetUtilNetworkInterfacesLazyHolder.NETWORK_INTERFACES; } static void set(Collection<NetworkInterface> ignored) { // a no-op setter to avoid exceptions when NetUtil is initialized at run-time } } private static final class NetUtilNetworkInterfacesLazyHolder { private static final Collection<NetworkInterface> NETWORK_INTERFACES = NetUtilInitializations.networkInterfaces(); } }
netty/netty
common/src/main/java/io/netty/util/NetUtilSubstitutions.java
23
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.net; import java.io.IOException; import java.io.UncheckedIOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.Random; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Platform; public class PortProber { public static final int HIGHEST_PORT = 65535; public static final int START_OF_USER_PORTS = 1024; private static final Random random = new Random(); private static final EphemeralPortRangeDetector ephemeralRangeDetector; private static final Platform current = Platform.getCurrent(); static { if (current.is(Platform.LINUX)) { ephemeralRangeDetector = LinuxEphemeralPortRangeDetector.getInstance(); } else if (current.is(Platform.XP)) { ephemeralRangeDetector = new OlderWindowsVersionEphemeralPortDetector(); } else { ephemeralRangeDetector = new FixedIANAPortRange(); } } private PortProber() { // Utility class } public static int findFreePort() { for (int i = 0; i < 5; i++) { int seedPort = createAcceptablePort(); int suggestedPort = checkPortIsFree(seedPort); if (suggestedPort != -1) { return suggestedPort; } } throw new RuntimeException("Unable to find a free port"); } /** * Returns a port that is within a probable free-range. * * <p>Based on the ports in <a href="http://en.wikipedia.org/wiki/Ephemeral_ports">...</a>, this * method stays away from all well-known ephemeral port ranges, since they can arbitrarily race * with the operating system in allocations. Due to the port-greedy nature of selenium this * happens fairly frequently. Staying within the known safe range increases the probability tests * will run green quite significantly. * * @return a random port number */ private static int createAcceptablePort() { synchronized (random) { final int FIRST_PORT; final int LAST_PORT; int ephemeralStart = Math.max(START_OF_USER_PORTS, ephemeralRangeDetector.getLowestEphemeralPort()); int ephemeralEnd = Math.min(HIGHEST_PORT, ephemeralRangeDetector.getHighestEphemeralPort()); /* * If the system provides a too short range of ephemeral ports (mostly on old windows systems) * use the range suggested from Internet Assigned Numbers Authority as ephemeral port range. */ if (ephemeralEnd - ephemeralStart < 5000) { EphemeralPortRangeDetector ianaRange = new FixedIANAPortRange(); ephemeralStart = ianaRange.getLowestEphemeralPort(); ephemeralEnd = ianaRange.getHighestEphemeralPort(); } int freeAbove = HIGHEST_PORT - ephemeralEnd; int freeBelow = Math.max(0, ephemeralStart - START_OF_USER_PORTS); if (freeAbove > freeBelow) { FIRST_PORT = ephemeralEnd; LAST_PORT = 65535; } else { FIRST_PORT = 1024; LAST_PORT = ephemeralStart; } if (FIRST_PORT == LAST_PORT) { return FIRST_PORT; } if (FIRST_PORT > LAST_PORT) { throw new UnsupportedOperationException("Could not find ephemeral port to use"); } final int randomInt = random.nextInt(); final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1)); return portWithoutOffset + FIRST_PORT; } } private static boolean isFree(String bindHost, int port) { try (ServerSocket socket = new ServerSocket()) { socket.setReuseAddress(true); socket.bind(new InetSocketAddress(bindHost, port)); return true; } catch (Exception e) { return false; } } static int checkPortIsFree(int port) { if (isFree("localhost", port) && isFree("0.0.0.0", port)) { return port; } return -1; } public static void waitForPortUp(int port, int timeout, TimeUnit unit) { long end = System.currentTimeMillis() + unit.toMillis(timeout); while (System.currentTimeMillis() < end) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress("localhost", port), 1000); return; } catch (ConnectException | SocketTimeoutException e) { // Ignore this } catch (IOException e) { throw new UncheckedIOException(e); } } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/net/PortProber.java
24
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.support.ui; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; import java.util.stream.Collectors; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.openqa.selenium.WrapsElement; /** Models a SELECT tag, providing helper methods to select and deselect options. */ public class Select implements ISelect, WrapsElement { private final WebElement element; private final boolean isMulti; /** * Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not, * then an UnexpectedTagNameException is thrown. * * @param element SELECT element to wrap * @throws UnexpectedTagNameException when element is not a SELECT */ public Select(WebElement element) { String tagName = element.getTagName(); if (null == tagName || !"select".equals(tagName.toLowerCase())) { throw new UnexpectedTagNameException("select", tagName); } this.element = element; String value = element.getDomAttribute("multiple"); // The atoms normalize the returned value, but check for "false" isMulti = (value != null && !"false".equals(value)); } @Override public WebElement getWrappedElement() { return element; } /** * @return Whether this select element support selecting multiple options at the same time? This * is done by checking the value of the "multiple" attribute. */ @Override public boolean isMultiple() { return isMulti; } /** * @return All options belonging to this select tag */ @Override public List<WebElement> getOptions() { return element.findElements(By.tagName("option")); } /** * @return All selected options belonging to this select tag */ @Override public List<WebElement> getAllSelectedOptions() { return getOptions().stream().filter(WebElement::isSelected).collect(Collectors.toList()); } /** * @return The first selected option in this select tag (or the currently selected option in a * normal select) * @throws NoSuchElementException If no option is selected */ @Override public WebElement getFirstSelectedOption() { return getOptions().stream() .filter(WebElement::isSelected) .findFirst() .orElseThrow(() -> new NoSuchElementException("No options are selected")); } /** * Select all options that display text matching the argument. That is, when given "Bar" this * would select an option like: * * <p>&lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param text The visible text to match against * @throws NoSuchElementException If no matching option elements are found */ @Override public void selectByVisibleText(String text) { assertSelectIsEnabled(); // try to find the option via XPATH ... List<WebElement> options = element.findElements( By.xpath(".//option[normalize-space(.) = " + Quotes.escape(text) + "]")); for (WebElement option : options) { setSelected(option, true); if (!isMultiple()) { return; } } boolean matched = !options.isEmpty(); if (!matched && text.contains(" ")) { String subStringWithoutSpace = getLongestSubstringWithoutSpace(text); List<WebElement> candidates; if ("".equals(subStringWithoutSpace)) { // hmm, text is either empty or contains only spaces - get all options ... candidates = element.findElements(By.tagName("option")); } else { // get candidates via XPATH ... candidates = element.findElements( By.xpath(".//option[contains(., " + Quotes.escape(subStringWithoutSpace) + ")]")); } String trimmed = text.trim(); for (WebElement option : candidates) { if (trimmed.equals(option.getText().trim())) { setSelected(option, true); if (!isMultiple()) { return; } matched = true; } } } if (!matched) { throw new NoSuchElementException("Cannot locate option with text: " + text); } } private String getLongestSubstringWithoutSpace(String s) { String result = ""; StringTokenizer st = new StringTokenizer(s, " "); while (st.hasMoreTokens()) { String t = st.nextToken(); if (t.length() > result.length()) { result = t; } } return result; } /** * Select the option at the given index. This is done by examining the "index" attribute of an * element, and not merely by counting. * * @param index The option at this index will be selected * @throws NoSuchElementException If no matching option elements are found */ @Override public void selectByIndex(int index) { assertSelectIsEnabled(); setSelectedByIndex(index, true); } /** * Select all options that have a value matching the argument. That is, when given "foo" this * would select an option like: * * <p>&lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param value The value to match against * @throws NoSuchElementException If no matching option elements are found */ @Override public void selectByValue(String value) { assertSelectIsEnabled(); for (WebElement option : findOptionsByValue(value)) { setSelected(option, true); if (!isMultiple()) { return; } } } /** * Clear all selected entries. This is only valid when the SELECT supports multiple selections. * * @throws UnsupportedOperationException If the SELECT does not support multiple selections */ @Override public void deselectAll() { if (!isMultiple()) { throw new UnsupportedOperationException( "You may only deselect all options of a multi-select"); } for (WebElement option : getOptions()) { setSelected(option, false); } } /** * Deselect all options that have a value matching the argument. That is, when given "foo" this * would deselect an option like: * * <p>&lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param value The value to match against * @throws NoSuchElementException If no matching option elements are found * @throws UnsupportedOperationException If the SELECT does not support multiple selections */ @Override public void deselectByValue(String value) { if (!isMultiple()) { throw new UnsupportedOperationException("You may only deselect options of a multi-select"); } for (WebElement option : findOptionsByValue(value)) { setSelected(option, false); } } /** * Deselect the option at the given index. This is done by examining the "index" attribute of an * element, and not merely by counting. * * @param index The option at this index will be deselected * @throws NoSuchElementException If no matching option elements are found * @throws UnsupportedOperationException If the SELECT does not support multiple selections */ @Override public void deselectByIndex(int index) { if (!isMultiple()) { throw new UnsupportedOperationException("You may only deselect options of a multi-select"); } setSelectedByIndex(index, false); } /** * Deselect all options that display text matching the argument. That is, when given "Bar" this * would deselect an option like: * * <p>&lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param text The visible text to match against * @throws NoSuchElementException If no matching option elements are found * @throws UnsupportedOperationException If the SELECT does not support multiple selections */ @Override public void deselectByVisibleText(String text) { if (!isMultiple()) { throw new UnsupportedOperationException("You may only deselect options of a multi-select"); } List<WebElement> options = element.findElements( By.xpath(".//option[normalize-space(.) = " + Quotes.escape(text) + "]")); if (options.isEmpty()) { throw new NoSuchElementException("Cannot locate option with text: " + text); } for (WebElement option : options) { setSelected(option, false); } } private List<WebElement> findOptionsByValue(String value) { List<WebElement> options = element.findElements(By.xpath(".//option[@value = " + Quotes.escape(value) + "]")); if (options.isEmpty()) { throw new NoSuchElementException("Cannot locate option with value: " + value); } return options; } private void setSelectedByIndex(int index, boolean select) { String match = String.valueOf(index); for (WebElement option : getOptions()) { if (match.equals(option.getAttribute("index"))) { setSelected(option, select); return; } } throw new NoSuchElementException("Cannot locate option with index: " + index); } /** * Select or deselect specified option * * @param option The option which state needs to be changed * @param select Indicates whether the option needs to be selected (true) or deselected (false) */ private void setSelected(WebElement option, boolean select) { assertOptionIsEnabled(option, select); if (option.isSelected() != select) { option.click(); } } private void assertOptionIsEnabled(WebElement option, boolean select) { if (select && !option.isEnabled()) { throw new UnsupportedOperationException("You may not select a disabled option"); } } private void assertSelectIsEnabled() { if (!element.isEnabled()) { throw new UnsupportedOperationException("You may not select an option in disabled select"); } } @Override public boolean equals(Object o) { if (!(o instanceof Select)) { return false; } Select select = (Select) o; return Objects.equals(element, select.element); } @Override public int hashCode() { return Objects.hash(element); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/support/ui/Select.java
25
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.net; import java.io.IOException; import java.io.UncheckedIOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.regex.Pattern; import org.openqa.selenium.internal.Require; public class Urls { private Urls() { // Utility class } /** * Encodes the text as an URL using UTF-8. * * @param value the text too encode * @return the encoded URI string * @see URLEncoder#encode(java.lang.String, java.lang.String) */ public static String urlEncode(String value) { try { return URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new UncheckedIOException(e); } } public static URL fromUri(URI uri) { try { return uri.toURL(); } catch (MalformedURLException e) { throw new UncheckedIOException(e); } } /** * Convert a string, which may just be a hostname, into a valid {@link URI}. If no scheme is * given, it is set to {@code http} by default. * * <p>We prefer to use {@code URI} instead of {@code URL} since the latter requires a scheme * handler to be registered for types, so strings like {@code docker://localhost:1234} would not * generally be a valid {@link URL} but would be a correct {@link URI}. * * <p>A known limitation is that URI fragments are not handled. In the expected use cases for this * method, that is not a problem. */ public static URI from(String rawUri) { Require.nonNull("URL to convert", rawUri); try { // Things to consider: // * A plain string hostname // * A host represented as an IPv4 address // * A host represented as an IPv6 address // * A host represented as an abbreviated IPv6 address // If there's no colon, then we have a plain hostname int colonIndex = rawUri.indexOf(':'); int slashIndex = rawUri.indexOf('/'); if (slashIndex == -1 && colonIndex == -1) { return createHttpUri(rawUri); } // Check the characters preceding the colon. If they're all numbers // (or there's no preceding character), we're dealing with a short form // ip6 address. if (colonIndex != -1) { if (colonIndex == 0) { return createHttpUri(rawUri); } if (Pattern.matches("\\d+", rawUri.substring(0, colonIndex))) { return createHttpUri(rawUri); } } // If there's a slash immediately after the colon, that's a scheme // and we can just create a URI from that. return new URI(rawUri); } catch (URISyntaxException e) { throw new UncheckedIOException(new IOException(e)); } } private static URI createHttpUri(String rawHost) { int slashIndex = rawHost.indexOf('/'); String host = slashIndex == -1 ? rawHost : rawHost.substring(0, slashIndex); String path = slashIndex == -1 ? null : rawHost.substring(slashIndex); try { return new URI("http", host, path, null); } catch (URISyntaxException e) { throw new UncheckedIOException(new IOException(e)); } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/net/Urls.java
26
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.bidi; import java.io.Closeable; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import org.openqa.selenium.internal.Require; public class BiDi implements Closeable { private final Duration timeout = Duration.ofSeconds(30); private final Connection connection; public BiDi(Connection connection) { this.connection = Require.nonNull("WebSocket connection", connection); } @Override public void close() { clearListeners(); disconnectSession(); connection.close(); } public void disconnectSession() { // TODO: Identify how to close a BiDi session. // Seems like https://w3c.github.io/webdriver-bidi/#issue-9f7aff26 needs to be fleshed out. } public <X> X send(Command<X> command) { Require.nonNull("Command to send", command); return connection.sendAndWait(command, timeout); } public <X> void addListener(Event<X> event, Consumer<X> handler) { Require.nonNull("Event to listen for", event); Require.nonNull("Handler to call", handler); send( new Command<>( "session.subscribe", Map.of("events", Collections.singletonList(event.getMethod())))); connection.addListener(event, handler); } public <X> void addListener(String browsingContextId, Event<X> event, Consumer<X> handler) { Require.nonNull("Event to listen for", event); Require.nonNull("Browsing context id", browsingContextId); Require.nonNull("Handler to call", handler); send( new Command<>( "session.subscribe", Map.of( "contexts", Collections.singletonList(browsingContextId), "events", Collections.singletonList(event.getMethod())))); connection.addListener(event, handler); } public <X> void addListener(Set<String> browsingContextIds, Event<X> event, Consumer<X> handler) { Require.nonNull("List of browsing context ids", browsingContextIds); Require.nonNull("Event to listen for", event); Require.nonNull("Handler to call", handler); send( new Command<>( "session.subscribe", Map.of( "contexts", browsingContextIds, "events", Collections.singletonList(event.getMethod())))); connection.addListener(event, handler); } public <X> void clearListener(Event<X> event) { Require.nonNull("Event to listen for", event); // The browser throws an error if we try to unsubscribe an event that was not subscribed in the // first place if (connection.isEventSubscribed(event)) { send( new Command<>( "session.unsubscribe", Map.of("events", Collections.singletonList(event.getMethod())))); connection.clearListener(event); } } public void clearListeners() { connection.clearListeners(); } public BiDiSessionStatus getBidiSessionStatus() { return send(new Command<>("session.status", Collections.emptyMap(), BiDiSessionStatus.class)); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/bidi/BiDi.java
27
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; /** * Represents the known architectures used in WebDriver. It attempts to smooth over some of Java's * rough edges when dealing with microprocessor architectures by, for instance, allowing you to * query if a particular architecture is 32- or 64-bit. * * @see org.openqa.selenium.Platform */ // Useful URLs: // http://hg.openjdk.java.net/jdk7/modules/jdk/file/a37326fa7f95/src/windows/native/java/lang/java_props_md.c public enum Architecture { // Architecture families X86( "x86", "i386", "ia32", "i686", "i486", "i86", "pentium", "pentium_pro", "pentium_pro+mmx", "pentium+mmx") { @Override public int getDataModel() { return 32; } }, X64("amd64", "ia64", "x86_64"), ARM("aarch64", "arm"), MIPS32("mips32") { @Override public int getDataModel() { return 32; } }, MIPS64("mips64"), // Meta architecture ANY("") { @Override public boolean is(Architecture compareWith) { return true; } }; private final String[] archIdentifiers; Architecture(String... partOfArch) { archIdentifiers = partOfArch; } /** * Heuristic for comparing two architectures. If architectures are found to be in the same * "architecture family" (e.g. i386, i686, x86 and ia32 are considered related), they will match. * * @param compareWith the architecture to compare with * @return true if architectures belong to the same architecture family, false otherwise */ public boolean is(Architecture compareWith) { return this.equals(compareWith); } /** * Gets the data model of the architecture. The data model tells you how big memory addresses are * on the given microprocessor architecture. * * @return 32- or 64-bit depending on architecture */ public int getDataModel() { return 64; } @Override public String toString() { return name().toLowerCase(); } /** * Gets current architecture. * * @return current architecture */ public static Architecture getCurrent() { return extractFromSysProperty(System.getProperty("os.arch")); } /** * Extracts architectures based on system properties in Java and a heuristic to overcome * differences between JDK implementations. If not able to determine the operating system's * architecture, it will throw. * * @param arch the architecture name to determine the architecture of * @return the most likely architecture based on the given architecture name * @throws UnsupportedOperationException if the architecture given is unknown or unsupported */ public static Architecture extractFromSysProperty(String arch) { if (arch != null) { arch = arch.toLowerCase(); } // Some architectures are basically the same even though they have different names. ia32, x86, // i386 and i686 are for WebDriver's purposes the same sort of 32-bit x86-esque architecture. // So each architecture defined in this enum has an array of strings with the different // identifiers it matches. for (Architecture architecture : values()) { if (architecture == Architecture.ANY) { continue; } for (String matcher : architecture.archIdentifiers) { if (matcher.equals(arch)) { return architecture; } } } throw new UnsupportedOperationException("Unknown architecture: " + arch); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/Architecture.java
28
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.internal.tcnative.Buffer; import io.netty.internal.tcnative.Library; import io.netty.internal.tcnative.SSL; import io.netty.internal.tcnative.SSLContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.NativeLibraryLoader; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static io.netty.handler.ssl.SslUtils.*; /** * Tells if <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public final class OpenSsl { private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class); private static final Throwable UNAVAILABILITY_CAUSE; static final List<String> DEFAULT_CIPHERS; static final Set<String> AVAILABLE_CIPHER_SUITES; private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES; private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES; private static final boolean SUPPORTS_KEYMANAGER_FACTORY; private static final boolean USE_KEYMANAGER_FACTORY; private static final boolean SUPPORTS_OCSP; private static final boolean TLSV13_SUPPORTED; private static final boolean IS_BORINGSSL; private static final Set<String> CLIENT_DEFAULT_PROTOCOLS; private static final Set<String> SERVER_DEFAULT_PROTOCOLS; static final Set<String> SUPPORTED_PROTOCOLS_SET; static final String[] EXTRA_SUPPORTED_TLS_1_3_CIPHERS; static final String EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; static final String[] NAMED_GROUPS; static final boolean JAVAX_CERTIFICATE_CREATION_SUPPORTED; // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL. // See https://github.com/netty/netty-tcnative/issues/567 // See https://www.java.com/en/configure_crypto.html for ordering private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" }; static { Throwable cause = null; if (SystemPropertyUtil.getBoolean("io.netty.handler.ssl.noOpenSsl", false)) { cause = new UnsupportedOperationException( "OpenSSL was explicit disabled with -Dio.netty.handler.ssl.noOpenSsl=true"); logger.debug( "netty-tcnative explicit disabled; " + OpenSslEngine.class.getSimpleName() + " will be unavailable.", cause); } else { // Test if netty-tcnative is in the classpath first. try { Class.forName("io.netty.internal.tcnative.SSLContext", false, PlatformDependent.getClassLoader(OpenSsl.class)); } catch (ClassNotFoundException t) { cause = t; logger.debug( "netty-tcnative not in the classpath; " + OpenSslEngine.class.getSimpleName() + " will be unavailable."); } // If in the classpath, try to load the native library and initialize netty-tcnative. if (cause == null) { try { // The JNI library was not already loaded. Load it now. loadTcNative(); } catch (Throwable t) { cause = t; logger.debug( "Failed to load netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " + "application has already loaded the symbols by some other means. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } try { String engine = SystemPropertyUtil.get("io.netty.handler.ssl.openssl.engine", null); if (engine == null) { logger.debug("Initialize netty-tcnative using engine: 'default'"); } else { logger.debug("Initialize netty-tcnative using engine: '{}'", engine); } initializeTcNative(engine); // The library was initialized successfully. If loading the library failed above, // reset the cause now since it appears that the library was loaded by some other // means. cause = null; } catch (Throwable t) { if (cause == null) { cause = t; } logger.debug( "Failed to initialize netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } } } UNAVAILABILITY_CAUSE = cause; CLIENT_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.client.protocols"); SERVER_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.server.protocols"); if (cause == null) { logger.debug("netty-tcnative using native library: {}", SSL.versionString()); final List<String> defaultCiphers = new ArrayList<String>(); final Set<String> availableOpenSslCipherSuites = new LinkedHashSet<String>(128); boolean supportsKeyManagerFactory = false; boolean useKeyManagerFactory = false; boolean tlsv13Supported = false; String[] namedGroups = DEFAULT_NAMED_GROUPS; String[] defaultConvertedNamedGroups = new String[namedGroups.length]; for (int i = 0; i < namedGroups.length; i++) { defaultConvertedNamedGroups[i] = GroupsConverter.toOpenSsl(namedGroups[i]); } IS_BORINGSSL = "BoringSSL".equals(versionString()); if (IS_BORINGSSL) { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = new String [] { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" , "TLS_CHACHA20_POLY1305_SHA256" }; StringBuilder ciphersBuilder = new StringBuilder(128); for (String cipher: EXTRA_SUPPORTED_TLS_1_3_CIPHERS) { ciphersBuilder.append(cipher).append(":"); } ciphersBuilder.setLength(ciphersBuilder.length() - 1); EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = ciphersBuilder.toString(); } else { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; } try { final long sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER); long certBio = 0; long keyBio = 0; long cert = 0; long key = 0; try { // As we delegate to the KeyManager / TrustManager of the JDK we need to ensure it can actually // handle TLSv13 as otherwise we may see runtime exceptions if (SslProvider.isTlsv13Supported(SslProvider.JDK)) { try { StringBuilder tlsv13Ciphers = new StringBuilder(); for (String cipher : TLSV13_CIPHERS) { String converted = CipherSuiteConverter.toOpenSsl(cipher, IS_BORINGSSL); if (converted != null) { tlsv13Ciphers.append(converted).append(':'); } } if (tlsv13Ciphers.length() == 0) { tlsv13Supported = false; } else { tlsv13Ciphers.setLength(tlsv13Ciphers.length() - 1); SSLContext.setCipherSuite(sslCtx, tlsv13Ciphers.toString(), true); tlsv13Supported = true; } } catch (Exception ignore) { tlsv13Supported = false; } } SSLContext.setCipherSuite(sslCtx, "ALL", false); final long ssl = SSL.newSSL(sslCtx, true); try { for (String c: SSL.getCiphers(ssl)) { // Filter out bad input. if (c == null || c.isEmpty() || availableOpenSslCipherSuites.contains(c) || // Filter out TLSv1.3 ciphers if not supported. !tlsv13Supported && isTLSv13Cipher(c)) { continue; } availableOpenSslCipherSuites.add(c); } if (IS_BORINGSSL) { // Currently BoringSSL does not include these when calling SSL.getCiphers() even when these // are supported. Collections.addAll(availableOpenSslCipherSuites, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); Collections.addAll(availableOpenSslCipherSuites, "AEAD-AES128-GCM-SHA256", "AEAD-AES256-GCM-SHA384", "AEAD-CHACHA20-POLY1305-SHA256"); } PemEncoded privateKey = PemPrivateKey.valueOf(PROBING_KEY.getBytes(CharsetUtil.US_ASCII)); try { // Let's check if we can set a callback, which may not work if the used OpenSSL version // is to old. SSLContext.setCertificateCallback(sslCtx, null); X509Certificate certificate = selfSignedCertificate(); certBio = ReferenceCountedOpenSslContext.toBIO(ByteBufAllocator.DEFAULT, certificate); cert = SSL.parseX509Chain(certBio); keyBio = ReferenceCountedOpenSslContext.toBIO( UnpooledByteBufAllocator.DEFAULT, privateKey.retain()); key = SSL.parsePrivateKey(keyBio, null); SSL.setKeyMaterial(ssl, cert, key); supportsKeyManagerFactory = true; try { boolean propertySet = SystemPropertyUtil.contains( "io.netty.handler.ssl.openssl.useKeyManagerFactory"); if (!IS_BORINGSSL) { useKeyManagerFactory = SystemPropertyUtil.getBoolean( "io.netty.handler.ssl.openssl.useKeyManagerFactory", true); if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and so will be ignored in the future"); } } else { useKeyManagerFactory = true; if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and will be ignored when using BoringSSL"); } } } catch (Throwable ignore) { logger.debug("Failed to get useKeyManagerFactory system property."); } } catch (Error ignore) { logger.debug("KeyManagerFactory not supported."); } finally { privateKey.release(); } } finally { SSL.freeSSL(ssl); if (certBio != 0) { SSL.freeBIO(certBio); } if (keyBio != 0) { SSL.freeBIO(keyBio); } if (cert != 0) { SSL.freeX509Chain(cert); } if (key != 0) { SSL.freePrivateKey(key); } } String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null); if (groups != null) { String[] nGroups = groups.split(","); Set<String> supportedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> supportedConvertedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> unsupportedNamedGroups = new LinkedHashSet<String>(); for (String namedGroup : nGroups) { String converted = GroupsConverter.toOpenSsl(namedGroup); if (SSLContext.setCurvesList(sslCtx, converted)) { supportedConvertedNamedGroups.add(converted); supportedNamedGroups.add(namedGroup); } else { unsupportedNamedGroups.add(namedGroup); } } if (supportedNamedGroups.isEmpty()) { namedGroups = defaultConvertedNamedGroups; logger.info("All configured namedGroups are not supported: {}. Use default: {}.", Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)), Arrays.toString(DEFAULT_NAMED_GROUPS)); } else { String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); if (unsupportedNamedGroups.isEmpty()) { logger.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ", Arrays.toString(groupArray)); } else { logger.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ", Arrays.toString(groupArray), Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS))); } namedGroups = supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); } } else { namedGroups = defaultConvertedNamedGroups; } } finally { SSLContext.free(sslCtx); } } catch (Exception e) { logger.warn("Failed to get the list of available OpenSSL cipher suites.", e); } NAMED_GROUPS = namedGroups; AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.unmodifiableSet(availableOpenSslCipherSuites); final Set<String> availableJavaCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() * 2); for (String cipher: AVAILABLE_OPENSSL_CIPHER_SUITES) { // Included converted but also openssl cipher name if (!isTLSv13Cipher(cipher)) { availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "TLS")); availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "SSL")); } else { // TLSv1.3 ciphers have the correct format. availableJavaCipherSuites.add(cipher); } } addIfSupported(availableJavaCipherSuites, defaultCiphers, DEFAULT_CIPHER_SUITES); addIfSupported(availableJavaCipherSuites, defaultCiphers, TLSV13_CIPHER_SUITES); // Also handle the extra supported ciphers as these will contain some more stuff on BoringSSL. addIfSupported(availableJavaCipherSuites, defaultCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, availableJavaCipherSuites); DEFAULT_CIPHERS = Collections.unmodifiableList(defaultCiphers); AVAILABLE_JAVA_CIPHER_SUITES = Collections.unmodifiableSet(availableJavaCipherSuites); final Set<String> availableCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() + AVAILABLE_JAVA_CIPHER_SUITES.size()); availableCipherSuites.addAll(AVAILABLE_OPENSSL_CIPHER_SUITES); availableCipherSuites.addAll(AVAILABLE_JAVA_CIPHER_SUITES); AVAILABLE_CIPHER_SUITES = availableCipherSuites; SUPPORTS_KEYMANAGER_FACTORY = supportsKeyManagerFactory; USE_KEYMANAGER_FACTORY = useKeyManagerFactory; Set<String> protocols = new LinkedHashSet<String>(6); // Seems like there is no way to explicitly disable SSLv2Hello in openssl so it is always enabled protocols.add(SslProtocols.SSL_v2_HELLO); if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV2, SSL.SSL_OP_NO_SSLv2)) { protocols.add(SslProtocols.SSL_v2); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV3, SSL.SSL_OP_NO_SSLv3)) { protocols.add(SslProtocols.SSL_v3); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_OP_NO_TLSv1)) { protocols.add(SslProtocols.TLS_v1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_1, SSL.SSL_OP_NO_TLSv1_1)) { protocols.add(SslProtocols.TLS_v1_1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_OP_NO_TLSv1_2)) { protocols.add(SslProtocols.TLS_v1_2); } // This is only supported by java8u272 and later. if (tlsv13Supported && doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_3, SSL.SSL_OP_NO_TLSv1_3)) { protocols.add(SslProtocols.TLS_v1_3); TLSV13_SUPPORTED = true; } else { TLSV13_SUPPORTED = false; } SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(protocols); SUPPORTS_OCSP = doesSupportOcsp(); if (logger.isDebugEnabled()) { logger.debug("Supported protocols (OpenSSL): {} ", SUPPORTED_PROTOCOLS_SET); logger.debug("Default cipher suites (OpenSSL): {}", DEFAULT_CIPHERS); } // Check if we can create a javax.security.cert.X509Certificate from our cert. This might fail on // JDK17 and above. In this case we will later throw an UnsupportedOperationException if someone // tries to access these via SSLSession. See https://github.com/netty/netty/issues/13560. boolean javaxCertificateCreationSupported; try { javax.security.cert.X509Certificate.getInstance(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)); javaxCertificateCreationSupported = true; } catch (javax.security.cert.CertificateException ex) { javaxCertificateCreationSupported = false; } JAVAX_CERTIFICATE_CREATION_SUPPORTED = javaxCertificateCreationSupported; } else { DEFAULT_CIPHERS = Collections.emptyList(); AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_CIPHER_SUITES = Collections.emptySet(); SUPPORTS_KEYMANAGER_FACTORY = false; USE_KEYMANAGER_FACTORY = false; SUPPORTED_PROTOCOLS_SET = Collections.emptySet(); SUPPORTS_OCSP = false; TLSV13_SUPPORTED = false; IS_BORINGSSL = false; EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; NAMED_GROUPS = DEFAULT_NAMED_GROUPS; JAVAX_CERTIFICATE_CREATION_SUPPORTED = false; } } static String checkTls13Ciphers(InternalLogger logger, String ciphers) { if (IS_BORINGSSL && !ciphers.isEmpty()) { assert EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length > 0; Set<String> boringsslTlsv13Ciphers = new HashSet<String>(EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length); Collections.addAll(boringsslTlsv13Ciphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); boolean ciphersNotMatch = false; for (String cipher: ciphers.split(":")) { if (boringsslTlsv13Ciphers.isEmpty()) { ciphersNotMatch = true; break; } if (!boringsslTlsv13Ciphers.remove(cipher) && !boringsslTlsv13Ciphers.remove(CipherSuiteConverter.toJava(cipher, "TLS"))) { ciphersNotMatch = true; break; } } // Also check if there are ciphers left. ciphersNotMatch |= !boringsslTlsv13Ciphers.isEmpty(); if (ciphersNotMatch) { if (logger.isInfoEnabled()) { StringBuilder javaCiphers = new StringBuilder(128); for (String cipher : ciphers.split(":")) { javaCiphers.append(CipherSuiteConverter.toJava(cipher, "TLS")).append(":"); } javaCiphers.setLength(javaCiphers.length() - 1); logger.info( "BoringSSL doesn't allow to enable or disable TLSv1.3 ciphers explicitly." + " Provided TLSv1.3 ciphers: '{}', default TLSv1.3 ciphers that will be used: '{}'.", javaCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING); } return EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; } } return ciphers; } static boolean isSessionCacheSupported() { return version() >= 0x10100000L; } /** * Returns a self-signed {@link X509Certificate} for {@code netty.io}. */ static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)) ); } private static boolean doesSupportOcsp() { boolean supportsOcsp = false; if (version() >= 0x10002000L) { long sslCtx = -1; try { sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_MODE_SERVER); SSLContext.enableOcsp(sslCtx, false); supportsOcsp = true; } catch (Exception ignore) { // ignore } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } return supportsOcsp; } private static boolean doesSupportProtocol(int protocol, int opt) { if (opt == 0) { // If the opt is 0 the protocol is not supported. This is for example the case with BoringSSL and SSLv2. return false; } long sslCtx = -1; try { sslCtx = SSLContext.make(protocol, SSL.SSL_MODE_COMBINED); return true; } catch (Exception ignore) { return false; } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } /** * Returns {@code true} if and only if * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public static boolean isAvailable() { return UNAVAILABILITY_CAUSE == null; } /** * Returns {@code true} if the used version of openssl supports * <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>. * * @deprecated use {@link SslProvider#isAlpnSupported(SslProvider)} with {@link SslProvider#OPENSSL}. */ @Deprecated public static boolean isAlpnSupported() { return version() >= 0x10002000L; } /** * Returns {@code true} if the used version of OpenSSL supports OCSP stapling. */ public static boolean isOcspSupported() { return SUPPORTS_OCSP; } /** * Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()} * returns {@code false}. */ public static int version() { return isAvailable() ? SSL.version() : -1; } /** * Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()} * returns {@code false}. */ public static String versionString() { return isAvailable() ? SSL.versionString() : null; } /** * Ensure that <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and * its OpenSSL support are available. * * @throws UnsatisfiedLinkError if unavailable */ public static void ensureAvailability() { if (UNAVAILABILITY_CAUSE != null) { throw (Error) new UnsatisfiedLinkError( "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE); } } /** * Returns the cause of unavailability of * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support. * * @return the cause if unavailable. {@code null} if available. */ public static Throwable unavailabilityCause() { return UNAVAILABILITY_CAUSE; } /** * @deprecated use {@link #availableOpenSslCipherSuites()} */ @Deprecated public static Set<String> availableCipherSuites() { return availableOpenSslCipherSuites(); } /** * Returns all the available OpenSSL cipher suites. * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableOpenSslCipherSuites() { return AVAILABLE_OPENSSL_CIPHER_SUITES; } /** * Returns all the available cipher suites (Java-style). * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableJavaCipherSuites() { return AVAILABLE_JAVA_CIPHER_SUITES; } /** * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL. * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted. */ public static boolean isCipherSuiteAvailable(String cipherSuite) { String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL); if (converted != null) { cipherSuite = converted; } return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite); } /** * Returns {@code true} if {@link javax.net.ssl.KeyManagerFactory} is supported when using OpenSSL. */ public static boolean supportsKeyManagerFactory() { return SUPPORTS_KEYMANAGER_FACTORY; } /** * Always returns {@code true} if {@link #isAvailable()} returns {@code true}. * * @deprecated Will be removed because hostname validation is always done by a * {@link javax.net.ssl.TrustManager} implementation. */ @Deprecated public static boolean supportsHostnameValidation() { return isAvailable(); } static boolean useKeyManagerFactory() { return USE_KEYMANAGER_FACTORY; } static long memoryAddress(ByteBuf buf) { assert buf.isDirect(); return buf.hasMemoryAddress() ? buf.memoryAddress() : // Use internalNioBuffer to reduce object creation. Buffer.address(buf.internalNioBuffer(0, buf.readableBytes())); } private OpenSsl() { } private static void loadTcNative() throws Exception { String os = PlatformDependent.normalizedOs(); String arch = PlatformDependent.normalizedArch(); Set<String> libNames = new LinkedHashSet<String>(5); String staticLibName = "netty_tcnative"; // First, try loading the platform-specific library. Platform-specific // libraries will be available if using a tcnative uber jar. if ("linux".equals(os)) { Set<String> classifiers = PlatformDependent.normalizedLinuxClassifiers(); for (String classifier : classifiers) { libNames.add(staticLibName + "_" + os + '_' + arch + "_" + classifier); } // generic arch-dependent library libNames.add(staticLibName + "_" + os + '_' + arch); // Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0). // note: should already be included from the classifiers but if not, we use this as an // additional fallback option here libNames.add(staticLibName + "_" + os + '_' + arch + "_fedora"); } else { libNames.add(staticLibName + "_" + os + '_' + arch); } libNames.add(staticLibName + "_" + arch); libNames.add(staticLibName); NativeLibraryLoader.loadFirstAvailable(PlatformDependent.getClassLoader(SSLContext.class), libNames.toArray(EmptyArrays.EMPTY_STRINGS)); } private static boolean initializeTcNative(String engine) throws Exception { return Library.initialize("provided", engine); } static void releaseIfNeeded(ReferenceCounted counted) { if (counted.refCnt() > 0) { ReferenceCountUtil.safeRelease(counted); } } static boolean isTlsv13Supported() { return TLSV13_SUPPORTED; } static boolean isOptionSupported(SslContextOption<?> option) { if (isAvailable()) { if (option == OpenSslContextOption.USE_TASKS) { return true; } // Check for options that are only supported by BoringSSL atm. if (isBoringSSL()) { return option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD || option == OpenSslContextOption.PRIVATE_KEY_METHOD || option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS || option == OpenSslContextOption.TLS_FALSE_START || option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES; } } return false; } private static Set<String> defaultProtocols(String property) { String protocolsString = SystemPropertyUtil.get(property, null); Set<String> protocols = new HashSet<String>(); if (protocolsString != null) { for (String proto : protocolsString.split(",")) { String p = proto.trim(); protocols.add(p); } } else { protocols.add(SslProtocols.TLS_v1_2); protocols.add(SslProtocols.TLS_v1_3); } return protocols; } static String[] defaultProtocols(boolean isClient) { final Collection<String> defaultProtocols = isClient ? CLIENT_DEFAULT_PROTOCOLS : SERVER_DEFAULT_PROTOCOLS; assert defaultProtocols != null; List<String> protocols = new ArrayList<String>(defaultProtocols.size()); for (String proto : defaultProtocols) { if (SUPPORTED_PROTOCOLS_SET.contains(proto)) { protocols.add(proto); } } return protocols.toArray(EmptyArrays.EMPTY_STRINGS); } static boolean isBoringSSL() { return IS_BORINGSSL; } }
netty/netty
handler/src/main/java/io/netty/handler/ssl/OpenSsl.java
29
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.openqa.selenium.internal.Require; public class MutableCapabilities implements Capabilities { private static final Set<String> OPTION_KEYS; static { HashSet<String> keys = new HashSet<>(); keys.add("goog:chromeOptions"); keys.add("ms:edgeOptions"); keys.add("moz:firefoxOptions"); keys.add("se:ieOptions"); OPTION_KEYS = Collections.unmodifiableSet(keys); } private final Map<String, Object> caps = new TreeMap<>(); public MutableCapabilities() { // no-arg constructor } public MutableCapabilities(Capabilities other) { this(other.asMap()); } public MutableCapabilities(Map<String, ?> capabilities) { capabilities.forEach( (key, value) -> { if (value != null) { setCapability(key, value); } }); } /** * Merge two {@link Capabilities} together and return the union of the two as a new {@link * Capabilities} instance. Capabilities from {@code other} will override those in {@code this}. */ @Override public MutableCapabilities merge(Capabilities other) { MutableCapabilities newInstance = new MutableCapabilities(this); if (other != null) { other.asMap().forEach(newInstance::setCapability); } return newInstance; } public void setCapability(String capabilityName, boolean value) { setCapability(capabilityName, (Object) value); } public void setCapability(String capabilityName, String value) { setCapability(capabilityName, (Object) value); } public void setCapability(String capabilityName, Platform value) { setCapability(capabilityName, (Object) value); } public void setCapability(String key, Object value) { Require.nonNull("Capability name", key); // We have to special-case some keys and values because of the popular idiom of calling // something like "capabilities.setCapability(SafariOptions.CAPABILITY, new SafariOptions());" // and this is no longer needed as options are capabilities. There will be a large amount of // legacy code that will always try and follow this pattern, however. if (OPTION_KEYS.contains(key) && value instanceof Capabilities) { ((Capabilities) value).asMap().forEach(this::setCapability); return; } if (value == null) { caps.remove(key); return; } SharedCapabilitiesMethods.setCapability(caps, key, value); } @Override public Map<String, Object> asMap() { return Collections.unmodifiableMap(caps); } @Override public Object getCapability(String capabilityName) { return caps.get(capabilityName); } @Override public Set<String> getCapabilityNames() { return Collections.unmodifiableSet(caps.keySet()); } public Map<String, Object> toJson() { return asMap(); } @Override public int hashCode() { return SharedCapabilitiesMethods.hashCode(this); } @Override public boolean equals(Object o) { if (!(o instanceof Capabilities)) { return false; } return SharedCapabilitiesMethods.equals(this, (Capabilities) o); } @Override public String toString() { return SharedCapabilitiesMethods.toString(this); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/MutableCapabilities.java
30
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.util.AttributeMap; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * A nexus to a network socket or a component which is capable of I/O * operations such as read, write, connect, and bind. * <p> * A channel provides a user: * <ul> * <li>the current state of the channel (e.g. is it open? is it connected?),</li> * <li>the {@linkplain ChannelConfig configuration parameters} of the channel (e.g. receive buffer size),</li> * <li>the I/O operations that the channel supports (e.g. read, write, connect, and bind), and</li> * <li>the {@link ChannelPipeline} which handles all I/O events and requests * associated with the channel.</li> * </ul> * * <h3>All I/O operations are asynchronous.</h3> * <p> * All I/O operations in Netty are asynchronous. It means any I/O calls will * return immediately with no guarantee that the requested I/O operation has * been completed at the end of the call. Instead, you will be returned with * a {@link ChannelFuture} instance which will notify you when the requested I/O * operation has succeeded, failed, or canceled. * * <h3>Channels are hierarchical</h3> * <p> * A {@link Channel} can have a {@linkplain #parent() parent} depending on * how it was created. For instance, a {@link SocketChannel}, that was accepted * by {@link ServerSocketChannel}, will return the {@link ServerSocketChannel} * as its parent on {@link #parent()}. * <p> * The semantics of the hierarchical structure depends on the transport * implementation where the {@link Channel} belongs to. For example, you could * write a new {@link Channel} implementation that creates the sub-channels that * share one socket connection, as <a href="http://beepcore.org/">BEEP</a> and * <a href="https://en.wikipedia.org/wiki/Secure_Shell">SSH</a> do. * * <h3>Downcast to access transport-specific operations</h3> * <p> * Some transports exposes additional operations that is specific to the * transport. Down-cast the {@link Channel} to sub-type to invoke such * operations. For example, with the old I/O datagram transport, multicast * join / leave operations are provided by {@link DatagramChannel}. * * <h3>Release resources</h3> * <p> * It is important to call {@link #close()} or {@link #close(ChannelPromise)} to release all * resources once you are done with the {@link Channel}. This ensures all resources are * released in a proper way, i.e. filehandles. */ public interface Channel extends AttributeMap, ChannelOutboundInvoker, Comparable<Channel> { /** * Returns the globally unique identifier of this {@link Channel}. */ ChannelId id(); /** * Return the {@link EventLoop} this {@link Channel} was registered to. */ EventLoop eventLoop(); /** * Returns the parent of this channel. * * @return the parent channel. * {@code null} if this channel does not have a parent channel. */ Channel parent(); /** * Returns the configuration of this channel. */ ChannelConfig config(); /** * Returns {@code true} if the {@link Channel} is open and may get active later */ boolean isOpen(); /** * Returns {@code true} if the {@link Channel} is registered with an {@link EventLoop}. */ boolean isRegistered(); /** * Return {@code true} if the {@link Channel} is active and so connected. */ boolean isActive(); /** * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature of the {@link Channel}. */ ChannelMetadata metadata(); /** * Returns the local address where this channel is bound to. The returned * {@link SocketAddress} is supposed to be down-cast into more concrete * type such as {@link InetSocketAddress} to retrieve the detailed * information. * * @return the local address of this channel. * {@code null} if this channel is not bound. */ SocketAddress localAddress(); /** * Returns the remote address where this channel is connected to. The * returned {@link SocketAddress} is supposed to be down-cast into more * concrete type such as {@link InetSocketAddress} to retrieve the detailed * information. * * @return the remote address of this channel. * {@code null} if this channel is not connected. * If this channel is not connected but it can receive messages * from arbitrary remote addresses (e.g. {@link DatagramChannel}, * use {@link DatagramPacket#recipient()} to determine * the origination of the received message as this method will * return {@code null}. */ SocketAddress remoteAddress(); /** * Returns the {@link ChannelFuture} which will be notified when this * channel is closed. This method always returns the same future instance. */ ChannelFuture closeFuture(); /** * Returns {@code true} if and only if the I/O thread will perform the * requested write operation immediately. Any write requests made when * this method returns {@code false} are queued until the I/O thread is * ready to process the queued write requests. * * {@link WriteBufferWaterMark} can be used to configure on which condition * the write buffer would cause this channel to change writability. */ boolean isWritable(); /** * Get how many bytes can be written until {@link #isWritable()} returns {@code false}. * This quantity will always be non-negative. If {@link #isWritable()} is {@code false} then 0. * * {@link WriteBufferWaterMark} can be used to define writability settings. */ long bytesBeforeUnwritable(); /** * Get how many bytes must be drained from underlying buffers until {@link #isWritable()} returns {@code true}. * This quantity will always be non-negative. If {@link #isWritable()} is {@code true} then 0. * * {@link WriteBufferWaterMark} can be used to define writability settings. */ long bytesBeforeWritable(); /** * Returns an <em>internal-use-only</em> object that provides unsafe operations. */ Unsafe unsafe(); /** * Return the assigned {@link ChannelPipeline}. */ ChannelPipeline pipeline(); /** * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s. */ ByteBufAllocator alloc(); @Override Channel read(); @Override Channel flush(); /** * <em>Unsafe</em> operations that should <em>never</em> be called from user-code. These methods * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the * following methods: * <ul> * <li>{@link #localAddress()}</li> * <li>{@link #remoteAddress()}</li> * <li>{@link #closeForcibly()}</li> * <li>{@link #register(EventLoop, ChannelPromise)}</li> * <li>{@link #deregister(ChannelPromise)}</li> * <li>{@link #voidPromise()}</li> * </ul> */ interface Unsafe { /** * Return the assigned {@link RecvByteBufAllocator.Handle} which will be used to allocate {@link ByteBuf}'s when * receiving data. */ RecvByteBufAllocator.Handle recvBufAllocHandle(); /** * Return the {@link SocketAddress} to which is bound local or * {@code null} if none. */ SocketAddress localAddress(); /** * Return the {@link SocketAddress} to which is bound remote or * {@code null} if none is bound yet. */ SocketAddress remoteAddress(); /** * Register the {@link Channel} of the {@link ChannelPromise} and notify * the {@link ChannelFuture} once the registration was complete. */ void register(EventLoop eventLoop, ChannelPromise promise); /** * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify * it once its done. */ void bind(SocketAddress localAddress, ChannelPromise promise); /** * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}. * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just * pass {@code null} to it. * * The {@link ChannelPromise} will get notified once the connect operation was complete. */ void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); /** * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the * operation was complete. */ void disconnect(ChannelPromise promise); /** * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the * operation was complete. */ void close(ChannelPromise promise); /** * Closes the {@link Channel} immediately without firing any events. Probably only useful * when registration attempt failed. */ void closeForcibly(); /** * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the * {@link ChannelPromise} once the operation was complete. */ void deregister(ChannelPromise promise); /** * Schedules a read operation that fills the inbound buffer of the first {@link ChannelInboundHandler} in the * {@link ChannelPipeline}. If there's already a pending read operation, this method does nothing. */ void beginRead(); /** * Schedules a write operation. */ void write(Object msg, ChannelPromise promise); /** * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}. */ void flush(); /** * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}. * It will never be notified of a success or error and so is only a placeholder for operations * that take a {@link ChannelPromise} as argument but for which you not want to get notified. */ ChannelPromise voidPromise(); /** * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored. */ ChannelOutboundBuffer outboundBuffer(); } }
netty/netty
transport/src/main/java/io/netty/channel/Channel.java
31
/* * The MIT License * * Copyright (c) 2008-2011, Sun Microsystems, Inc., Alan Harder, Jerome Lacoste, Kohsuke Kawaguchi, * bap2000, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package executable; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.MissingResourceException; import java.util.NavigableSet; import java.util.TreeSet; import java.util.UUID; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Launcher class for stand-alone execution of Jenkins as * {@code java -jar jenkins.war}. * * <p>On a high-level architectural note, this class is intended to be a very thin wrapper whose * primary purpose is to extract Winstone and delegate to Winstone's own initialization mechanism. * The logic in this class should only perform Jenkins-specific argument and environment validation * and Jenkins-specific Winstone customization prior to delegating to Winstone. * * <p>In particular, managing the logging subsystem is completely delegated to Winstone, and this * class should neither assume that logging has been initialized nor take advantage of the logging * subsystem. In the event that this class needs to print information to the user, it should do so * via the standard output (stdout) and standard error (stderr) streams rather than via the logging * subsystem. Such messages should generally be avoided except for fatal scenarios, such as an * inappropriate Java Virtual Machine (JVM) or some other serious failure that would preclude * starting Winstone. * * @author Kohsuke Kawaguchi */ public class Main { /** * This list must remain synchronized with the one in {@code * JavaVersionRecommendationAdminMonitor}. */ private static final NavigableSet<Integer> SUPPORTED_JAVA_VERSIONS = new TreeSet<>(List.of(11, 17, 21)); /** * Sets custom session cookie name. * It may be used to prevent randomization of JSESSIONID cookies and issues like * <a href="https://issues.jenkins-ci.org/browse/JENKINS-25046">JENKINS-25046</a>. * @since 2.66 */ private static final String JSESSIONID_COOKIE_NAME = System.getProperty("executableWar.jetty.sessionIdCookieName"); /** * Disables usage of the custom cookie names when starting the WAR file. * If the flag is specified, the session ID will be defined by the internal Jetty logic. * In such case it becomes configurable via * <a href="http://www.eclipse.org/jetty/documentation/9.4.x/jetty-xml-config.html">Jetty XML Config file</a>> * or via system properties. * @since 2.66 */ private static final boolean DISABLE_CUSTOM_JSESSIONID_COOKIE_NAME = Boolean.getBoolean("executableWar.jetty.disableCustomSessionIdCookieName"); /** * Flag to bypass the Java version check when starting. */ private static final String ENABLE_FUTURE_JAVA_CLI_SWITCH = "--enable-future-java"; /*package*/ static void verifyJavaVersion(int releaseVersion, boolean enableFutureJava) { if (SUPPORTED_JAVA_VERSIONS.contains(releaseVersion)) { // Great! } else if (releaseVersion >= SUPPORTED_JAVA_VERSIONS.first()) { if (enableFutureJava) { System.err.printf( "Running with Java %d from %s, which is not fully supported. " + "Continuing because %s is set. " + "Supported Java versions are: %s. " + "See https://jenkins.io/redirect/java-support/ for more information.%n", releaseVersion, System.getProperty("java.home"), ENABLE_FUTURE_JAVA_CLI_SWITCH, SUPPORTED_JAVA_VERSIONS); } else if (releaseVersion > SUPPORTED_JAVA_VERSIONS.last()) { throw new UnsupportedClassVersionError( String.format( "Running with Java %d from %s, which is not yet fully supported.%n" + "Run the command again with the %s flag to enable preview support for future Java versions.%n" + "Supported Java versions are: %s", releaseVersion, System.getProperty("java.home"), ENABLE_FUTURE_JAVA_CLI_SWITCH, SUPPORTED_JAVA_VERSIONS)); } else { throw new UnsupportedClassVersionError( String.format( "Running with Java %d from %s, which is not fully supported.%n" + "Run the command again with the %s flag to bypass this error.%n" + "Supported Java versions are: %s", releaseVersion, System.getProperty("java.home"), ENABLE_FUTURE_JAVA_CLI_SWITCH, SUPPORTED_JAVA_VERSIONS)); } } else { throw new UnsupportedClassVersionError( String.format( "Running with Java %d from %s, which is older than the minimum required version (Java %d).%n" + "Supported Java versions are: %s", releaseVersion, System.getProperty("java.home"), SUPPORTED_JAVA_VERSIONS.first(), SUPPORTED_JAVA_VERSIONS)); } } /** * Returns true if the Java runtime version check should not be done, and any version allowed. * * @see #ENABLE_FUTURE_JAVA_CLI_SWITCH */ private static boolean isFutureJavaEnabled(String[] args) { return hasArgument(ENABLE_FUTURE_JAVA_CLI_SWITCH, args) || Boolean.parseBoolean(System.getenv("JENKINS_ENABLE_FUTURE_JAVA")); } // TODO: Rework everything to use List private static boolean hasArgument(@NonNull String argument, @NonNull String[] args) { for (String arg : args) { if (argument.equals(arg)) { return true; } } return false; } @SuppressFBWarnings( value = "PATH_TRAVERSAL_IN", justification = "User provided values for running the program") public static void main(String[] args) throws IllegalAccessException { try { verifyJavaVersion(Runtime.version().feature(), isFutureJavaEnabled(args)); } catch (UnsupportedClassVersionError e) { System.err.println(e.getMessage()); System.err.println("See https://jenkins.io/redirect/java-support/ for more information."); System.exit(1); } //Allows to pass arguments through stdin to "hide" sensitive parameters like httpsKeyStorePassword //to achieve this use --paramsFromStdIn if (hasArgument("--paramsFromStdIn", args)) { System.out.println("--paramsFromStdIn detected. Parameters are going to be read from stdin. Other parameters passed directly will be ignored."); String argsInStdIn; try { argsInStdIn = new String(System.in.readNBytes(131072), StandardCharsets.UTF_8).trim(); } catch (IOException e) { throw new UncheckedIOException(e); } args = argsInStdIn.split(" +"); } // If someone just wants to know the version, print it out as soon as possible, with no extraneous file or webroot info. // This makes it easier to grab the version from a script final List<String> arguments = new ArrayList<>(List.of(args)); if (arguments.contains("--version")) { System.out.println(getVersion("?")); return; } File extractedFilesFolder = null; for (String arg : args) { if (arg.startsWith("--extractedFilesFolder=")) { extractedFilesFolder = new File(arg.substring("--extractedFilesFolder=".length())); if (!extractedFilesFolder.isDirectory()) { System.err.println("The extractedFilesFolder value is not a directory. Ignoring."); extractedFilesFolder = null; } } } for (String arg : args) { if (arg.startsWith("--pluginroot=")) { System.setProperty("hudson.PluginManager.workDir", new File(arg.substring("--pluginroot=".length())).getAbsolutePath()); // if specified multiple times, the first one wins break; } } // this is so that JFreeChart can work nicely even if we are launched as a daemon System.setProperty("java.awt.headless", "true"); File me = whoAmI(extractedFilesFolder); System.out.println("Running from: " + me); System.setProperty("executable-war", me.getAbsolutePath()); // remember the location so that we can access it from within webapp // figure out the arguments trimOffOurOptions(arguments); arguments.add(0, "--warfile=" + me.getAbsolutePath()); if (!hasOption(arguments, "--webroot=")) { // defaults to ~/.jenkins/war since many users reported that cron job attempts to clean up // the contents in the temporary directory. final File jenkinsHome = getJenkinsHome(); final File webRoot = new File(jenkinsHome, "war"); System.out.println("webroot: " + webRoot); arguments.add("--webroot=" + webRoot); } // only do a cleanup if you set the extractedFilesFolder property. if (extractedFilesFolder != null) { deleteContentsFromFolder(extractedFilesFolder, "winstone.*\\.jar"); } // put winstone jar in a file system so that we can load jars from there File tmpJar = extractFromJar("winstone.jar", "winstone", ".jar", extractedFilesFolder); tmpJar.deleteOnExit(); // clean up any previously extracted copy, since // winstone doesn't do so and that causes problems when newer version of Jenkins // is deployed. File tempFile; try { tempFile = File.createTempFile("dummy", "dummy"); } catch (IOException e) { throw new UncheckedIOException(e); } deleteWinstoneTempContents(new File(tempFile.getParent(), "winstone/" + me.getName())); if (!tempFile.delete()) { System.err.println("Failed to delete temporary file: " + tempFile); } // locate the Winstone launcher ClassLoader cl; try { cl = new URLClassLoader(new URL[] {tmpJar.toURI().toURL()}); } catch (MalformedURLException e) { throw new UncheckedIOException(e); } Class<?> launcher; Method mainMethod; try { launcher = cl.loadClass("winstone.Launcher"); mainMethod = launcher.getMethod("main", String[].class); } catch (ClassNotFoundException | NoSuchMethodException e) { throw new AssertionError(e); } // override the usage screen Field usage; try { usage = launcher.getField("USAGE"); } catch (NoSuchFieldException e) { throw new AssertionError(e); } usage.set(null, "Jenkins Automation Server Engine " + getVersion("") + "\n" + "Usage: java -jar jenkins.war [--option=value] [--option=value]\n" + "\n" + "Options:\n" + " --webroot = folder where the WAR file is expanded into. Default is ${JENKINS_HOME}/war\n" + " --pluginroot = folder where the plugin archives are expanded into. Default is ${JENKINS_HOME}/plugins\n" + " (NOTE: this option does not change the directory where the plugin archives are stored)\n" + " --extractedFilesFolder = folder where extracted files are to be located. Default is the temp folder\n" + " " + ENABLE_FUTURE_JAVA_CLI_SWITCH + " = allows running with Java versions which are not fully supported\n" + " --paramsFromStdIn = Read parameters from standard input (stdin)\n" + " --version = Print version to standard output (stdout) and exit\n" + "{OPTIONS}"); if (!DISABLE_CUSTOM_JSESSIONID_COOKIE_NAME) { /* Set an unique cookie name. As can be seen in discussions like http://stackoverflow.com/questions/1146112/jsessionid-collision-between-two-servers-on-same-ip-but-different-ports and http://stackoverflow.com/questions/1612177/are-http-cookies-port-specific, RFC 2965 says cookies from one port of one host may be sent to a different port of the same host. This means if someone runs multiple Jenkins on different ports of the same host, their sessions get mixed up. To fix the problem, use unique session cookie name. This change breaks the cluster mode of Winstone, as all nodes in the cluster must share the same session cookie name. Jenkins doesn't support clustered operation anyway, so we need to do this here, and not in Winstone. */ try { Field f = cl.loadClass("winstone.WinstoneSession").getField("SESSION_COOKIE_NAME"); f.setAccessible(true); if (JSESSIONID_COOKIE_NAME != null) { // Use the user-defined cookie name f.set(null, JSESSIONID_COOKIE_NAME); } else { // Randomize session names by default to prevent collisions when running multiple Jenkins instances on the same host. f.set(null, "JSESSIONID." + UUID.randomUUID().toString().replace("-", "").substring(0, 8)); } } catch (ClassNotFoundException | NoSuchFieldException e) { throw new AssertionError(e); } } // run Thread.currentThread().setContextClassLoader(cl); try { mainMethod.invoke(null, new Object[] {arguments.toArray(new String[0])}); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof IOException) { throw new UncheckedIOException((IOException) t); } else if (t instanceof Exception) { throw new RuntimeException(t); } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(e); } } } private static void trimOffOurOptions(List<String> arguments) { arguments.removeIf(arg -> arg.startsWith("--extractedFilesFolder") || arg.startsWith("--pluginroot") || arg.startsWith(ENABLE_FUTURE_JAVA_CLI_SWITCH)); } /** * Figures out the version from the manifest. */ private static String getVersion(String fallback) { try { Enumeration<URL> manifests = Main.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL res = manifests.nextElement(); Manifest manifest = new Manifest(res.openStream()); String v = manifest.getMainAttributes().getValue("Jenkins-Version"); if (v != null) { return v; } } } catch (IOException e) { throw new UncheckedIOException(e); } return fallback; } private static boolean hasOption(List<String> args, String prefix) { for (String s : args) { if (s.startsWith(prefix)) { return true; } } return false; } /** * Figures out the URL of {@code jenkins.war}. */ @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") public static File whoAmI(File directory) { // JNLP returns the URL where the jar was originally placed (like http://jenkins-ci.org/...) // not the local cached file. So we need a rather round about approach to get to // the local file name. // There is no portable way to find where the locally cached copy // of jenkins.war/jar is; JDK 6 is too smart. (See JENKINS-2326.) try { URL classFile = Main.class.getClassLoader().getResource("executable/Main.class"); JarFile jf = ((JarURLConnection) classFile.openConnection()).getJarFile(); return new File(jf.getName()); } catch (Exception x) { System.err.println("ZipFile.name trick did not work, using fallback: " + x); } File myself; try { myself = File.createTempFile("jenkins", ".jar", directory); } catch (IOException e) { throw new UncheckedIOException(e); } myself.deleteOnExit(); try (InputStream is = Main.class.getProtectionDomain().getCodeSource().getLocation().openStream(); OutputStream os = new FileOutputStream(myself)) { is.transferTo(os); } catch (IOException e) { throw new UncheckedIOException(e); } return myself; } /** * Extract a resource from jar, mark it for deletion upon exit, and return its location. */ @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "User provided values for running the program.") private static File extractFromJar(String resource, String fileName, String suffix, File directory) { URL res = Main.class.getResource(resource); if (res == null) { throw new MissingResourceException("Unable to find the resource: " + resource, Main.class.getName(), resource); } // put this jar in a file system so that we can load jars from there File tmp; try { tmp = File.createTempFile(fileName, suffix, directory); } catch (IOException e) { String tmpdir = directory == null ? System.getProperty("java.io.tmpdir") : directory.getAbsolutePath(); throw new UncheckedIOException("Jenkins failed to create a temporary file in " + tmpdir + ": " + e, e); } try (InputStream is = res.openStream(); OutputStream os = new FileOutputStream(tmp)) { is.transferTo(os); } catch (IOException e) { throw new UncheckedIOException(e); } tmp.deleteOnExit(); return tmp; } /** * Search contents to delete in a folder that match with some patterns. * * @param folder folder where the contents are. * @param patterns patterns that identifies the contents to search. */ private static void deleteContentsFromFolder(File folder, final String... patterns) { File[] files = folder.listFiles(); if (files != null) { for (File file : files) { for (String pattern : patterns) { if (file.getName().matches(pattern)) { deleteWinstoneTempContents(file); } } } } } private static void deleteWinstoneTempContents(File file) { if (!file.exists()) { return; } if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { // be defensive for (File value : files) { deleteWinstoneTempContents(value); } } } if (!file.delete()) { System.err.println("Failed to delete temporary Winstone file: " + file); } } /** * Determines the home directory for Jenkins. * <p> * People makes configuration mistakes, so we are trying to be nice * with those by doing {@link String#trim()}. */ @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "User provided values for running the program.") private static File getJenkinsHome() { // check the system property for the home directory first for (String name : HOME_NAMES) { String sysProp = System.getProperty(name); if (sysProp != null) { return new File(sysProp.trim()); } } // look at the env var next for (String name : HOME_NAMES) { String env = System.getenv(name); if (env != null) { return new File(env.trim()); } } // otherwise pick a place by ourselves File legacyHome = new File(new File(System.getProperty("user.home")), ".hudson"); if (legacyHome.exists()) { return legacyHome; // before rename, this is where it was stored } return new File(new File(System.getProperty("user.home")), ".jenkins"); } private static final String[] HOME_NAMES = {"JENKINS_HOME", "HUDSON_HOME"}; }
jenkinsci/jenkins
war/src/main/java/executable/Main.java
32
/* * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.rxjava3.core; import java.util.*; import java.util.concurrent.*; import java.util.stream.*; import org.reactivestreams.*; import io.reactivex.rxjava3.annotations.*; import io.reactivex.rxjava3.disposables.*; import io.reactivex.rxjava3.exceptions.*; import io.reactivex.rxjava3.functions.*; import io.reactivex.rxjava3.internal.functions.*; import io.reactivex.rxjava3.internal.fuseable.*; import io.reactivex.rxjava3.internal.jdk8.*; import io.reactivex.rxjava3.internal.observers.*; import io.reactivex.rxjava3.internal.operators.flowable.*; import io.reactivex.rxjava3.internal.operators.maybe.*; import io.reactivex.rxjava3.internal.operators.mixed.*; import io.reactivex.rxjava3.internal.operators.observable.ObservableElementAtMaybe; import io.reactivex.rxjava3.internal.util.ErrorMode; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import io.reactivex.rxjava3.schedulers.*; /** * The {@code Maybe} class represents a deferred computation and emission of a single value, no value at all or an exception. * <p> * The {@code Maybe} class implements the {@link MaybeSource} base interface and the default consumer * type it interacts with is the {@link MaybeObserver} via the {@link #subscribe(MaybeObserver)} method. * <p> * The {@code Maybe} operates with the following sequential protocol: * <pre><code> * onSubscribe (onSuccess | onError | onComplete)? * </code></pre> * <p> * Note that {@code onSuccess}, {@code onError} and {@code onComplete} are mutually exclusive events; unlike {@link Observable}, * {@code onSuccess} is never followed by {@code onError} or {@code onComplete}. * <p> * Like {@code Observable}, a running {@code Maybe} can be stopped through the {@link Disposable} instance * provided to consumers through {@link MaybeObserver#onSubscribe}. * <p> * Like an {@code Observable}, a {@code Maybe} is lazy, can be either "hot" or "cold", synchronous or * asynchronous. {@code Maybe} instances returned by the methods of this class are <em>cold</em> * and there is a standard <em>hot</em> implementation in the form of a subject: * {@link io.reactivex.rxjava3.subjects.MaybeSubject MaybeSubject}. * <p> * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/maybe.png" alt=""> * <p> * See {@link Flowable} or {@code Observable} for the * implementation of the Reactive Pattern for a stream or vector of values. * <p> * Example: * <pre><code> * Disposable d = Maybe.just("Hello World") * .delay(10, TimeUnit.SECONDS, Schedulers.io()) * .subscribeWith(new DisposableMaybeObserver&lt;String&gt;() { * &#64;Override * public void onStart() { * System.out.println("Started"); * } * * &#64;Override * public void onSuccess(String value) { * System.out.println("Success: " + value); * } * * &#64;Override * public void onError(Throwable error) { * error.printStackTrace(); * } * * &#64;Override * public void onComplete() { * System.out.println("Done!"); * } * }); * * Thread.sleep(5000); * * d.dispose(); * </code></pre> * <p> * Note that by design, subscriptions via {@link #subscribe(MaybeObserver)} can't be disposed * from the outside (hence the * {@code void} return of the {@link #subscribe(MaybeObserver)} method) and it is the * responsibility of the implementor of the {@code MaybeObserver} to allow this to happen. * RxJava supports such usage with the standard * {@link io.reactivex.rxjava3.observers.DisposableMaybeObserver DisposableMaybeObserver} instance. * For convenience, the {@link #subscribeWith(MaybeObserver)} method is provided as well to * allow working with a {@code MaybeObserver} (or subclass) instance to be applied with in * a fluent manner (such as in the example above). * * @param <T> the value type * @since 2.0 * @see io.reactivex.rxjava3.observers.DisposableMaybeObserver */ public abstract class Maybe<@NonNull T> implements MaybeSource<T> { /** * Runs multiple {@link MaybeSource}s provided by an {@link Iterable} sequence and * signals the events of the first one that signals (disposing the rest). * <p> * <img width="640" height="518" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources the {@code Iterable} sequence of sources. A subscription to each source will * occur in the same order as in the {@code Iterable}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code sources} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> amb(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new MaybeAmb<>(null, sources)); } /** * Runs multiple {@link MaybeSource}s and signals the events of the first one that signals (disposing * the rest). * <p> * <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ambArray.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources the array of sources. A subscription to each source will * occur in the same order as in the array. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code sources} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Maybe<T> ambArray(@NonNull MaybeSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return empty(); } if (sources.length == 1) { @SuppressWarnings("unchecked") MaybeSource<T> source = (MaybeSource<T>)sources[0]; return wrap(source); } return RxJavaPlugins.onAssembly(new MaybeAmb<>(sources, null)); } /** * Concatenate the single values, in a non-overlapping fashion, of the {@link MaybeSource} sources provided by * an {@link Iterable} sequence as a {@link Flowable} sequence. * <p> * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources the {@code Iterable} sequence of {@code MaybeSource} instances * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> concat(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new MaybeConcatIterable<>(sources)); } /** * Returns a {@link Flowable} that emits the items emitted by two {@link MaybeSource}s, one after the other. * <p> * <img width="640" height="423" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common value type * @param source1 * a {@code MaybeSource} to be concatenated * @param source2 * a {@code MaybeSource} to be concatenated * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> concat(@NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); return concatArray(source1, source2); } /** * Returns a {@link Flowable} that emits the items emitted by three {@link MaybeSource}s, one after the other. * <p> * <img width="640" height="423" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common value type * @param source1 * a {@code MaybeSource} to be concatenated * @param source2 * a {@code MaybeSource} to be concatenated * @param source3 * a {@code MaybeSource} to be concatenated * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code source3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> concat( @NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull MaybeSource<? extends T> source3) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); return concatArray(source1, source2, source3); } /** * Returns a {@link Flowable} that emits the items emitted by four {@link MaybeSource}s, one after the other. * <p> * <img width="640" height="423" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common value type * @param source1 * a {@code MaybeSource} to be concatenated * @param source2 * a {@code MaybeSource} to be concatenated * @param source3 * a {@code MaybeSource} to be concatenated * @param source4 * a {@code MaybeSource} to be concatenated * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code source4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> concat( @NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull MaybeSource<? extends T> source3, @NonNull MaybeSource<? extends T> source4) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); return concatArray(source1, source2, source3, source4); } /** * Concatenate the single values, in a non-overlapping fashion, of the {@link MaybeSource} sources provided by * a {@link Publisher} sequence as a {@link Flowable} sequence. * <p> * <img width="640" height="416" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer and * expects the {@code Publisher} to honor backpressure as well. If the sources {@code Publisher} * violates this, a {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException} is signaled.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources the {@code Publisher} of {@code MaybeSource} instances * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concat(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { return concat(sources, 2); } /** * Concatenate the single values, in a non-overlapping fashion, of the {@link MaybeSource} sources provided by * a {@link Publisher} sequence as a {@link Flowable} sequence. * <p> * <img width="640" height="416" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer and * expects the {@code Publisher} to honor backpressure as well. If the sources {@code Publisher} * violates this, a {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException} is signaled.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources the {@code Publisher} of {@code MaybeSource} instances * @param prefetch the number of {@code MaybeSource}s to prefetch from the {@code Publisher} * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code prefetch} is non-positive * @return the new {@code Flowable} instance */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> concat(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int prefetch) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new FlowableConcatMapMaybePublisher<>(sources, Functions.identity(), ErrorMode.IMMEDIATE, prefetch)); } /** * Concatenate the single values, in a non-overlapping fashion, of the {@link MaybeSource} sources in the array * as a {@link Flowable} sequence. * <p> * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArray.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources the array of {@code MaybeSource} instances * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs public static <@NonNull T> Flowable<T> concatArray(@NonNull MaybeSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return Flowable.empty(); } if (sources.length == 1) { @SuppressWarnings("unchecked") MaybeSource<T> source = (MaybeSource<T>)sources[0]; return RxJavaPlugins.onAssembly(new MaybeToFlowable<>(source)); } return RxJavaPlugins.onAssembly(new MaybeConcatArray<>(sources)); } /** * Concatenates a variable number of {@link MaybeSource} sources and delays errors from any of them * till all terminate as a {@link Flowable} sequence. * <p> * <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayDelayError.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param sources the array of sources * @param <T> the common base value type * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs @NonNull public static <@NonNull T> Flowable<T> concatArrayDelayError(@NonNull MaybeSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return Flowable.empty(); } else if (sources.length == 1) { @SuppressWarnings("unchecked") MaybeSource<T> source = (MaybeSource<T>)sources[0]; return RxJavaPlugins.onAssembly(new MaybeToFlowable<>(source)); } return RxJavaPlugins.onAssembly(new MaybeConcatArrayDelayError<>(sources)); } /** * Concatenates a sequence of {@link MaybeSource} eagerly into a {@link Flowable} sequence. * <p> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the * source {@code MaybeSource}s. The operator buffers the value emitted by these {@code MaybeSource}s and then drains them * in order, each one after the previous one completes. * <p> * <img width="640" height="490" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayEager.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Flowable<T> concatArrayEager(@NonNull MaybeSource<? extends T>... sources) { return Flowable.fromArray(sources).concatMapEager((Function)MaybeToPublisher.instance()); } /** * Concatenates a sequence of {@link MaybeSource} eagerly into a {@link Flowable} sequence. * <p> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the * source {@code MaybeSource}s. The operator buffers the value emitted by these {@code MaybeSource}s and then drains them * in order, each one after the previous one completes. * <p> * <img width="640" height="428" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayEagerDelayError.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Flowable<T> concatArrayEagerDelayError(@NonNull MaybeSource<? extends T>... sources) { return Flowable.fromArray(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), true); } /** * Concatenates the {@link Iterable} sequence of {@link MaybeSource}s into a single sequence by subscribing to each {@code MaybeSource}, * one after the other, one at a time and delays any errors till the all inner {@code MaybeSource}s terminate * as a {@link Flowable} sequence. * <p> * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError3.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources the {@code Iterable} sequence of {@code MaybeSource}s * @return the new {@code Flowable} with the concatenating behavior * @throws NullPointerException if {@code sources} is {@code null} */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> concatDelayError(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromIterable(sources).concatMapMaybeDelayError(Functions.identity()); } /** * Concatenates the {@link Publisher} sequence of {@link MaybeSource}s into a single sequence by subscribing to each inner {@code MaybeSource}, * one after the other, one at a time and delays any errors till the all inner and the outer {@code Publisher} terminate * as a {@link Flowable} sequence. * <p> * <img width="640" height="360" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>{@code concatDelayError} fully supports backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources the {@code Publisher} sequence of {@code MaybeSource}s * @return the new {@code Flowable} with the concatenating behavior * @throws NullPointerException if {@code sources} is {@code null} */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromPublisher(sources).concatMapMaybeDelayError(Functions.identity()); } /** * Concatenates the {@link Publisher} sequence of {@link MaybeSource}s into a single sequence by subscribing to each inner {@code MaybeSource}, * one after the other, one at a time and delays any errors till the all inner and the outer {@code Publisher} terminate * as a {@link Flowable} sequence. * <p> * <img width="640" height="299" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>{@code concatDelayError} fully supports backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources the {@code Publisher} sequence of {@code MaybeSource}s * @param prefetch The number of upstream items to prefetch so that fresh items are * ready to be mapped when a previous {@code MaybeSource} terminates. * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code MaybeSource}s. * @return the new {@code Flowable} with the concatenating behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code prefetch} is non-positive * @since 3.0.0 */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int prefetch) { return Flowable.fromPublisher(sources).concatMapMaybeDelayError(Functions.identity(), true, prefetch); } /** * Concatenates a sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence. * <p> * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.i.png" alt=""> * <p> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the * source {@code MaybeSource}s. The operator buffers the values emitted by these {@code MaybeSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource} that need to be eagerly concatenated * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEager(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromIterable(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), false); } /** * Concatenates a sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence and * runs a limited number of the inner sequences at once. * <p> * <img width="640" height="439" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.in.png" alt=""> * <p> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the * source {@code MaybeSource}s. The operator buffers the values emitted by these {@code MaybeSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource} that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code MaybeSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code MaybeSource}s can be active at the same time * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEager(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources, int maxConcurrency) { return Flowable.fromIterable(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), false, maxConcurrency, 1); } /** * Concatenates a {@link Publisher} sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code MaybeSource}s as they are observed. The operator buffers the values emitted by these * {@code MaybeSource}s and then drains them in order, each one after the previous one completes. * <p> * <img width="640" height="511" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream and the outer {@code Publisher} is * expected to support backpressure. Violating this assumption, the operator will * signal {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEager(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromPublisher(sources).concatMapEager((Function)MaybeToPublisher.instance()); } /** * Concatenates a {@link Publisher} sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence, * running at most the given number of inner {@code MaybeSource}s at once. * <p> * <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.pn.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code MaybeSource}s as they are observed. The operator buffers the values emitted by these * {@code MaybeSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream and the outer {@code Publisher} is * expected to support backpressure. Violating this assumption, the operator will * signal {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code MaybeSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code MaybeSource}s can be active at the same time * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEager(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int maxConcurrency) { return Flowable.fromPublisher(sources).concatMapEager((Function)MaybeToPublisher.instance(), maxConcurrency, 1); } /** * Concatenates a sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence, * delaying errors until all inner {@code MaybeSource}s terminate. * <p> * <img width="640" height="428" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEagerDelayError.i.png" alt=""> * <p> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the * source {@code MaybeSource}s. The operator buffers the values emitted by these {@code MaybeSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource} that need to be eagerly concatenated * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEagerDelayError(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromIterable(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), true); } /** * Concatenates a sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence, * delaying errors until all inner {@code MaybeSource}s terminate and * runs a limited number of inner {@code MaybeSource}s at once. * <p> * <img width="640" height="379" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEagerDelayError.in.png" alt=""> * <p> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the * source {@code MaybeSource}s. The operator buffers the values emitted by these {@code MaybeSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource} that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code MaybeSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code MaybeSource}s can be active at the same time * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEagerDelayError(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources, int maxConcurrency) { return Flowable.fromIterable(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), true, maxConcurrency, 1); } /** * Concatenates a {@link Publisher} sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence, * delaying errors until all the inner and the outer sequence terminate. * <p> * <img width="640" height="495" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEagerDelayError.p.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code MaybeSource}s as they are observed. The operator buffers the values emitted by these * {@code MaybeSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream and the outer {@code Publisher} is * expected to support backpressure. Violating this assumption, the operator will * signal {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEagerDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromPublisher(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), true); } /** * Concatenates a {@link Publisher} sequence of {@link MaybeSource}s eagerly into a {@link Flowable} sequence, * delaying errors until all the inner and the outer sequence terminate and * runs a limited number of the inner {@code MaybeSource}s at once. * <p> * <img width="640" height="421" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEagerDelayError.pn.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code MaybeSource}s as they are observed. The operator buffers the values emitted by these * {@code MaybeSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream and the outer {@code Publisher} is * expected to support backpressure. Violating this assumption, the operator will * signal {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code MaybeSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code MaybeSource}s can be active at the same time * @return the new {@code Flowable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @since 3.0.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> concatEagerDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int maxConcurrency) { return Flowable.fromPublisher(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), true, maxConcurrency, 1); } /** * Provides an API (via a cold {@code Maybe}) that bridges the reactive world with the callback-style world. * <p> * <img width="640" height="499" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.create.png" alt=""> * <p> * Example: * <pre><code> * Maybe.&lt;Event&gt;create(emitter -&gt; { * Callback listener = new Callback() { * &#64;Override * public void onEvent(Event e) { * if (e.isNothing()) { * emitter.onComplete(); * } else { * emitter.onSuccess(e); * } * } * * &#64;Override * public void onFailure(Exception e) { * emitter.onError(e); * } * }; * * AutoCloseable c = api.someMethod(listener); * * emitter.setCancellable(c::close); * * }); * </code></pre> * <p> * Whenever a {@link MaybeObserver} subscribes to the returned {@code Maybe}, the provided * {@link MaybeOnSubscribe} callback is invoked with a fresh instance of a {@link MaybeEmitter} * that will interact only with that specific {@code MaybeObserver}. If this {@code MaybeObserver} * disposes the flow (making {@link MaybeEmitter#isDisposed} return {@code true}), * other observers subscribed to the same returned {@code Maybe} are not affected. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code create} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param onSubscribe the emitter that is called when a {@code MaybeObserver} subscribes to the returned {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onSubscribe} is {@code null} * @see MaybeOnSubscribe * @see Cancellable */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> create(@NonNull MaybeOnSubscribe<T> onSubscribe) { Objects.requireNonNull(onSubscribe, "onSubscribe is null"); return RxJavaPlugins.onAssembly(new MaybeCreate<>(onSubscribe)); } /** * Calls a {@link Supplier} for each individual {@link MaybeObserver} to return the actual {@link MaybeSource} source to * be subscribed to. * <p> * <img width="640" height="498" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.defer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param supplier the {@code Supplier} that is called for each individual {@code MaybeObserver} and * returns a {@code MaybeSource} instance to subscribe to * @return the new {@code Maybe} instance * @throws NullPointerException if {@code supplier} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> defer(@NonNull Supplier<? extends @NonNull MaybeSource<? extends T>> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new MaybeDefer<>(supplier)); } /** * Returns a (singleton) {@code Maybe} instance that calls {@link MaybeObserver#onComplete onComplete} * immediately. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/empty.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code empty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @return the shared {@code Maybe} instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @NonNull public static <@NonNull T> Maybe<T> empty() { return RxJavaPlugins.onAssembly((Maybe<T>)MaybeEmpty.INSTANCE); } /** * Returns a {@code Maybe} that invokes a subscriber's {@link MaybeObserver#onError onError} method when the * subscriber subscribes to it. * <p> * <img width="640" height="447" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.error.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param throwable * the particular {@link Throwable} to pass to {@link MaybeObserver#onError onError} * @param <T> * the type of the item (ostensibly) emitted by the {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code throwable} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> error(@NonNull Throwable throwable) { Objects.requireNonNull(throwable, "throwable is null"); return RxJavaPlugins.onAssembly(new MaybeError<>(throwable)); } /** * Returns a {@code Maybe} that invokes a {@link MaybeObserver}'s {@link MaybeObserver#onError onError} method when the * {@code MaybeObserver} subscribes to it. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.error.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param supplier * a {@link Supplier} factory to return a {@link Throwable} for each individual {@code MaybeObserver} * @param <T> * the type of the items (ostensibly) emitted by the {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code supplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> error(@NonNull Supplier<? extends @NonNull Throwable> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new MaybeErrorCallable<>(supplier)); } /** * Returns a {@code Maybe} instance that runs the given {@link Action} for each {@link MaybeObserver} and * emits either its exception or simply completes. * <p> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromAction.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> If the {@code Action} throws an exception, the respective {@link Throwable} is * delivered to the downstream via {@link MaybeObserver#onError(Throwable)}, * except when the downstream has disposed the resulting {@code Maybe} source. * In this latter case, the {@code Throwable} is delivered to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. * </dd> * </dl> * @param <T> the target type * @param action the {@code Action} to run for each {@code MaybeObserver} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code action} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromAction(@NonNull Action action) { Objects.requireNonNull(action, "action is null"); return RxJavaPlugins.onAssembly(new MaybeFromAction<>(action)); } /** * Wraps a {@link CompletableSource} into a {@code Maybe}. * <p> * <img width="640" height="280" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromCompletable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the target type * @param completableSource the {@code CompletableSource} to convert from * @return the new {@code Maybe} instance * @throws NullPointerException if {@code completableSource} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromCompletable(@NonNull CompletableSource completableSource) { Objects.requireNonNull(completableSource, "completableSource is null"); return RxJavaPlugins.onAssembly(new MaybeFromCompletable<>(completableSource)); } /** * Wraps a {@link SingleSource} into a {@code Maybe}. * <p> * <img width="640" height="344" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the target type * @param single the {@code SingleSource} to convert from * @return the new {@code Maybe} instance * @throws NullPointerException if {@code single} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromSingle(@NonNull SingleSource<T> single) { Objects.requireNonNull(single, "single is null"); return RxJavaPlugins.onAssembly(new MaybeFromSingle<>(single)); } /** * Returns a {@code Maybe} that invokes the given {@link Callable} for each individual {@link MaybeObserver} that * subscribes and emits the resulting non-{@code null} item via {@code onSuccess} while * considering a {@code null} result from the {@code Callable} as indication for valueless completion * via {@code onComplete}. * <p> * <img width="640" height="183" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromCallable.png" alt=""> * <p> * This operator allows you to defer the execution of the given {@code Callable} until a {@code MaybeObserver} * subscribes to the returned {@code Maybe}. In other terms, this source operator evaluates the given * {@code Callable} "lazily". * <p> * Note that the {@code null} handling of this operator differs from the similar source operators in the other * {@link io.reactivex.rxjava3.core base reactive classes}. Those operators signal a {@link NullPointerException} if the value returned by their * {@code Callable} is {@code null} while this {@code fromCallable} considers it to indicate the * returned {@code Maybe} is empty. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>Any non-fatal exception thrown by {@link Callable#call()} will be forwarded to {@code onError}, * except if the {@code MaybeObserver} disposed the subscription in the meantime. In this latter case, * the exception is forwarded to the global error handler via * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} wrapped into a * {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. * Fatal exceptions are rethrown and usually will end up in the executing thread's * {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.</dd> * </dl> * * @param callable * a {@code Callable} instance whose execution should be deferred and performed for each individual * {@code MaybeObserver} that subscribes to the returned {@code Maybe}. * @param <T> * the type of the item emitted by the {@code Maybe}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code callable} is {@code null} * @see #defer(Supplier) * @see #fromSupplier(Supplier) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<@NonNull T> fromCallable(@NonNull Callable<? extends @Nullable T> callable) { Objects.requireNonNull(callable, "callable is null"); return RxJavaPlugins.onAssembly(new MaybeFromCallable<>(callable)); } /** * Converts a {@link Future} into a {@code Maybe}, treating a {@code null} result as an indication of emptiness. * <p> * <img width="640" height="204" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromFuture.png" alt=""> * <p> * The operator calls {@link Future#get()}, which is a blocking method, on the subscription thread. * It is recommended applying {@link #subscribeOn(Scheduler)} to move this blocking wait to a * background thread, and if the {@link Scheduler} supports it, interrupt the wait when the flow * is disposed. * <p> * Unlike 1.x, disposing the {@code Maybe} won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futureMaybe.doOnDispose(() -> future.cancel(true));}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromFuture} does not operate by default on a particular {@code Scheduler}.</dd> * </dl> * * @param future * the source {@code Future} * @param <T> * the type of object that the {@code Future} returns, and also the type of item to be emitted by * the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code future} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> * @see #fromCompletionStage(CompletionStage) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromFuture(@NonNull Future<? extends T> future) { Objects.requireNonNull(future, "future is null"); return RxJavaPlugins.onAssembly(new MaybeFromFuture<>(future, 0L, null)); } /** * Converts a {@link Future} into a {@code Maybe}, with a timeout on the {@code Future}. * <p> * <img width="640" height="176" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromFuture.t.png" alt=""> * <p> * The operator calls {@link Future#get(long, TimeUnit)}, which is a blocking method, on the subscription thread. * It is recommended applying {@link #subscribeOn(Scheduler)} to move this blocking wait to a * background thread, and if the {@link Scheduler} supports it, interrupt the wait when the flow * is disposed. * <p> * Unlike 1.x, disposing the {@code Maybe} won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futureMaybe.doOnCancel(() -> future.cancel(true));}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromFuture} does not operate by default on a particular {@code Scheduler}.</dd> * </dl> * * @param future * the source {@code Future} * @param timeout * the maximum time to wait before calling {@code get} * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @param <T> * the type of object that the {@code Future} returns, and also the type of item to be emitted by * the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code future} or {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> * @see #fromCompletionStage(CompletionStage) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromFuture(@NonNull Future<? extends T> future, long timeout, @NonNull TimeUnit unit) { Objects.requireNonNull(future, "future is null"); Objects.requireNonNull(unit, "unit is null"); return RxJavaPlugins.onAssembly(new MaybeFromFuture<>(future, timeout, unit)); } /** * Wraps an {@link ObservableSource} into a {@code Maybe} and emits the very first item * or completes if the source is empty. * <p> * <img width="640" height="276" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromObservable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the target type * @param source the {@code ObservableSource} to convert from * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromObservable(@NonNull ObservableSource<T> source) { Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new ObservableElementAtMaybe<>(source, 0L)); } /** * Wraps a {@link Publisher} into a {@code Maybe} and emits the very first item * or completes if the source is empty. * <p> * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromPublisher.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator consumes the given {@code Publisher} in an unbounded manner * (requesting {@link Long#MAX_VALUE}) but cancels it after one item received.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromPublisher} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the target type * @param source the {@code Publisher} to convert from * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) public static <@NonNull T> Maybe<T> fromPublisher(@NonNull Publisher<T> source) { Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new FlowableElementAtMaybePublisher<>(source, 0L)); } /** * Returns a {@code Maybe} instance that runs the given {@link Runnable} for each {@link MaybeObserver} and * emits either its unchecked exception or simply completes. * <p> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromRunnable.png" alt=""> * <p> * If the code to be wrapped needs to throw a checked or more broader {@link Throwable} exception, that * exception has to be converted to an unchecked exception by the wrapped code itself. Alternatively, * use the {@link #fromAction(Action)} method which allows the wrapped code to throw any {@code Throwable} * exception and will signal it to observers as-is. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> If the {@code Runnable} throws an exception, the respective {@code Throwable} is * delivered to the downstream via {@link MaybeObserver#onError(Throwable)}, * except when the downstream has disposed this {@code Maybe} source. * In this latter case, the {@code Throwable} is delivered to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. * </dd> * </dl> * @param <T> the target type * @param run the {@code Runnable} to run for each {@code MaybeObserver} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code run} is {@code null} * @see #fromAction(Action) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> fromRunnable(@NonNull Runnable run) { Objects.requireNonNull(run, "run is null"); return RxJavaPlugins.onAssembly(new MaybeFromRunnable<>(run)); } /** * Returns a {@code Maybe} that invokes the given {@link Supplier} for each individual {@link MaybeObserver} that * subscribes and emits the resulting non-{@code null} item via {@code onSuccess} while * considering a {@code null} result from the {@code Supplier} as indication for valueless completion * via {@code onComplete}. * <p> * This operator allows you to defer the execution of the given {@code Supplier} until a {@code MaybeObserver} * subscribes to the returned {@code Maybe}. In other terms, this source operator evaluates the given * {@code Supplier} "lazily". * <p> * <img width="640" height="311" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromSupplier.v3.png" alt=""> * <p> * Note that the {@code null} handling of this operator differs from the similar source operators in the other * {@link io.reactivex.rxjava3.core base reactive classes}. Those operators signal a {@link NullPointerException} if the value returned by their * {@code Supplier} is {@code null} while this {@code fromSupplier} considers it to indicate the * returned {@code Maybe} is empty. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromSupplier} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>Any non-fatal exception thrown by {@link Supplier#get()} will be forwarded to {@code onError}, * except if the {@code MaybeObserver} disposed the subscription in the meantime. In this latter case, * the exception is forwarded to the global error handler via * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} wrapped into a * {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. * Fatal exceptions are rethrown and usually will end up in the executing thread's * {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.</dd> * </dl> * * @param supplier * a {@code Supplier} instance whose execution should be deferred and performed for each individual * {@code MaybeObserver} that subscribes to the returned {@code Maybe}. * @param <T> * the type of the item emitted by the {@code Maybe}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code supplier} is {@code null} * @see #defer(Supplier) * @see #fromCallable(Callable) * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<@NonNull T> fromSupplier(@NonNull Supplier<? extends @Nullable T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new MaybeFromSupplier<>(supplier)); } /** * Returns a {@code Maybe} that emits a specified item. * <p> * <img width="640" height="485" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.just.png" alt=""> * <p> * To convert any object into a {@code Maybe} that emits that object, pass that object into the * {@code just} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item * the item to emit * @param <T> * the type of that item * @return the new {@code Maybe} instance * @throws NullPointerException if {@code item} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> just(T item) { Objects.requireNonNull(item, "item is null"); return RxJavaPlugins.onAssembly(new MaybeJust<>(item)); } /** * Merges an {@link Iterable} sequence of {@link MaybeSource} instances into a single {@link Flowable} sequence, * running all {@code MaybeSource}s at once. * <p> * <img width="640" height="301" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * @param <T> the common and resulting value type * @param sources the {@code Iterable} sequence of {@code MaybeSource} sources * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see #mergeDelayError(Iterable) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> merge(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromIterable(sources).flatMapMaybe(Functions.identity(), false, Integer.MAX_VALUE); } /** * Merges a {@link Publisher} sequence of {@link MaybeSource} instances into a single {@link Flowable} sequence, * running all {@code MaybeSource}s at once. * <p> * <img width="640" height="325" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * @param <T> the common and resulting value type * @param sources the {@code Flowable} sequence of {@code MaybeSource} sources * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see #mergeDelayError(Publisher) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> merge(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { return merge(sources, Integer.MAX_VALUE); } /** * Merges a {@link Publisher} sequence of {@link MaybeSource} instances into a single {@link Flowable} sequence, * running at most maxConcurrency {@code MaybeSource}s at once. * <p> * <img width="640" height="260" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * @param <T> the common and resulting value type * @param sources the {@code Flowable} sequence of {@code MaybeSource} sources * @param maxConcurrency the maximum number of concurrently running {@code MaybeSource}s * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @see #mergeDelayError(Publisher, int) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> merge(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int maxConcurrency) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); return RxJavaPlugins.onAssembly(new FlowableFlatMapMaybePublisher<>(sources, Functions.identity(), false, maxConcurrency)); } /** * Flattens a {@link MaybeSource} that emits a {@code MaybeSource} into a single {@code MaybeSource} that emits the item * emitted by the nested {@code MaybeSource}, without any transformation. * <p> * <img width="640" height="394" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.oo.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>The resulting {@code Maybe} emits the outer source's or the inner {@code MaybeSource}'s {@link Throwable} as is. * Unlike the other {@code merge()} operators, this operator won't and can't produce a {@link CompositeException} because there is * only one possibility for the outer or the inner {@code MaybeSource} to emit an {@code onError} signal. * Therefore, there is no need for a {@code mergeDelayError(MaybeSource<MaybeSource<T>>)} operator. * </dd> * </dl> * * @param <T> the value type of the sources and the output * @param source * a {@code MaybeSource} that emits a {@code MaybeSource} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) public static <@NonNull T> Maybe<T> merge(@NonNull MaybeSource<? extends MaybeSource<? extends T>> source) { Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new MaybeFlatten(source, Functions.identity())); } /** * Flattens two {@link MaybeSource}s into a single {@link Flowable}, without any transformation. * <p> * <img width="640" height="279" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.2.png" alt=""> * <p> * You can combine items emitted by multiple {@code MaybeSource}s so that they appear as a single {@code Flowable}, by * using the {@code merge} method. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common value type * @param source1 * a {@code MaybeSource} to be merged * @param source2 * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(MaybeSource, MaybeSource) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> merge( @NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2 ) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); return mergeArray(source1, source2); } /** * Flattens three {@link MaybeSource}s into a single {@link Flowable}, without any transformation. * <p> * <img width="640" height="301" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.3.png" alt=""> * <p> * You can combine items emitted by multiple {@code MaybeSource}s so that they appear as a single {@code Flowable}, by using * the {@code merge} method. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(MaybeSource, MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common value type * @param source1 * a {@code MaybeSource} to be merged * @param source2 * a {@code MaybeSource} to be merged * @param source3 * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code source3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(MaybeSource, MaybeSource, MaybeSource) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> merge( @NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull MaybeSource<? extends T> source3 ) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); return mergeArray(source1, source2, source3); } /** * Flattens four {@link MaybeSource}s into a single {@link Flowable}, without any transformation. * <p> * <img width="640" height="289" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.4.png" alt=""> * <p> * You can combine items emitted by multiple {@code MaybeSource}s so that they appear as a single {@code Flowable}, by using * the {@code merge} method. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(MaybeSource, MaybeSource, MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common value type * @param source1 * a {@code MaybeSource} to be merged * @param source2 * a {@code MaybeSource} to be merged * @param source3 * a {@code MaybeSource} to be merged * @param source4 * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code source4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(MaybeSource, MaybeSource, MaybeSource, MaybeSource) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> merge( @NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull MaybeSource<? extends T> source3, @NonNull MaybeSource<? extends T> source4 ) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); return mergeArray(source1, source2, source3, source4); } /** * Merges an array of {@link MaybeSource} instances into a single {@link Flowable} sequence, * running all {@code MaybeSource}s at once. * <p> * <img width="640" height="272" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeArray.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(MaybeSource...)} to merge sources and terminate only when all source {@code MaybeSource}s * have completed or failed with an error. * </dd> * </dl> * @param <T> the common and resulting value type * @param sources the array sequence of {@code MaybeSource} sources * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see #mergeArrayDelayError(MaybeSource...) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs public static <@NonNull T> Flowable<T> mergeArray(MaybeSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return Flowable.empty(); } if (sources.length == 1) { @SuppressWarnings("unchecked") MaybeSource<T> source = (MaybeSource<T>)sources[0]; return RxJavaPlugins.onAssembly(new MaybeToFlowable<>(source)); } return RxJavaPlugins.onAssembly(new MaybeMergeArray<>(sources)); } /** * Flattens an array of {@link MaybeSource}s into one {@link Flowable}, in a way that allows a subscriber to receive all * successfully emitted items from each of the source {@code MaybeSource}s without being interrupted by an error * notification from one of them. * <p> * <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeArrayDelayError.png" alt=""> * <p> * This behaves like {@link #merge(Publisher)} except that if any of the merged {@code MaybeSource}s notify of an * error via {@link Subscriber#onError onError}, {@code mergeArrayDelayError} will refrain from propagating that * error notification until all of the merged {@code MaybeSource}s have finished emitting items. * <p> * Even if multiple merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeArrayDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the array of {@code MaybeSource}s * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs @NonNull public static <@NonNull T> Flowable<T> mergeArrayDelayError(@NonNull MaybeSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); return Flowable.fromArray(sources).flatMapMaybe(Functions.identity(), true, Math.max(1, sources.length)); } /** * Flattens an {@link Iterable} sequence of {@link MaybeSource}s into one {@link Flowable}, in a way that allows a subscriber to receive all * successfully emitted items from each of the source {@code MaybeSource}s without being interrupted by an error * notification from one of them. * <p> * <img width="640" height="467" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.i.png" alt=""> * <p> * This behaves like {@link #merge(Publisher)} except that if any of the merged {@code MaybeSource}s notify of an * error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code MaybeSource}s have finished emitting items. * <p> * <img width="640" height="467" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.i.png" alt=""> * <p> * Even if multiple merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code MaybeSource}s * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> mergeDelayError(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) { return Flowable.fromIterable(sources).flatMapMaybe(Functions.identity(), true, Integer.MAX_VALUE); } /** * Flattens a {@link Publisher} that emits {@link MaybeSource}s into one {@link Flowable}, in a way that allows a subscriber to * receive all successfully emitted items from all of the source {@code MaybeSource}s without being interrupted by * an error notification from one of them or even the main {@code Publisher}. * <p> * <img width="640" height="456" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.p.png" alt=""> * <p> * This behaves like {@link #merge(Publisher)} except that if any of the merged {@code MaybeSource}s notify of an * error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code MaybeSource}s and the main {@code Publisher} have finished emitting items. * <p> * Even if multiple merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed * in unbounded mode (i.e., no backpressure is applied to it).</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * a {@code Publisher} that emits {@code MaybeSource}s * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Flowable<T> mergeDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { return mergeDelayError(sources, Integer.MAX_VALUE); } /** * Flattens a {@link Publisher} that emits {@link MaybeSource}s into one {@link Flowable}, in a way that allows a subscriber to * receive all successfully emitted items from all of the source {@code MaybeSource}s without being interrupted by * an error notification from one of them or even the main {@code Publisher} as well as limiting the total number of active {@code MaybeSource}s. * <p> * <img width="640" height="429" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.pn.png" alt=""> * <p> * This behaves like {@link #merge(Publisher, int)} except that if any of the merged {@code MaybeSource}s notify of an * error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code MaybeSource}s and the main {@code Publisher} have finished emitting items. * <p> * Even if multiple merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed * in unbounded mode (i.e., no backpressure is applied to it).</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.1.9 - experimental * @param <T> the common element base type * @param sources * a {@code Publisher} that emits {@code MaybeSource}s * @param maxConcurrency the maximum number of active inner {@code MaybeSource}s to be merged at a time * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> mergeDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int maxConcurrency) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); return RxJavaPlugins.onAssembly(new FlowableFlatMapMaybePublisher<>(sources, Functions.identity(), true, maxConcurrency)); } /** * Flattens two {@link MaybeSource}s into one {@link Flowable}, in a way that allows a subscriber to receive all * successfully emitted items from each of the source {@code MaybeSource}s without being interrupted by an error * notification from one of them. * <p> * <img width="640" height="414" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.2.png" alt=""> * <p> * This behaves like {@link #merge(MaybeSource, MaybeSource)} except that if any of the merged {@code MaybeSource}s * notify of an error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from * propagating that error notification until all of the merged {@code MaybeSource}s have finished emitting items. * <p> * Even if both merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * a {@code MaybeSource} to be merged * @param source2 * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> mergeDelayError(@NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); return mergeArrayDelayError(source1, source2); } /** * Flattens three {@link MaybeSource} into one {@link Flowable}, in a way that allows a subscriber to receive all * successfully emitted items from all of the source {@code MaybeSource}s without being interrupted by an error * notification from one of them. * <p> * <img width="640" height="467" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.3.png" alt=""> * <p> * This behaves like {@link #merge(MaybeSource, MaybeSource, MaybeSource)} except that if any of the merged * {@code MaybeSource}s notify of an error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain * from propagating that error notification until all of the merged {@code MaybeSource}s have finished emitting * items. * <p> * Even if multiple merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * a {@code MaybeSource} to be merged * @param source2 * a {@code MaybeSource} to be merged * @param source3 * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code source3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> mergeDelayError(@NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull MaybeSource<? extends T> source3) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); return mergeArrayDelayError(source1, source2, source3); } /** * Flattens four {@link MaybeSource}s into one {@link Flowable}, in a way that allows a subscriber to receive all * successfully emitted items from all of the source {@code MaybeSource}s without being interrupted by an error * notification from one of them. * <p> * <img width="640" height="461" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeDelayError.4.png" alt=""> * <p> * This behaves like {@link #merge(MaybeSource, MaybeSource, MaybeSource, MaybeSource)} except that if any of * the merged {@code MaybeSource}s notify of an error via {@link Subscriber#onError onError}, {@code mergeDelayError} * will refrain from propagating that error notification until all of the merged {@code MaybeSource}s have finished * emitting items. * <p> * Even if multiple merged {@code MaybeSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its subscribers once. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * a {@code MaybeSource} to be merged * @param source2 * a {@code MaybeSource} to be merged * @param source3 * a {@code MaybeSource} to be merged * @param source4 * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code source4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> mergeDelayError( @NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull MaybeSource<? extends T> source3, @NonNull MaybeSource<? extends T> source4) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); return mergeArrayDelayError(source1, source2, source3, source4); } /** * Returns a {@code Maybe} that never sends any items or notifications to a {@link MaybeObserver}. * <p> * <img width="640" height="185" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/never.v3.png" alt=""> * <p> * This {@code Maybe} is useful primarily for testing purposes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code never} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the type of items (not) emitted by the {@code Maybe} * @return the shared {@code Maybe} instance * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Never</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @NonNull public static <@NonNull T> Maybe<T> never() { return RxJavaPlugins.onAssembly((Maybe<T>)MaybeNever.INSTANCE); } /** * Returns a {@link Single} that emits a {@link Boolean} value that indicates whether two {@link MaybeSource} sequences are the * same by comparing the items emitted by each {@code MaybeSource} pairwise. * <p> * <img width="640" height="187" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.sequenceEqual.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source1 * the first {@code MaybeSource} to compare * @param source2 * the second {@code MaybeSource} to compare * @param <T> * the type of items emitted by each {@code MaybeSource} * @return the new {@code Single} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Single<Boolean> sequenceEqual(@NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2) { return sequenceEqual(source1, source2, ObjectHelper.equalsPredicate()); } /** * Returns a {@link Single} that emits a {@link Boolean} value that indicates whether two {@link MaybeSource}s are the * same by comparing the items emitted by each {@code MaybeSource} pairwise based on the results of a specified * equality function. * <p> * <img width="640" height="247" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.sequenceEqual.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source1 * the first {@code MaybeSource} to compare * @param source2 * the second {@code MaybeSource} to compare * @param isEqual * a function used to compare items emitted by each {@code MaybeSource} * @param <T> * the type of items emitted by each {@code MaybeSource} * @return the new {@code Single} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code isEqual} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Single<Boolean> sequenceEqual(@NonNull MaybeSource<? extends T> source1, @NonNull MaybeSource<? extends T> source2, @NonNull BiPredicate<? super T, ? super T> isEqual) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(isEqual, "isEqual is null"); return RxJavaPlugins.onAssembly(new MaybeEqualSingle<>(source1, source2, isEqual)); } /** * Switches between {@link MaybeSource}s emitted by the source {@link Publisher} whenever * a new {@code MaybeSource} is emitted, disposing the previously running {@code MaybeSource}, * exposing the success items as a {@link Flowable} sequence. * <p> * <img width="640" height="521" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.switchOnNext.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code sources} {@code Publisher} is consumed in an unbounded manner (requesting {@link Long#MAX_VALUE}). * The returned {@code Flowable} respects the backpressure from the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchOnNext} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>The returned sequence fails with the first error signaled by the {@code sources} {@code Publisher} * or the currently running {@code MaybeSource}, disposing the rest. Late errors are * forwarded to the global error handler via {@link RxJavaPlugins#onError(Throwable)}.</dd> * </dl> * @param <T> the element type of the {@code MaybeSource}s * @param sources the {@code Publisher} sequence of inner {@code MaybeSource}s to switch between * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 * @see #switchOnNextDelayError(Publisher) * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> switchOnNext(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapMaybePublisher<>(sources, Functions.identity(), false)); } /** * Switches between {@link MaybeSource}s emitted by the source {@link Publisher} whenever * a new {@code MaybeSource} is emitted, disposing the previously running {@code MaybeSource}, * exposing the success items as a {@link Flowable} sequence and delaying all errors from * all of them until all terminate. * <p> * <img width="640" height="423" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.switchOnNextDelayError.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code sources} {@code Publisher} is consumed in an unbounded manner (requesting {@link Long#MAX_VALUE}). * The returned {@code Flowable} respects the backpressure from the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchOnNextDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>The returned {@code Flowable} collects all errors emitted by either the {@code sources} * {@code Publisher} or any inner {@code MaybeSource} and emits them as a {@link CompositeException} * when all sources terminate. If only one source ever failed, its error is emitted as-is at the end.</dd> * </dl> * @param <T> the element type of the {@code MaybeSource}s * @param sources the {@code Publisher} sequence of inner {@code MaybeSource}s to switch between * @return the new {@code Flowable} instance * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 * @see #switchOnNext(Publisher) * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Flowable<T> switchOnNextDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapMaybePublisher<>(sources, Functions.identity(), true)); } /** * Returns a {@code Maybe} that emits {@code 0L} after a specified delay. * <p> * <img width="640" height="391" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param delay * the initial delay before emitting a single {@code 0L} * @param unit * time units to use for {@code delay} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public static Maybe<Long> timer(long delay, @NonNull TimeUnit unit) { return timer(delay, unit, Schedulers.computation()); } /** * Returns a {@code Maybe} that emits {@code 0L} after a specified delay on a specified {@link Scheduler}. * <p> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timer.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param delay * the initial delay before emitting a single 0L * @param unit * time units to use for {@code delay} * @param scheduler * the {@code Scheduler} to use for scheduling the item * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Maybe<Long> timer(long delay, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeTimer(Math.max(0L, delay), unit, scheduler)); } /** * <strong>Advanced use only:</strong> creates a {@code Maybe} instance without * any safeguards by using a callback that is called with a {@link MaybeObserver}. * <p> * <img width="640" height="262" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.unsafeCreate.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsafeCreate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param onSubscribe the function that is called with the subscribing {@code MaybeObserver} * @return the new {@code Maybe} instance * @throws IllegalArgumentException if {@code onSubscribe} is a {@code Maybe} * @throws NullPointerException if {@code onSubscribe} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> unsafeCreate(@NonNull MaybeSource<T> onSubscribe) { if (onSubscribe instanceof Maybe) { throw new IllegalArgumentException("unsafeCreate(Maybe) should be upgraded"); } Objects.requireNonNull(onSubscribe, "onSubscribe is null"); return RxJavaPlugins.onAssembly(new MaybeUnsafeCreate<>(onSubscribe)); } /** * Constructs a {@code Maybe} that creates a dependent resource object which is disposed of when the * generated {@link MaybeSource} terminates or the downstream calls dispose(). * <p> * <img width="640" height="378" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.using.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the element type of the generated {@code MaybeSource} * @param <D> the type of the resource associated with the output sequence * @param resourceSupplier * the factory function to create a resource object that depends on the {@code Maybe} * @param sourceSupplier * the factory function to create a {@code MaybeSource} * @param resourceCleanup * the function that will dispose of the resource * @return the new {@code Maybe} instance * @throws NullPointerException if {@code resourceSupplier}, {@code sourceSupplier} or {@code resourceCleanup} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull D> Maybe<T> using(@NonNull Supplier<? extends D> resourceSupplier, @NonNull Function<? super D, ? extends MaybeSource<? extends T>> sourceSupplier, @NonNull Consumer<? super D> resourceCleanup) { return using(resourceSupplier, sourceSupplier, resourceCleanup, true); } /** * Constructs a {@code Maybe} that creates a dependent resource object which is disposed first ({code eager == true}) * when the generated {@link MaybeSource} terminates or the downstream disposes; or after ({code eager == false}). * <p> * <img width="640" height="323" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.using.b.png" alt=""> * <p> * Eager disposal is particularly appropriate for a synchronous {@code Maybe} that reuses resources. {@code disposeAction} will * only be called once per subscription. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the element type of the generated {@code MaybeSource} * @param <D> the type of the resource associated with the output sequence * @param resourceSupplier * the factory function to create a resource object that depends on the {@code Maybe} * @param sourceSupplier * the factory function to create a {@code MaybeSource} * @param resourceCleanup * the function that will dispose of the resource * @param eager * If {@code true} then resource disposal will happen either on a {@code dispose()} call before the upstream is disposed * or just before the emission of a terminal event ({@code onSuccess}, {@code onComplete} or {@code onError}). * If {@code false} the resource disposal will happen either on a {@code dispose()} call after the upstream is disposed * or just after the emission of a terminal event ({@code onSuccess}, {@code onComplete} or {@code onError}). * @return the new {@code Maybe} instance * @throws NullPointerException if {@code resourceSupplier}, {@code sourceSupplier} or {@code resourceCleanup} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull D> Maybe<T> using(@NonNull Supplier<? extends D> resourceSupplier, @NonNull Function<? super D, ? extends MaybeSource<? extends T>> sourceSupplier, @NonNull Consumer<? super D> resourceCleanup, boolean eager) { Objects.requireNonNull(resourceSupplier, "resourceSupplier is null"); Objects.requireNonNull(sourceSupplier, "sourceSupplier is null"); Objects.requireNonNull(resourceCleanup, "resourceCleanup is null"); return RxJavaPlugins.onAssembly(new MaybeUsing<T, D>(resourceSupplier, sourceSupplier, resourceCleanup, eager)); } /** * Wraps a {@link MaybeSource} instance into a new {@code Maybe} instance if not already a {@code Maybe} * instance. * <p> * <img width="640" height="232" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.wrap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param source the source to wrap * @return the new wrapped or cast {@code Maybe} instance * @throws NullPointerException if {@code source} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Maybe<T> wrap(@NonNull MaybeSource<T> source) { if (source instanceof Maybe) { return RxJavaPlugins.onAssembly((Maybe<T>)source); } Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new MaybeUnsafeCreate<>(source)); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * items emitted, in sequence, by an {@link Iterable} of other {@link MaybeSource}s. * <p> * <img width="640" height="341" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.i.png" alt=""> * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common value type * @param <R> the zipped result type * @param sources * an {@code Iterable} of source {@code MaybeSource}s * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code zipper} or {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull R> Maybe<R> zip(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> zipper) { Objects.requireNonNull(zipper, "zipper is null"); Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new MaybeZipIterable<>(sources, zipper)); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * two items emitted, in sequence, by two other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results * in an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull BiFunction<? super T1, ? super T2, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * three items emitted, in sequence, by three other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull Function3<? super T1, ? super T2, ? super T3, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * four items emitted, in sequence, by four other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param source4 * a fourth source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull MaybeSource<? extends T4> source4, @NonNull Function4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * five items emitted, in sequence, by five other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param source4 * a fourth source {@code MaybeSource} * @param source5 * a fifth source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull MaybeSource<? extends T4> source4, @NonNull MaybeSource<? extends T5> source5, @NonNull Function5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * six items emitted, in sequence, by six other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param source4 * a fourth source {@code MaybeSource} * @param source5 * a fifth source {@code MaybeSource} * @param source6 * a sixth source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull MaybeSource<? extends T4> source4, @NonNull MaybeSource<? extends T5> source5, @NonNull MaybeSource<? extends T6> source6, @NonNull Function6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * seven items emitted, in sequence, by seven other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <T7> the value type of the seventh source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param source4 * a fourth source {@code MaybeSource} * @param source5 * a fifth source {@code MaybeSource} * @param source6 * a sixth source {@code MaybeSource} * @param source7 * a seventh source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7} or {@code zipper} is {@code null} * @return the new {@code Maybe} instance * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull MaybeSource<? extends T4> source4, @NonNull MaybeSource<? extends T5> source5, @NonNull MaybeSource<? extends T6> source6, @NonNull MaybeSource<? extends T7> source7, @NonNull Function7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6, source7); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * eight items emitted, in sequence, by eight other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <T7> the value type of the seventh source * @param <T8> the value type of the eighth source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param source4 * a fourth source {@code MaybeSource} * @param source5 * a fifth source {@code MaybeSource} * @param source6 * a sixth source {@code MaybeSource} * @param source7 * a seventh source {@code MaybeSource} * @param source8 * an eighth source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7}, {@code source8} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull T8, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull MaybeSource<? extends T4> source4, @NonNull MaybeSource<? extends T5> source5, @NonNull MaybeSource<? extends T6> source6, @NonNull MaybeSource<? extends T7> source7, @NonNull MaybeSource<? extends T8> source8, @NonNull Function8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(source8, "source8 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6, source7, source8); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * nine items emitted, in sequence, by nine other {@link MaybeSource}s. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zip.n.png" alt=""> * <p> * This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <T7> the value type of the seventh source * @param <T8> the value type of the eighth source * @param <T9> the value type of the ninth source * @param <R> the zipped result type * @param source1 * the first source {@code MaybeSource} * @param source2 * a second source {@code MaybeSource} * @param source3 * a third source {@code MaybeSource} * @param source4 * a fourth source {@code MaybeSource} * @param source5 * a fifth source {@code MaybeSource} * @param source6 * a sixth source {@code MaybeSource} * @param source7 * a seventh source {@code MaybeSource} * @param source8 * an eighth source {@code MaybeSource} * @param source9 * a ninth source {@code MaybeSource} * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7}, {@code source8}, {@code source9} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull T8, @NonNull T9, @NonNull R> Maybe<R> zip( @NonNull MaybeSource<? extends T1> source1, @NonNull MaybeSource<? extends T2> source2, @NonNull MaybeSource<? extends T3> source3, @NonNull MaybeSource<? extends T4> source4, @NonNull MaybeSource<? extends T5> source5, @NonNull MaybeSource<? extends T6> source6, @NonNull MaybeSource<? extends T7> source7, @NonNull MaybeSource<? extends T8> source8, @NonNull MaybeSource<? extends T9> source9, @NonNull Function9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(source8, "source8 is null"); Objects.requireNonNull(source9, "source9 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6, source7, source8, source9); } /** * Returns a {@code Maybe} that emits the results of a specified combiner function applied to combinations of * items emitted, in sequence, by an array of other {@link MaybeSource}s. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * * <p> * <img width="640" height="340" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zipArray.png" alt=""> * <p>This operator terminates eagerly if any of the source {@code MaybeSource}s signal an {@code onError} or {@code onComplete}. This * also means it is possible some sources may not get subscribed to at all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zipArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element type * @param <R> the result type * @param sources * an array of source {@code MaybeSource}s * @param zipper * a function that, when applied to an item emitted by each of the source {@code MaybeSource}s, results in * an item that will be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code sources} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs public static <@NonNull T, @NonNull R> Maybe<R> zipArray(@NonNull Function<? super Object[], ? extends R> zipper, @NonNull MaybeSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return empty(); } Objects.requireNonNull(zipper, "zipper is null"); return RxJavaPlugins.onAssembly(new MaybeZipArray<>(sources, zipper)); } // ------------------------------------------------------------------ // Instance methods // ------------------------------------------------------------------ /** * Mirrors the {@link MaybeSource} (current or provided) that first signals an event. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ambWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * a {@code MaybeSource} competing to react first. A subscription to this provided source will occur after * subscribing to the current source. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code other} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> ambWith(@NonNull MaybeSource<? extends T> other) { Objects.requireNonNull(other, "other is null"); return ambArray(this, other); } /** * Waits in a blocking fashion until the current {@code Maybe} signals a success value (which is returned), * {@code null} if completed or an exception (which is propagated). * <p> * <img width="640" height="285" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingGet.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * @return the success value */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @Nullable public final T blockingGet() { BlockingMultiObserver<T> observer = new BlockingMultiObserver<>(); subscribe(observer); return observer.blockingGet(); } /** * Waits in a blocking fashion until the current {@code Maybe} signals a success value (which is returned), * defaultValue if completed or an exception (which is propagated). * <p> * <img width="640" height="297" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingGet.v.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * @param defaultValue the default item to return if this {@code Maybe} is empty * @return the success value * @throws NullPointerException if {@code defaultValue} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingGet(@NonNull T defaultValue) { Objects.requireNonNull(defaultValue, "defaultValue is null"); BlockingMultiObserver<T> observer = new BlockingMultiObserver<>(); subscribe(observer); return observer.blockingGet(defaultValue); } /** * Subscribes to the current {@code Maybe} and <em>blocks the current thread</em> until it terminates. * <p> * <img width="640" height="238" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingSubscribe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the current {@code Maybe} signals an error, * the {@link Throwable} is routed to the global error handler via {@link RxJavaPlugins#onError(Throwable)}. * If the current thread is interrupted, an {@link InterruptedException} is routed to the same global error handler. * </dd> * </dl> * @since 3.0.0 * @see #blockingSubscribe(Consumer) * @see #blockingSubscribe(Consumer, Consumer) * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe() { blockingSubscribe(Functions.emptyConsumer(), Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION); } /** * Subscribes to the current {@code Maybe} and calls given {@code onSuccess} callback on the <em>current thread</em> * when it completes normally. * <p> * <img width="640" height="245" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingSubscribe.c.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If either the current {@code Maybe} signals an error or {@code onSuccess} throws, * the respective {@link Throwable} is routed to the global error handler via {@link RxJavaPlugins#onError(Throwable)}. * If the current thread is interrupted, an {@link InterruptedException} is routed to the same global error handler. * </dd> * </dl> * @param onSuccess the {@link Consumer} to call if the current {@code Maybe} succeeds * @throws NullPointerException if {@code onSuccess} is {@code null} * @since 3.0.0 * @see #blockingSubscribe(Consumer, Consumer) * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Consumer<? super T> onSuccess) { blockingSubscribe(onSuccess, Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION); } /** * Subscribes to the current {@code Maybe} and calls the appropriate callback on the <em>current thread</em> * when it terminates. * <p> * <img width="640" height="256" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingSubscribe.cc.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If either {@code onSuccess} or {@code onError} throw, the {@link Throwable} is routed to the * global error handler via {@link RxJavaPlugins#onError(Throwable)}. * If the current thread is interrupted, the {@code onError} consumer is called with an {@link InterruptedException}. * </dd> * </dl> * @param onSuccess the {@link Consumer} to call if the current {@code Maybe} succeeds * @param onError the {@code Consumer} to call if the current {@code Maybe} signals an error * @throws NullPointerException if {@code onSuccess} or {@code onError} is {@code null} * @since 3.0.0 * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Consumer<? super T> onSuccess, @NonNull Consumer<? super Throwable> onError) { blockingSubscribe(onSuccess, onError, Functions.EMPTY_ACTION); } /** * Subscribes to the current {@code Maybe} and calls the appropriate callback on the <em>current thread</em> * when it terminates. * <p> * <img width="640" height="251" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingSubscribe.cca.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If either {@code onSuccess}, {@code onError} or {@code onComplete} throw, the {@link Throwable} is routed to the * global error handler via {@link RxJavaPlugins#onError(Throwable)}. * If the current thread is interrupted, the {@code onError} consumer is called with an {@link InterruptedException}. * </dd> * </dl> * @param onSuccess the {@link Consumer} to call if the current {@code Maybe} succeeds * @param onError the {@code Consumer} to call if the current {@code Maybe} signals an error * @param onComplete the {@link Action} to call if the current {@code Maybe} completes without a value * @throws NullPointerException if {@code onSuccess}, {@code onError} or {@code onComplete} is {@code null} * @since 3.0.0 */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Consumer<? super T> onSuccess, @NonNull Consumer<? super Throwable> onError, @NonNull Action onComplete) { Objects.requireNonNull(onSuccess, "onSuccess is null"); Objects.requireNonNull(onError, "onError is null"); Objects.requireNonNull(onComplete, "onComplete is null"); BlockingMultiObserver<T> observer = new BlockingMultiObserver<>(); subscribe(observer); observer.blockingConsume(onSuccess, onError, onComplete); } /** * Subscribes to the current {@code Maybe} and calls the appropriate {@link MaybeObserver} method on the <em>current thread</em>. * <p> * <img width="640" height="398" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.blockingSubscribe.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>An {@code onError} signal is delivered to the {@link MaybeObserver#onError(Throwable)} method. * If any of the {@code MaybeObserver}'s methods throw, the {@link RuntimeException} is propagated to the caller of this method. * If the current thread is interrupted, an {@link InterruptedException} is delivered to {@code observer.onError}. * </dd> * </dl> * @param observer the {@code MaybeObserver} to call methods on the current thread * @throws NullPointerException if {@code observer} is {@code null} * @since 3.0.0 */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull MaybeObserver<? super T> observer) { Objects.requireNonNull(observer, "observer is null"); BlockingDisposableMultiObserver<T> blockingObserver = new BlockingDisposableMultiObserver<>(); observer.onSubscribe(blockingObserver); subscribe(blockingObserver); blockingObserver.blockingConsume(observer); } /** * Returns a {@code Maybe} that subscribes to this {@code Maybe} lazily, caches its event * and replays it, to all the downstream subscribers. * <p> * <img width="640" height="244" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.cache.png" alt=""> * <p> * The operator subscribes only when the first downstream subscriber subscribes and maintains * a single subscription towards this {@code Maybe}. * <p> * <em>Note:</em> You sacrifice the ability to dispose the origin when you use the {@code cache}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Maybe} instance * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> cache() { return RxJavaPlugins.onAssembly(new MaybeCache<>(this)); } /** * Casts the success value of the current {@code Maybe} into the target type or signals a * {@link ClassCastException} if not compatible. * <p> * <img width="640" height="318" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.cast.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cast} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <U> the target type * @param clazz the type token to use for casting the success result from the current {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code clazz} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<U> cast(@NonNull Class<? extends U> clazz) { Objects.requireNonNull(clazz, "clazz is null"); return map(Functions.castFunction(clazz)); } /** * Transform a {@code Maybe} by applying a particular {@link MaybeTransformer} function to it. * <p> * <img width="640" height="615" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.compose.png" alt=""> * <p> * This method operates on the {@code Maybe} itself whereas {@link #lift} operates on the {@code Maybe}'s {@link MaybeObserver}s. * <p> * If the operator you are creating is designed to act on the individual item emitted by a {@code Maybe}, use * {@link #lift}. If your operator is designed to transform the current {@code Maybe} as a whole (for instance, by * applying a particular set of existing RxJava operators to it) use {@code compose}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code compose} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> the value type of the {@code Maybe} returned by the transformer function * @param transformer the transformer function, not {@code null} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code transformer} is {@code null} * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators">RxJava wiki: Implementing Your Own Operators</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull R> Maybe<R> compose(@NonNull MaybeTransformer<? super T, ? extends R> transformer) { return wrap(((MaybeTransformer<T, R>) Objects.requireNonNull(transformer, "transformer is null")).apply(this)); } /** * Returns a {@code Maybe} that is based on applying a specified function to the item emitted by the current {@code Maybe}, * where that function returns a {@link MaybeSource}. * <p> * <img width="640" height="216" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatMap.png" alt=""> * <p> * Note that flatMap and concatMap for {@code Maybe} is the same operation. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <R> the result value type * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a {@code MaybeSource} * @return the new {@code Maybe} instance * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @throws NullPointerException if {@code mapper} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> concatMap(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { return flatMap(mapper); } /** * Returns a {@link Completable} that completes based on applying a specified function to the item emitted by the * current {@code Maybe}, where that function returns a {@code Completable}. * <p> * <img width="640" height="304" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatMapCompletable.png" alt=""> * <p> * This operator is an alias for {@link #flatMapCompletable(Function)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a * {@code Completable} * @return the new {@code Completable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable concatMapCompletable(@NonNull Function<? super T, ? extends CompletableSource> mapper) { return flatMapCompletable(mapper); } /** * Returns a {@code Maybe} based on applying a specified function to the item emitted by the * current {@code Maybe}, where that function returns a {@link Single}. * When this {@code Maybe} just completes the resulting {@code Maybe} completes as well. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatMapSingle.png" alt=""> * <p> * This operator is an alias for {@link #flatMapSingle(Function)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> the result value type * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a * {@code Single} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> concatMapSingle(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) { return flatMapSingle(mapper); } /** * Returns a {@link Flowable} that emits the items emitted from the current {@code Maybe}, then the {@code other} {@link MaybeSource}, one after * the other, without interleaving them. * <p> * <img width="640" height="172" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatWith.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * a {@code MaybeSource} to be concatenated after the current * @return the new {@code Flowable} instance * @throws NullPointerException if {@code other} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> concatWith(@NonNull MaybeSource<? extends T> other) { Objects.requireNonNull(other, "other is null"); return concat(this, other); } /** * Returns a {@link Single} that emits a {@link Boolean} that indicates whether the current {@code Maybe} emitted a * specified item. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.contains.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item * the item to search for in the emissions from the current {@code Maybe}, not {@code null} * @return the new {@code Single} instance * @throws NullPointerException if {@code item} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<Boolean> contains(@NonNull Object item) { Objects.requireNonNull(item, "item is null"); return RxJavaPlugins.onAssembly(new MaybeContains<>(this, item)); } /** * Returns a {@link Single} that counts the total number of items emitted (0 or 1) by the current {@code Maybe} and emits * this count as a 64-bit {@link Long}. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.count.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code count} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Single} instance * @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Single<Long> count() { return RxJavaPlugins.onAssembly(new MaybeCount<>(this)); } /** * Returns a {@link Single} that emits the item emitted by the current {@code Maybe} or a specified default item * if the current {@code Maybe} is empty. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.defaultIfEmpty.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code defaultIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultItem * the item to emit if the current {@code Maybe} emits no items * @return the new {@code Single} instance * @throws NullPointerException if {@code defaultItem} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/defaultifempty.html">ReactiveX operators documentation: DefaultIfEmpty</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> defaultIfEmpty(@NonNull T defaultItem) { Objects.requireNonNull(defaultItem, "defaultItem is null"); return RxJavaPlugins.onAssembly(new MaybeToSingle<>(this, defaultItem)); } /** * Maps the {@link Notification} success value of the current {@code Maybe} back into normal * {@code onSuccess}, {@code onError} or {@code onComplete} signals. * <p> * <img width="640" height="268" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.dematerialize.png" alt=""> * <p> * The intended use of the {@code selector} function is to perform a * type-safe identity mapping (see example) on a source that is already of type * {@code Notification<T>}. The Java language doesn't allow * limiting instance methods to a certain generic argument shape, therefore, * a function is used to ensure the conversion remains type safe. * <p> * Regular {@code onError} or {@code onComplete} signals from the current {@code Maybe} are passed along to the downstream. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p> * Example: * <pre><code> * Maybe.just(Notification.createOnNext(1)) * .dematerialize(notification -&gt; notification) * .test() * .assertResult(1); * </code></pre> * @param <R> the result type * @param selector the function called with the success item and should * return a {@code Notification} instance. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code selector} is {@code null} * @since 3.0.0 * @see #materialize() */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> dematerialize(@NonNull Function<? super T, @NonNull Notification<R>> selector) { Objects.requireNonNull(selector, "selector is null"); return RxJavaPlugins.onAssembly(new MaybeDematerialize<>(this, selector)); } /** * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a * specified delay. * An error signal will not be delayed. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delay.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the delay to shift the source by * @param unit * the {@link TimeUnit} in which {@code time} is defined * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> * @see #delay(long, TimeUnit, Scheduler, boolean) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Maybe<T> delay(long time, @NonNull TimeUnit unit) { return delay(time, unit, Schedulers.computation(), false); } /** * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a * specified delay. * <p> * <img width="640" height="340" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delay.tb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time the delay to shift the source by * @param unit the {@link TimeUnit} in which {@code time} is defined * @param delayError if {@code true}, both success and error signals are delayed. if {@code false}, only success signals are delayed. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> * @see #delay(long, TimeUnit, Scheduler, boolean) * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Maybe<T> delay(long time, @NonNull TimeUnit unit, boolean delayError) { return delay(time, unit, Schedulers.computation(), delayError); } /** * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a * specified delay. * An error signal will not be delayed. * <p> * <img width="640" height="434" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delay.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify the {@link Scheduler} where the non-blocking wait and emission happens</dd> * </dl> * * @param time the delay to shift the source by * @param unit the {@link TimeUnit} in which {@code time} is defined * @param scheduler the {@code Scheduler} to use for delaying * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> * @see #delay(long, TimeUnit, Scheduler, boolean) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final Maybe<T> delay(long time, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { return delay(time, unit, scheduler, false); } /** * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a * specified delay running on the specified {@link Scheduler}. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delay.tsb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param time * the delay to shift the source by * @param unit * the {@link TimeUnit} in which {@code time} is defined * @param scheduler * the {@code Scheduler} to use for delaying * @param delayError if {@code true}, both success and error signals are delayed. if {@code false}, only success signals are delayed. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> delay(long time, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean delayError) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeDelay<>(this, Math.max(0L, time), unit, scheduler, delayError)); } /** * Delays the emission of this {@code Maybe} until the given {@link Publisher} signals an item or completes. * <p> * <img width="640" height="175" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delay.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code delayIndicator} is consumed in an unbounded manner but is cancelled after * the first item it produces.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the subscription delay value type (ignored) * @param delayIndicator * the {@code Publisher} that gets subscribed to when this {@code Maybe} signals an event and that * signal is emitted when the {@code Publisher} signals an item or completes * @return the new {@code Maybe} instance * @throws NullPointerException if {@code delayIndicator} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) public final <@NonNull U> Maybe<T> delay(@NonNull Publisher<U> delayIndicator) { Objects.requireNonNull(delayIndicator, "delayIndicator is null"); return RxJavaPlugins.onAssembly(new MaybeDelayOtherPublisher<>(this, delayIndicator)); } /** * Returns a {@code Maybe} that delays the subscription to this {@code Maybe} * until the other {@link Publisher} emits an element or completes normally. * <p> * <img width="640" height="214" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delaySubscription.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code Publisher} source is consumed in an unbounded fashion (without applying backpressure).</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the value type of the other {@code Publisher}, irrelevant * @param subscriptionIndicator the other {@code Publisher} that should trigger the subscription * to this {@code Publisher}. * @throws NullPointerException if {@code subscriptionIndicator} is {@code null} * @return the new {@code Maybe} instance */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> delaySubscription(@NonNull Publisher<U> subscriptionIndicator) { Objects.requireNonNull(subscriptionIndicator, "subscriptionIndicator is null"); return RxJavaPlugins.onAssembly(new MaybeDelaySubscriptionOtherPublisher<>(this, subscriptionIndicator)); } /** * Returns a {@code Maybe} that delays the subscription to the current {@code Maybe} by a given amount of time. * <p> * <img width="640" height="471" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delaySubscription.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delaySubscription} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the time to delay the subscription * @param unit * the time unit of {@code delay} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> * @see #delaySubscription(long, TimeUnit, Scheduler) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Maybe<T> delaySubscription(long time, @NonNull TimeUnit unit) { return delaySubscription(time, unit, Schedulers.computation()); } /** * Returns a {@code Maybe} that delays the subscription to the current {@code Maybe} by a given amount of time, * both waiting and subscribing on a given {@link Scheduler}. * <p> * <img width="640" height="420" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.delaySubscription.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param time * the time to delay the subscription * @param unit * the time unit of {@code delay} * @param scheduler * the {@code Scheduler} on which the waiting and subscription will happen * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final Maybe<T> delaySubscription(long time, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { return delaySubscription(Flowable.timer(time, unit, scheduler)); } /** * Calls the specified {@link Consumer} with the success item after this item has been emitted to the downstream. * <p>Note that the {@code onAfterSuccess} action is shared between subscriptions and as such * should be thread-safe. * <p> * <img width="640" height="527" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doAfterSuccess.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doAfterSuccess} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.0.1 - experimental * @param onAfterSuccess the {@code Consumer} that will be called after emitting an item from upstream to the downstream * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onAfterSuccess} is {@code null} * @since 2.1 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doAfterSuccess(@NonNull Consumer<? super T> onAfterSuccess) { Objects.requireNonNull(onAfterSuccess, "onAfterSuccess is null"); return RxJavaPlugins.onAssembly(new MaybeDoAfterSuccess<>(this, onAfterSuccess)); } /** * Registers an {@link Action} to be called when this {@code Maybe} invokes either * {@link MaybeObserver#onComplete onSuccess}, * {@link MaybeObserver#onComplete onComplete} or {@link MaybeObserver#onError onError}. * <p> * <img width="640" height="249" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doAfterTerminate.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onAfterTerminate * an {@code Action} to be invoked when the current {@code Maybe} finishes * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onAfterTerminate} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doAfterTerminate(@NonNull Action onAfterTerminate) { return RxJavaPlugins.onAssembly(new MaybePeek<>(this, Functions.emptyConsumer(), // onSubscribe Functions.emptyConsumer(), // onSuccess Functions.emptyConsumer(), // onError Functions.EMPTY_ACTION, // onComplete Objects.requireNonNull(onAfterTerminate, "onAfterTerminate is null"), Functions.EMPTY_ACTION // dispose )); } /** * Calls the specified action after this {@code Maybe} signals {@code onSuccess}, {@code onError} or {@code onComplete} or gets disposed by * the downstream. * <p> * <img width="640" height="247" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doFinally.png" alt=""> * <p> * In case of a race between a terminal event and a dispose call, the provided {@code onFinally} action * is executed once per subscription. * <p>Note that the {@code onFinally} action is shared between subscriptions and as such * should be thread-safe. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.0.1 - experimental * @param onFinally the action called when this {@code Maybe} terminates or gets disposed * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onFinally} is {@code null} * @since 2.1 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doFinally(@NonNull Action onFinally) { Objects.requireNonNull(onFinally, "onFinally is null"); return RxJavaPlugins.onAssembly(new MaybeDoFinally<>(this, onFinally)); } /** * Calls the shared {@link Action} if a {@link MaybeObserver} subscribed to the current {@code Maybe} * disposes the common {@link Disposable} it received via {@code onSubscribe}. * <p> * <img width="640" height="277" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doOnDispose.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnDispose} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onDispose the action called when the subscription is disposed * @throws NullPointerException if {@code onDispose} is {@code null} * @return the new {@code Maybe} instance */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnDispose(@NonNull Action onDispose) { return RxJavaPlugins.onAssembly(new MaybePeek<>(this, Functions.emptyConsumer(), // onSubscribe Functions.emptyConsumer(), // onSuccess Functions.emptyConsumer(), // onError Functions.EMPTY_ACTION, // onComplete Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) after Objects.requireNonNull(onDispose, "onDispose is null") )); } /** * Invokes an {@link Action} just before the current {@code Maybe} calls {@code onComplete}. * <p> * <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnComplete.m.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnComplete} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onComplete * the action to invoke when the current {@code Maybe} calls {@code onComplete} * @return the new {@code Maybe} with the side-effecting behavior applied * @throws NullPointerException if {@code onComplete} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnComplete(@NonNull Action onComplete) { return RxJavaPlugins.onAssembly(new MaybePeek<>(this, Functions.emptyConsumer(), // onSubscribe Functions.emptyConsumer(), // onSuccess Functions.emptyConsumer(), // onError Objects.requireNonNull(onComplete, "onComplete is null"), Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) Functions.EMPTY_ACTION // dispose )); } /** * Calls the shared {@link Consumer} with the error sent via {@code onError} for each * {@link MaybeObserver} that subscribes to the current {@code Maybe}. * <p> * <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnError.m.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onError the consumer called with the success value of {@code onError} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onError} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnError(@NonNull Consumer<? super Throwable> onError) { return RxJavaPlugins.onAssembly(new MaybePeek<>(this, Functions.emptyConsumer(), // onSubscribe Functions.emptyConsumer(), // onSuccess Objects.requireNonNull(onError, "onError is null"), Functions.EMPTY_ACTION, // onComplete Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) Functions.EMPTY_ACTION // dispose )); } /** * Calls the given {@code onEvent} callback with the (success value, {@code null}) for an {@code onSuccess}, ({@code null}, throwable) for * an {@code onError} or ({@code null}, {@code null}) for an {@code onComplete} signal from this {@code Maybe} before delivering said * signal to the downstream. * <p> * <img width="640" height="297" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doOnEvent.png" alt=""> * <p> * The exceptions thrown from the callback will override the event so the downstream receives the * error instead of the original signal. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnEvent} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onEvent the callback to call with the success value or the exception, whichever is not {@code null} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onEvent} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> doOnEvent(@NonNull BiConsumer<@Nullable ? super T, @Nullable ? super Throwable> onEvent) { Objects.requireNonNull(onEvent, "onEvent is null"); return RxJavaPlugins.onAssembly(new MaybeDoOnEvent<>(this, onEvent)); } /** * Calls the appropriate {@code onXXX} method (shared between all {@link MaybeObserver}s) for the lifecycle events of * the sequence (subscription, disposal). * <p> * <img width="640" height="183" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doOnLifecycle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnLifecycle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onSubscribe * a {@link Consumer} called with the {@link Disposable} sent via {@link MaybeObserver#onSubscribe(Disposable)} * @param onDispose * called when the downstream disposes the {@code Disposable} via {@code dispose()} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onSubscribe} or {@code onDispose} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> doOnLifecycle(@NonNull Consumer<? super Disposable> onSubscribe, @NonNull Action onDispose) { Objects.requireNonNull(onSubscribe, "onSubscribe is null"); Objects.requireNonNull(onDispose, "onDispose is null"); return RxJavaPlugins.onAssembly(new MaybeDoOnLifecycle<>(this, onSubscribe, onDispose)); } /** * Calls the shared {@link Consumer} with the {@link Disposable} sent through the {@code onSubscribe} for each * {@link MaybeObserver} that subscribes to the current {@code Maybe}. * <p> * <img width="640" height="506" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doOnSubscribe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onSubscribe the {@code Consumer} called with the {@code Disposable} sent via {@code onSubscribe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onSubscribe} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnSubscribe(@NonNull Consumer<? super Disposable> onSubscribe) { return RxJavaPlugins.onAssembly(new MaybePeek<>(this, Objects.requireNonNull(onSubscribe, "onSubscribe is null"), Functions.emptyConsumer(), // onSuccess Functions.emptyConsumer(), // onError Functions.EMPTY_ACTION, // onComplete Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) Functions.EMPTY_ACTION // dispose )); } /** * Returns a {@code Maybe} instance that calls the given onTerminate callback * just before this {@code Maybe} completes normally or with an exception. * <p> * <img width="640" height="249" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doOnTerminate.png" alt=""> * <p> * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or * {@code onError} notification. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.2.7 - experimental * @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onTerminate} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> * @see #doOnTerminate(Action) * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnTerminate(@NonNull Action onTerminate) { Objects.requireNonNull(onTerminate, "onTerminate is null"); return RxJavaPlugins.onAssembly(new MaybeDoOnTerminate<>(this, onTerminate)); } /** * Calls the shared {@link Consumer} with the success value sent via {@code onSuccess} for each * {@link MaybeObserver} that subscribes to the current {@code Maybe}. * <p> * <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnSuccess.m.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnSuccess} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onSuccess the {@code Consumer} called with the success value of the upstream * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onSuccess} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnSuccess(@NonNull Consumer<? super T> onSuccess) { return RxJavaPlugins.onAssembly(new MaybePeek<>(this, Functions.emptyConsumer(), // onSubscribe Objects.requireNonNull(onSuccess, "onSuccess is null"), Functions.emptyConsumer(), // onError Functions.EMPTY_ACTION, // onComplete Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) Functions.EMPTY_ACTION // dispose )); } /** * Filters the success item of the {@code Maybe} via a predicate function and emitting it if the predicate * returns {@code true}, completing otherwise. * <p> * <img width="640" height="291" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.filter.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code filter} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * a function that evaluates the item emitted by the current {@code Maybe}, returning {@code true} * if it passes the filter * @return the new {@code Maybe} instance * @throws NullPointerException if {@code predicate} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> filter(@NonNull Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return RxJavaPlugins.onAssembly(new MaybeFilter<>(this, predicate)); } /** * Returns a {@code Maybe} that is based on applying a specified function to the item emitted by the current {@code Maybe}, * where that function returns a {@link MaybeSource}. * <p> * <img width="640" height="357" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>Note that flatMap and concatMap for {@code Maybe} is the same operation. * * @param <R> the result value type * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a {@code MaybeSource} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> flatMap(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatten<>(this, mapper)); } /** * Maps the {@code onSuccess}, {@code onError} or {@code onComplete} signals of the current {@code Maybe} into a {@link MaybeSource} and emits that * {@code MaybeSource}'s signals. * <p> * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.mmm.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the result type * @param onSuccessMapper * a function that returns a {@code MaybeSource} to merge for the {@code onSuccess} item emitted by this {@code Maybe} * @param onErrorMapper * a function that returns a {@code MaybeSource} to merge for an {@code onError} notification from this {@code Maybe} * @param onCompleteSupplier * a function that returns a {@code MaybeSource} to merge for an {@code onComplete} notification this {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code onSuccessMapper}, {@code onErrorMapper} or {@code onCompleteSupplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> flatMap( @NonNull Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper, @NonNull Function<? super Throwable, ? extends MaybeSource<? extends R>> onErrorMapper, @NonNull Supplier<? extends MaybeSource<? extends R>> onCompleteSupplier) { Objects.requireNonNull(onSuccessMapper, "onSuccessMapper is null"); Objects.requireNonNull(onErrorMapper, "onErrorMapper is null"); Objects.requireNonNull(onCompleteSupplier, "onCompleteSupplier is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapNotification<>(this, onSuccessMapper, onErrorMapper, onCompleteSupplier)); } /** * Returns a {@code Maybe} that emits the results of a specified function to the pair of values emitted by the * current {@code Maybe} and a specified mapped {@link MaybeSource}. * <p> * <img width="640" height="268" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.combiner.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the type of items emitted by the {@code MaybeSource} returned by the {@code mapper} function * @param <R> * the type of items emitted by the resulting {@code Maybe} * @param mapper * a function that returns a {@code MaybeSource} for the item emitted by the current {@code Maybe} * @param combiner * a function that combines one item emitted by each of the source and collection {@code MaybeSource} and * returns an item to be emitted by the resulting {@code MaybeSource} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code mapper} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U, @NonNull R> Maybe<R> flatMap(@NonNull Function<? super T, ? extends MaybeSource<? extends U>> mapper, @NonNull BiFunction<? super T, ? super U, ? extends R> combiner) { Objects.requireNonNull(mapper, "mapper is null"); Objects.requireNonNull(combiner, "combiner is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapBiSelector<>(this, mapper, combiner)); } /** * Maps the success value of the current {@code Maybe} into an {@link Iterable} and emits its items as a * {@link Flowable} sequence. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsFlowable.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code flattenAsFlowable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the type of item emitted by the inner {@code Iterable} * @param mapper * a function that returns an {@code Iterable} sequence of values for when given an item emitted by the * current {@code Maybe} * @return the new {@code Flowable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @see #flattenStreamAsFlowable(Function) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Flowable<U> flattenAsFlowable(@NonNull Function<? super T, @NonNull ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapIterableFlowable<>(this, mapper)); } /** * Maps the success value of the current {@code Maybe} into an {@link Iterable} and emits its items as an * {@link Observable} sequence. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flattenAsObservable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the type of item emitted by the resulting {@code Iterable} * @param mapper * a function that returns an {@code Iterable} sequence of values for when given an item emitted by the * current {@code Maybe} * @return the new {@code Observable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Observable<U> flattenAsObservable(@NonNull Function<? super T, @NonNull ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapIterableObservable<>(this, mapper)); } /** * Returns an {@link Observable} that is based on applying a specified function to the item emitted by the current {@code Maybe}, * where that function returns an {@link ObservableSource}. * <p> * <img width="640" height="302" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMapObservable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> the result value type * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns an {@code ObservableSource} * @return the new {@code Observable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Observable<R> flatMapObservable(@NonNull Function<? super T, ? extends ObservableSource<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapObservable<>(this, mapper)); } /** * Returns a {@link Flowable} that emits items based on applying a specified function to the item emitted by the * current {@code Maybe}, where that function returns a {@link Publisher}. * <p> * <img width="640" height="312" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapPublisher.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the downstream backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMapPublisher} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> the result value type * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a * {@code Flowable} * @return the new {@code Flowable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Flowable<R> flatMapPublisher(@NonNull Function<? super T, @NonNull ? extends Publisher<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapPublisher<>(this, mapper)); } /** * Returns a {@code Maybe} based on applying a specified function to the item emitted by the * current {@code Maybe}, where that function returns a {@link Single}. * When this {@code Maybe} just completes the resulting {@code Maybe} completes as well. * <p> * <img width="640" height="357" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * <p>History: 2.0.2 - experimental * @param <R> the result value type * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a * {@code Single} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @since 2.1 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> flatMapSingle(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapSingle<>(this, mapper)); } /** * Returns a {@link Completable} that completes based on applying a specified function to the item emitted by the * current {@code Maybe}, where that function returns a {@code Completable}. * <p> * <img width="640" height="303" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapCompletable3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param mapper * a function that, when applied to the item emitted by the current {@code Maybe}, returns a * {@code Completable} * @return the new {@code Completable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable flatMapCompletable(@NonNull Function<? super T, ? extends CompletableSource> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapCompletable<>(this, mapper)); } /** * Hides the identity of this {@code Maybe} and its {@link Disposable}. * <p> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.hide.png" alt=""> * <p>Allows preventing certain identity-based * optimizations (fusion). * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code hide} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code Maybe} instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> hide() { return RxJavaPlugins.onAssembly(new MaybeHide<>(this)); } /** * Returns a {@link Completable} that ignores the item emitted by the current {@code Maybe} and only calls {@code onComplete} or {@code onError}. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ignoreElement.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ignoreElement} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Completable} instance * @see <a href="http://reactivex.io/documentation/operators/ignoreelements.html">ReactiveX operators documentation: IgnoreElements</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Completable ignoreElement() { return RxJavaPlugins.onAssembly(new MaybeIgnoreElementCompletable<>(this)); } /** * Returns a {@link Single} that emits {@code true} if the current {@code Maybe} is empty, otherwise {@code false}. * <p> * <img width="640" height="444" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.isEmpty.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code isEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Single} instance * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Single<Boolean> isEmpty() { return RxJavaPlugins.onAssembly(new MaybeIsEmptySingle<>(this)); } /** * <strong>This method requires advanced knowledge about building operators, please consider * other standard composition methods first;</strong> * Returns a {@code Maybe} which, when subscribed to, invokes the {@link MaybeOperator#apply(MaybeObserver) apply(MaybeObserver)} method * of the provided {@link MaybeOperator} for each individual downstream {@code Maybe} and allows the * insertion of a custom operator by accessing the downstream's {@link MaybeObserver} during this subscription phase * and providing a new {@code MaybeObserver}, containing the custom operator's intended business logic, that will be * used in the subscription process going further upstream. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.lift.png" alt=""> * <p> * Generally, such a new {@code MaybeObserver} will wrap the downstream's {@code MaybeObserver} and forwards the * {@code onSuccess}, {@code onError} and {@code onComplete} events from the upstream directly or according to the * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the * flow control calls of {@code dispose} and {@code isDisposed} that would have traveled upstream and perform * additional actions depending on the same business logic requirements. * <p> * Example: * <pre><code> * // Step 1: Create the consumer type that will be returned by the MaybeOperator.apply(): * * public final class CustomMaybeObserver&lt;T&gt; implements MaybeObserver&lt;T&gt;, Disposable { * * // The downstream's MaybeObserver that will receive the onXXX events * final MaybeObserver&lt;? super String&gt; downstream; * * // The connection to the upstream source that will call this class' onXXX methods * Disposable upstream; * * // The constructor takes the downstream subscriber and usually any other parameters * public CustomMaybeObserver(MaybeObserver&lt;? super String&gt; downstream) { * this.downstream = downstream; * } * * // In the subscription phase, the upstream sends a Disposable to this class * // and subsequently this class has to send a Disposable to the downstream. * // Note that relaying the upstream's Disposable directly is not allowed in RxJava * &#64;Override * public void onSubscribe(Disposable d) { * if (upstream != null) { * d.dispose(); * } else { * upstream = d; * downstream.onSubscribe(this); * } * } * * // The upstream calls this with the next item and the implementation's * // responsibility is to emit an item to the downstream based on the intended * // business logic, or if it can't do so for the particular item, * // request more from the upstream * &#64;Override * public void onSuccess(T item) { * String str = item.toString(); * if (str.length() &lt; 2) { * downstream.onSuccess(str); * } else { * // Maybe is expected to produce one of the onXXX events only * downstream.onComplete(); * } * } * * // Some operators may handle the upstream's error while others * // could just forward it to the downstream. * &#64;Override * public void onError(Throwable throwable) { * downstream.onError(throwable); * } * * // When the upstream completes, usually the downstream should complete as well. * &#64;Override * public void onComplete() { * downstream.onComplete(); * } * * // Some operators may use their own resources which should be cleaned up if * // the downstream disposes the flow before it completed. Operators without * // resources can simply forward the dispose to the upstream. * // In some cases, a disposed flag may be set by this method so that other parts * // of this class may detect the dispose and stop sending events * // to the downstream. * &#64;Override * public void dispose() { * upstream.dispose(); * } * * // Some operators may simply forward the call to the upstream while others * // can return the disposed flag set in dispose(). * &#64;Override * public boolean isDisposed() { * return upstream.isDisposed(); * } * } * * // Step 2: Create a class that implements the MaybeOperator interface and * // returns the custom consumer type from above in its apply() method. * // Such class may define additional parameters to be submitted to * // the custom consumer type. * * final class CustomMaybeOperator&lt;T&gt; implements MaybeOperator&lt;String&gt; { * &#64;Override * public MaybeObserver&lt;? super String&gt; apply(MaybeObserver&lt;? super T&gt; upstream) { * return new CustomMaybeObserver&lt;T&gt;(upstream); * } * } * * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it * // or reusing an existing one. * * Maybe.just(5) * .lift(new CustomMaybeOperator&lt;Integer&gt;()) * .test() * .assertResult("5"); * * Maybe.just(15) * .lift(new CustomMaybeOperator&lt;Integer&gt;()) * .test() * .assertResult(); * </code></pre> * <p> * Creating custom operators can be complicated and it is recommended one consults the * <a href="https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0">RxJava wiki: Writing operators</a> page about * the tools, requirements, rules, considerations and pitfalls of implementing them. * <p> * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Maybe} * class and creating a {@link MaybeTransformer} with it is recommended. * <p> * Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method * requires a non-{@code null} {@code MaybeObserver} instance to be returned, which is then unconditionally subscribed to * the current {@code Maybe}. For example, if the operator decided there is no reason to subscribe to the * upstream source because of some optimization possibility or a failure to prepare the operator, it still has to * return a {@code MaybeObserver} that should immediately dispose the upstream's {@link Disposable} in its * {@code onSubscribe} method. Again, using a {@code MaybeTransformer} and extending the {@code Maybe} is * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code lift} does not operate by default on a particular {@link Scheduler}, however, the * {@code MaybeOperator} may use a {@code Scheduler} to support its own asynchronous behavior.</dd> * </dl> * * @param <R> the output value type * @param lift the {@code MaybeOperator} that receives the downstream's {@code MaybeObserver} and should return * a {@code MaybeObserver} with custom behavior to be used as the consumer for the current * {@code Maybe}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code lift} is {@code null} * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0">RxJava wiki: Writing operators</a> * @see #compose(MaybeTransformer) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> lift(@NonNull MaybeOperator<? extends R, ? super T> lift) { Objects.requireNonNull(lift, "lift is null"); return RxJavaPlugins.onAssembly(new MaybeLift<>(this, lift)); } /** * Returns a {@code Maybe} that applies a specified function to the item emitted by the current {@code Maybe} and * emits the result of this function application. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.map.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code map} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> the result value type * @param mapper * a function to apply to the item emitted by the {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code mapper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull R> Maybe<R> map(@NonNull Function<? super T, ? extends R> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeMap<>(this, mapper)); } /** * Maps the signal types of this {@code Maybe} into a {@link Notification} of the same kind * and emits it as a {@link Single}'s {@code onSuccess} value to downstream. * <p> * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.2.4 - experimental * @return the new {@code Single} instance * @since 3.0.0 * @see Single#dematerialize(Function) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Single<Notification<T>> materialize() { return RxJavaPlugins.onAssembly(new MaybeMaterialize<>(this)); } /** * Flattens this {@code Maybe} and another {@link MaybeSource} into a single {@link Flowable}, without any transformation. * <p> * <img width="640" height="218" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.mergeWith.png" alt=""> * <p> * You can combine items emitted by multiple {@code Maybe}s so that they appear as a single {@code Flowable}, by * using the {@code mergeWith} method. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * a {@code MaybeSource} to be merged * @return the new {@code Flowable} instance * @throws NullPointerException if {@code other} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { Objects.requireNonNull(other, "other is null"); return merge(this, other); } /** * Wraps a {@code Maybe} to emit its item (or notify of its error) on a specified {@link Scheduler}, * asynchronously. * <p> * <img width="640" height="183" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.observeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param scheduler * the {@code Scheduler} to notify subscribers on * @return the new {@code Maybe} instance that its subscribers are notified on the specified * {@code Scheduler} * @throws NullPointerException if {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/observeon.html">ReactiveX operators documentation: ObserveOn</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #subscribeOn */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> observeOn(@NonNull Scheduler scheduler) { Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeObserveOn<>(this, scheduler)); } /** * Filters the items emitted by the current {@code Maybe}, only emitting its success value if that * is an instance of the supplied {@link Class}. * <p> * <img width="640" height="291" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ofType.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ofType} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the output type * @param clazz * the class type to filter the items emitted by the current {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code clazz} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<U> ofType(@NonNull Class<U> clazz) { Objects.requireNonNull(clazz, "clazz is null"); return filter(Functions.isInstanceOf(clazz)).cast(clazz); } /** * Calls the specified converter function during assembly time and returns its resulting value. * <p> * <img width="640" height="731" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.to.png" alt=""> * <p> * This allows fluent conversion to any other type. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code to} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current {@code Maybe} instance and returns a value * @return the converted value * @throws NullPointerException if {@code converter} is {@code null} * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> R to(@NonNull MaybeConverter<T, ? extends R> converter) { return Objects.requireNonNull(converter, "converter is null").apply(this); } /** * Converts this {@code Maybe} into a backpressure-aware {@link Flowable} instance composing cancellation * through. * <p> * <img width="640" height="346" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.toFlowable.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toFlowable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code Flowable} instance */ @SuppressWarnings("unchecked") @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Flowable<T> toFlowable() { if (this instanceof FuseToFlowable) { return ((FuseToFlowable<T>)this).fuseToFlowable(); } return RxJavaPlugins.onAssembly(new MaybeToFlowable<>(this)); } /** * Returns a {@link Future} representing the single value emitted by the current {@code Maybe} * or {@code null} if the current {@code Maybe} is empty. * <p> * <img width="640" height="292" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/Maybe.toFuture.png" alt=""> * <p> * Cancelling the {@code Future} will cancel the subscription to the current {@code Maybe}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toFuture} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Future} instance * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX documentation: To</a> * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Future<T> toFuture() { return subscribeWith(new FutureMultiObserver<>()); } /** * Converts this {@code Maybe} into an {@link Observable} instance composing disposal * through. * <p> * <img width="640" height="346" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.toObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toObservable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code Observable} instance */ @SuppressWarnings("unchecked") @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Observable<T> toObservable() { if (this instanceof FuseToObservable) { return ((FuseToObservable<T>)this).fuseToObservable(); } return RxJavaPlugins.onAssembly(new MaybeToObservable<>(this)); } /** * Converts this {@code Maybe} into a {@link Single} instance composing disposal * through and turning an empty {@code Maybe} into a signal of {@link NoSuchElementException}. * <p> * <img width="640" height="361" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.toSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code Single} instance * @see #defaultIfEmpty(Object) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Single<T> toSingle() { return RxJavaPlugins.onAssembly(new MaybeToSingle<>(this, null)); } /** * Returns a {@code Maybe} instance that if this {@code Maybe} emits an error, it will emit an {@code onComplete} * and swallow the throwable. * <p> * <img width="640" height="372" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onErrorComplete.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code Maybe} instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> onErrorComplete() { return onErrorComplete(Functions.alwaysTrue()); } /** * Returns a {@code Maybe} instance that if this {@code Maybe} emits an error and the predicate returns * {@code true}, it will emit an {@code onComplete} and swallow the throwable. * <p> * <img width="640" height="220" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onErrorComplete.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param predicate the predicate to call when an {@link Throwable} is emitted which should return {@code true} * if the {@code Throwable} should be swallowed and replaced with an {@code onComplete}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code predicate} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorComplete(@NonNull Predicate<? super Throwable> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return RxJavaPlugins.onAssembly(new MaybeOnErrorComplete<>(this, predicate)); } /** * Resumes the flow with the given {@link MaybeSource} when the current {@code Maybe} fails instead of * signaling the error via {@code onError}. * <p> * <img width="640" height="298" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onErrorResumeWith.png" alt=""> * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorResumeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param fallback * the next {@code MaybeSource} that will take over if the current {@code Maybe} encounters * an error * @return the new {@code Maybe} instance * @throws NullPointerException if {@code fallback} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorResumeWith(@NonNull MaybeSource<? extends T> fallback) { Objects.requireNonNull(fallback, "fallback is null"); return onErrorResumeNext(Functions.justFunction(fallback)); } /** * Resumes the flow with a {@link MaybeSource} returned for the failure {@link Throwable} of the current {@code Maybe} by a * function instead of signaling the error via {@code onError}. * <p> * <img width="640" height="298" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onErrorResumeNext.png" alt=""> * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param fallbackSupplier * a function that returns a {@code MaybeSource} that will take over if the current {@code Maybe} encounters * an error * @return the new {@code Maybe} instance * @throws NullPointerException if {@code fallbackSupplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorResumeNext(@NonNull Function<? super Throwable, ? extends MaybeSource<? extends T>> fallbackSupplier) { Objects.requireNonNull(fallbackSupplier, "fallbackSupplier is null"); return RxJavaPlugins.onAssembly(new MaybeOnErrorNext<>(this, fallbackSupplier)); } /** * Ends the flow with a success item returned by a function for the {@link Throwable} error signaled by the current * {@code Maybe} instead of signaling the error via {@code onError}. * <p> * <img width="640" height="377" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onErrorReturn.png" alt=""> * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorReturn} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param itemSupplier * a function that returns a single value that will be emitted as success value * the current {@code Maybe} signals an {@code onError} event * @return the new {@code Maybe} instance * @throws NullPointerException if {@code itemSupplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorReturn(@NonNull Function<? super Throwable, ? extends T> itemSupplier) { Objects.requireNonNull(itemSupplier, "itemSupplier is null"); return RxJavaPlugins.onAssembly(new MaybeOnErrorReturn<>(this, itemSupplier)); } /** * Ends the flow with the given success item when the current {@code Maybe} fails instead of signaling the error via {@code onError}. * <p> * <img width="640" height="377" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onErrorReturnItem.png" alt=""> * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorReturnItem} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item * the value that is emitted as {@code onSuccess} in case the current {@code Maybe} signals an {@code onError} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code item} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorReturnItem(@NonNull T item) { Objects.requireNonNull(item, "item is null"); return onErrorReturn(Functions.justFunction(item)); } /** * Nulls out references to the upstream producer and downstream {@link MaybeObserver} if * the sequence is terminated or downstream calls {@code dispose()}. * <p> * <img width="640" height="263" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.onTerminateDetach.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code Maybe} instance * the sequence is terminated or downstream calls {@code dispose()} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> onTerminateDetach() { return RxJavaPlugins.onAssembly(new MaybeDetach<>(this)); } /** * Returns a {@link Flowable} that repeats the sequence of items emitted by the current {@code Maybe} indefinitely. * <p> * <img width="640" height="276" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.repeat.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Flowable} instance * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Flowable<T> repeat() { return repeat(Long.MAX_VALUE); } /** * Returns a {@link Flowable} that repeats the sequence of items emitted by the current {@code Maybe} at most * {@code count} times. * <p> * <img width="640" height="294" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.repeat.n.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator honors downstream backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param times * the number of times the current {@code Maybe} items are repeated, a count of 0 will yield an empty * sequence * @return the new {@code Flowable} instance * @throws IllegalArgumentException * if {@code times} is negative * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Flowable<T> repeat(long times) { return toFlowable().repeat(times); } /** * Returns a {@link Flowable} that repeats the sequence of items emitted by the current {@code Maybe} until * the provided stop function returns {@code true}. * <p> * <img width="640" height="329" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.repeatUntil.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator honors downstream backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeatUntil} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param stop * a boolean supplier that is called when the current {@code Flowable} completes and unless it returns * {@code false}, the current {@code Flowable} is resubscribed * @return the new {@code Flowable} instance * @throws NullPointerException * if {@code stop} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Flowable<T> repeatUntil(@NonNull BooleanSupplier stop) { return toFlowable().repeatUntil(stop); } /** * Returns a {@link Flowable} that emits the same values as the current {@code Maybe} with the exception of an * {@code onComplete}. An {@code onComplete} notification from the source will result in the emission of * a {@code void} item to the {@code Flowable} provided as an argument to the {@code notificationHandler} * function. If that {@link Publisher} calls {@code onComplete} or {@code onError} then {@code repeatWhen} will * call {@code onComplete} or {@code onError} on the child observer. Otherwise, this operator will * resubscribe to the current {@code Maybe}. * <p> * <img width="640" height="562" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.repeatWhen.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well. * If this expectation is violated, the operator <em>may</em> throw an {@link IllegalStateException}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeatWhen} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param handler * receives a {@code Publisher} of notifications with which a user can complete or error, aborting the repeat. * @return the new {@code Flowable} instance * @throws NullPointerException if {@code handler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Flowable<T> repeatWhen(@NonNull Function<? super Flowable<Object>, @NonNull ? extends Publisher<@NonNull ?>> handler) { return toFlowable().repeatWhen(handler); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe}, resubscribing to it if it calls {@code onError} * (infinite retry count). * <p> * <img width="640" height="393" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retry.png" alt=""> * <p> * If the current {@code Maybe} calls {@link MaybeObserver#onError}, this operator will resubscribe to the current * {@code Maybe} rather than propagating the {@code onError} call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Maybe} instance * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> retry() { return retry(Long.MAX_VALUE, Functions.alwaysTrue()); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe}, resubscribing to it if it calls {@code onError} * and the predicate returns {@code true} for that specific exception and retry count. * <p> * <img width="640" height="230" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retry.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the predicate that determines if a resubscription may happen in case of a specific exception * and retry count * @return the new {@code Maybe} instance * @throws NullPointerException if {@code predicate} is {@code null} * @see #retry() * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> retry(@NonNull BiPredicate<? super Integer, ? super Throwable> predicate) { return toFlowable().retry(predicate).singleElement(); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe}, resubscribing to it if it calls {@code onError} * up to a specified number of retries. * <p> * <img width="640" height="329" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retry.n.png" alt=""> * <p> * If the current {@code Maybe} calls {@link MaybeObserver#onError}, this operator will resubscribe to the current * {@code Maybe} for a maximum of {@code count} resubscriptions rather than propagating the * {@code onError} call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param times * the number of times to resubscribe if the current {@code Maybe} fails * @return the new {@code Maybe} instance * @throws IllegalArgumentException if {@code times} is negative * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> retry(long times) { return retry(times, Functions.alwaysTrue()); } /** * Retries at most {@code times} or until the predicate returns {@code false}, whichever happens first. * <p> * <img width="640" height="259" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retry.nf.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param times the number of times to resubscribe if the current {@code Maybe} fails * @param predicate the predicate called with the failure {@link Throwable} and should return {@code true} to trigger a retry. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code predicate} is {@code null} * @throws IllegalArgumentException if {@code times} is negative */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> retry(long times, @NonNull Predicate<? super Throwable> predicate) { return toFlowable().retry(times, predicate).singleElement(); } /** * Retries the current {@code Maybe} if it fails and the predicate returns {@code true}. * <p> * <img width="640" height="240" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retry.g.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate the predicate that receives the failure {@link Throwable} and should return {@code true} to trigger a retry. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code predicate} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> retry(@NonNull Predicate<? super Throwable> predicate) { return retry(Long.MAX_VALUE, predicate); } /** * Retries until the given stop function returns {@code true}. * <p> * <img width="640" height="285" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retryUntil.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retryUntil} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param stop the function that should return {@code true} to stop retrying * @return the new {@code Maybe} instance * @throws NullPointerException if {@code stop} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> retryUntil(@NonNull BooleanSupplier stop) { Objects.requireNonNull(stop, "stop is null"); return retry(Long.MAX_VALUE, Functions.predicateReverseFor(stop)); } /** * Returns a {@code Maybe} that emits the same values as the current {@code Maybe} with the exception of an * {@code onError}. An {@code onError} notification from the source will result in the emission of a * {@link Throwable} item to the {@link Flowable} provided as an argument to the {@code notificationHandler} * function. If the returned {@link Publisher} calls {@code onComplete} or {@code onError} then {@code retry} will call * {@code onComplete} or {@code onError} on the child subscription. Otherwise, this operator will * resubscribe to the current {@code Maybe}. * <p> * <img width="640" height="405" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.retryWhen.png" alt=""> * <p> * Example: * * This retries 3 times, each time incrementing the number of seconds it waits. * * <pre><code> * Maybe.create((MaybeEmitter&lt;? super String&gt; s) -&gt; { * System.out.println("subscribing"); * s.onError(new RuntimeException("always fails")); * }, BackpressureStrategy.BUFFER).retryWhen(attempts -&gt; { * return attempts.zipWith(Publisher.range(1, 3), (n, i) -&gt; i).flatMap(i -&gt; { * System.out.println("delay retry by " + i + " second(s)"); * return Flowable.timer(i, TimeUnit.SECONDS); * }); * }).blockingForEach(System.out::println); * </code></pre> * * Output is: * * <pre> {@code * subscribing * delay retry by 1 second(s) * subscribing * delay retry by 2 second(s) * subscribing * delay retry by 3 second(s) * subscribing * } </pre> * <p> * Note that the inner {@code Publisher} returned by the handler function should signal * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to * the operator is asynchronous, signalling {@code onNext} followed by {@code onComplete} immediately may * result in the sequence to be completed immediately. Similarly, if this inner * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is * active, the sequence is terminated with the same signal immediately. * <p> * The following example demonstrates how to retry an asynchronous source with a delay: * <pre><code> * Maybe.timer(1, TimeUnit.SECONDS) * .doOnSubscribe(s -&gt; System.out.println("subscribing")) * .map(v -&gt; { throw new RuntimeException(); }) * .retryWhen(errors -&gt; { * AtomicInteger counter = new AtomicInteger(); * return errors * .takeWhile(e -&gt; counter.getAndIncrement() != 3) * .flatMap(e -&gt; { * System.out.println("delay retry by " + counter.get() + " second(s)"); * return Flowable.timer(counter.get(), TimeUnit.SECONDS); * }); * }) * .blockingGet(); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param handler * receives a {@code Publisher} of notifications with which a user can complete or error, aborting the * retry * @return the new {@code Maybe} instance * @throws NullPointerException if {@code handler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Maybe<T> retryWhen( @NonNull Function<? super Flowable<Throwable>, @NonNull ? extends Publisher<@NonNull ?>> handler) { return toFlowable().retryWhen(handler).singleElement(); } /** * Wraps the given {@link MaybeObserver}, catches any {@link RuntimeException}s thrown by its * {@link MaybeObserver#onSubscribe(Disposable)}, {@link MaybeObserver#onSuccess(Object)}, * {@link MaybeObserver#onError(Throwable)} or {@link MaybeObserver#onComplete()} methods * and routes those to the global error handler via {@link RxJavaPlugins#onError(Throwable)}. * <p> * By default, the {@code Maybe} protocol forbids the {@code onXXX} methods to throw, but some * {@code MaybeObserver} implementation may do it anyway, causing undefined behavior in the * upstream. This method and the underlying safe wrapper ensures such misbehaving consumers don't * disrupt the protocol. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code safeSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param observer the potentially misbehaving {@code MaybeObserver} * @throws NullPointerException if {@code observer} is {@code null} * @see #subscribe(Consumer,Consumer, Action) * @since 3.0.0 */ @SchedulerSupport(SchedulerSupport.NONE) public final void safeSubscribe(@NonNull MaybeObserver<? super T> observer) { Objects.requireNonNull(observer, "observer is null"); subscribe(new SafeMaybeObserver<>(observer)); } /** * Returns a {@link Flowable} which first runs the other {@link CompletableSource} * then the current {@code Maybe} if the other completed normally. * <p> * <img width="640" height="268" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.startWith.c.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param other the other {@code CompletableSource} to run first * @return the new {@code Flowable} instance * @throws NullPointerException if {@code other} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public final Flowable<T> startWith(@NonNull CompletableSource other) { Objects.requireNonNull(other, "other is null"); return Flowable.concat(Completable.wrap(other).<T>toFlowable(), toFlowable()); } /** * Returns a {@link Flowable} which first runs the other {@link SingleSource} * then the current {@code Maybe} if the other succeeded normally. * <p> * <img width="640" height="237" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.startWith.s.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param other the other {@code SingleSource} to run first * @return the new {@code Flowable} instance * @throws NullPointerException if {@code other} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public final Flowable<T> startWith(@NonNull SingleSource<T> other) { Objects.requireNonNull(other, "other is null"); return Flowable.concat(Single.wrap(other).toFlowable(), toFlowable()); } /** * Returns a {@link Flowable} which first runs the other {@link MaybeSource} * then the current {@code Maybe} if the other succeeded or completed normally. * <p> * <img width="640" height="178" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.startWith.m.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param other the other {@code MaybeSource} to run first * @return the new {@code Flowable} instance * @throws NullPointerException if {@code other} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public final Flowable<T> startWith(@NonNull MaybeSource<T> other) { Objects.requireNonNull(other, "other is null"); return Flowable.concat(Maybe.wrap(other).toFlowable(), toFlowable()); } /** * Returns an {@link Observable} which first delivers the events * of the other {@link ObservableSource} then runs the current {@code Maybe}. * <p> * <img width="640" height="179" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.startWith.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param other the other {@code ObservableSource} to run first * @return the new {@code Observable} instance * @throws NullPointerException if {@code other} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> startWith(@NonNull ObservableSource<T> other) { Objects.requireNonNull(other, "other is null"); return Observable.wrap(other).concatWith(this.toObservable()); } /** * Returns a {@link Flowable} which first delivers the events * of the other {@link Publisher} then runs the current {@code Maybe}. * <p> * <img width="640" height="179" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.startWith.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer * and expects the other {@code Publisher} to honor it as well.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param other the other {@code Publisher} to run first * @return the new {@code Flowable} instance * @throws NullPointerException if {@code other} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> startWith(@NonNull Publisher<T> other) { Objects.requireNonNull(other, "other is null"); return toFlowable().startWith(other); } /** * Subscribes to a {@code Maybe} and ignores {@code onSuccess} and {@code onComplete} emissions. * <p> * If the {@code Maybe} emits an error, it is wrapped into an * {@link io.reactivex.rxjava3.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the {@link RxJavaPlugins#onError(Throwable)} handler. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@link Disposable} instance that can be used for disposing the subscription at any time * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> * @see #subscribe(Consumer, Consumer, Action, DisposableContainer) */ @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Disposable subscribe() { return subscribe(Functions.emptyConsumer(), Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION); } /** * Subscribes to a {@code Maybe} and provides a callback to handle the items it emits. * <p> * If the {@code Maybe} emits an error, it is wrapped into an * {@link io.reactivex.rxjava3.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the {@link RxJavaPlugins#onError(Throwable)} handler. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onSuccess * the {@code Consumer<T>} you have designed to accept a success value from the {@code Maybe} * @return the new {@link Disposable} instance that can be used for disposing the subscription at any time * @throws NullPointerException * if {@code onSuccess} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> * @see #subscribe(Consumer, Consumer, Action, DisposableContainer) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Disposable subscribe(@NonNull Consumer<? super T> onSuccess) { return subscribe(onSuccess, Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION); } /** * Subscribes to a {@code Maybe} and provides callbacks to handle the items it emits and any error * notification it issues. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onSuccess * the {@code Consumer<T>} you have designed to accept a success value from the {@code Maybe} * @param onError * the {@code Consumer<Throwable>} you have designed to accept any error notification from the * {@code Maybe} * @return the new {@link Disposable} instance that can be used for disposing the subscription at any time * @throws NullPointerException * if {@code onSuccess} is {@code null}, or * if {@code onError} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> * @see #subscribe(Consumer, Consumer, Action, DisposableContainer) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Disposable subscribe(@NonNull Consumer<? super T> onSuccess, @NonNull Consumer<? super Throwable> onError) { return subscribe(onSuccess, onError, Functions.EMPTY_ACTION); } /** * Subscribes to a {@code Maybe} and provides callbacks to handle the items it emits and any error or * completion notification it issues. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onSuccess * the {@code Consumer<T>} you have designed to accept a success value from the {@code Maybe} * @param onError * the {@code Consumer<Throwable>} you have designed to accept any error notification from the * {@code Maybe} * @param onComplete * the {@link Action} you have designed to accept a completion notification from the * {@code Maybe} * @return the new {@link Disposable} instance that can be used for disposing the subscription at any time * @throws NullPointerException * if {@code onSuccess}, {@code onError} or * {@code onComplete} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> * @see #subscribe(Consumer, Consumer, Action, DisposableContainer) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(@NonNull Consumer<? super T> onSuccess, @NonNull Consumer<? super Throwable> onError, @NonNull Action onComplete) { Objects.requireNonNull(onSuccess, "onSuccess is null"); Objects.requireNonNull(onError, "onError is null"); Objects.requireNonNull(onComplete, "onComplete is null"); return subscribeWith(new MaybeCallbackObserver<>(onSuccess, onError, onComplete)); } /** * Wraps the given onXXX callbacks into a {@link Disposable} {@link MaybeObserver}, * adds it to the given {@link DisposableContainer} and ensures, that if the upstream * terminates or this particular {@code Disposable} is disposed, the {@code MaybeObserver} is removed * from the given composite. * <p> * The {@code MaybeObserver} will be removed after the callback for the terminal event has been invoked. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onSuccess the callback for upstream items * @param onError the callback for an upstream error * @param onComplete the callback for an upstream completion without any value or error * @param container the {@code DisposableContainer} (such as {@link CompositeDisposable}) to add and remove the * created {@code Disposable} {@code MaybeObserver} * @return the {@code Disposable} that allows disposing the particular subscription. * @throws NullPointerException * if {@code onSuccess}, {@code onError}, * {@code onComplete} or {@code container} is {@code null} * @since 3.1.0 */ @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Disposable subscribe( @NonNull Consumer<? super T> onSuccess, @NonNull Consumer<? super Throwable> onError, @NonNull Action onComplete, @NonNull DisposableContainer container) { Objects.requireNonNull(onSuccess, "onSuccess is null"); Objects.requireNonNull(onError, "onError is null"); Objects.requireNonNull(onComplete, "onComplete is null"); Objects.requireNonNull(container, "container is null"); DisposableAutoReleaseMultiObserver<T> observer = new DisposableAutoReleaseMultiObserver<>( container, onSuccess, onError, onComplete); container.add(observer); subscribe(observer); return observer; } @SchedulerSupport(SchedulerSupport.NONE) @Override public final void subscribe(@NonNull MaybeObserver<? super T> observer) { Objects.requireNonNull(observer, "observer is null"); observer = RxJavaPlugins.onSubscribe(this, observer); Objects.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null MaybeObserver. Please check the handler provided to RxJavaPlugins.setOnMaybeSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins"); try { subscribeActual(observer); } catch (NullPointerException ex) { throw ex; } catch (Throwable ex) { Exceptions.throwIfFatal(ex); NullPointerException npe = new NullPointerException("subscribeActual failed"); npe.initCause(ex); throw npe; } } /** * Implement this method in subclasses to handle the incoming {@link MaybeObserver}s. * <p>There is no need to call any of the plugin hooks on the current {@code Maybe} instance or * the {@code MaybeObserver}; all hooks and basic safeguards have been * applied by {@link #subscribe(MaybeObserver)} before this method gets called. * @param observer the {@code MaybeObserver} to handle, not {@code null} */ protected abstract void subscribeActual(@NonNull MaybeObserver<? super T> observer); /** * Asynchronously subscribes subscribers to this {@code Maybe} on the specified {@link Scheduler}. * <p> * <img width="640" height="753" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.subscribeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param scheduler * the {@code Scheduler} to perform subscription actions on * @return the new {@code Maybe} instance * @throws NullPointerException if {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX operators documentation: SubscribeOn</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #observeOn */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> subscribeOn(@NonNull Scheduler scheduler) { Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeSubscribeOn<>(this, scheduler)); } /** * Subscribes a given {@link MaybeObserver} (subclass) to this {@code Maybe} and returns the given * {@code MaybeObserver} as is. * <p>Usage example: * <pre><code> * Maybe&lt;Integer&gt; source = Maybe.just(1); * CompositeDisposable composite = new CompositeDisposable(); * * DisposableMaybeObserver&lt;Integer&gt; ds = new DisposableMaybeObserver&lt;&gt;() { * // ... * }; * * composite.add(source.subscribeWith(ds)); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <E> the type of the {@code MaybeObserver} to use and return * @param observer the {@code MaybeObserver} (subclass) to use and return, not {@code null} * @return the input {@code observer} * @throws NullPointerException if {@code observer} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull E extends MaybeObserver<? super T>> E subscribeWith(E observer) { subscribe(observer); return observer; } /** * Returns a {@code Maybe} that emits the items emitted by the current {@code Maybe} or the items of an alternate * {@link MaybeSource} if the current {@code Maybe} is empty. * <p> * <img width="640" height="222" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.switchIfEmpty.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * the alternate {@code MaybeSource} to subscribe to if the main does not emit any items * @return the new {@code Maybe} instance * @throws NullPointerException if {@code other} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> switchIfEmpty(@NonNull MaybeSource<? extends T> other) { Objects.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new MaybeSwitchIfEmpty<>(this, other)); } /** * Returns a {@link Single} that emits the items emitted by the current {@code Maybe} or the item of an alternate * {@link SingleSource} if the current {@code Maybe} is empty. * <p> * <img width="640" height="312" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.switchIfEmpty.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.1.4 - experimental * @param other * the alternate {@code SingleSource} to subscribe to if the main does not emit any items * @return the new {@code Single} instance * @throws NullPointerException if {@code other} is {@code null} * @since 2.2 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> switchIfEmpty(@NonNull SingleSource<? extends T> other) { Objects.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new MaybeSwitchIfEmptySingle<>(this, other)); } /** * Returns a {@code Maybe} that emits the items emitted by the current {@code Maybe} until a second {@link MaybeSource} * emits an item. * <p> * <img width="640" height="219" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.takeUntil.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * the {@code MaybeSource} whose first emitted item will cause {@code takeUntil} to stop emitting items * from the current {@code Maybe} * @param <U> * the type of items emitted by {@code other} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code other} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> takeUntil(@NonNull MaybeSource<U> other) { Objects.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new MaybeTakeUntilMaybe<>(this, other)); } /** * Returns a {@code Maybe} that emits the item emitted by the current {@code Maybe} until a second {@link Publisher} * emits an item. * <p> * <img width="640" height="199" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.takeUntil.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code Publisher} is consumed in an unbounded fashion and is cancelled after the first item * emitted.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * the {@code Publisher} whose first emitted item will cause {@code takeUntil} to stop emitting items * from the source {@code Publisher} * @param <U> * the type of items emitted by {@code other} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code other} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> takeUntil(@NonNull Publisher<U> other) { Objects.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new MaybeTakeUntilPublisher<>(this, other)); } /** * Measures the time (in milliseconds) between the subscription and success item emission * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) * success value. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timeInterval()}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeInterval} uses the {@code computation} {@link Scheduler} * for determining the current time upon subscription and upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @return the new {@code Maybe} instance * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<Timed<T>> timeInterval() { return timeInterval(TimeUnit.MILLISECONDS, Schedulers.computation()); } /** * Measures the time (in milliseconds) between the subscription and success item emission * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) * success value. * <p> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.s.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timeInterval(Scheduler)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeInterval} uses the provided {@link Scheduler} * for determining the current time upon subscription and upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @param scheduler the {@code Scheduler} used for providing the current time * @return the new {@code Maybe} instance * @throws NullPointerException if {@code scheduler} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<Timed<T>> timeInterval(@NonNull Scheduler scheduler) { return timeInterval(TimeUnit.MILLISECONDS, scheduler); } /** * Measures the time between the subscription and success item emission * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) * success value. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timeInterval(TimeUnit)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeInterval} uses the {@code computation} {@link Scheduler} * for determining the current time upon subscription and upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @param unit the time unit for measurement * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<Timed<T>> timeInterval(@NonNull TimeUnit unit) { return timeInterval(unit, Schedulers.computation()); } /** * Measures the time between the subscription and success item emission * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) * success value. * <p> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.s.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timeInterval(TimeUnit, Scheduler)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeInterval} uses the provided {@link Scheduler} * for determining the current time upon subscription and upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @param unit the time unit for measurement * @param scheduler the {@code Scheduler} used for providing the current time * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<Timed<T>> timeInterval(@NonNull TimeUnit unit, @NonNull Scheduler scheduler) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeTimeInterval<>(this, unit, scheduler, true)); } /** * Combines the success value from the current {@code Maybe} with the current time (in milliseconds) of * its reception, using the {@code computation} {@link Scheduler} as time source, * then signals them as a {@link Timed} instance. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timestamp()}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timestamp} uses the {@code computation} {@code Scheduler} * for determining the current time upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @return the new {@code Maybe} instance * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<Timed<T>> timestamp() { return timestamp(TimeUnit.MILLISECONDS, Schedulers.computation()); } /** * Combines the success value from the current {@code Maybe} with the current time (in milliseconds) of * its reception, using the given {@link Scheduler} as time source, * then signals them as a {@link Timed} instance. * <p> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.s.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timestamp(Scheduler)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timestamp} uses the provided {@code Scheduler} * for determining the current time upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @param scheduler the {@code Scheduler} used for providing the current time * @return the new {@code Maybe} instance * @throws NullPointerException if {@code scheduler} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<Timed<T>> timestamp(@NonNull Scheduler scheduler) { return timestamp(TimeUnit.MILLISECONDS, scheduler); } /** * Combines the success value from the current {@code Maybe} with the current time of * its reception, using the {@code computation} {@link Scheduler} as time source, * then signals it as a {@link Timed} instance. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timestamp(TimeUnit)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timestamp} uses the {@code computation} {@code Scheduler}, * for determining the current time upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @param unit the time unit for measurement * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<Timed<T>> timestamp(@NonNull TimeUnit unit) { return timestamp(unit, Schedulers.computation()); } /** * Combines the success value from the current {@code Maybe} with the current time of * its reception, using the given {@link Scheduler} as time source, * then signals it as a {@link Timed} instance. * <p> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.s.png" alt=""> * <p> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will * pass along the signals to the downstream. To measure the time to termination, * use {@link #materialize()} and apply {@link Single#timestamp(TimeUnit, Scheduler)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timestamp} uses the provided {@code Scheduler}, * which is used for determining the current time upon receiving the * success item from the current {@code Maybe}.</dd> * </dl> * @param unit the time unit for measurement * @param scheduler the {@code Scheduler} used for providing the current time * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<Timed<T>> timestamp(@NonNull TimeUnit unit, @NonNull Scheduler scheduler) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeTimeInterval<>(this, unit, scheduler, false)); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe} but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting {@code Maybe} terminates and notifies {@link MaybeObserver}s of a {@link TimeoutException}. * <p> * <img width="640" height="261" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout * maximum duration between emitted items before a timeout occurs * @param unit * the unit of time that applies to the {@code timeout} argument. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Maybe<T> timeout(long timeout, @NonNull TimeUnit unit) { return timeout(timeout, unit, Schedulers.computation()); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe} but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the current {@code Maybe} is disposed and resulting {@code Maybe} begins instead to mirror a fallback {@link MaybeSource}. * <p> * <img width="640" height="226" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.tm.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout * maximum duration between items before a timeout occurs * @param unit * the unit of time that applies to the {@code timeout} argument * @param fallback * the fallback {@code MaybeSource} to use in case of a timeout * @return the new {@code Maybe} instance * @throws NullPointerException if {@code unit} or {@code fallback} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<T> timeout(long timeout, @NonNull TimeUnit unit, @NonNull MaybeSource<? extends T> fallback) { Objects.requireNonNull(fallback, "fallback is null"); return timeout(timeout, unit, Schedulers.computation(), fallback); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe} but applies a timeout policy for each emitted * item using a specified {@link Scheduler}. If the next item isn't emitted within the specified timeout duration * starting from its predecessor, the current {@code Maybe} is disposed and resulting {@code Maybe} begins instead * to mirror a fallback {@link MaybeSource}. * <p> * <img width="640" height="227" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.tsm.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param timeout * maximum duration between items before a timeout occurs * @param unit * the unit of time that applies to the {@code timeout} argument * @param fallback * the {@code MaybeSource} to use as the fallback in case of a timeout * @param scheduler * the {@code Scheduler} to run the timeout timers on * @return the new {@code Maybe} instance * @throws NullPointerException if {@code fallback}, {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> timeout(long timeout, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull MaybeSource<? extends T> fallback) { Objects.requireNonNull(fallback, "fallback is null"); return timeout(timer(timeout, unit, scheduler), fallback); } /** * Returns a {@code Maybe} that mirrors the current {@code Maybe} but applies a timeout policy for each emitted * item, where this policy is governed on a specified {@link Scheduler}. If the next item isn't emitted within the * specified timeout duration starting from its predecessor, the resulting {@code Maybe} terminates and * notifies {@link MaybeObserver}s of a {@link TimeoutException}. * <p> * <img width="640" height="261" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param timeout * maximum duration between items before a timeout occurs * @param unit * the unit of time that applies to the {@code timeout} argument * @param scheduler * the {@code Scheduler} to run the timeout timers on * @return the new {@code Maybe} instance * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final Maybe<T> timeout(long timeout, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { return timeout(timer(timeout, unit, scheduler)); } /** * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals, a * {@link TimeoutException} is signaled instead. * <p> * <img width="640" height="235" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <U> the value type of the * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess} * or {@code onComplete}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code timeoutIndicator} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> timeout(@NonNull MaybeSource<U> timeoutIndicator) { Objects.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); return RxJavaPlugins.onAssembly(new MaybeTimeoutMaybe<>(this, timeoutIndicator, null)); } /** * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals, * the current {@code Maybe} is disposed and the {@code fallback} {@code MaybeSource} subscribed to * as a continuation. * <p> * <img width="640" height="194" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.mm.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <U> the value type of the * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess} * or {@code onComplete}. * @param fallback the {@code MaybeSource} that is subscribed to if the current {@code Maybe} times out * @return the new {@code Maybe} instance * @throws NullPointerException if {@code timeoutIndicator} or {@code fallback} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> timeout(@NonNull MaybeSource<U> timeoutIndicator, @NonNull MaybeSource<? extends T> fallback) { Objects.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); Objects.requireNonNull(fallback, "fallback is null"); return RxJavaPlugins.onAssembly(new MaybeTimeoutMaybe<>(this, timeoutIndicator, fallback)); } /** * If the current {@code Maybe} source didn't signal an event before the {@code timeoutIndicator} {@link Publisher} signals, a * {@link TimeoutException} is signaled instead. * <p> * <img width="640" height="212" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code timeoutIndicator} {@code Publisher} is consumed in an unbounded manner and * is cancelled after its first item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <U> the value type of the * @param timeoutIndicator the {@code Publisher} that indicates the timeout by signaling {@code onSuccess} * or {@code onComplete}. * @return the new {@code Maybe} instance * @throws NullPointerException if {@code timeoutIndicator} is {@code null} */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> timeout(@NonNull Publisher<U> timeoutIndicator) { Objects.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); return RxJavaPlugins.onAssembly(new MaybeTimeoutPublisher<>(this, timeoutIndicator, null)); } /** * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link Publisher} signals, * the current {@code Maybe} is disposed and the {@code fallback} {@link MaybeSource} subscribed to * as a continuation. * <p> * <img width="640" height="169" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeout.pm.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code timeoutIndicator} {@code Publisher} is consumed in an unbounded manner and * is cancelled after its first item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <U> the value type of the * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess} * or {@code onComplete} * @param fallback the {@code MaybeSource} that is subscribed to if the current {@code Maybe} times out * @return the new {@code Maybe} instance * @throws NullPointerException if {@code timeoutIndicator} or {@code fallback} is {@code null} */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U> Maybe<T> timeout(@NonNull Publisher<U> timeoutIndicator, @NonNull MaybeSource<? extends T> fallback) { Objects.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); Objects.requireNonNull(fallback, "fallback is null"); return RxJavaPlugins.onAssembly(new MaybeTimeoutPublisher<>(this, timeoutIndicator, fallback)); } /** * Returns a {@code Maybe} which makes sure when a {@link MaybeObserver} disposes the {@link Disposable}, * that call is propagated up on the specified {@link Scheduler}. * <p> * <img width="640" height="693" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.unsubscribeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsubscribeOn} calls {@code dispose()} of the upstream on the {@code Scheduler} you specify.</dd> * </dl> * @param scheduler the target scheduler where to execute the disposal * @return the new {@code Maybe} instance * @throws NullPointerException if {@code scheduler} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> unsubscribeOn(@NonNull Scheduler scheduler) { Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new MaybeUnsubscribeOn<>(this, scheduler)); } /** * Waits until this and the other {@link MaybeSource} signal a success value then applies the given {@link BiFunction} * to those values and emits the {@code BiFunction}'s resulting value to downstream. * * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.zipWith.png" alt=""> * * <p>If either this or the other {@code MaybeSource} is empty or signals an error, the resulting {@code Maybe} will * terminate immediately and dispose the other source. * * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zipWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the type of items emitted by the {@code other} {@code MaybeSource} * @param <R> * the type of items emitted by the resulting {@code Maybe} * @param other * the other {@code MaybeSource} * @param zipper * a function that combines the pairs of items from the two {@code MaybeSource}s to generate the items to * be emitted by the resulting {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code other} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <@NonNull U, @NonNull R> Maybe<R> zipWith(@NonNull MaybeSource<? extends U> other, @NonNull BiFunction<? super T, ? super U, ? extends R> zipper) { Objects.requireNonNull(other, "other is null"); return zip(this, other, zipper); } // ------------------------------------------------------------------ // Test helper // ------------------------------------------------------------------ /** * Creates a {@link TestObserver} and subscribes * it to this {@code Maybe}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code TestObserver} instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final TestObserver<T> test() { TestObserver<T> to = new TestObserver<>(); subscribe(to); return to; } /** * Creates a {@link TestObserver} optionally in cancelled state, then subscribes it to this {@code Maybe}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param dispose if {@code true}, the {@code TestObserver} will be disposed before subscribing to this * {@code Maybe}. * @return the new {@code TestObserver} instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final TestObserver<T> test(boolean dispose) { TestObserver<T> to = new TestObserver<>(); if (dispose) { to.dispose(); } subscribe(to); return to; } // ------------------------------------------------------------------------- // JDK 8 Support // ------------------------------------------------------------------------- /** * Converts the existing value of the provided optional into a {@link #just(Object)} * or an empty optional into an {@link #empty()} {@code Maybe} instance. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromOptional.m.png" alt=""> * <p> * Note that the operator takes an already instantiated optional reference and does not * by any means create this original optional. If the optional is to be created per * consumer upon subscription, use {@link #defer(Supplier)} around {@code fromOptional}: * <pre><code> * Maybe.defer(() -&gt; Maybe.fromOptional(createOptional())); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromOptional} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the element type of the optional value * @param optional the optional value to convert into a {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code optional} is {@code null} * @since 3.0.0 * @see #just(Object) * @see #empty() */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Maybe<@NonNull T> fromOptional(@NonNull Optional<T> optional) { Objects.requireNonNull(optional, "optional is null"); return optional.map(Maybe::just).orElseGet(Maybe::empty); } /** * Signals the completion value or error of the given (hot) {@link CompletionStage}-based asynchronous calculation. * <p> * <img width="640" height="262" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromCompletionStage.s.png" alt=""> * <p> * Note that the operator takes an already instantiated, running or terminated {@code CompletionStage}. * If the {@code CompletionStage} is to be created per consumer upon subscription, use {@link #defer(Supplier)} * around {@code fromCompletionStage}: * <pre><code> * Maybe.defer(() -&gt; Maybe.fromCompletionStage(createCompletionStage())); * </code></pre> * <p> * If the {@code CompletionStage} completes with {@code null}, the resulting {@code Maybe} is completed via {@code onComplete}. * <p> * Canceling the flow can't cancel the execution of the {@code CompletionStage} because {@code CompletionStage} * itself doesn't support cancellation. Instead, the operator detaches from the {@code CompletionStage}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCompletionStage} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the element type of the {@code CompletionStage} * @param stage the {@code CompletionStage} to convert to {@code Maybe} and signal its terminal value or error * @return the new {@code Maybe} instance * @throws NullPointerException if {@code stage} is {@code null} * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Maybe<@NonNull T> fromCompletionStage(@NonNull CompletionStage<T> stage) { Objects.requireNonNull(stage, "stage is null"); return RxJavaPlugins.onAssembly(new MaybeFromCompletionStage<>(stage)); } /** * Maps the upstream success value into an {@link Optional} and emits the contained item if not empty. * <p> * <img width="640" height="323" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mapOptional.m.png" alt=""> * * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mapOptional} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <R> the non-{@code null} output type * @param mapper the function that receives the upstream success item and should return a <em>non-empty</em> {@code Optional} * to emit as the success output or an <em>empty</em> {@code Optional} to complete the {@code Maybe} * @return the new {@code Maybe} instance * @throws NullPointerException if {@code mapper} is {@code null} * @since 3.0.0 * @see #map(Function) * @see #filter(Predicate) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull R> Maybe<R> mapOptional(@NonNull Function<? super T, @NonNull Optional<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeMapOptional<>(this, mapper)); } /** * Signals the upstream success item (or a {@link NoSuchElementException} if the upstream is empty) via * a {@link CompletionStage}. * <p> * <img width="640" height="349" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toCompletionStage.m.png" alt=""> * <p> * The upstream can be canceled by converting the resulting {@code CompletionStage} into * {@link CompletableFuture} via {@link CompletionStage#toCompletableFuture()} and * calling {@link CompletableFuture#cancel(boolean)} on it. * The upstream will be also cancelled if the resulting {@code CompletionStage} is converted to and * completed manually by {@link CompletableFuture#complete(Object)} or {@link CompletableFuture#completeExceptionally(Throwable)}. * <p> * {@code CompletionStage}s don't have a notion of emptiness and allow {@code null}s, therefore, one can either use * {@link #toCompletionStage(Object)} with {@code null} or turn the upstream into a sequence of {@link Optional}s and * default to {@link Optional#empty()}: * <pre><code> * CompletionStage&lt;Optional&lt;T&gt;&gt; stage = source.map(Optional::of).toCompletionStage(Optional.empty()); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toCompletionStage} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new {@code CompletionStage} instance * @since 3.0.0 * @see #toCompletionStage(Object) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final CompletionStage<T> toCompletionStage() { return subscribeWith(new CompletionStageConsumer<>(false, null)); } /** * Signals the upstream success item (or the default item if the upstream is empty) via * a {@link CompletionStage}. * <p> * <img width="640" height="323" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toCompletionStage.mv.png" alt=""> * <p> * The upstream can be canceled by converting the resulting {@code CompletionStage} into * {@link CompletableFuture} via {@link CompletionStage#toCompletableFuture()} and * calling {@link CompletableFuture#cancel(boolean)} on it. * The upstream will be also cancelled if the resulting {@code CompletionStage} is converted to and * completed manually by {@link CompletableFuture#complete(Object)} or {@link CompletableFuture#completeExceptionally(Throwable)}. * <p> * {@code CompletionStage}s don't have a notion of emptiness and allow {@code null}s, therefore, one can either use * a {@code defaultItem} of {@code null} or turn the flow into a sequence of {@link Optional}s and default to {@link Optional#empty()}: * <pre><code> * CompletionStage&lt;Optional&lt;T&gt;&gt; stage = source.map(Optional::of).toCompletionStage(Optional.empty()); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toCompletionStage} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param defaultItem the item to signal if the upstream is empty * @return the new {@code CompletionStage} instance * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final CompletionStage<T> toCompletionStage(@Nullable T defaultItem) { return subscribeWith(new CompletionStageConsumer<>(true, defaultItem)); } /** * Maps the upstream succecss value into a Java {@link Stream} and emits its * items to the downstream consumer as a {@link Flowable}. * <p> * <img width="640" height="246" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenStreamAsFlowable.m.png" alt=""> * <p> * The operator closes the {@code Stream} upon cancellation and when it terminates. The exceptions raised when * closing a {@code Stream} are routed to the global error handler ({@link RxJavaPlugins#onError(Throwable)}. * If a {@code Stream} should not be closed, turn it into an {@link Iterable} and use {@link #flattenAsFlowable(Function)}: * <pre><code> * source.flattenAsFlowable(item -&gt; createStream(item)::iterator); * </code></pre> * <p> * Primitive streams are not supported and items have to be boxed manually (e.g., via {@link IntStream#boxed()}): * <pre><code> * source.flattenStreamAsFlowable(item -&gt; IntStream.rangeClosed(1, 10).boxed()); * </code></pre> * <p> * {@code Stream} does not support concurrent usage so creating and/or consuming the same instance multiple times * from multiple threads can lead to undefined behavior. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream and iterates the given {@code Stream} * on demand (i.e., when requested).</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code flattenStreamAsFlowable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <R> the element type of the {@code Stream} and the output {@code Flowable} * @param mapper the function that receives the upstream success item and should * return a {@code Stream} of values to emit. * @return the new {@code Flowable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @since 3.0.0 * @see #flattenAsFlowable(Function) * @see #flattenStreamAsObservable(Function) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) @NonNull public final <@NonNull R> Flowable<R> flattenStreamAsFlowable(@NonNull Function<? super T, @NonNull ? extends Stream<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlattenStreamAsFlowable<>(this, mapper)); } /** * Maps the upstream succecss value into a Java {@link Stream} and emits its * items to the downstream consumer as an {@link Observable}. * <img width="640" height="241" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenStreamAsObservable.m.png" alt=""> * <p> * The operator closes the {@code Stream} upon cancellation and when it terminates. The exceptions raised when * closing a {@code Stream} are routed to the global error handler ({@link RxJavaPlugins#onError(Throwable)}. * If a {@code Stream} should not be closed, turn it into an {@link Iterable} and use {@link #flattenAsObservable(Function)}: * <pre><code> * source.flattenAsObservable(item -&gt; createStream(item)::iterator); * </code></pre> * <p> * Primitive streams are not supported and items have to be boxed manually (e.g., via {@link IntStream#boxed()}): * <pre><code> * source.flattenStreamAsObservable(item -&gt; IntStream.rangeClosed(1, 10).boxed()); * </code></pre> * <p> * {@code Stream} does not support concurrent usage so creating and/or consuming the same instance multiple times * from multiple threads can lead to undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flattenStreamAsObservable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <R> the element type of the {@code Stream} and the output {@code Observable} * @param mapper the function that receives the upstream success item and should * return a {@code Stream} of values to emit. * @return the new {@code Observable} instance * @throws NullPointerException if {@code mapper} is {@code null} * @since 3.0.0 * @see #flattenAsObservable(Function) * @see #flattenStreamAsFlowable(Function) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull R> Observable<R> flattenStreamAsObservable(@NonNull Function<? super T, @NonNull ? extends Stream<? extends R>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlattenStreamAsObservable<>(this, mapper)); } }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/core/Maybe.java
33
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import io.netty.util.ByteProcessor; import io.netty.util.ReferenceCounted; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; /** * A random and sequential accessible sequence of zero or more bytes (octets). * This interface provides an abstract view for one or more primitive byte * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. * * <h3>Creation of a buffer</h3> * * It is recommended to create a new buffer using the helper methods in * {@link Unpooled} rather than calling an individual implementation's * constructor. * * <h3>Random Access Indexing</h3> * * Just like an ordinary primitive byte array, {@link ByteBuf} uses * <a href="https://en.wikipedia.org/wiki/Zero-based_numbering">zero-based indexing</a>. * It means the index of the first byte is always {@code 0} and the index of the last byte is * always {@link #capacity() capacity - 1}. For example, to iterate all bytes of a buffer, you * can do the following, regardless of its internal implementation: * * <pre> * {@link ByteBuf} buffer = ...; * for (int i = 0; i &lt; buffer.capacity(); i ++) { * byte b = buffer.getByte(i); * System.out.println((char) b); * } * </pre> * * <h3>Sequential Access Indexing</h3> * * {@link ByteBuf} provides two pointer variables to support sequential * read and write operations - {@link #readerIndex() readerIndex} for a read * operation and {@link #writerIndex() writerIndex} for a write operation * respectively. The following diagram shows how a buffer is segmented into * three areas by the two pointers: * * <pre> * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * | | (CONTENT) | | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * </pre> * * <h4>Readable bytes (the actual content)</h4> * * This segment is where the actual data is stored. Any operation whose name * starts with {@code read} or {@code skip} will get or skip the data at the * current {@link #readerIndex() readerIndex} and increase it by the number of * read bytes. If the argument of the read operation is also a * {@link ByteBuf} and no destination index is specified, the specified * buffer's {@link #writerIndex() writerIndex} is increased together. * <p> * If there's not enough content left, {@link IndexOutOfBoundsException} is * raised. The default value of newly allocated, wrapped or copied buffer's * {@link #readerIndex() readerIndex} is {@code 0}. * * <pre> * // Iterates the readable bytes of a buffer. * {@link ByteBuf} buffer = ...; * while (buffer.isReadable()) { * System.out.println(buffer.readByte()); * } * </pre> * * <h4>Writable bytes</h4> * * This segment is a undefined space which needs to be filled. Any operation * whose name starts with {@code write} will write the data at the current * {@link #writerIndex() writerIndex} and increase it by the number of written * bytes. If the argument of the write operation is also a {@link ByteBuf}, * and no source index is specified, the specified buffer's * {@link #readerIndex() readerIndex} is increased together. * <p> * If there's not enough writable bytes left, {@link IndexOutOfBoundsException} * is raised. The default value of newly allocated buffer's * {@link #writerIndex() writerIndex} is {@code 0}. The default value of * wrapped or copied buffer's {@link #writerIndex() writerIndex} is the * {@link #capacity() capacity} of the buffer. * * <pre> * // Fills the writable bytes of a buffer with random integers. * {@link ByteBuf} buffer = ...; * while (buffer.maxWritableBytes() >= 4) { * buffer.writeInt(random.nextInt()); * } * </pre> * * <h4>Discardable bytes</h4> * * This segment contains the bytes which were read already by a read operation. * Initially, the size of this segment is {@code 0}, but its size increases up * to the {@link #writerIndex() writerIndex} as read operations are executed. * The read bytes can be discarded by calling {@link #discardReadBytes()} to * reclaim unused area as depicted by the following diagram: * * <pre> * BEFORE discardReadBytes() * * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * * * AFTER discardReadBytes() * * +------------------+--------------------------------------+ * | readable bytes | writable bytes (got more space) | * +------------------+--------------------------------------+ * | | | * readerIndex (0) <= writerIndex (decreased) <= capacity * </pre> * * Please note that there is no guarantee about the content of writable bytes * after calling {@link #discardReadBytes()}. The writable bytes will not be * moved in most cases and could even be filled with completely different data * depending on the underlying buffer implementation. * * <h4>Clearing the buffer indexes</h4> * * You can set both {@link #readerIndex() readerIndex} and * {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}. * It does not clear the buffer content (e.g. filling with {@code 0}) but just * clears the two pointers. Please also note that the semantic of this * operation is different from {@link ByteBuffer#clear()}. * * <pre> * BEFORE clear() * * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * * * AFTER clear() * * +---------------------------------------------------------+ * | writable bytes (got more space) | * +---------------------------------------------------------+ * | | * 0 = readerIndex = writerIndex <= capacity * </pre> * * <h3>Search operations</h3> * * For simple single-byte searches, use {@link #indexOf(int, int, byte)} and {@link #bytesBefore(int, int, byte)}. * {@link #bytesBefore(byte)} is especially useful when you deal with a {@code NUL}-terminated string. * For complicated searches, use {@link #forEachByte(int, int, ByteProcessor)} with a {@link ByteProcessor} * implementation. * * <h3>Mark and reset</h3> * * There are two marker indexes in every buffer. One is for storing * {@link #readerIndex() readerIndex} and the other is for storing * {@link #writerIndex() writerIndex}. You can always reposition one of the * two indexes by calling a reset method. It works in a similar fashion to * the mark and reset methods in {@link InputStream} except that there's no * {@code readlimit}. * * <h3>Derived buffers</h3> * * You can create a view of an existing buffer by calling one of the following methods: * <ul> * <li>{@link #duplicate()}</li> * <li>{@link #slice()}</li> * <li>{@link #slice(int, int)}</li> * <li>{@link #readSlice(int)}</li> * <li>{@link #retainedDuplicate()}</li> * <li>{@link #retainedSlice()}</li> * <li>{@link #retainedSlice(int, int)}</li> * <li>{@link #readRetainedSlice(int)}</li> * </ul> * A derived buffer will have an independent {@link #readerIndex() readerIndex}, * {@link #writerIndex() writerIndex} and marker indexes, while it shares * other internal data representation, just like a NIO buffer does. * <p> * In case a completely fresh copy of an existing buffer is required, please * call {@link #copy()} method instead. * * <h4>Non-retained and retained derived buffers</h4> * * Note that the {@link #duplicate()}, {@link #slice()}, {@link #slice(int, int)} and {@link #readSlice(int)} does NOT * call {@link #retain()} on the returned derived buffer, and thus its reference count will NOT be increased. If you * need to create a derived buffer with increased reference count, consider using {@link #retainedDuplicate()}, * {@link #retainedSlice()}, {@link #retainedSlice(int, int)} and {@link #readRetainedSlice(int)} which may return * a buffer implementation that produces less garbage. * * <h3>Conversion to existing JDK types</h3> * * <h4>Byte array</h4> * * If a {@link ByteBuf} is backed by a byte array (i.e. {@code byte[]}), * you can access it directly via the {@link #array()} method. To determine * if a buffer is backed by a byte array, {@link #hasArray()} should be used. * * <h4>NIO Buffers</h4> * * If a {@link ByteBuf} can be converted into an NIO {@link ByteBuffer} which shares its * content (i.e. view buffer), you can get it via the {@link #nioBuffer()} method. To determine * if a buffer can be converted into an NIO buffer, use {@link #nioBufferCount()}. * * <h4>Strings</h4> * * Various {@link #toString(Charset)} methods convert a {@link ByteBuf} * into a {@link String}. Please note that {@link #toString()} is not a * conversion method. * * <h4>I/O Streams</h4> * * Please refer to {@link ByteBufInputStream} and * {@link ByteBufOutputStream}. */ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf>, ByteBufConvertible { /** * Returns the number of bytes (octets) this buffer can contain. */ public abstract int capacity(); /** * Adjusts the capacity of this buffer. If the {@code newCapacity} is less than the current * capacity, the content of this buffer is truncated. If the {@code newCapacity} is greater * than the current capacity, the buffer is appended with unspecified data whose length is * {@code (newCapacity - currentCapacity)}. * * @throws IllegalArgumentException if the {@code newCapacity} is greater than {@link #maxCapacity()} */ public abstract ByteBuf capacity(int newCapacity); /** * Returns the maximum allowed capacity of this buffer. This value provides an upper * bound on {@link #capacity()}. */ public abstract int maxCapacity(); /** * Returns the {@link ByteBufAllocator} which created this buffer. */ public abstract ByteBufAllocator alloc(); /** * Returns the <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> * of this buffer. * * @deprecated use the Little Endian accessors, e.g. {@code getShortLE}, {@code getIntLE} * instead of creating a buffer with swapped {@code endianness}. */ @Deprecated public abstract ByteOrder order(); /** * Returns a buffer with the specified {@code endianness} which shares the whole region, * indexes, and marks of this buffer. Modifying the content, the indexes, or the marks of the * returned buffer or this buffer affects each other's content, indexes, and marks. If the * specified {@code endianness} is identical to this buffer's byte order, this method can * return {@code this}. This method does not modify {@code readerIndex} or {@code writerIndex} * of this buffer. * * @deprecated use the Little Endian accessors, e.g. {@code getShortLE}, {@code getIntLE} * instead of creating a buffer with swapped {@code endianness}. */ @Deprecated public abstract ByteBuf order(ByteOrder endianness); /** * Return the underlying buffer instance if this buffer is a wrapper of another buffer. * * @return {@code null} if this buffer is not a wrapper */ public abstract ByteBuf unwrap(); /** * Returns {@code true} if and only if this buffer is backed by an * NIO direct buffer. */ public abstract boolean isDirect(); /** * Returns {@code true} if and only if this buffer is read-only. */ public abstract boolean isReadOnly(); /** * Returns a read-only version of this buffer. */ public abstract ByteBuf asReadOnly(); /** * Returns the {@code readerIndex} of this buffer. */ public abstract int readerIndex(); /** * Sets the {@code readerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code readerIndex} is * less than {@code 0} or * greater than {@code this.writerIndex} */ public abstract ByteBuf readerIndex(int readerIndex); /** * Returns the {@code writerIndex} of this buffer. */ public abstract int writerIndex(); /** * Sets the {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code writerIndex} is * less than {@code this.readerIndex} or * greater than {@code this.capacity} */ public abstract ByteBuf writerIndex(int writerIndex); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer * in one shot. This method is useful when you have to worry about the * invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)} * methods. For example, the following code will fail: * * <pre> * // Create a buffer whose readerIndex, writerIndex and capacity are * // 0, 0 and 8 respectively. * {@link ByteBuf} buf = {@link Unpooled}.buffer(8); * * // IndexOutOfBoundsException is thrown because the specified * // readerIndex (2) cannot be greater than the current writerIndex (0). * buf.readerIndex(2); * buf.writerIndex(4); * </pre> * * The following code will also fail: * * <pre> * // Create a buffer whose readerIndex, writerIndex and capacity are * // 0, 8 and 8 respectively. * {@link ByteBuf} buf = {@link Unpooled}.wrappedBuffer(new byte[8]); * * // readerIndex becomes 8. * buf.readLong(); * * // IndexOutOfBoundsException is thrown because the specified * // writerIndex (4) cannot be less than the current readerIndex (8). * buf.writerIndex(4); * buf.readerIndex(2); * </pre> * * By contrast, this method guarantees that it never * throws an {@link IndexOutOfBoundsException} as long as the specified * indexes meet basic constraints, regardless what the current index * values of the buffer are: * * <pre> * // No matter what the current state of the buffer is, the following * // call always succeeds as long as the capacity of the buffer is not * // less than 4. * buf.setIndex(2, 4); * </pre> * * @throws IndexOutOfBoundsException * if the specified {@code readerIndex} is less than 0, * if the specified {@code writerIndex} is less than the specified * {@code readerIndex} or if the specified {@code writerIndex} is * greater than {@code this.capacity} */ public abstract ByteBuf setIndex(int readerIndex, int writerIndex); /** * Returns the number of readable bytes which is equal to * {@code (this.writerIndex - this.readerIndex)}. */ public abstract int readableBytes(); /** * Returns the number of writable bytes which is equal to * {@code (this.capacity - this.writerIndex)}. */ public abstract int writableBytes(); /** * Returns the maximum possible number of writable bytes, which is equal to * {@code (this.maxCapacity - this.writerIndex)}. */ public abstract int maxWritableBytes(); /** * Returns the maximum number of bytes which can be written for certain without involving * an internal reallocation or data-copy. The returned value will be &ge; {@link #writableBytes()} * and &le; {@link #maxWritableBytes()}. */ public int maxFastWritableBytes() { return writableBytes(); } /** * Returns {@code true} * if and only if {@code (this.writerIndex - this.readerIndex)} is greater * than {@code 0}. */ public abstract boolean isReadable(); /** * Returns {@code true} if and only if this buffer contains equal to or more than the specified number of elements. */ public abstract boolean isReadable(int size); /** * Returns {@code true} * if and only if {@code (this.capacity - this.writerIndex)} is greater * than {@code 0}. */ public abstract boolean isWritable(); /** * Returns {@code true} if and only if this buffer has enough room to allow writing the specified number of * elements. */ public abstract boolean isWritable(int size); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to * {@code 0}. * This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}. * <p> * Please note that the behavior of this method is different * from that of NIO buffer, which sets the {@code limit} to * the {@code capacity} of the buffer. */ public abstract ByteBuf clear(); /** * Marks the current {@code readerIndex} in this buffer. You can * reposition the current {@code readerIndex} to the marked * {@code readerIndex} by calling {@link #resetReaderIndex()}. * The initial value of the marked {@code readerIndex} is {@code 0}. */ public abstract ByteBuf markReaderIndex(); /** * Repositions the current {@code readerIndex} to the marked * {@code readerIndex} in this buffer. * * @throws IndexOutOfBoundsException * if the current {@code writerIndex} is less than the marked * {@code readerIndex} */ public abstract ByteBuf resetReaderIndex(); /** * Marks the current {@code writerIndex} in this buffer. You can * reposition the current {@code writerIndex} to the marked * {@code writerIndex} by calling {@link #resetWriterIndex()}. * The initial value of the marked {@code writerIndex} is {@code 0}. */ public abstract ByteBuf markWriterIndex(); /** * Repositions the current {@code writerIndex} to the marked * {@code writerIndex} in this buffer. * * @throws IndexOutOfBoundsException * if the current {@code readerIndex} is greater than the marked * {@code writerIndex} */ public abstract ByteBuf resetWriterIndex(); /** * Discards the bytes between the 0th index and {@code readerIndex}. * It moves the bytes between {@code readerIndex} and {@code writerIndex} * to the 0th index, and sets {@code readerIndex} and {@code writerIndex} * to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. * <p> * Please refer to the class documentation for more detailed explanation. */ public abstract ByteBuf discardReadBytes(); /** * Similar to {@link ByteBuf#discardReadBytes()} except that this method might discard * some, all, or none of read bytes depending on its internal implementation to reduce * overall memory bandwidth consumption at the cost of potentially additional memory * consumption. */ public abstract ByteBuf discardSomeReadBytes(); /** * Expands the buffer {@link #capacity()} to make sure the number of * {@linkplain #writableBytes() writable bytes} is equal to or greater than the * specified value. If there are enough writable bytes in this buffer, this method * returns with no side effect. * * @param minWritableBytes * the expected minimum number of writable bytes * @throws IndexOutOfBoundsException * if {@link #writerIndex()} + {@code minWritableBytes} &gt; {@link #maxCapacity()}. * @see #capacity(int) */ public abstract ByteBuf ensureWritable(int minWritableBytes); /** * Expands the buffer {@link #capacity()} to make sure the number of * {@linkplain #writableBytes() writable bytes} is equal to or greater than the * specified value. Unlike {@link #ensureWritable(int)}, this method returns a status code. * * @param minWritableBytes * the expected minimum number of writable bytes * @param force * When {@link #writerIndex()} + {@code minWritableBytes} &gt; {@link #maxCapacity()}: * <ul> * <li>{@code true} - the capacity of the buffer is expanded to {@link #maxCapacity()}</li> * <li>{@code false} - the capacity of the buffer is unchanged</li> * </ul> * @return {@code 0} if the buffer has enough writable bytes, and its capacity is unchanged. * {@code 1} if the buffer does not have enough bytes, and its capacity is unchanged. * {@code 2} if the buffer has enough writable bytes, and its capacity has been increased. * {@code 3} if the buffer does not have enough bytes, but its capacity has been * increased to its maximum. */ public abstract int ensureWritable(int minWritableBytes, boolean force); /** * Gets a boolean at the specified absolute (@code index) in this buffer. * This method does not modify the {@code readerIndex} or {@code writerIndex} * of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ public abstract boolean getBoolean(int index); /** * Gets a byte at the specified absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ public abstract byte getByte(int index); /** * Gets an unsigned byte at the specified absolute {@code index} in this * buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ public abstract short getUnsignedByte(int index); /** * Gets a 16-bit short integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract short getShort(int index); /** * Gets a 16-bit short integer at the specified absolute {@code index} in * this buffer in Little Endian Byte Order. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract short getShortLE(int index); /** * Gets an unsigned 16-bit short integer at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract int getUnsignedShort(int index); /** * Gets an unsigned 16-bit short integer at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract int getUnsignedShortLE(int index); /** * Gets a 24-bit medium integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ public abstract int getMedium(int index); /** * Gets a 24-bit medium integer at the specified absolute {@code index} in * this buffer in the Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ public abstract int getMediumLE(int index); /** * Gets an unsigned 24-bit medium integer at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ public abstract int getUnsignedMedium(int index); /** * Gets an unsigned 24-bit medium integer at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ public abstract int getUnsignedMediumLE(int index); /** * Gets a 32-bit integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract int getInt(int index); /** * Gets a 32-bit integer at the specified absolute {@code index} in * this buffer with Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract int getIntLE(int index); /** * Gets an unsigned 32-bit integer at the specified absolute {@code index} * in this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract long getUnsignedInt(int index); /** * Gets an unsigned 32-bit integer at the specified absolute {@code index} * in this buffer in Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract long getUnsignedIntLE(int index); /** * Gets a 64-bit long integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public abstract long getLong(int index); /** * Gets a 64-bit long integer at the specified absolute {@code index} in * this buffer in Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public abstract long getLongLE(int index); /** * Gets a 2-byte UTF-16 character at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract char getChar(int index); /** * Gets a 32-bit floating point number at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract float getFloat(int index); /** * Gets a 32-bit floating point number at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public float getFloatLE(int index) { return Float.intBitsToFloat(getIntLE(index)); } /** * Gets a 64-bit floating point number at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public abstract double getDouble(int index); /** * Gets a 64-bit floating point number at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public double getDoubleLE(int index) { return Double.longBitsToDouble(getLongLE(index)); } /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination becomes * non-writable. This method is basically same with * {@link #getBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code writerIndex} of the destination by the * number of the transferred bytes while * {@link #getBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.writableBytes} is greater than * {@code this.capacity} */ public abstract ByteBuf getBytes(int index, ByteBuf dst); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. This method is basically same * with {@link #getBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code writerIndex} of the destination by the * number of the transferred bytes while * {@link #getBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code length} is greater than {@code dst.writableBytes} */ public abstract ByteBuf getBytes(int index, ByteBuf dst, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code dstIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code dstIndex + length} is greater than * {@code dst.capacity} */ public abstract ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.length} is greater than * {@code this.capacity} */ public abstract ByteBuf getBytes(int index, byte[] dst); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of this buffer. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code dstIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code dstIndex + length} is greater than * {@code dst.length} */ public abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination's position * reaches its limit. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer while the destination's {@code position} will be increased. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.remaining()} is greater than * {@code this.capacity} */ public abstract ByteBuf getBytes(int index, ByteBuffer dst); /** * Transfers this buffer's data to the specified stream starting at the * specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified stream threw an exception during I/O */ public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException; /** * Transfers this buffer's data to the specified channel starting at the * specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int getBytes(int index, GatheringByteChannel out, int length) throws IOException; /** * Transfers this buffer's data starting at the specified absolute {@code index} * to the specified channel starting at the given file position. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. This method does not modify the channel's position. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int getBytes(int index, FileChannel out, long position, int length) throws IOException; /** * Gets a {@link CharSequence} with the given length at the given index. * * @param length the length to read * @param charset that should be used * @return the sequence * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract CharSequence getCharSequence(int index, int length, Charset charset); /** * Sets the specified boolean at the specified absolute {@code index} in this * buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ public abstract ByteBuf setBoolean(int index, boolean value); /** * Sets the specified byte at the specified absolute {@code index} in this * buffer. The 24 high-order bits of the specified value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ public abstract ByteBuf setByte(int index, int value); /** * Sets the specified 16-bit short integer at the specified absolute * {@code index} in this buffer. The 16 high-order bits of the specified * value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract ByteBuf setShort(int index, int value); /** * Sets the specified 16-bit short integer at the specified absolute * {@code index} in this buffer with the Little Endian Byte Order. * The 16 high-order bits of the specified value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract ByteBuf setShortLE(int index, int value); /** * Sets the specified 24-bit medium integer at the specified absolute * {@code index} in this buffer. Please note that the most significant * byte is ignored in the specified value. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ public abstract ByteBuf setMedium(int index, int value); /** * Sets the specified 24-bit medium integer at the specified absolute * {@code index} in this buffer in the Little Endian Byte Order. * Please note that the most significant byte is ignored in the * specified value. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ public abstract ByteBuf setMediumLE(int index, int value); /** * Sets the specified 32-bit integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract ByteBuf setInt(int index, int value); /** * Sets the specified 32-bit integer at the specified absolute * {@code index} in this buffer with Little Endian byte order * . * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract ByteBuf setIntLE(int index, int value); /** * Sets the specified 64-bit long integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public abstract ByteBuf setLong(int index, long value); /** * Sets the specified 64-bit long integer at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public abstract ByteBuf setLongLE(int index, long value); /** * Sets the specified 2-byte UTF-16 character at the specified absolute * {@code index} in this buffer. * The 16 high-order bits of the specified value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ public abstract ByteBuf setChar(int index, int value); /** * Sets the specified 32-bit floating-point number at the specified * absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public abstract ByteBuf setFloat(int index, float value); /** * Sets the specified 32-bit floating-point number at the specified * absolute {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ public ByteBuf setFloatLE(int index, float value) { return setIntLE(index, Float.floatToRawIntBits(value)); } /** * Sets the specified 64-bit floating-point number at the specified * absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public abstract ByteBuf setDouble(int index, double value); /** * Sets the specified 64-bit floating-point number at the specified * absolute {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ public ByteBuf setDoubleLE(int index, double value) { return setLongLE(index, Double.doubleToRawLongBits(value)); } /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer becomes * unreadable. This method is basically same with * {@link #setBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code readerIndex} of the source buffer by * the number of the transferred bytes while * {@link #setBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.readableBytes} is greater than * {@code this.capacity} */ public abstract ByteBuf setBytes(int index, ByteBuf src); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. This method is basically same * with {@link #setBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code readerIndex} of the source buffer by * the number of the transferred bytes while * {@link #setBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code length} is greater than {@code src.readableBytes} */ public abstract ByteBuf setBytes(int index, ByteBuf src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code srcIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code srcIndex + length} is greater than * {@code src.capacity} */ public abstract ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.length} is greater than * {@code this.capacity} */ public abstract ByteBuf setBytes(int index, byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code srcIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code srcIndex + length} is greater than {@code src.length} */ public abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer's position * reaches its limit. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.remaining()} is greater than * {@code this.capacity} */ public abstract ByteBuf setBytes(int index, ByteBuffer src); /** * Transfers the content of the specified source stream to this buffer * starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified {@link InputStream} reached EOF. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified stream threw an exception during I/O */ public abstract int setBytes(int index, InputStream in, int length) throws IOException; /** * Transfers the content of the specified source channel to this buffer * starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed or it reached EOF. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int setBytes(int index, ScatteringByteChannel in, int length) throws IOException; /** * Transfers the content of the specified source channel starting at the given file position * to this buffer starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. This method does not modify the channel's position. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed or it reached EOF. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int setBytes(int index, FileChannel in, long position, int length) throws IOException; /** * Fills this buffer with <tt>NUL (0x00)</tt> starting at the specified * absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of <tt>NUL</tt>s to write to the buffer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} */ public abstract ByteBuf setZero(int index, int length); /** * Writes the specified {@link CharSequence} at the given {@code index}. * The {@code writerIndex} is not modified by this method. * * @param index on which the sequence should be written * @param sequence to write * @param charset that should be used. * @return the written number of bytes. * @throws IndexOutOfBoundsException * if the sequence at the given index would be out of bounds of the buffer capacity */ public abstract int setCharSequence(int index, CharSequence sequence, Charset charset); /** * Gets a boolean at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ public abstract boolean readBoolean(); /** * Gets a byte at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ public abstract byte readByte(); /** * Gets an unsigned byte at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ public abstract short readUnsignedByte(); /** * Gets a 16-bit short integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ public abstract short readShort(); /** * Gets a 16-bit short integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ public abstract short readShortLE(); /** * Gets an unsigned 16-bit short integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ public abstract int readUnsignedShort(); /** * Gets an unsigned 16-bit short integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ public abstract int readUnsignedShortLE(); /** * Gets a 24-bit medium integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ public abstract int readMedium(); /** * Gets a 24-bit medium integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the * {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ public abstract int readMediumLE(); /** * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ public abstract int readUnsignedMedium(); /** * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ public abstract int readUnsignedMediumLE(); /** * Gets a 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ public abstract int readInt(); /** * Gets a 32-bit integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ public abstract int readIntLE(); /** * Gets an unsigned 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ public abstract long readUnsignedInt(); /** * Gets an unsigned 32-bit integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ public abstract long readUnsignedIntLE(); /** * Gets a 64-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ public abstract long readLong(); /** * Gets a 64-bit integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ public abstract long readLongLE(); /** * Gets a 2-byte UTF-16 character at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ public abstract char readChar(); /** * Gets a 32-bit floating point number at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ public abstract float readFloat(); /** * Gets a 32-bit floating point number at the current {@code readerIndex} * in Little Endian Byte Order and increases the {@code readerIndex} * by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ public float readFloatLE() { return Float.intBitsToFloat(readIntLE()); } /** * Gets a 64-bit floating point number at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ public abstract double readDouble(); /** * Gets a 64-bit floating point number at the current {@code readerIndex} * in Little Endian Byte Order and increases the {@code readerIndex} * by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ public double readDoubleLE() { return Double.longBitsToDouble(readLongLE()); } /** * Transfers this buffer's data to a newly created buffer starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * The returned buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and {@code length} respectively. * * @param length the number of bytes to transfer * * @return the newly created buffer which contains the transferred bytes * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract ByteBuf readBytes(int length); /** * Returns a new slice of this buffer's sub-region starting at the current * {@code readerIndex} and increases the {@code readerIndex} by the size * of the new slice (= {@code length}). * <p> * Also be aware that this method will NOT call {@link #retain()} and so the * reference count will NOT be increased. * * @param length the size of the new slice * * @return the newly created slice * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract ByteBuf readSlice(int length); /** * Returns a new retained slice of this buffer's sub-region starting at the current * {@code readerIndex} and increases the {@code readerIndex} by the size * of the new slice (= {@code length}). * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #readSlice(int)}. * This method behaves similarly to {@code readSlice(...).retain()} except that this method may return * a buffer implementation that produces less garbage. * * @param length the size of the new slice * * @return the newly created slice * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract ByteBuf readRetainedSlice(int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} until the destination becomes * non-writable, and increases the {@code readerIndex} by the number of the * transferred bytes. This method is basically same with * {@link #readBytes(ByteBuf, int, int)}, except that this method * increases the {@code writerIndex} of the destination by the number of * the transferred bytes while {@link #readBytes(ByteBuf, int, int)} * does not. * * @throws IndexOutOfBoundsException * if {@code dst.writableBytes} is greater than * {@code this.readableBytes} */ public abstract ByteBuf readBytes(ByteBuf dst); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). This method * is basically same with {@link #readBytes(ByteBuf, int, int)}, * except that this method increases the {@code writerIndex} of the * destination by the number of the transferred bytes (= {@code length}) * while {@link #readBytes(ByteBuf, int, int)} does not. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} or * if {@code length} is greater than {@code dst.writableBytes} */ public abstract ByteBuf readBytes(ByteBuf dst, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code dstIndex} is less than {@code 0}, * if {@code length} is greater than {@code this.readableBytes}, or * if {@code dstIndex + length} is greater than * {@code dst.capacity} */ public abstract ByteBuf readBytes(ByteBuf dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code dst.length}). * * @throws IndexOutOfBoundsException * if {@code dst.length} is greater than {@code this.readableBytes} */ public abstract ByteBuf readBytes(byte[] dst); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code dstIndex} is less than {@code 0}, * if {@code length} is greater than {@code this.readableBytes}, or * if {@code dstIndex + length} is greater than {@code dst.length} */ public abstract ByteBuf readBytes(byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} until the destination's position * reaches its limit, and increases the {@code readerIndex} by the * number of the transferred bytes. * * @throws IndexOutOfBoundsException * if {@code dst.remaining()} is greater than * {@code this.readableBytes} */ public abstract ByteBuf readBytes(ByteBuffer dst); /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified stream threw an exception during I/O */ public abstract ByteBuf readBytes(OutputStream out, int length) throws IOException; /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int readBytes(GatheringByteChannel out, int length) throws IOException; /** * Gets a {@link CharSequence} with the given length at the current {@code readerIndex} * and increases the {@code readerIndex} by the given length. * * @param length the length to read * @param charset that should be used * @return the sequence * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract CharSequence readCharSequence(int length, Charset charset); /** * Transfers this buffer's data starting at the current {@code readerIndex} * to the specified channel starting at the given file position. * This method does not modify the channel's position. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int readBytes(FileChannel out, long position, int length) throws IOException; /** * Increases the current {@code readerIndex} by the specified * {@code length} in this buffer. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract ByteBuf skipBytes(int length); /** * Sets the specified boolean at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 1} in this buffer. * If {@code this.writableBytes} is less than {@code 1}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeBoolean(boolean value); /** * Sets the specified byte at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 1} in this buffer. * The 24 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 1}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeByte(int value); /** * Sets the specified 16-bit short integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} * in this buffer. The 16 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 2}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeShort(int value); /** * Sets the specified 16-bit short integer in the Little Endian Byte * Order at the current {@code writerIndex} and increases the * {@code writerIndex} by {@code 2} in this buffer. * The 16 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 2}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeShortLE(int value); /** * Sets the specified 24-bit medium integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 3} * in this buffer. * If {@code this.writableBytes} is less than {@code 3}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeMedium(int value); /** * Sets the specified 24-bit medium integer at the current * {@code writerIndex} in the Little Endian Byte Order and * increases the {@code writerIndex} by {@code 3} in this * buffer. * If {@code this.writableBytes} is less than {@code 3}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeMediumLE(int value); /** * Sets the specified 32-bit integer at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 4} in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeInt(int value); /** * Sets the specified 32-bit integer at the current {@code writerIndex} * in the Little Endian Byte Order and increases the {@code writerIndex} * by {@code 4} in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeIntLE(int value); /** * Sets the specified 64-bit long integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} * in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeLong(long value); /** * Sets the specified 64-bit long integer at the current * {@code writerIndex} in the Little Endian Byte Order and * increases the {@code writerIndex} by {@code 8} * in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeLongLE(long value); /** * Sets the specified 2-byte UTF-16 character at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} * in this buffer. The 16 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 2}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeChar(int value); /** * Sets the specified 32-bit floating point number at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 4} * in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeFloat(float value); /** * Sets the specified 32-bit floating point number at the current * {@code writerIndex} in Little Endian Byte Order and increases * the {@code writerIndex} by {@code 4} in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public ByteBuf writeFloatLE(float value) { return writeIntLE(Float.floatToRawIntBits(value)); } /** * Sets the specified 64-bit floating point number at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} * in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeDouble(double value); /** * Sets the specified 64-bit floating point number at the current * {@code writerIndex} in Little Endian Byte Order and increases * the {@code writerIndex} by {@code 8} in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public ByteBuf writeDoubleLE(double value) { return writeLongLE(Double.doubleToRawLongBits(value)); } /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer becomes * unreadable, and increases the {@code writerIndex} by the number of * the transferred bytes. This method is basically same with * {@link #writeBytes(ByteBuf, int, int)}, except that this method * increases the {@code readerIndex} of the source buffer by the number of * the transferred bytes while {@link #writeBytes(ByteBuf, int, int)} * does not. * If {@code this.writableBytes} is less than {@code src.readableBytes}, * {@link #ensureWritable(int)} will be called in an attempt to expand * capacity to accommodate. */ public abstract ByteBuf writeBytes(ByteBuf src); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). This method * is basically same with {@link #writeBytes(ByteBuf, int, int)}, * except that this method increases the {@code readerIndex} of the source * buffer by the number of the transferred bytes (= {@code length}) while * {@link #writeBytes(ByteBuf, int, int)} does not. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if {@code length} is greater then {@code src.readableBytes} */ public abstract ByteBuf writeBytes(ByteBuf src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code srcIndex} is less than {@code 0}, or * if {@code srcIndex + length} is greater than {@code src.capacity} */ public abstract ByteBuf writeBytes(ByteBuf src, int srcIndex, int length); /** * Transfers the specified source array's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code src.length}). * If {@code this.writableBytes} is less than {@code src.length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ public abstract ByteBuf writeBytes(byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code srcIndex} is less than {@code 0}, or * if {@code srcIndex + length} is greater than {@code src.length} */ public abstract ByteBuf writeBytes(byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer's position * reaches its limit, and increases the {@code writerIndex} by the * number of the transferred bytes. * If {@code this.writableBytes} is less than {@code src.remaining()}, * {@link #ensureWritable(int)} will be called in an attempt to expand * capacity to accommodate. */ public abstract ByteBuf writeBytes(ByteBuffer src); /** * Transfers the content of the specified stream to this buffer * starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified {@link InputStream} reached EOF. * * @throws IOException if the specified stream threw an exception during I/O */ public abstract int writeBytes(InputStream in, int length) throws IOException; /** * Transfers the content of the specified channel to this buffer * starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed or it reached EOF. * * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int writeBytes(ScatteringByteChannel in, int length) throws IOException; /** * Transfers the content of the specified channel starting at the given file position * to this buffer starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * This method does not modify the channel's position. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed or it reached EOF. * * @throws IOException * if the specified channel threw an exception during I/O */ public abstract int writeBytes(FileChannel in, long position, int length) throws IOException; /** * Fills this buffer with <tt>NUL (0x00)</tt> starting at the current * {@code writerIndex} and increases the {@code writerIndex} by the * specified {@code length}. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the number of <tt>NUL</tt>s to write to the buffer */ public abstract ByteBuf writeZero(int length); /** * Writes the specified {@link CharSequence} at the current {@code writerIndex} and increases * the {@code writerIndex} by the written bytes. * in this buffer. * If {@code this.writableBytes} is not large enough to write the whole sequence, * {@link #ensureWritable(int)} will be called in an attempt to expand capacity to accommodate. * * @param sequence to write * @param charset that should be used * @return the written number of bytes */ public abstract int writeCharSequence(CharSequence sequence, Charset charset); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search takes place from the specified {@code fromIndex} * (inclusive) to the specified {@code toIndex} (exclusive). * <p> * If {@code fromIndex} is greater than {@code toIndex}, the search is * performed in a reversed order from {@code fromIndex} (exclusive) * down to {@code toIndex} (inclusive). * <p> * Note that the lower index is always included and higher always excluded. * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the absolute index of the first occurrence if found. * {@code -1} otherwise. */ public abstract int indexOf(int fromIndex, int toIndex, byte value); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search takes place from the current {@code readerIndex} * (inclusive) to the current {@code writerIndex} (exclusive). * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the number of bytes between the current {@code readerIndex} * and the first occurrence if found. {@code -1} otherwise. */ public abstract int bytesBefore(byte value); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search starts from the current {@code readerIndex} * (inclusive) and lasts for the specified {@code length}. * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the number of bytes between the current {@code readerIndex} * and the first occurrence if found. {@code -1} otherwise. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ public abstract int bytesBefore(int length, byte value); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search starts from the specified {@code index} (inclusive) * and lasts for the specified {@code length}. * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the number of bytes between the specified {@code index} * and the first occurrence if found. {@code -1} otherwise. * * @throws IndexOutOfBoundsException * if {@code index + length} is greater than {@code this.capacity} */ public abstract int bytesBefore(int index, int length, byte value); /** * Iterates over the readable bytes of this buffer with the specified {@code processor} in ascending order. * * @return {@code -1} if the processor iterated to or beyond the end of the readable bytes. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public abstract int forEachByte(ByteProcessor processor); /** * Iterates over the specified area of this buffer with the specified {@code processor} in ascending order. * (i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}) * * @return {@code -1} if the processor iterated to or beyond the end of the specified area. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public abstract int forEachByte(int index, int length, ByteProcessor processor); /** * Iterates over the readable bytes of this buffer with the specified {@code processor} in descending order. * * @return {@code -1} if the processor iterated to or beyond the beginning of the readable bytes. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public abstract int forEachByteDesc(ByteProcessor processor); /** * Iterates over the specified area of this buffer with the specified {@code processor} in descending order. * (i.e. {@code (index + length - 1)}, {@code (index + length - 2)}, ... {@code index}) * * * @return {@code -1} if the processor iterated to or beyond the beginning of the specified area. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public abstract int forEachByteDesc(int index, int length, ByteProcessor processor); /** * Returns a copy of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer does not affect each other at all. * This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ public abstract ByteBuf copy(); /** * Returns a copy of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer does not affect each other at all. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ public abstract ByteBuf copy(int index, int length); /** * Returns a slice of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer affects each other's content * while they maintain separate indexes and marks. This method is * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Also be aware that this method will NOT call {@link #retain()} and so the * reference count will NOT be increased. */ public abstract ByteBuf slice(); /** * Returns a retained slice of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer affects each other's content * while they maintain separate indexes and marks. This method is * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #slice()}. * This method behaves similarly to {@code slice().retain()} except that this method may return * a buffer implementation that produces less garbage. */ public abstract ByteBuf retainedSlice(); /** * Returns a slice of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer affects each other's content while * they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Also be aware that this method will NOT call {@link #retain()} and so the * reference count will NOT be increased. */ public abstract ByteBuf slice(int index, int length); /** * Returns a retained slice of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer affects each other's content while * they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #slice(int, int)}. * This method behaves similarly to {@code slice(...).retain()} except that this method may return * a buffer implementation that produces less garbage. */ public abstract ByteBuf retainedSlice(int index, int length); /** * Returns a buffer which shares the whole region of this buffer. * Modifying the content of the returned buffer or this buffer affects * each other's content while they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * The reader and writer marks will not be duplicated. Also be aware that this method will * NOT call {@link #retain()} and so the reference count will NOT be increased. * @return A buffer whose readable content is equivalent to the buffer returned by {@link #slice()}. * However this buffer will share the capacity of the underlying buffer, and therefore allows access to all of the * underlying content if necessary. */ public abstract ByteBuf duplicate(); /** * Returns a retained buffer which shares the whole region of this buffer. * Modifying the content of the returned buffer or this buffer affects * each other's content while they maintain separate indexes and marks. * This method is identical to {@code buf.slice(0, buf.capacity())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #slice(int, int)}. * This method behaves similarly to {@code duplicate().retain()} except that this method may return * a buffer implementation that produces less garbage. */ public abstract ByteBuf retainedDuplicate(); /** * Returns the maximum number of NIO {@link ByteBuffer}s that consist this buffer. Note that {@link #nioBuffers()} * or {@link #nioBuffers(int, int)} might return a less number of {@link ByteBuffer}s. * * @return {@code -1} if this buffer has no underlying {@link ByteBuffer}. * the number of the underlying {@link ByteBuffer}s if this buffer has at least one underlying * {@link ByteBuffer}. Note that this method does not return {@code 0} to avoid confusion. * * @see #nioBuffer() * @see #nioBuffer(int, int) * @see #nioBuffers() * @see #nioBuffers(int, int) */ public abstract int nioBufferCount(); /** * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}. The returned buffer * either share or contains the copied content of this buffer, while changing the position * and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method is identical to {@code buf.nioBuffer(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. * Please note that the returned NIO buffer will not see the changes of this buffer if this buffer * is a dynamic buffer and it adjusted its capacity. * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffers() * @see #nioBuffers(int, int) */ public abstract ByteBuffer nioBuffer(); /** * Exposes this buffer's sub-region as an NIO {@link ByteBuffer}. The returned buffer * either share or contains the copied content of this buffer, while changing the position * and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. * Please note that the returned NIO buffer will not see the changes of this buffer if this buffer * is a dynamic buffer and it adjusted its capacity. * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffers() * @see #nioBuffers(int, int) */ public abstract ByteBuffer nioBuffer(int index, int length); /** * Internal use only: Exposes the internal NIO buffer. */ public abstract ByteBuffer internalNioBuffer(int index, int length); /** * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}'s. The returned buffer * either share or contains the copied content of this buffer, while changing the position * and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. * Please note that the returned NIO buffer will not see the changes of this buffer if this buffer * is a dynamic buffer and it adjusted its capacity. * * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffer() * @see #nioBuffer(int, int) */ public abstract ByteBuffer[] nioBuffers(); /** * Exposes this buffer's bytes as an NIO {@link ByteBuffer}'s for the specified index and length * The returned buffer either share or contains the copied content of this buffer, while changing * the position and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic * buffer and it adjusted its capacity. * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffer() * @see #nioBuffer(int, int) */ public abstract ByteBuffer[] nioBuffers(int index, int length); /** * Returns {@code true} if and only if this buffer has a backing byte array. * If this method returns true, you can safely call {@link #array()} and * {@link #arrayOffset()}. */ public abstract boolean hasArray(); /** * Returns the backing byte array of this buffer. * * @throws UnsupportedOperationException * if there no accessible backing byte array */ public abstract byte[] array(); /** * Returns the offset of the first byte within the backing byte array of * this buffer. * * @throws UnsupportedOperationException * if there no accessible backing byte array */ public abstract int arrayOffset(); /** * Returns {@code true} if and only if this buffer has a reference to the low-level memory address that points * to the backing data. */ public abstract boolean hasMemoryAddress(); /** * Returns the low-level memory address that point to the first byte of ths backing data. * * @throws UnsupportedOperationException * if this buffer does not support accessing the low-level memory address */ public abstract long memoryAddress(); /** * Returns {@code true} if this {@link ByteBuf} implementation is backed by a single memory region. * Composite buffer implementations must return false even if they currently hold &le; 1 components. * For buffers that return {@code true}, it's guaranteed that a successful call to {@link #discardReadBytes()} * will increase the value of {@link #maxFastWritableBytes()} by the current {@code readerIndex}. * <p> * This method will return {@code false} by default, and a {@code false} return value does not necessarily * mean that the implementation is composite or that it is <i>not</i> backed by a single memory region. */ public boolean isContiguous() { return false; } /** * A {@code ByteBuf} can turn into itself. * @return This {@code ByteBuf} instance. */ @Override public ByteBuf asByteBuf() { return this; } /** * Decodes this buffer's readable bytes into a string with the specified * character set name. This method is identical to * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws UnsupportedCharsetException * if the specified character set name is not supported by the * current VM */ public abstract String toString(Charset charset); /** * Decodes this buffer's sub-region into a string with the specified * character set. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. */ public abstract String toString(int index, int length, Charset charset); /** * Returns a hash code which was calculated from the content of this * buffer. If there's a byte array which is * {@linkplain #equals(Object) equal to} this array, both arrays should * return the same value. */ @Override public abstract int hashCode(); /** * Determines if the content of the specified buffer is identical to the * content of this array. 'Identical' here means: * <ul> * <li>the size of the contents of the two buffers are same and</li> * <li>every single byte of the content of the two buffers are same.</li> * </ul> * Please note that it does not compare {@link #readerIndex()} nor * {@link #writerIndex()}. This method also returns {@code false} for * {@code null} and an object which is not an instance of * {@link ByteBuf} type. */ @Override public abstract boolean equals(Object obj); /** * Compares the content of the specified buffer to the content of this * buffer. Comparison is performed in the same manner with the string * comparison functions of various languages such as {@code strcmp}, * {@code memcmp} and {@link String#compareTo(String)}. */ @Override public abstract int compareTo(ByteBuf buffer); /** * Returns the string representation of this buffer. This method does not * necessarily return the whole content of the buffer but returns * the values of the key properties such as {@link #readerIndex()}, * {@link #writerIndex()} and {@link #capacity()}. */ @Override public abstract String toString(); @Override public abstract ByteBuf retain(int increment); @Override public abstract ByteBuf retain(); @Override public abstract ByteBuf touch(); @Override public abstract ByteBuf touch(Object hint); /** * Used internally by {@link AbstractByteBuf#ensureAccessible()} to try to guard * against using the buffer after it was released (best-effort). */ boolean isAccessible() { return refCnt() != 0; } }
netty/netty
buffer/src/main/java/io/netty/buffer/ByteBuf.java
34
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import io.netty.util.AsciiString; import io.netty.util.ByteProcessor; import io.netty.util.CharsetUtil; import io.netty.util.IllegalReferenceCountException; import io.netty.util.Recycler.EnhancedHandle; import io.netty.util.ResourceLeakDetector; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.MathUtil; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SWARUtil; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.Arrays; import java.util.Locale; import static io.netty.util.internal.MathUtil.isOutOfBounds; import static io.netty.util.internal.ObjectUtil.checkNotNull; import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero; import static io.netty.util.internal.StringUtil.NEWLINE; import static io.netty.util.internal.StringUtil.isSurrogate; /** * A collection of utility methods that is related with handling {@link ByteBuf}, * such as the generation of hex dump and swapping an integer's byte order. */ public final class ByteBufUtil { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ByteBufUtil.class); private static final FastThreadLocal<byte[]> BYTE_ARRAYS = new FastThreadLocal<byte[]>() { @Override protected byte[] initialValue() throws Exception { return PlatformDependent.allocateUninitializedArray(MAX_TL_ARRAY_LEN); } }; private static final byte WRITE_UTF_UNKNOWN = (byte) '?'; private static final int MAX_CHAR_BUFFER_SIZE; private static final int THREAD_LOCAL_BUFFER_SIZE; private static final int MAX_BYTES_PER_CHAR_UTF8 = (int) CharsetUtil.encoder(CharsetUtil.UTF_8).maxBytesPerChar(); static final int WRITE_CHUNK_SIZE = 8192; static final ByteBufAllocator DEFAULT_ALLOCATOR; static { String allocType = SystemPropertyUtil.get( "io.netty.allocator.type", PlatformDependent.isAndroid() ? "unpooled" : "pooled"); ByteBufAllocator alloc; if ("unpooled".equals(allocType)) { alloc = UnpooledByteBufAllocator.DEFAULT; logger.debug("-Dio.netty.allocator.type: {}", allocType); } else if ("pooled".equals(allocType)) { alloc = PooledByteBufAllocator.DEFAULT; logger.debug("-Dio.netty.allocator.type: {}", allocType); } else if ("adaptive".equals(allocType)) { alloc = new AdaptiveByteBufAllocator(); logger.debug("-Dio.netty.allocator.type: {}", allocType); } else { alloc = PooledByteBufAllocator.DEFAULT; logger.debug("-Dio.netty.allocator.type: pooled (unknown: {})", allocType); } DEFAULT_ALLOCATOR = alloc; THREAD_LOCAL_BUFFER_SIZE = SystemPropertyUtil.getInt("io.netty.threadLocalDirectBufferSize", 0); logger.debug("-Dio.netty.threadLocalDirectBufferSize: {}", THREAD_LOCAL_BUFFER_SIZE); MAX_CHAR_BUFFER_SIZE = SystemPropertyUtil.getInt("io.netty.maxThreadLocalCharBufferSize", 16 * 1024); logger.debug("-Dio.netty.maxThreadLocalCharBufferSize: {}", MAX_CHAR_BUFFER_SIZE); } static final int MAX_TL_ARRAY_LEN = 1024; /** * Allocates a new array if minLength > {@link ByteBufUtil#MAX_TL_ARRAY_LEN} */ static byte[] threadLocalTempArray(int minLength) { return minLength <= MAX_TL_ARRAY_LEN ? BYTE_ARRAYS.get() : PlatformDependent.allocateUninitializedArray(minLength); } /** * @return whether the specified buffer has a nonzero ref count */ public static boolean isAccessible(ByteBuf buffer) { return buffer.isAccessible(); } /** * @throws IllegalReferenceCountException if the buffer has a zero ref count * @return the passed in buffer */ public static ByteBuf ensureAccessible(ByteBuf buffer) { if (!buffer.isAccessible()) { throw new IllegalReferenceCountException(buffer.refCnt()); } return buffer; } /** * Returns a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a> * of the specified buffer's readable bytes. */ public static String hexDump(ByteBuf buffer) { return hexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); } /** * Returns a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a> * of the specified buffer's sub-region. */ public static String hexDump(ByteBuf buffer, int fromIndex, int length) { return HexUtil.hexDump(buffer, fromIndex, length); } /** * Returns a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a> * of the specified byte array. */ public static String hexDump(byte[] array) { return hexDump(array, 0, array.length); } /** * Returns a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a> * of the specified byte array's sub-region. */ public static String hexDump(byte[] array, int fromIndex, int length) { return HexUtil.hexDump(array, fromIndex, length); } /** * Decode a 2-digit hex byte from within a string. */ public static byte decodeHexByte(CharSequence s, int pos) { return StringUtil.decodeHexByte(s, pos); } /** * Decodes a string generated by {@link #hexDump(byte[])} */ public static byte[] decodeHexDump(CharSequence hexDump) { return StringUtil.decodeHexDump(hexDump, 0, hexDump.length()); } /** * Decodes part of a string generated by {@link #hexDump(byte[])} */ public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) { return StringUtil.decodeHexDump(hexDump, fromIndex, length); } /** * Used to determine if the return value of {@link ByteBuf#ensureWritable(int, boolean)} means that there is * adequate space and a write operation will succeed. * @param ensureWritableResult The return value from {@link ByteBuf#ensureWritable(int, boolean)}. * @return {@code true} if {@code ensureWritableResult} means that there is adequate space and a write operation * will succeed. */ public static boolean ensureWritableSuccess(int ensureWritableResult) { return ensureWritableResult == 0 || ensureWritableResult == 2; } /** * Calculates the hash code of the specified buffer. This method is * useful when implementing a new buffer type. */ public static int hashCode(ByteBuf buffer) { final int aLen = buffer.readableBytes(); final int intCount = aLen >>> 2; final int byteCount = aLen & 3; int hashCode = EmptyByteBuf.EMPTY_BYTE_BUF_HASH_CODE; int arrayIndex = buffer.readerIndex(); if (buffer.order() == ByteOrder.BIG_ENDIAN) { for (int i = intCount; i > 0; i --) { hashCode = 31 * hashCode + buffer.getInt(arrayIndex); arrayIndex += 4; } } else { for (int i = intCount; i > 0; i --) { hashCode = 31 * hashCode + swapInt(buffer.getInt(arrayIndex)); arrayIndex += 4; } } for (int i = byteCount; i > 0; i --) { hashCode = 31 * hashCode + buffer.getByte(arrayIndex ++); } if (hashCode == 0) { hashCode = 1; } return hashCode; } /** * Returns the reader index of needle in haystack, or -1 if needle is not in haystack. * This method uses the <a href="https://en.wikipedia.org/wiki/Two-way_string-matching_algorithm">Two-Way * string matching algorithm</a>, which yields O(1) space complexity and excellent performance. */ public static int indexOf(ByteBuf needle, ByteBuf haystack) { if (haystack == null || needle == null) { return -1; } if (needle.readableBytes() > haystack.readableBytes()) { return -1; } int n = haystack.readableBytes(); int m = needle.readableBytes(); if (m == 0) { return 0; } // When the needle has only one byte that can be read, // the ByteBuf.indexOf() can be used if (m == 1) { return haystack.indexOf(haystack.readerIndex(), haystack.writerIndex(), needle.getByte(needle.readerIndex())); } int i; int j = 0; int aStartIndex = needle.readerIndex(); int bStartIndex = haystack.readerIndex(); long suffixes = maxSuf(needle, m, aStartIndex, true); long prefixes = maxSuf(needle, m, aStartIndex, false); int ell = Math.max((int) (suffixes >> 32), (int) (prefixes >> 32)); int per = Math.max((int) suffixes, (int) prefixes); int memory; int length = Math.min(m - per, ell + 1); if (equals(needle, aStartIndex, needle, aStartIndex + per, length)) { memory = -1; while (j <= n - m) { i = Math.max(ell, memory) + 1; while (i < m && needle.getByte(i + aStartIndex) == haystack.getByte(i + j + bStartIndex)) { ++i; } if (i > n) { return -1; } if (i >= m) { i = ell; while (i > memory && needle.getByte(i + aStartIndex) == haystack.getByte(i + j + bStartIndex)) { --i; } if (i <= memory) { return j + bStartIndex; } j += per; memory = m - per - 1; } else { j += i - ell; memory = -1; } } } else { per = Math.max(ell + 1, m - ell - 1) + 1; while (j <= n - m) { i = ell + 1; while (i < m && needle.getByte(i + aStartIndex) == haystack.getByte(i + j + bStartIndex)) { ++i; } if (i > n) { return -1; } if (i >= m) { i = ell; while (i >= 0 && needle.getByte(i + aStartIndex) == haystack.getByte(i + j + bStartIndex)) { --i; } if (i < 0) { return j + bStartIndex; } j += per; } else { j += i - ell; } } } return -1; } private static long maxSuf(ByteBuf x, int m, int start, boolean isSuffix) { int p = 1; int ms = -1; int j = start; int k = 1; byte a; byte b; while (j + k < m) { a = x.getByte(j + k); b = x.getByte(ms + k); boolean suffix = isSuffix ? a < b : a > b; if (suffix) { j += k; k = 1; p = j - ms; } else if (a == b) { if (k != p) { ++k; } else { j += p; k = 1; } } else { ms = j; j = ms + 1; k = p = 1; } } return ((long) ms << 32) + p; } /** * Returns {@code true} if and only if the two specified buffers are * identical to each other for {@code length} bytes starting at {@code aStartIndex} * index for the {@code a} buffer and {@code bStartIndex} index for the {@code b} buffer. * A more compact way to express this is: * <p> * {@code a[aStartIndex : aStartIndex + length] == b[bStartIndex : bStartIndex + length]} */ public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length) { checkNotNull(a, "a"); checkNotNull(b, "b"); // All indexes and lengths must be non-negative checkPositiveOrZero(aStartIndex, "aStartIndex"); checkPositiveOrZero(bStartIndex, "bStartIndex"); checkPositiveOrZero(length, "length"); if (a.writerIndex() - length < aStartIndex || b.writerIndex() - length < bStartIndex) { return false; } final int longCount = length >>> 3; final int byteCount = length & 7; if (a.order() == b.order()) { for (int i = longCount; i > 0; i --) { if (a.getLong(aStartIndex) != b.getLong(bStartIndex)) { return false; } aStartIndex += 8; bStartIndex += 8; } } else { for (int i = longCount; i > 0; i --) { if (a.getLong(aStartIndex) != swapLong(b.getLong(bStartIndex))) { return false; } aStartIndex += 8; bStartIndex += 8; } } for (int i = byteCount; i > 0; i --) { if (a.getByte(aStartIndex) != b.getByte(bStartIndex)) { return false; } aStartIndex ++; bStartIndex ++; } return true; } /** * Returns {@code true} if and only if the two specified buffers are * identical to each other as described in {@link ByteBuf#equals(Object)}. * This method is useful when implementing a new buffer type. */ public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { if (bufferA == bufferB) { return true; } final int aLen = bufferA.readableBytes(); if (aLen != bufferB.readableBytes()) { return false; } return equals(bufferA, bufferA.readerIndex(), bufferB, bufferB.readerIndex(), aLen); } /** * Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}. * This method is useful when implementing a new buffer type. */ public static int compare(ByteBuf bufferA, ByteBuf bufferB) { if (bufferA == bufferB) { return 0; } final int aLen = bufferA.readableBytes(); final int bLen = bufferB.readableBytes(); final int minLength = Math.min(aLen, bLen); final int uintCount = minLength >>> 2; final int byteCount = minLength & 3; int aIndex = bufferA.readerIndex(); int bIndex = bufferB.readerIndex(); if (uintCount > 0) { boolean bufferAIsBigEndian = bufferA.order() == ByteOrder.BIG_ENDIAN; final long res; int uintCountIncrement = uintCount << 2; if (bufferA.order() == bufferB.order()) { res = bufferAIsBigEndian ? compareUintBigEndian(bufferA, bufferB, aIndex, bIndex, uintCountIncrement) : compareUintLittleEndian(bufferA, bufferB, aIndex, bIndex, uintCountIncrement); } else { res = bufferAIsBigEndian ? compareUintBigEndianA(bufferA, bufferB, aIndex, bIndex, uintCountIncrement) : compareUintBigEndianB(bufferA, bufferB, aIndex, bIndex, uintCountIncrement); } if (res != 0) { // Ensure we not overflow when cast return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, res)); } aIndex += uintCountIncrement; bIndex += uintCountIncrement; } for (int aEnd = aIndex + byteCount; aIndex < aEnd; ++aIndex, ++bIndex) { int comp = bufferA.getUnsignedByte(aIndex) - bufferB.getUnsignedByte(bIndex); if (comp != 0) { return comp; } } return aLen - bLen; } private static long compareUintBigEndian( ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement) { for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { long comp = bufferA.getUnsignedInt(aIndex) - bufferB.getUnsignedInt(bIndex); if (comp != 0) { return comp; } } return 0; } private static long compareUintLittleEndian( ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement) { for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { long comp = uintFromLE(bufferA.getUnsignedIntLE(aIndex)) - uintFromLE(bufferB.getUnsignedIntLE(bIndex)); if (comp != 0) { return comp; } } return 0; } private static long compareUintBigEndianA( ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement) { for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { long a = bufferA.getUnsignedInt(aIndex); long b = uintFromLE(bufferB.getUnsignedIntLE(bIndex)); long comp = a - b; if (comp != 0) { return comp; } } return 0; } private static long compareUintBigEndianB( ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement) { for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { long a = uintFromLE(bufferA.getUnsignedIntLE(aIndex)); long b = bufferB.getUnsignedInt(bIndex); long comp = a - b; if (comp != 0) { return comp; } } return 0; } private static long uintFromLE(long value) { return Long.reverseBytes(value) >>> Integer.SIZE; } private static int unrolledFirstIndexOf(AbstractByteBuf buffer, int fromIndex, int byteCount, byte value) { assert byteCount > 0 && byteCount < 8; if (buffer._getByte(fromIndex) == value) { return fromIndex; } if (byteCount == 1) { return -1; } if (buffer._getByte(fromIndex + 1) == value) { return fromIndex + 1; } if (byteCount == 2) { return -1; } if (buffer._getByte(fromIndex + 2) == value) { return fromIndex + 2; } if (byteCount == 3) { return -1; } if (buffer._getByte(fromIndex + 3) == value) { return fromIndex + 3; } if (byteCount == 4) { return -1; } if (buffer._getByte(fromIndex + 4) == value) { return fromIndex + 4; } if (byteCount == 5) { return -1; } if (buffer._getByte(fromIndex + 5) == value) { return fromIndex + 5; } if (byteCount == 6) { return -1; } if (buffer._getByte(fromIndex + 6) == value) { return fromIndex + 6; } return -1; } /** * This is using a SWAR (SIMD Within A Register) batch read technique to minimize bound-checks and improve memory * usage while searching for {@code value}. */ static int firstIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || buffer.capacity() == 0) { return -1; } final int length = toIndex - fromIndex; buffer.checkIndex(fromIndex, length); if (!PlatformDependent.isUnaligned()) { return linearFirstIndexOf(buffer, fromIndex, toIndex, value); } assert PlatformDependent.isUnaligned(); int offset = fromIndex; final int byteCount = length & 7; if (byteCount > 0) { final int index = unrolledFirstIndexOf(buffer, fromIndex, byteCount, value); if (index != -1) { return index; } offset += byteCount; if (offset == toIndex) { return -1; } } final int longCount = length >>> 3; final ByteOrder nativeOrder = ByteOrder.nativeOrder(); final boolean isNative = nativeOrder == buffer.order(); final boolean useLE = nativeOrder == ByteOrder.LITTLE_ENDIAN; final long pattern = SWARUtil.compilePattern(value); for (int i = 0; i < longCount; i++) { // use the faster available getLong final long word = useLE? buffer._getLongLE(offset) : buffer._getLong(offset); final long result = SWARUtil.applyPattern(word, pattern); if (result != 0) { return offset + SWARUtil.getIndex(result, isNative); } offset += Long.BYTES; } return -1; } private static int linearFirstIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value) { for (int i = fromIndex; i < toIndex; i++) { if (buffer._getByte(i) == value) { return i; } } return -1; } /** * The default implementation of {@link ByteBuf#indexOf(int, int, byte)}. * This method is useful when implementing a new buffer type. */ public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { return buffer.indexOf(fromIndex, toIndex, value); } /** * Toggles the endianness of the specified 16-bit short integer. */ public static short swapShort(short value) { return Short.reverseBytes(value); } /** * Toggles the endianness of the specified 24-bit medium integer. */ public static int swapMedium(int value) { int swapped = value << 16 & 0xff0000 | value & 0xff00 | value >>> 16 & 0xff; if ((swapped & 0x800000) != 0) { swapped |= 0xff000000; } return swapped; } /** * Toggles the endianness of the specified 32-bit integer. */ public static int swapInt(int value) { return Integer.reverseBytes(value); } /** * Toggles the endianness of the specified 64-bit long integer. */ public static long swapLong(long value) { return Long.reverseBytes(value); } /** * Writes a big-endian 16-bit short integer to the buffer. */ @SuppressWarnings("deprecation") public static ByteBuf writeShortBE(ByteBuf buf, int shortValue) { return buf.order() == ByteOrder.BIG_ENDIAN? buf.writeShort(shortValue) : buf.writeShort(swapShort((short) shortValue)); } /** * Sets a big-endian 16-bit short integer to the buffer. */ @SuppressWarnings("deprecation") public static ByteBuf setShortBE(ByteBuf buf, int index, int shortValue) { return buf.order() == ByteOrder.BIG_ENDIAN? buf.setShort(index, shortValue) : buf.setShort(index, swapShort((short) shortValue)); } /** * Writes a big-endian 24-bit medium integer to the buffer. */ @SuppressWarnings("deprecation") public static ByteBuf writeMediumBE(ByteBuf buf, int mediumValue) { return buf.order() == ByteOrder.BIG_ENDIAN? buf.writeMedium(mediumValue) : buf.writeMedium(swapMedium(mediumValue)); } /** * Reads a big-endian unsigned 16-bit short integer from the buffer. */ @SuppressWarnings("deprecation") public static int readUnsignedShortBE(ByteBuf buf) { return buf.order() == ByteOrder.BIG_ENDIAN? buf.readUnsignedShort() : swapShort((short) buf.readUnsignedShort()) & 0xFFFF; } /** * Reads a big-endian 32-bit integer from the buffer. */ @SuppressWarnings("deprecation") public static int readIntBE(ByteBuf buf) { return buf.order() == ByteOrder.BIG_ENDIAN? buf.readInt() : swapInt(buf.readInt()); } /** * Read the given amount of bytes into a new {@link ByteBuf} that is allocated from the {@link ByteBufAllocator}. */ public static ByteBuf readBytes(ByteBufAllocator alloc, ByteBuf buffer, int length) { boolean release = true; ByteBuf dst = alloc.buffer(length); try { buffer.readBytes(dst); release = false; return dst; } finally { if (release) { dst.release(); } } } static int lastIndexOf(final AbstractByteBuf buffer, int fromIndex, final int toIndex, final byte value) { assert fromIndex > toIndex; final int capacity = buffer.capacity(); fromIndex = Math.min(fromIndex, capacity); if (fromIndex <= 0) { // fromIndex is the exclusive upper bound. return -1; } final int length = fromIndex - toIndex; buffer.checkIndex(toIndex, length); if (!PlatformDependent.isUnaligned()) { return linearLastIndexOf(buffer, fromIndex, toIndex, value); } final int longCount = length >>> 3; if (longCount > 0) { final ByteOrder nativeOrder = ByteOrder.nativeOrder(); final boolean isNative = nativeOrder == buffer.order(); final boolean useLE = nativeOrder == ByteOrder.LITTLE_ENDIAN; final long pattern = SWARUtil.compilePattern(value); for (int i = 0, offset = fromIndex - Long.BYTES; i < longCount; i++, offset -= Long.BYTES) { // use the faster available getLong final long word = useLE? buffer._getLongLE(offset) : buffer._getLong(offset); final long result = SWARUtil.applyPattern(word, pattern); if (result != 0) { // used the oppoiste endianness since we are looking for the last index. return offset + Long.BYTES - 1 - SWARUtil.getIndex(result, !isNative); } } } return unrolledLastIndexOf(buffer, fromIndex - (longCount << 3), length & 7, value); } private static int linearLastIndexOf(final AbstractByteBuf buffer, final int fromIndex, final int toIndex, final byte value) { for (int i = fromIndex - 1; i >= toIndex; i--) { if (buffer._getByte(i) == value) { return i; } } return -1; } private static int unrolledLastIndexOf(final AbstractByteBuf buffer, final int fromIndex, final int byteCount, final byte value) { assert byteCount >= 0 && byteCount < 8; if (byteCount == 0) { return -1; } if (buffer._getByte(fromIndex - 1) == value) { return fromIndex - 1; } if (byteCount == 1) { return -1; } if (buffer._getByte(fromIndex - 2) == value) { return fromIndex - 2; } if (byteCount == 2) { return -1; } if (buffer._getByte(fromIndex - 3) == value) { return fromIndex - 3; } if (byteCount == 3) { return -1; } if (buffer._getByte(fromIndex - 4) == value) { return fromIndex - 4; } if (byteCount == 4) { return -1; } if (buffer._getByte(fromIndex - 5) == value) { return fromIndex - 5; } if (byteCount == 5) { return -1; } if (buffer._getByte(fromIndex - 6) == value) { return fromIndex - 6; } if (byteCount == 6) { return -1; } if (buffer._getByte(fromIndex - 7) == value) { return fromIndex - 7; } return -1; } private static CharSequence checkCharSequenceBounds(CharSequence seq, int start, int end) { if (MathUtil.isOutOfBounds(start, end - start, seq.length())) { throw new IndexOutOfBoundsException("expected: 0 <= start(" + start + ") <= end (" + end + ") <= seq.length(" + seq.length() + ')'); } return seq; } /** * Encode a {@link CharSequence} in <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write * it to a {@link ByteBuf} allocated with {@code alloc}. * @param alloc The allocator used to allocate a new {@link ByteBuf}. * @param seq The characters to write into a buffer. * @return The {@link ByteBuf} which contains the <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> encoded * result. */ public static ByteBuf writeUtf8(ByteBufAllocator alloc, CharSequence seq) { // UTF-8 uses max. 3 bytes per char, so calculate the worst case. ByteBuf buf = alloc.buffer(utf8MaxBytes(seq)); writeUtf8(buf, seq); return buf; } /** * Encode a {@link CharSequence} in <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write * it to a {@link ByteBuf}. * <p> * It behaves like {@link #reserveAndWriteUtf8(ByteBuf, CharSequence, int)} with {@code reserveBytes} * computed by {@link #utf8MaxBytes(CharSequence)}.<br> * This method returns the actual number of bytes written. */ public static int writeUtf8(ByteBuf buf, CharSequence seq) { int seqLength = seq.length(); return reserveAndWriteUtf8Seq(buf, seq, 0, seqLength, utf8MaxBytes(seqLength)); } /** * Equivalent to <code>{@link #writeUtf8(ByteBuf, CharSequence) writeUtf8(buf, seq.subSequence(start, end))}</code> * but avoids subsequence object allocation. */ public static int writeUtf8(ByteBuf buf, CharSequence seq, int start, int end) { checkCharSequenceBounds(seq, start, end); return reserveAndWriteUtf8Seq(buf, seq, start, end, utf8MaxBytes(end - start)); } /** * Encode a {@link CharSequence} in <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write * it into {@code reserveBytes} of a {@link ByteBuf}. * <p> * The {@code reserveBytes} must be computed (ie eagerly using {@link #utf8MaxBytes(CharSequence)} * or exactly with {@link #utf8Bytes(CharSequence)}) to ensure this method to not fail: for performance reasons * the index checks will be performed using just {@code reserveBytes}.<br> * This method returns the actual number of bytes written. */ public static int reserveAndWriteUtf8(ByteBuf buf, CharSequence seq, int reserveBytes) { return reserveAndWriteUtf8Seq(buf, seq, 0, seq.length(), reserveBytes); } /** * Equivalent to <code>{@link #reserveAndWriteUtf8(ByteBuf, CharSequence, int) * reserveAndWriteUtf8(buf, seq.subSequence(start, end), reserveBytes)}</code> but avoids * subsequence object allocation if possible. * * @return actual number of bytes written */ public static int reserveAndWriteUtf8(ByteBuf buf, CharSequence seq, int start, int end, int reserveBytes) { return reserveAndWriteUtf8Seq(buf, checkCharSequenceBounds(seq, start, end), start, end, reserveBytes); } private static int reserveAndWriteUtf8Seq(ByteBuf buf, CharSequence seq, int start, int end, int reserveBytes) { for (;;) { if (buf instanceof WrappedCompositeByteBuf) { // WrappedCompositeByteBuf is a sub-class of AbstractByteBuf so it needs special handling. buf = buf.unwrap(); } else if (buf instanceof AbstractByteBuf) { AbstractByteBuf byteBuf = (AbstractByteBuf) buf; byteBuf.ensureWritable0(reserveBytes); int written = writeUtf8(byteBuf, byteBuf.writerIndex, reserveBytes, seq, start, end); byteBuf.writerIndex += written; return written; } else if (buf instanceof WrappedByteBuf) { // Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path. buf = buf.unwrap(); } else { byte[] bytes = seq.subSequence(start, end).toString().getBytes(CharsetUtil.UTF_8); buf.writeBytes(bytes); return bytes.length; } } } static int writeUtf8(AbstractByteBuf buffer, int writerIndex, int reservedBytes, CharSequence seq, int len) { return writeUtf8(buffer, writerIndex, reservedBytes, seq, 0, len); } // Fast-Path implementation static int writeUtf8(AbstractByteBuf buffer, int writerIndex, int reservedBytes, CharSequence seq, int start, int end) { if (seq instanceof AsciiString) { writeAsciiString(buffer, writerIndex, (AsciiString) seq, start, end); return end - start; } if (PlatformDependent.hasUnsafe()) { if (buffer.hasArray()) { return unsafeWriteUtf8(buffer.array(), PlatformDependent.byteArrayBaseOffset(), buffer.arrayOffset() + writerIndex, seq, start, end); } if (buffer.hasMemoryAddress()) { return unsafeWriteUtf8(null, buffer.memoryAddress(), writerIndex, seq, start, end); } } else { if (buffer.hasArray()) { return safeArrayWriteUtf8(buffer.array(), buffer.arrayOffset() + writerIndex, seq, start, end); } if (buffer.isDirect()) { assert buffer.nioBufferCount() == 1; final ByteBuffer internalDirectBuffer = buffer.internalNioBuffer(writerIndex, reservedBytes); final int bufferPosition = internalDirectBuffer.position(); return safeDirectWriteUtf8(internalDirectBuffer, bufferPosition, seq, start, end); } } return safeWriteUtf8(buffer, writerIndex, seq, start, end); } // AsciiString Fast-Path implementation - no explicit bound-checks static void writeAsciiString(AbstractByteBuf buffer, int writerIndex, AsciiString seq, int start, int end) { final int begin = seq.arrayOffset() + start; final int length = end - start; if (PlatformDependent.hasUnsafe()) { if (buffer.hasArray()) { PlatformDependent.copyMemory(seq.array(), begin, buffer.array(), buffer.arrayOffset() + writerIndex, length); return; } if (buffer.hasMemoryAddress()) { PlatformDependent.copyMemory(seq.array(), begin, buffer.memoryAddress() + writerIndex, length); return; } } if (buffer.hasArray()) { System.arraycopy(seq.array(), begin, buffer.array(), buffer.arrayOffset() + writerIndex, length); return; } buffer.setBytes(writerIndex, seq.array(), begin, length); } // Safe off-heap Fast-Path implementation private static int safeDirectWriteUtf8(ByteBuffer buffer, int writerIndex, CharSequence seq, int start, int end) { assert !(seq instanceof AsciiString); int oldWriterIndex = writerIndex; // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = start; i < end; i++) { char c = seq.charAt(i); if (c < 0x80) { buffer.put(writerIndex++, (byte) c); } else if (c < 0x800) { buffer.put(writerIndex++, (byte) (0xc0 | (c >> 6))); buffer.put(writerIndex++, (byte) (0x80 | (c & 0x3f))); } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { buffer.put(writerIndex++, WRITE_UTF_UNKNOWN); continue; } // Surrogate Pair consumes 2 characters. if (++i == end) { buffer.put(writerIndex++, WRITE_UTF_UNKNOWN); break; } // Extra method is copied here to NOT allow inlining of writeUtf8 // and increase the chance to inline CharSequence::charAt instead char c2 = seq.charAt(i); if (!Character.isLowSurrogate(c2)) { buffer.put(writerIndex++, WRITE_UTF_UNKNOWN); buffer.put(writerIndex++, Character.isHighSurrogate(c2)? WRITE_UTF_UNKNOWN : (byte) c2); } else { int codePoint = Character.toCodePoint(c, c2); // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. buffer.put(writerIndex++, (byte) (0xf0 | (codePoint >> 18))); buffer.put(writerIndex++, (byte) (0x80 | ((codePoint >> 12) & 0x3f))); buffer.put(writerIndex++, (byte) (0x80 | ((codePoint >> 6) & 0x3f))); buffer.put(writerIndex++, (byte) (0x80 | (codePoint & 0x3f))); } } else { buffer.put(writerIndex++, (byte) (0xe0 | (c >> 12))); buffer.put(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f))); buffer.put(writerIndex++, (byte) (0x80 | (c & 0x3f))); } } return writerIndex - oldWriterIndex; } // Safe off-heap Fast-Path implementation private static int safeWriteUtf8(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int start, int end) { assert !(seq instanceof AsciiString); int oldWriterIndex = writerIndex; // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = start; i < end; i++) { char c = seq.charAt(i); if (c < 0x80) { buffer._setByte(writerIndex++, (byte) c); } else if (c < 0x800) { buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6))); buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); continue; } // Surrogate Pair consumes 2 characters. if (++i == end) { buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); break; } // Extra method is copied here to NOT allow inlining of writeUtf8 // and increase the chance to inline CharSequence::charAt instead char c2 = seq.charAt(i); if (!Character.isLowSurrogate(c2)) { buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); buffer._setByte(writerIndex++, Character.isHighSurrogate(c2)? WRITE_UTF_UNKNOWN : c2); } else { int codePoint = Character.toCodePoint(c, c2); // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. buffer._setByte(writerIndex++, (byte) (0xf0 | (codePoint >> 18))); buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 12) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 6) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | (codePoint & 0x3f))); } } else { buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12))); buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); } } return writerIndex - oldWriterIndex; } // safe byte[] Fast-Path implementation private static int safeArrayWriteUtf8(byte[] buffer, int writerIndex, CharSequence seq, int start, int end) { int oldWriterIndex = writerIndex; for (int i = start; i < end; i++) { char c = seq.charAt(i); if (c < 0x80) { buffer[writerIndex++] = (byte) c; } else if (c < 0x800) { buffer[writerIndex++] = (byte) (0xc0 | (c >> 6)); buffer[writerIndex++] = (byte) (0x80 | (c & 0x3f)); } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { buffer[writerIndex++] = WRITE_UTF_UNKNOWN; continue; } // Surrogate Pair consumes 2 characters. if (++i == end) { buffer[writerIndex++] = WRITE_UTF_UNKNOWN; break; } char c2 = seq.charAt(i); // Extra method is copied here to NOT allow inlining of writeUtf8 // and increase the chance to inline CharSequence::charAt instead if (!Character.isLowSurrogate(c2)) { buffer[writerIndex++] = WRITE_UTF_UNKNOWN; buffer[writerIndex++] = (byte) (Character.isHighSurrogate(c2)? WRITE_UTF_UNKNOWN : c2); } else { int codePoint = Character.toCodePoint(c, c2); // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. buffer[writerIndex++] = (byte) (0xf0 | (codePoint >> 18)); buffer[writerIndex++] = (byte) (0x80 | ((codePoint >> 12) & 0x3f)); buffer[writerIndex++] = (byte) (0x80 | ((codePoint >> 6) & 0x3f)); buffer[writerIndex++] = (byte) (0x80 | (codePoint & 0x3f)); } } else { buffer[writerIndex++] = (byte) (0xe0 | (c >> 12)); buffer[writerIndex++] = (byte) (0x80 | ((c >> 6) & 0x3f)); buffer[writerIndex++] = (byte) (0x80 | (c & 0x3f)); } } return writerIndex - oldWriterIndex; } // unsafe Fast-Path implementation private static int unsafeWriteUtf8(byte[] buffer, long memoryOffset, int writerIndex, CharSequence seq, int start, int end) { assert !(seq instanceof AsciiString); long writerOffset = memoryOffset + writerIndex; final long oldWriterOffset = writerOffset; for (int i = start; i < end; i++) { char c = seq.charAt(i); if (c < 0x80) { PlatformDependent.putByte(buffer, writerOffset++, (byte) c); } else if (c < 0x800) { PlatformDependent.putByte(buffer, writerOffset++, (byte) (0xc0 | (c >> 6))); PlatformDependent.putByte(buffer, writerOffset++, (byte) (0x80 | (c & 0x3f))); } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { PlatformDependent.putByte(buffer, writerOffset++, WRITE_UTF_UNKNOWN); continue; } // Surrogate Pair consumes 2 characters. if (++i == end) { PlatformDependent.putByte(buffer, writerOffset++, WRITE_UTF_UNKNOWN); break; } char c2 = seq.charAt(i); // Extra method is copied here to NOT allow inlining of writeUtf8 // and increase the chance to inline CharSequence::charAt instead if (!Character.isLowSurrogate(c2)) { PlatformDependent.putByte(buffer, writerOffset++, WRITE_UTF_UNKNOWN); PlatformDependent.putByte(buffer, writerOffset++, (byte) (Character.isHighSurrogate(c2)? WRITE_UTF_UNKNOWN : c2)); } else { int codePoint = Character.toCodePoint(c, c2); // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. PlatformDependent.putByte(buffer, writerOffset++, (byte) (0xf0 | (codePoint >> 18))); PlatformDependent.putByte(buffer, writerOffset++, (byte) (0x80 | ((codePoint >> 12) & 0x3f))); PlatformDependent.putByte(buffer, writerOffset++, (byte) (0x80 | ((codePoint >> 6) & 0x3f))); PlatformDependent.putByte(buffer, writerOffset++, (byte) (0x80 | (codePoint & 0x3f))); } } else { PlatformDependent.putByte(buffer, writerOffset++, (byte) (0xe0 | (c >> 12))); PlatformDependent.putByte(buffer, writerOffset++, (byte) (0x80 | ((c >> 6) & 0x3f))); PlatformDependent.putByte(buffer, writerOffset++, (byte) (0x80 | (c & 0x3f))); } } return (int) (writerOffset - oldWriterOffset); } /** * Returns max bytes length of UTF8 character sequence of the given length. */ public static int utf8MaxBytes(final int seqLength) { return seqLength * MAX_BYTES_PER_CHAR_UTF8; } /** * Returns max bytes length of UTF8 character sequence. * <p> * It behaves like {@link #utf8MaxBytes(int)} applied to {@code seq} {@link CharSequence#length()}. */ public static int utf8MaxBytes(CharSequence seq) { if (seq instanceof AsciiString) { return seq.length(); } return utf8MaxBytes(seq.length()); } /** * Returns the exact bytes length of UTF8 character sequence. * <p> * This method is producing the exact length according to {@link #writeUtf8(ByteBuf, CharSequence)}. */ public static int utf8Bytes(final CharSequence seq) { return utf8ByteCount(seq, 0, seq.length()); } /** * Equivalent to <code>{@link #utf8Bytes(CharSequence) utf8Bytes(seq.subSequence(start, end))}</code> * but avoids subsequence object allocation. * <p> * This method is producing the exact length according to {@link #writeUtf8(ByteBuf, CharSequence, int, int)}. */ public static int utf8Bytes(final CharSequence seq, int start, int end) { return utf8ByteCount(checkCharSequenceBounds(seq, start, end), start, end); } private static int utf8ByteCount(final CharSequence seq, int start, int end) { if (seq instanceof AsciiString) { return end - start; } int i = start; // ASCII fast path while (i < end && seq.charAt(i) < 0x80) { ++i; } // !ASCII is packed in a separate method to let the ASCII case be smaller return i < end ? (i - start) + utf8BytesNonAscii(seq, i, end) : i - start; } private static int utf8BytesNonAscii(final CharSequence seq, final int start, final int end) { int encodedLength = 0; for (int i = start; i < end; i++) { final char c = seq.charAt(i); // making it 100% branchless isn't rewarding due to the many bit operations necessary! if (c < 0x800) { // branchless version of: (c <= 127 ? 0:1) + 1 encodedLength += ((0x7f - c) >>> 31) + 1; } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { encodedLength++; // WRITE_UTF_UNKNOWN continue; } // Surrogate Pair consumes 2 characters. if (++i == end) { encodedLength++; // WRITE_UTF_UNKNOWN break; } if (!Character.isLowSurrogate(seq.charAt(i))) { // WRITE_UTF_UNKNOWN + (Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2) encodedLength += 2; continue; } // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. encodedLength += 4; } else { encodedLength += 3; } } return encodedLength; } /** * Encode a {@link CharSequence} in <a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a> and write * it to a {@link ByteBuf} allocated with {@code alloc}. * @param alloc The allocator used to allocate a new {@link ByteBuf}. * @param seq The characters to write into a buffer. * @return The {@link ByteBuf} which contains the <a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a> encoded * result. */ public static ByteBuf writeAscii(ByteBufAllocator alloc, CharSequence seq) { // ASCII uses 1 byte per char ByteBuf buf = alloc.buffer(seq.length()); writeAscii(buf, seq); return buf; } /** * Encode a {@link CharSequence} in <a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a> and write it * to a {@link ByteBuf}. * * This method returns the actual number of bytes written. */ public static int writeAscii(ByteBuf buf, CharSequence seq) { // ASCII uses 1 byte per char for (;;) { if (buf instanceof WrappedCompositeByteBuf) { // WrappedCompositeByteBuf is a sub-class of AbstractByteBuf so it needs special handling. buf = buf.unwrap(); } else if (buf instanceof AbstractByteBuf) { final int len = seq.length(); AbstractByteBuf byteBuf = (AbstractByteBuf) buf; byteBuf.ensureWritable0(len); if (seq instanceof AsciiString) { writeAsciiString(byteBuf, byteBuf.writerIndex, (AsciiString) seq, 0, len); } else { final int written = writeAscii(byteBuf, byteBuf.writerIndex, seq, len); assert written == len; } byteBuf.writerIndex += len; return len; } else if (buf instanceof WrappedByteBuf) { // Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path. buf = buf.unwrap(); } else { byte[] bytes = seq.toString().getBytes(CharsetUtil.US_ASCII); buf.writeBytes(bytes); return bytes.length; } } } static int writeAscii(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len) { if (seq instanceof AsciiString) { writeAsciiString(buffer, writerIndex, (AsciiString) seq, 0, len); } else { writeAsciiCharSequence(buffer, writerIndex, seq, len); } return len; } private static int writeAsciiCharSequence(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len) { // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = 0; i < len; i++) { buffer._setByte(writerIndex++, AsciiString.c2b(seq.charAt(i))); } return len; } /** * Encode the given {@link CharBuffer} using the given {@link Charset} into a new {@link ByteBuf} which * is allocated via the {@link ByteBufAllocator}. */ public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset) { return encodeString0(alloc, false, src, charset, 0); } /** * Encode the given {@link CharBuffer} using the given {@link Charset} into a new {@link ByteBuf} which * is allocated via the {@link ByteBufAllocator}. * * @param alloc The {@link ByteBufAllocator} to allocate {@link ByteBuf}. * @param src The {@link CharBuffer} to encode. * @param charset The specified {@link Charset}. * @param extraCapacity the extra capacity to alloc except the space for decoding. */ public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset, int extraCapacity) { return encodeString0(alloc, false, src, charset, extraCapacity); } static ByteBuf encodeString0(ByteBufAllocator alloc, boolean enforceHeap, CharBuffer src, Charset charset, int extraCapacity) { final CharsetEncoder encoder = CharsetUtil.encoder(charset); int length = (int) ((double) src.remaining() * encoder.maxBytesPerChar()) + extraCapacity; boolean release = true; final ByteBuf dst; if (enforceHeap) { dst = alloc.heapBuffer(length); } else { dst = alloc.buffer(length); } try { final ByteBuffer dstBuf = dst.internalNioBuffer(dst.readerIndex(), length); final int pos = dstBuf.position(); CoderResult cr = encoder.encode(src, dstBuf, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = encoder.flush(dstBuf); if (!cr.isUnderflow()) { cr.throwException(); } dst.writerIndex(dst.writerIndex() + dstBuf.position() - pos); release = false; return dst; } catch (CharacterCodingException x) { throw new IllegalStateException(x); } finally { if (release) { dst.release(); } } } @SuppressWarnings("deprecation") static String decodeString(ByteBuf src, int readerIndex, int len, Charset charset) { if (len == 0) { return StringUtil.EMPTY_STRING; } final byte[] array; final int offset; if (src.hasArray()) { array = src.array(); offset = src.arrayOffset() + readerIndex; } else { array = threadLocalTempArray(len); offset = 0; src.getBytes(readerIndex, array, 0, len); } if (CharsetUtil.US_ASCII.equals(charset)) { // Fast-path for US-ASCII which is used frequently. return new String(array, 0, offset, len); } return new String(array, offset, len, charset); } /** * Returns a cached thread-local direct buffer, if available. * * @return a cached thread-local direct buffer, if available. {@code null} otherwise. */ public static ByteBuf threadLocalDirectBuffer() { if (THREAD_LOCAL_BUFFER_SIZE <= 0) { return null; } if (PlatformDependent.hasUnsafe()) { return ThreadLocalUnsafeDirectByteBuf.newInstance(); } else { return ThreadLocalDirectByteBuf.newInstance(); } } /** * Create a copy of the underlying storage from {@code buf} into a byte array. * The copy will start at {@link ByteBuf#readerIndex()} and copy {@link ByteBuf#readableBytes()} bytes. */ public static byte[] getBytes(ByteBuf buf) { return getBytes(buf, buf.readerIndex(), buf.readableBytes()); } /** * Create a copy of the underlying storage from {@code buf} into a byte array. * The copy will start at {@code start} and copy {@code length} bytes. */ public static byte[] getBytes(ByteBuf buf, int start, int length) { return getBytes(buf, start, length, true); } /** * Return an array of the underlying storage from {@code buf} into a byte array. * The copy will start at {@code start} and copy {@code length} bytes. * If {@code copy} is true a copy will be made of the memory. * If {@code copy} is false the underlying storage will be shared, if possible. */ public static byte[] getBytes(ByteBuf buf, int start, int length, boolean copy) { int capacity = buf.capacity(); if (isOutOfBounds(start, length, capacity)) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= start + length(" + length + ") <= " + "buf.capacity(" + capacity + ')'); } if (buf.hasArray()) { int baseOffset = buf.arrayOffset() + start; byte[] bytes = buf.array(); if (copy || baseOffset != 0 || length != bytes.length) { return Arrays.copyOfRange(bytes, baseOffset, baseOffset + length); } else { return bytes; } } byte[] bytes = PlatformDependent.allocateUninitializedArray(length); buf.getBytes(start, bytes); return bytes; } /** * Copies the all content of {@code src} to a {@link ByteBuf} using {@link ByteBuf#writeBytes(byte[], int, int)}. * * @param src the source string to copy * @param dst the destination buffer */ public static void copy(AsciiString src, ByteBuf dst) { copy(src, 0, dst, src.length()); } /** * Copies the content of {@code src} to a {@link ByteBuf} using {@link ByteBuf#setBytes(int, byte[], int, int)}. * Unlike the {@link #copy(AsciiString, ByteBuf)} and {@link #copy(AsciiString, int, ByteBuf, int)} methods, * this method do not increase a {@code writerIndex} of {@code dst} buffer. * * @param src the source string to copy * @param srcIdx the starting offset of characters to copy * @param dst the destination buffer * @param dstIdx the starting offset in the destination buffer * @param length the number of characters to copy */ public static void copy(AsciiString src, int srcIdx, ByteBuf dst, int dstIdx, int length) { if (isOutOfBounds(srcIdx, length, src.length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length(" + length + ") <= srcLen(" + src.length() + ')'); } checkNotNull(dst, "dst").setBytes(dstIdx, src.array(), srcIdx + src.arrayOffset(), length); } /** * Copies the content of {@code src} to a {@link ByteBuf} using {@link ByteBuf#writeBytes(byte[], int, int)}. * * @param src the source string to copy * @param srcIdx the starting offset of characters to copy * @param dst the destination buffer * @param length the number of characters to copy */ public static void copy(AsciiString src, int srcIdx, ByteBuf dst, int length) { if (isOutOfBounds(srcIdx, length, src.length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length(" + length + ") <= srcLen(" + src.length() + ')'); } checkNotNull(dst, "dst").writeBytes(src.array(), srcIdx + src.arrayOffset(), length); } /** * Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans. */ public static String prettyHexDump(ByteBuf buffer) { return prettyHexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); } /** * Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans, * starting at the given {@code offset} using the given {@code length}. */ public static String prettyHexDump(ByteBuf buffer, int offset, int length) { return HexUtil.prettyHexDump(buffer, offset, length); } /** * Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified * {@link StringBuilder} that is easy to read by humans. */ public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf) { appendPrettyHexDump(dump, buf, buf.readerIndex(), buf.readableBytes()); } /** * Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified * {@link StringBuilder} that is easy to read by humans, starting at the given {@code offset} using * the given {@code length}. */ public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length) { HexUtil.appendPrettyHexDump(dump, buf, offset, length); } /* Separate class so that the expensive static initialization is only done when needed */ private static final class HexUtil { private static final char[] BYTE2CHAR = new char[256]; private static final char[] HEXDUMP_TABLE = new char[256 * 4]; private static final String[] HEXPADDING = new String[16]; private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4]; private static final String[] BYTE2HEX = new String[256]; private static final String[] BYTEPADDING = new String[16]; static { final char[] DIGITS = "0123456789abcdef".toCharArray(); for (int i = 0; i < 256; i ++) { HEXDUMP_TABLE[ i << 1 ] = DIGITS[i >>> 4 & 0x0F]; HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F]; } int i; // Generate the lookup table for hex dump paddings for (i = 0; i < HEXPADDING.length; i ++) { int padding = HEXPADDING.length - i; StringBuilder buf = new StringBuilder(padding * 3); for (int j = 0; j < padding; j ++) { buf.append(" "); } HEXPADDING[i] = buf.toString(); } // Generate the lookup table for the start-offset header in each row (up to 64KiB). for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i ++) { StringBuilder buf = new StringBuilder(12); buf.append(NEWLINE); buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L)); buf.setCharAt(buf.length() - 9, '|'); buf.append('|'); HEXDUMP_ROWPREFIXES[i] = buf.toString(); } // Generate the lookup table for byte-to-hex-dump conversion for (i = 0; i < BYTE2HEX.length; i ++) { BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i); } // Generate the lookup table for byte dump paddings for (i = 0; i < BYTEPADDING.length; i ++) { int padding = BYTEPADDING.length - i; StringBuilder buf = new StringBuilder(padding); for (int j = 0; j < padding; j ++) { buf.append(' '); } BYTEPADDING[i] = buf.toString(); } // Generate the lookup table for byte-to-char conversion for (i = 0; i < BYTE2CHAR.length; i ++) { if (i <= 0x1f || i >= 0x7f) { BYTE2CHAR[i] = '.'; } else { BYTE2CHAR[i] = (char) i; } } } private static String hexDump(ByteBuf buffer, int fromIndex, int length) { checkPositiveOrZero(length, "length"); if (length == 0) { return ""; } int endIndex = fromIndex + length; char[] buf = new char[length << 1]; int srcIdx = fromIndex; int dstIdx = 0; for (; srcIdx < endIndex; srcIdx ++, dstIdx += 2) { System.arraycopy( HEXDUMP_TABLE, buffer.getUnsignedByte(srcIdx) << 1, buf, dstIdx, 2); } return new String(buf); } private static String hexDump(byte[] array, int fromIndex, int length) { checkPositiveOrZero(length, "length"); if (length == 0) { return ""; } int endIndex = fromIndex + length; char[] buf = new char[length << 1]; int srcIdx = fromIndex; int dstIdx = 0; for (; srcIdx < endIndex; srcIdx ++, dstIdx += 2) { System.arraycopy( HEXDUMP_TABLE, (array[srcIdx] & 0xFF) << 1, buf, dstIdx, 2); } return new String(buf); } private static String prettyHexDump(ByteBuf buffer, int offset, int length) { if (length == 0) { return StringUtil.EMPTY_STRING; } else { int rows = length / 16 + ((length & 15) == 0? 0 : 1) + 4; StringBuilder buf = new StringBuilder(rows * 80); appendPrettyHexDump(buf, buffer, offset, length); return buf.toString(); } } private static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length) { if (isOutOfBounds(offset, length, buf.capacity())) { throw new IndexOutOfBoundsException( "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length + ") <= " + "buf.capacity(" + buf.capacity() + ')'); } if (length == 0) { return; } dump.append( " +-------------------------------------------------+" + NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" + NEWLINE + "+--------+-------------------------------------------------+----------------+"); final int fullRows = length >>> 4; final int remainder = length & 0xF; // Dump the rows which have 16 bytes. for (int row = 0; row < fullRows; row ++) { int rowStartIndex = (row << 4) + offset; // Per-row prefix. appendHexDumpRowPrefix(dump, row, rowStartIndex); // Hex dump int rowEndIndex = rowStartIndex + 16; for (int j = rowStartIndex; j < rowEndIndex; j ++) { dump.append(BYTE2HEX[buf.getUnsignedByte(j)]); } dump.append(" |"); // ASCII dump for (int j = rowStartIndex; j < rowEndIndex; j ++) { dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]); } dump.append('|'); } // Dump the last row which has less than 16 bytes. if (remainder != 0) { int rowStartIndex = (fullRows << 4) + offset; appendHexDumpRowPrefix(dump, fullRows, rowStartIndex); // Hex dump int rowEndIndex = rowStartIndex + remainder; for (int j = rowStartIndex; j < rowEndIndex; j ++) { dump.append(BYTE2HEX[buf.getUnsignedByte(j)]); } dump.append(HEXPADDING[remainder]); dump.append(" |"); // Ascii dump for (int j = rowStartIndex; j < rowEndIndex; j ++) { dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]); } dump.append(BYTEPADDING[remainder]); dump.append('|'); } dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+"); } private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) { if (row < HEXDUMP_ROWPREFIXES.length) { dump.append(HEXDUMP_ROWPREFIXES[row]); } else { dump.append(NEWLINE); dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L)); dump.setCharAt(dump.length() - 9, '|'); dump.append('|'); } } } static final class ThreadLocalUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf { private static final ObjectPool<ThreadLocalUnsafeDirectByteBuf> RECYCLER = ObjectPool.newPool(new ObjectCreator<ThreadLocalUnsafeDirectByteBuf>() { @Override public ThreadLocalUnsafeDirectByteBuf newObject(Handle<ThreadLocalUnsafeDirectByteBuf> handle) { return new ThreadLocalUnsafeDirectByteBuf(handle); } }); static ThreadLocalUnsafeDirectByteBuf newInstance() { ThreadLocalUnsafeDirectByteBuf buf = RECYCLER.get(); buf.resetRefCnt(); return buf; } private final EnhancedHandle<ThreadLocalUnsafeDirectByteBuf> handle; private ThreadLocalUnsafeDirectByteBuf(Handle<ThreadLocalUnsafeDirectByteBuf> handle) { super(UnpooledByteBufAllocator.DEFAULT, 256, Integer.MAX_VALUE); this.handle = (EnhancedHandle<ThreadLocalUnsafeDirectByteBuf>) handle; } @Override protected void deallocate() { if (capacity() > THREAD_LOCAL_BUFFER_SIZE) { super.deallocate(); } else { clear(); handle.unguardedRecycle(this); } } } static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf { private static final ObjectPool<ThreadLocalDirectByteBuf> RECYCLER = ObjectPool.newPool( new ObjectCreator<ThreadLocalDirectByteBuf>() { @Override public ThreadLocalDirectByteBuf newObject(Handle<ThreadLocalDirectByteBuf> handle) { return new ThreadLocalDirectByteBuf(handle); } }); static ThreadLocalDirectByteBuf newInstance() { ThreadLocalDirectByteBuf buf = RECYCLER.get(); buf.resetRefCnt(); return buf; } private final EnhancedHandle<ThreadLocalDirectByteBuf> handle; private ThreadLocalDirectByteBuf(Handle<ThreadLocalDirectByteBuf> handle) { super(UnpooledByteBufAllocator.DEFAULT, 256, Integer.MAX_VALUE); this.handle = (EnhancedHandle<ThreadLocalDirectByteBuf>) handle; } @Override protected void deallocate() { if (capacity() > THREAD_LOCAL_BUFFER_SIZE) { super.deallocate(); } else { clear(); handle.unguardedRecycle(this); } } } /** * Returns {@code true} if the given {@link ByteBuf} is valid text using the given {@link Charset}, * otherwise return {@code false}. * * @param buf The given {@link ByteBuf}. * @param charset The specified {@link Charset}. */ public static boolean isText(ByteBuf buf, Charset charset) { return isText(buf, buf.readerIndex(), buf.readableBytes(), charset); } /** * Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid * text using the given {@link Charset}, otherwise return {@code false}. * * @param buf The given {@link ByteBuf}. * @param index The start index of the specified buffer. * @param length The length of the specified buffer. * @param charset The specified {@link Charset}. * * @throws IndexOutOfBoundsException if {@code index} + {@code length} is greater than {@code buf.readableBytes} */ public static boolean isText(ByteBuf buf, int index, int length, Charset charset) { checkNotNull(buf, "buf"); checkNotNull(charset, "charset"); final int maxIndex = buf.readerIndex() + buf.readableBytes(); if (index < 0 || length < 0 || index > maxIndex - length) { throw new IndexOutOfBoundsException("index: " + index + " length: " + length); } if (charset.equals(CharsetUtil.UTF_8)) { return isUtf8(buf, index, length); } else if (charset.equals(CharsetUtil.US_ASCII)) { return isAscii(buf, index, length); } else { CharsetDecoder decoder = CharsetUtil.decoder(charset, CodingErrorAction.REPORT, CodingErrorAction.REPORT); try { if (buf.nioBufferCount() == 1) { decoder.decode(buf.nioBuffer(index, length)); } else { ByteBuf heapBuffer = buf.alloc().heapBuffer(length); try { heapBuffer.writeBytes(buf, index, length); decoder.decode(heapBuffer.internalNioBuffer(heapBuffer.readerIndex(), length)); } finally { heapBuffer.release(); } } return true; } catch (CharacterCodingException ignore) { return false; } } } /** * Aborts on a byte which is not a valid ASCII character. */ private static final ByteProcessor FIND_NON_ASCII = new ByteProcessor() { @Override public boolean process(byte value) { return value >= 0; } }; /** * Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid * ASCII text, otherwise return {@code false}. * * @param buf The given {@link ByteBuf}. * @param index The start index of the specified buffer. * @param length The length of the specified buffer. */ private static boolean isAscii(ByteBuf buf, int index, int length) { return buf.forEachByte(index, length, FIND_NON_ASCII) == -1; } /** * Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid * UTF8 text, otherwise return {@code false}. * * @param buf The given {@link ByteBuf}. * @param index The start index of the specified buffer. * @param length The length of the specified buffer. * * @see * <a href=https://www.ietf.org/rfc/rfc3629.txt>UTF-8 Definition</a> * * <pre> * 1. Bytes format of UTF-8 * * The table below summarizes the format of these different octet types. * The letter x indicates bits available for encoding bits of the character number. * * Char. number range | UTF-8 octet sequence * (hexadecimal) | (binary) * --------------------+--------------------------------------------- * 0000 0000-0000 007F | 0xxxxxxx * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * </pre> * * <pre> * 2. Syntax of UTF-8 Byte Sequences * * UTF8-octets = *( UTF8-char ) * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4 * UTF8-1 = %x00-7F * UTF8-2 = %xC2-DF UTF8-tail * UTF8-3 = %xE0 %xA0-BF UTF8-tail / * %xE1-EC 2( UTF8-tail ) / * %xED %x80-9F UTF8-tail / * %xEE-EF 2( UTF8-tail ) * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / * %xF1-F3 3( UTF8-tail ) / * %xF4 %x80-8F 2( UTF8-tail ) * UTF8-tail = %x80-BF * </pre> */ private static boolean isUtf8(ByteBuf buf, int index, int length) { final int endIndex = index + length; while (index < endIndex) { byte b1 = buf.getByte(index++); byte b2, b3, b4; if ((b1 & 0x80) == 0) { // 1 byte continue; } if ((b1 & 0xE0) == 0xC0) { // 2 bytes // // Bit/Byte pattern // 110xxxxx 10xxxxxx // C2..DF 80..BF if (index >= endIndex) { // no enough bytes return false; } b2 = buf.getByte(index++); if ((b2 & 0xC0) != 0x80) { // 2nd byte not starts with 10 return false; } if ((b1 & 0xFF) < 0xC2) { // out of lower bound return false; } } else if ((b1 & 0xF0) == 0xE0) { // 3 bytes // // Bit/Byte pattern // 1110xxxx 10xxxxxx 10xxxxxx // E0 A0..BF 80..BF // E1..EC 80..BF 80..BF // ED 80..9F 80..BF // E1..EF 80..BF 80..BF if (index > endIndex - 2) { // no enough bytes return false; } b2 = buf.getByte(index++); b3 = buf.getByte(index++); if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) { // 2nd or 3rd bytes not start with 10 return false; } if ((b1 & 0x0F) == 0x00 && (b2 & 0xFF) < 0xA0) { // out of lower bound return false; } if ((b1 & 0x0F) == 0x0D && (b2 & 0xFF) > 0x9F) { // out of upper bound return false; } } else if ((b1 & 0xF8) == 0xF0) { // 4 bytes // // Bit/Byte pattern // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // F0 90..BF 80..BF 80..BF // F1..F3 80..BF 80..BF 80..BF // F4 80..8F 80..BF 80..BF if (index > endIndex - 3) { // no enough bytes return false; } b2 = buf.getByte(index++); b3 = buf.getByte(index++); b4 = buf.getByte(index++); if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80 || (b4 & 0xC0) != 0x80) { // 2nd, 3rd or 4th bytes not start with 10 return false; } if ((b1 & 0xFF) > 0xF4 // b1 invalid || (b1 & 0xFF) == 0xF0 && (b2 & 0xFF) < 0x90 // b2 out of lower bound || (b1 & 0xFF) == 0xF4 && (b2 & 0xFF) > 0x8F) { // b2 out of upper bound return false; } } else { return false; } } return true; } /** * Read bytes from the given {@link ByteBuffer} into the given {@link OutputStream} using the {@code position} and * {@code length}. The position and limit of the given {@link ByteBuffer} may be adjusted. */ static void readBytes(ByteBufAllocator allocator, ByteBuffer buffer, int position, int length, OutputStream out) throws IOException { if (buffer.hasArray()) { out.write(buffer.array(), position + buffer.arrayOffset(), length); } else { int chunkLen = Math.min(length, WRITE_CHUNK_SIZE); buffer.clear().position(position); if (length <= MAX_TL_ARRAY_LEN || !allocator.isDirectBufferPooled()) { getBytes(buffer, threadLocalTempArray(chunkLen), 0, chunkLen, out, length); } else { // if direct buffers are pooled chances are good that heap buffers are pooled as well. ByteBuf tmpBuf = allocator.heapBuffer(chunkLen); try { byte[] tmp = tmpBuf.array(); int offset = tmpBuf.arrayOffset(); getBytes(buffer, tmp, offset, chunkLen, out, length); } finally { tmpBuf.release(); } } } } private static void getBytes(ByteBuffer inBuffer, byte[] in, int inOffset, int inLen, OutputStream out, int outLen) throws IOException { do { int len = Math.min(inLen, outLen); inBuffer.get(in, inOffset, len); out.write(in, inOffset, len); outLen -= len; } while (outLen > 0); } /** * Set {@link AbstractByteBuf#leakDetector}'s {@link ResourceLeakDetector.LeakListener}. * * @param leakListener If leakListener is not null, it will be notified once a ByteBuf leak is detected. */ public static void setLeakListener(ResourceLeakDetector.LeakListener leakListener) { AbstractByteBuf.leakDetector.setLeakListener(leakListener); } private ByteBufUtil() { } }
netty/netty
buffer/src/main/java/io/netty/buffer/ByteBufUtil.java
35
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.base64.Base64; import io.netty.util.CharsetUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.KeyException; import java.security.KeyStore; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Reads a PEM file and converts it into a list of DERs so that they are imported into a {@link KeyStore} easily. */ final class PemReader { private static final InternalLogger logger = InternalLoggerFactory.getInstance(PemReader.class); private static final Pattern CERT_HEADER = Pattern.compile( "-+BEGIN\\s[^-\\r\\n]*CERTIFICATE[^-\\r\\n]*-+(?:\\s|\\r|\\n)+"); private static final Pattern CERT_FOOTER = Pattern.compile( "-+END\\s[^-\\r\\n]*CERTIFICATE[^-\\r\\n]*-+(?:\\s|\\r|\\n)*"); private static final Pattern KEY_HEADER = Pattern.compile( "-+BEGIN\\s[^-\\r\\n]*PRIVATE\\s+KEY[^-\\r\\n]*-+(?:\\s|\\r|\\n)+"); private static final Pattern KEY_FOOTER = Pattern.compile( "-+END\\s[^-\\r\\n]*PRIVATE\\s+KEY[^-\\r\\n]*-+(?:\\s|\\r|\\n)*"); private static final Pattern BODY = Pattern.compile("[a-z0-9+/=][a-z0-9+/=\\r\\n]*", Pattern.CASE_INSENSITIVE); static ByteBuf[] readCertificates(File file) throws CertificateException { try { InputStream in = new FileInputStream(file); try { return readCertificates(in); } finally { safeClose(in); } } catch (FileNotFoundException e) { throw new CertificateException("could not find certificate file: " + file); } } static ByteBuf[] readCertificates(InputStream in) throws CertificateException { String content; try { content = readContent(in); } catch (IOException e) { throw new CertificateException("failed to read certificate input stream", e); } List<ByteBuf> certs = new ArrayList<ByteBuf>(); Matcher m = CERT_HEADER.matcher(content); int start = 0; for (;;) { if (!m.find(start)) { break; } // Here and below it's necessary to save the position as it is reset // after calling usePattern() on Android due to a bug. // // See https://issuetracker.google.com/issues/293206296 start = m.end(); m.usePattern(BODY); if (!m.find(start)) { break; } ByteBuf base64 = Unpooled.copiedBuffer(m.group(0), CharsetUtil.US_ASCII); start = m.end(); m.usePattern(CERT_FOOTER); if (!m.find(start)) { // Certificate is incomplete. break; } ByteBuf der = Base64.decode(base64); base64.release(); certs.add(der); start = m.end(); m.usePattern(CERT_HEADER); } if (certs.isEmpty()) { throw new CertificateException("found no certificates in input stream"); } return certs.toArray(new ByteBuf[0]); } static ByteBuf readPrivateKey(File file) throws KeyException { try { InputStream in = new FileInputStream(file); try { return readPrivateKey(in); } finally { safeClose(in); } } catch (FileNotFoundException e) { throw new KeyException("could not find key file: " + file); } } static ByteBuf readPrivateKey(InputStream in) throws KeyException { String content; try { content = readContent(in); } catch (IOException e) { throw new KeyException("failed to read key input stream", e); } int start = 0; Matcher m = KEY_HEADER.matcher(content); if (!m.find(start)) { throw keyNotFoundException(); } start = m.end(); m.usePattern(BODY); if (!m.find(start)) { throw keyNotFoundException(); } ByteBuf base64 = Unpooled.copiedBuffer(m.group(0), CharsetUtil.US_ASCII); start = m.end(); m.usePattern(KEY_FOOTER); if (!m.find(start)) { // Key is incomplete. throw keyNotFoundException(); } ByteBuf der = Base64.decode(base64); base64.release(); return der; } private static KeyException keyNotFoundException() { return new KeyException("could not find a PKCS #8 private key in input stream" + " (see https://netty.io/wiki/sslcontextbuilder-and-private-key.html for more information)"); } private static String readContent(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { byte[] buf = new byte[8192]; for (;;) { int ret = in.read(buf); if (ret < 0) { break; } out.write(buf, 0, ret); } return out.toString(CharsetUtil.US_ASCII.name()); } finally { safeClose(out); } } private static void safeClose(InputStream in) { try { in.close(); } catch (IOException e) { logger.warn("Failed to close a stream.", e); } } private static void safeClose(OutputStream out) { try { out.close(); } catch (IOException e) { logger.warn("Failed to close a stream.", e); } } private PemReader() { } }
netty/netty
handler/src/main/java/io/netty/handler/ssl/PemReader.java
36
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import java.net.URL; import java.time.Duration; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.logging.Logs; /** * WebDriver is a remote control interface that enables introspection and control of user agents * (browsers). The methods in this interface fall into three categories: * * <ul> * <li>Control of the browser itself * <li>Selection of {@link WebElement}s * <li>Debugging aids * </ul> * * <p>Key methods are {@link WebDriver#get(String)}, which is used to load a new web page, and the * various methods similar to {@link WebDriver#findElement(By)}, which is used to find {@link * WebElement}s. * * <p>Currently, you will need to instantiate implementations of this interface directly. It is * hoped that you write your tests against this interface so that you may "swap in" a more fully * featured browser when there is a requirement for one. * * <p>Most implementations of this interface follow <a href="https://w3c.github.io/webdriver/">W3C * WebDriver specification</a> */ public interface WebDriver extends SearchContext { // Navigation /** * Load a new web page in the current browser window. This is done using an HTTP POST operation, * and the method will block until the load is complete (with the default 'page load strategy'. * This will follow redirects issued either by the server or as a meta-redirect from within the * returned HTML. Should a meta-redirect "rest" for any duration of time, it is best to wait until * this timeout is over, since should the underlying page change whilst your test is executing the * results of future calls against this interface will be against the freshly loaded page. Synonym * for {@link org.openqa.selenium.WebDriver.Navigation#to(String)}. * * <p>See <a href="https://w3c.github.io/webdriver/#navigate-to">W3C WebDriver specification</a> * for more details. * * @param url The URL to load. Must be a fully qualified URL * @see org.openqa.selenium.PageLoadStrategy */ void get(String url); /** * Get a string representing the current URL that the browser is looking at. * * <p>See <a href="https://w3c.github.io/webdriver/#get-current-url">W3C WebDriver * specification</a> for more details. * * @return The URL of the page currently loaded in the browser */ String getCurrentUrl(); // General properties /** * Get the title of the current page. * * <p>See <a href="https://w3c.github.io/webdriver/#get-title">W3C WebDriver specification</a> for * more details. * * @return The title of the current page, with leading and trailing whitespace stripped, or null * if one is not already set */ String getTitle(); /** * Find all elements within the current page using the given mechanism. This method is affected by * the 'implicit wait' times in force at the time of execution. When implicitly waiting, this * method will return as soon as there are more than 0 items in the found collection, or will * return an empty list if the timeout is reached. * * <p>See <a href="https://w3c.github.io/webdriver/#find-elements">W3C WebDriver specification</a> * for more details. * * @param by The locating mechanism to use * @return A list of all matching {@link WebElement}s, or an empty list if nothing matches * @see org.openqa.selenium.By * @see org.openqa.selenium.WebDriver.Timeouts */ @Override List<WebElement> findElements(By by); /** * Find the first {@link WebElement} using the given method. This method is affected by the * 'implicit wait' times in force at the time of execution. The findElement(..) invocation will * return a matching row, or try again repeatedly until the configured timeout is reached. * * <p>findElement should not be used to look for non-present elements, use {@link * #findElements(By)} and assert zero length response instead. * * <p>See <a href="https://w3c.github.io/webdriver/#find-element">W3C WebDriver specification</a> * for more details. * * @param by The locating mechanism to use * @return The first matching element on the current page * @throws NoSuchElementException If no matching elements are found * @see org.openqa.selenium.By * @see org.openqa.selenium.WebDriver.Timeouts */ @Override WebElement findElement(By by); // Misc /** * Get the source of the last loaded page. If the page has been modified after loading (for * example, by Javascript) there is no guarantee that the returned text is that of the modified * page. Please consult the documentation of the particular driver being used to determine whether * the returned text reflects the current state of the page or the text last sent by the web * server. The page source returned is a representation of the underlying DOM: do not expect it to * be formatted or escaped in the same way as the response sent from the web server. Think of it * as an artist's impression. * * <p>See <a href="https://w3c.github.io/webdriver/#get-page-source">W3C WebDriver * specification</a> for more details. * * @return The source of the current page */ String getPageSource(); /** * Close the current window, quitting the browser if it's the last window currently open. * * <p>See <a href="https://w3c.github.io/webdriver/#close-window">W3C WebDriver specification</a> * for more details. */ void close(); /** Quits this driver, closing every associated window. */ void quit(); /** * Return a set of window handles which can be used to iterate over all open windows of this * WebDriver instance by passing them to {@link #switchTo()}.{@link Options#window()} * * <p>See <a href="https://w3c.github.io/webdriver/#get-window-handles">W3C WebDriver * specification</a> for more details. * * @return A set of window handles which can be used to iterate over all open windows. */ Set<String> getWindowHandles(); /** * Return an opaque handle to this window that uniquely identifies it within this driver instance. * This can be used to switch to this window at a later date * * <p>See <a href="https://w3c.github.io/webdriver/#get-window-handle">W3C WebDriver * specification</a> for more details. * * @return the current window handle */ String getWindowHandle(); /** * Send future commands to a different frame or window. * * @return A TargetLocator which can be used to select a frame or window * @see org.openqa.selenium.WebDriver.TargetLocator */ TargetLocator switchTo(); /** * An abstraction allowing the driver to access the browser's history and to navigate to a given * URL. * * @return A {@link org.openqa.selenium.WebDriver.Navigation} that allows the selection of what to * do next */ Navigation navigate(); /** * Gets the Option interface * * @return An option interface * @see org.openqa.selenium.WebDriver.Options */ Options manage(); /** An interface for managing stuff you would do in a browser menu */ interface Options { /** * Add a specific cookie. If the cookie's domain name is left blank, it is assumed that the * cookie is meant for the domain of the current document. * * <p>See <a href="https://w3c.github.io/webdriver/#add-cookie">W3C WebDriver specification</a> * for more details. * * @param cookie The cookie to add. */ void addCookie(Cookie cookie); /** * Delete the named cookie from the current domain. This is equivalent to setting the named * cookie's expiry date to some time in the past. * * <p>See <a href="https://w3c.github.io/webdriver/#delete-cookie">W3C WebDriver * specification</a> for more details. * * @param name The name of the cookie to delete */ void deleteCookieNamed(String name); /** * Delete a cookie from the browser's "cookie jar". The domain of the cookie will be ignored. * * @param cookie nom nom nom */ void deleteCookie(Cookie cookie); /** * Delete all the cookies for the current domain. * * <p>See <a href="https://w3c.github.io/webdriver/#delete-all-cookies">W3C WebDriver * specification</a> for more details. */ void deleteAllCookies(); /** * Get all the cookies for the current domain. * * <p>See <a href="https://w3c.github.io/webdriver/#get-all-cookies">W3C WebDriver * specification</a> for more details. * * @return A Set of cookies for the current domain. */ Set<Cookie> getCookies(); /** * Get a cookie with a given name. * * <p>See <a href="https://w3c.github.io/webdriver/#get-named-cookie">W3C WebDriver * specification</a> for more details. * * @param name the name of the cookie * @return the cookie, or null if no cookie with the given name is present */ Cookie getCookieNamed(String name); /** * @return the interface for managing driver timeouts. */ Timeouts timeouts(); /** * @return the interface for managing the current window. */ Window window(); /** * Gets the {@link Logs} interface used to fetch different types of logs. * * <p>To set the logging preferences {@link LoggingPreferences}. * * @return A Logs interface. */ @Beta Logs logs(); } /** * An interface for managing timeout behavior for WebDriver instances. * * <p>See <a href="https://w3c.github.io/webdriver/#set-timeouts">W3C WebDriver specification</a> * for more details. */ interface Timeouts { /** * @deprecated Use {@link #implicitlyWait(Duration)} * <p>Specifies the amount of time the driver should wait when searching for an element if * it is not immediately present. * <p>When searching for a single element, the driver should poll the page until the element * has been found, or this timeout expires before throwing a {@link NoSuchElementException}. * When searching for multiple elements, the driver should poll the page until at least one * element has been found or this timeout has expired. * <p>Increasing the implicit wait timeout should be used judiciously as it will have an * adverse effect on test run time, especially when used with slower location strategies * like XPath. * <p>If the timeout is negative, not null, or greater than 2e16 - 1, an error code with * invalid argument will be returned. * @param time The amount of time to wait. * @param unit The unit of measure for {@code time}. * @return A self reference. */ @Deprecated Timeouts implicitlyWait(long time, TimeUnit unit); /** * Specifies the amount of time the driver should wait when searching for an element if it is * not immediately present. * * <p>When searching for a single element, the driver should poll the page until the element has * been found, or this timeout expires before throwing a {@link NoSuchElementException}. When * searching for multiple elements, the driver should poll the page until at least one element * has been found or this timeout has expired. * * <p>Increasing the implicit wait timeout should be used judiciously as it will have an adverse * effect on test run time, especially when used with slower location strategies like XPath. * * <p>If the timeout is negative, not null, or greater than 2e16 - 1, an error code with invalid * argument will be returned. * * @param duration The duration to wait. * @return A self reference. */ default Timeouts implicitlyWait(Duration duration) { return implicitlyWait(duration.toMillis(), TimeUnit.MILLISECONDS); } /** * Gets the amount of time the driver should wait when searching for an element if it is not * immediately present. * * @return The amount of time the driver should wait when searching for an element. * @see <a href="https://www.w3.org/TR/webdriver/#get-timeouts">W3C WebDriver</a> */ default Duration getImplicitWaitTimeout() { throw new UnsupportedCommandException(); } /** * @deprecated Use {@link #scriptTimeout(Duration)} * <p>Sets the amount of time to wait for an asynchronous script to finish execution before * throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an * error code with invalid argument will be returned. * @param time The timeout value. * @param unit The unit of time. * @return A self reference. * @see JavascriptExecutor#executeAsyncScript(String, Object...) * @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> */ @Deprecated Timeouts setScriptTimeout(long time, TimeUnit unit); /** * Sets the amount of time to wait for an asynchronous script to finish execution before * throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an error * code with invalid argument will be returned. * * @param duration The timeout value. * @deprecated Use {@link #scriptTimeout(Duration)} * @return A self reference. * @see JavascriptExecutor#executeAsyncScript(String, Object...) * @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> */ @Deprecated default Timeouts setScriptTimeout(Duration duration) { return setScriptTimeout(duration.toMillis(), TimeUnit.MILLISECONDS); } /** * Sets the amount of time to wait for an asynchronous script to finish execution before * throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an error * code with invalid argument will be returned. * * @param duration The timeout value. * @return A self reference. * @see JavascriptExecutor#executeAsyncScript(String, Object...) * @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> */ default Timeouts scriptTimeout(Duration duration) { return setScriptTimeout(duration); } /** * Gets the amount of time to wait for an asynchronous script to finish execution before * throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an error * code with invalid argument will be returned. * * @return The amount of time to wait for an asynchronous script to finish execution. * @see <a href="https://www.w3.org/TR/webdriver/#get-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> */ default Duration getScriptTimeout() { throw new UnsupportedCommandException(); } /** * @param time The timeout value. * @param unit The unit of time. * @return A Timeouts interface. * @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> * @deprecated Use {@link #pageLoadTimeout(Duration)} * <p>Sets the amount of time to wait for a page load to complete before throwing an error. * If the timeout is negative, not null, or greater than 2e16 - 1, an error code with * invalid argument will be returned. */ @Deprecated Timeouts pageLoadTimeout(long time, TimeUnit unit); /** * Sets the amount of time to wait for a page load to complete before throwing an error. If the * timeout is negative, not null, or greater than 2e16 - 1, an error code with invalid argument * will be returned. * * @param duration The timeout value. * @return A Timeouts interface. * @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> */ default Timeouts pageLoadTimeout(Duration duration) { return pageLoadTimeout(duration.toMillis(), TimeUnit.MILLISECONDS); } /** * Gets the amount of time to wait for a page load to complete before throwing an error. If the * timeout is negative, not null, or greater than 2e16 - 1, an error code with invalid argument * will be returned. * * @return The amount of time to wait for a page load to complete. * @see <a href="https://www.w3.org/TR/webdriver/#get-timeouts">W3C WebDriver</a> * @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a> */ default Duration getPageLoadTimeout() { throw new UnsupportedCommandException(); } } /** Used to locate a given frame or window. */ interface TargetLocator { /** * Select a frame by its (zero-based) index. Selecting a frame by index is equivalent to the JS * expression window.frames[index] where "window" is the DOM window represented by the current * context. Once the frame has been selected, all subsequent calls on the WebDriver interface * are made to that frame. * * <p>See <a href="https://w3c.github.io/webdriver/#switch-to-frame">W3C WebDriver * specification</a> for more details. * * @param index (zero-based) index * @return This driver focused on the given frame * @throws NoSuchFrameException If the frame cannot be found */ WebDriver frame(int index); /** * Select a frame by its name or ID. Frames located by matching name attributes are always given * precedence over those matched by ID. * * @param nameOrId the name of the frame window, the id of the &lt;frame&gt; or &lt;iframe&gt; * element, or the (zero-based) index * @return This driver focused on the given frame * @throws NoSuchFrameException If the frame cannot be found */ WebDriver frame(String nameOrId); /** * Select a frame using its previously located {@link WebElement}. * * <p>See <a href="https://w3c.github.io/webdriver/#switch-to-frame">W3C WebDriver * specification</a> for more details. * * @param frameElement The frame element to switch to. * @return This driver focused on the given frame. * @throws NoSuchFrameException If the given element is neither an IFRAME nor a FRAME element. * @throws StaleElementReferenceException If the WebElement has gone stale. * @see WebDriver#findElement(By) */ WebDriver frame(WebElement frameElement); /** * Change focus to the parent context. If the current context is the top level browsing context, * the context remains unchanged. * * <p>See <a href="https://w3c.github.io/webdriver/#switch-to-parent-frame">W3C WebDriver * specification</a> for more details. * * @return This driver focused on the parent frame */ WebDriver parentFrame(); /** * Switch the focus of future commands for this driver to the window with the given name/handle. * * <p>See <a href="https://w3c.github.io/webdriver/#switch-to-window">W3C WebDriver * specification</a> for more details. * * @param nameOrHandle The name of the window or the handle as returned by {@link * WebDriver#getWindowHandle()} * @return This driver focused on the given window * @throws NoSuchWindowException If the window cannot be found */ WebDriver window(String nameOrHandle); /** * Creates a new browser window and switches the focus for future commands of this driver to the * new window. * * <p>See <a href="https://w3c.github.io/webdriver/#new-window">W3C WebDriver specification</a> * for more details. * * @param typeHint The type of new browser window to be created. The created window is not * guaranteed to be of the requested type; if the driver does not support the requested * type, a new browser window will be created of whatever type the driver does support. * @return This driver focused on the given window */ WebDriver newWindow(WindowType typeHint); /** * Selects either the first frame on the page, or the main document when a page contains * iframes. * * <p>See <a href="https://w3c.github.io/webdriver/#switch-to-frame">W3C WebDriver * specification</a> for more details. * * @return This driver focused on the top window/first frame. */ WebDriver defaultContent(); /** * Switches to the element that currently has focus within the document currently "switched to", * or the body element if this cannot be detected. This matches the semantics of calling * "document.activeElement" in Javascript. * * <p>See <a href="https://w3c.github.io/webdriver/#get-active-element">W3C WebDriver * specification</a> for more details. * * @return The WebElement with focus, or the body element if no element with focus can be * detected. */ WebElement activeElement(); /** * Switches to the currently active modal dialog for this particular driver instance. * * @return A handle to the dialog. * @throws NoAlertPresentException If the dialog cannot be found */ Alert alert(); } interface Navigation { /** * Move back a single "item" in the browser's history. * * <p>See <a href="https://w3c.github.io/webdriver/#back">W3C WebDriver specification</a> for * more details. */ void back(); /** * Move a single "item" forward in the browser's history. Does nothing if we are on the latest * page viewed. * * <p>See <a href="https://w3c.github.io/webdriver/#forward">W3C WebDriver specification</a> for * more details. */ void forward(); /** * Load a new web page in the current browser window. This is done using an HTTP POST operation, * and the method will block until the load is complete. This will follow redirects issued * either by the server or as a meta-redirect from within the returned HTML. Should a * meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over, * since should the underlying page change whilst your test is executing the results of future * calls against this interface will be against the freshly loaded page. * * <p>See <a href="https://w3c.github.io/webdriver/#navigate-to">W3C WebDriver specification</a> * for more details. * * @param url The URL to load. Must be a fully qualified URL */ void to(String url); /** * Overloaded version of {@link #to(String)} that makes it easy to pass in a URL. * * @param url URL */ void to(URL url); /** * Refresh the current page * * <p>See <a href="https://w3c.github.io/webdriver/#refresh">W3C WebDriver specification</a> for * more details. */ void refresh(); } @Beta interface Window { /** * Get the size of the current window. This will return the outer window dimension, not just the * view port. * * <p>See <a href="https://w3c.github.io/webdriver/#get-window-rect">W3C WebDriver * specification</a> for more details. * * @return The current window size. */ Dimension getSize(); /** * Set the size of the current window. This will change the outer window dimension, not just the * view port, synonymous to window.resizeTo() in JS. * * <p>See <a href="https://w3c.github.io/webdriver/#set-window-rect">W3C WebDriver * specification</a> for more details. * * @param targetSize The target size. */ void setSize(Dimension targetSize); /** * Get the position of the current window, relative to the upper left corner of the screen. * * <p>See <a href="https://w3c.github.io/webdriver/#get-window-rect">W3C WebDriver * specification</a> for more details. * * @return The current window position. */ Point getPosition(); /** * Set the position of the current window. This is relative to the upper left corner of the * screen, synonymous to window.moveTo() in JS. * * <p>See <a href="https://w3c.github.io/webdriver/#set-window-rect">W3C WebDriver * specification</a> for more details. * * @param targetPosition The target position of the window. */ void setPosition(Point targetPosition); /** * Maximizes the current window if it is not already maximized * * <p>See <a href="https://w3c.github.io/webdriver/#maximize-window">W3C WebDriver * specification</a> for more details. */ void maximize(); /** * Minimizes the current window if it is not already minimized * * <p>See <a href="https://w3c.github.io/webdriver/#minimize-window">W3C WebDriver * specification</a> for more details. */ void minimize(); /** * Fullscreen the current window if it is not already fullscreen * * <p>See <a href="https://w3c.github.io/webdriver/#fullscreen-window">W3C WebDriver * specification</a> for more details. */ void fullscreen(); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/WebDriver.java
37
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.remote; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.WebDriverException; /** Maps exceptions to status codes for sending over the wire. */ public class ErrorHandler { private static final String MESSAGE = "message"; private static final String SCREEN_SHOT = "screen"; private static final String CLASS = "class"; private static final String STACK_TRACE = "stackTrace"; private static final String LINE_NUMBER = "lineNumber"; private static final String METHOD_NAME = "methodName"; private static final String CLASS_NAME = "className"; private static final String FILE_NAME = "fileName"; private static final String UNKNOWN_CLASS = "<anonymous class>"; private static final String UNKNOWN_METHOD = "<anonymous method>"; private static final String UNKNOWN_FILE = null; private final ErrorCodes errorCodes; private boolean includeServerErrors; public ErrorHandler() { this(true); } /** * @param includeServerErrors Whether to include server-side details in thrown exceptions if the * information is available. */ public ErrorHandler(boolean includeServerErrors) { this.includeServerErrors = includeServerErrors; this.errorCodes = new ErrorCodes(); } /** * @param includeServerErrors Whether to include server-side details in thrown exceptions if the * information is available. * @param codes The ErrorCodes object to use for linking error codes to exceptions. */ public ErrorHandler(ErrorCodes codes, boolean includeServerErrors) { this.includeServerErrors = includeServerErrors; this.errorCodes = codes; } public boolean isIncludeServerErrors() { return includeServerErrors; } public void setIncludeServerErrors(boolean includeServerErrors) { this.includeServerErrors = includeServerErrors; } @SuppressWarnings("unchecked") public Response throwIfResponseFailed(Response response, long duration) throws RuntimeException { if ("success".equals(response.getState())) { return response; } if (response.getValue() instanceof Throwable) { Throwable throwable = (Throwable) response.getValue(); if (throwable instanceof Error) { throw (Error) throwable; } if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } throw new RuntimeException(throwable); } Class<? extends WebDriverException> outerErrorType = errorCodes.getExceptionType(response.getStatus()); Object value = response.getValue(); String message = null; Throwable cause = null; if (value instanceof Map) { Map<String, Object> rawErrorData = (Map<String, Object>) value; if (!rawErrorData.containsKey(MESSAGE) && rawErrorData.containsKey("value")) { try { rawErrorData = (Map<String, Object>) rawErrorData.get("value"); } catch (ClassCastException cce) { message = String.valueOf(cce); } } try { message = (String) rawErrorData.get(MESSAGE); } catch (ClassCastException e) { // Ok, try to recover gracefully. message = String.valueOf(e); } Throwable serverError = rebuildServerError(rawErrorData, response.getStatus()); // If serverError is null, then the server did not provide a className (only expected if // the server is a Java process) or a stack trace. The lack of a className is OK, but // not having a stacktrace really hurts our ability to debug problems. if (serverError == null) { if (includeServerErrors) { // TODO: this should probably link to a wiki article with more info. message += " (WARNING: The server did not provide any stacktrace information)"; } } else if (!includeServerErrors) { // TODO: wiki article with more info. message += " (WARNING: The client has suppressed server-side stacktraces)"; } else { cause = serverError; if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { message += " (WARNING: The server did not provide any stacktrace information)"; } } if (rawErrorData.get(SCREEN_SHOT) != null) { cause = new ScreenshotException(String.valueOf(rawErrorData.get(SCREEN_SHOT)), cause); } } else if (value != null) { message = String.valueOf(value); } String duration1 = duration(duration); if (message != null && !message.contains(duration1)) { message = message + duration1; } WebDriverException toThrow = null; if (outerErrorType.equals(UnhandledAlertException.class) && value instanceof Map) { toThrow = createUnhandledAlertException(value); } if (toThrow == null) { toThrow = createThrowable( outerErrorType, new Class<?>[] {String.class, Throwable.class, Integer.class}, new Object[] {message, cause, response.getStatus()}); } if (toThrow == null) { toThrow = createThrowable( outerErrorType, new Class<?>[] {String.class, Throwable.class}, new Object[] {message, cause}); } if (toThrow == null) { toThrow = createThrowable(outerErrorType, new Class<?>[] {String.class}, new Object[] {message}); } if (toThrow == null) { toThrow = new WebDriverException(message, cause); } throw toThrow; } @SuppressWarnings("unchecked") private UnhandledAlertException createUnhandledAlertException(Object value) { Map<String, Object> rawErrorData = (Map<String, Object>) value; if (rawErrorData.containsKey("alert") || rawErrorData.containsKey("alertText")) { Object alertText = rawErrorData.get("alertText"); if (alertText == null) { Map<String, Object> alert = (Map<String, Object>) rawErrorData.get("alert"); if (alert != null) { alertText = alert.get("text"); } } return createThrowable( UnhandledAlertException.class, new Class<?>[] {String.class, String.class}, new Object[] {rawErrorData.get("message"), alertText}); } return null; } private String duration(long duration) { String prefix = "\nCommand duration or timeout: "; if (duration < 1000) { return prefix + duration + " milliseconds"; } return prefix + (new BigDecimal(duration).divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_UP)) + " seconds"; } private <T extends Throwable> T createThrowable( Class<T> clazz, Class<?>[] parameterTypes, Object[] parameters) { try { Constructor<T> constructor = clazz.getConstructor(parameterTypes); return constructor.newInstance(parameters); } catch (OutOfMemoryError | ReflectiveOperationException e) { // Do nothing - fall through. } return null; } private Throwable rebuildServerError(Map<String, Object> rawErrorData, int responseStatus) { if (rawErrorData.get(CLASS) == null && rawErrorData.get(STACK_TRACE) == null) { // Not enough information for us to try to rebuild an error. return null; } Throwable toReturn = null; String message = (String) rawErrorData.get(MESSAGE); Class<?> clazz = null; // First: allow Remote Driver to specify the Selenium Server internal exception if (rawErrorData.get(CLASS) != null) { String className = (String) rawErrorData.get(CLASS); try { clazz = Class.forName(className); } catch (ClassNotFoundException ignored) { // Ok, fall-through } } // If the above fails, map Response Status to Exception class if (null == clazz) { clazz = errorCodes.getExceptionType(responseStatus); } if (clazz.equals(UnhandledAlertException.class)) { toReturn = createUnhandledAlertException(rawErrorData); } else if (Throwable.class.isAssignableFrom(clazz)) { @SuppressWarnings({"unchecked"}) Class<? extends Throwable> throwableType = (Class<? extends Throwable>) clazz; toReturn = createThrowable(throwableType, new Class<?>[] {String.class}, new Object[] {message}); } if (toReturn == null) { toReturn = new UnknownServerException(message); } // Note: if we have a class name above, we should always have a stack trace. // The inverse is not always true. StackTraceElement[] stackTrace = new StackTraceElement[0]; if (rawErrorData.get(STACK_TRACE) != null) { @SuppressWarnings({"unchecked"}) List<Map<String, Object>> stackTraceInfo = (List<Map<String, Object>>) rawErrorData.get(STACK_TRACE); stackTrace = stackTraceInfo.stream() .map(entry -> new FrameInfoToStackFrame().apply(entry)) .filter(Objects::nonNull) .toArray(StackTraceElement[]::new); } toReturn.setStackTrace(stackTrace); return toReturn; } /** Exception used as a place holder if the server returns an error without a stack trace. */ public static class UnknownServerException extends WebDriverException { private UnknownServerException(String s) { super(s); } } /** * Function that can rebuild a {@link StackTraceElement} from the frame info included with a * WebDriver JSON response. */ private static class FrameInfoToStackFrame implements Function<Map<String, Object>, StackTraceElement> { @Override public StackTraceElement apply(Map<String, Object> frameInfo) { if (frameInfo == null) { return null; } Optional<Number> maybeLineNumberInteger = Optional.empty(); final Object lineNumberObject = frameInfo.get(LINE_NUMBER); if (lineNumberObject instanceof Number) { maybeLineNumberInteger = Optional.of((Number) lineNumberObject); } else if (lineNumberObject != null) { // might be a Number as a String try { maybeLineNumberInteger = Optional.of(Integer.parseInt(lineNumberObject.toString())); } catch (NumberFormatException e) { maybeLineNumberInteger = Optional.empty(); } } // default -1 for unknown, see StackTraceElement constructor javadoc final int lineNumber = maybeLineNumberInteger.orElse(-1).intValue(); // Gracefully handle remote servers that don't (or can't) send back // complete stack trace info. At least some of this information should // be included... String className = frameInfo.containsKey(CLASS_NAME) ? toStringOrNull(frameInfo.get(CLASS_NAME)) : UNKNOWN_CLASS; String methodName = frameInfo.containsKey(METHOD_NAME) ? toStringOrNull(frameInfo.get(METHOD_NAME)) : UNKNOWN_METHOD; String fileName = frameInfo.containsKey(FILE_NAME) ? toStringOrNull(frameInfo.get(FILE_NAME)) : UNKNOWN_FILE; return new StackTraceElement(className, methodName, fileName, lineNumber); } private static String toStringOrNull(Object o) { return o == null ? null : o.toString(); } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/remote/ErrorHandler.java
38
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import java.util.List; /** * Represents an HTML element. Generally, all interesting operations to do with interacting with a * page will be performed through this interface. * * <p>All method calls will do a freshness check to ensure that the element reference is still * valid. This essentially determines whether the element is still attached to the DOM. If this test * fails, then an {@link org.openqa.selenium.StaleElementReferenceException} is thrown, and all * future calls to this instance will fail. */ public interface WebElement extends SearchContext, TakesScreenshot { /** * Click this element. If this causes a new page to load, you should discard all references to * this element and any further operations performed on this element will throw a * StaleElementReferenceException. * * <p>Note that if click() is done by sending a native event (which is the default on most * browsers/platforms) then the method will _not_ wait for the next page to load and the caller * should verify that themselves. * * <p>There are some preconditions for an element to be clicked. The element must be visible, and * it must have a height and width greater than 0. * * <p>See <a href="https://w3c.github.io/webdriver/#element-click">W3C WebDriver specification</a> * for more details. * * @throws StaleElementReferenceException If the element no longer exists as initially defined */ void click(); /** * If this current element is a form, or an element within a form, then this will be submitted to * the remote server. If this causes the current page to change, then this method will block until * the new page is loaded. * * @throws NoSuchElementException If the given element is not within a form */ void submit(); /** * Use this method to simulate typing into an element, which may set its value. * * <p>See <a href="https://w3c.github.io/webdriver/#element-send-keys">W3C WebDriver * specification</a> for more details. * * @param keysToSend character sequence to send to the element * @throws IllegalArgumentException if keysToSend is null */ void sendKeys(CharSequence... keysToSend); /** * If this element is a form entry element, this will reset its value. * * <p>See <a href="https://w3c.github.io/webdriver/#element-clear">W3C WebDriver specification</a> * and <a href="https://html.spec.whatwg.org/#concept-form-reset-control">HTML specification</a> * for more details. */ void clear(); /** * Get the tag name of this element. <b>Not</b> the value of the name attribute: will return * <code>"input"</code> for the element <code>&lt;input name="foo" /&gt;</code>. * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-tag-name">W3C WebDriver * specification</a> for more details. * * @return The tag name of this element. */ String getTagName(); /** * Get the value of the given property of the element. Will return the current value, even if this * has been modified after the page has been loaded. * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-property">W3C WebDriver * specification</a> for more details. * * @param name The name of the property. * @return The property's current value or null if the value is not set. */ default String getDomProperty(String name) { throw new UnsupportedOperationException("getDomProperty"); } /** * Get the value of the given attribute of the element. * * <p>This method, unlike {@link #getAttribute(String)}, returns the value of the attribute with * the given name but not the property with the same name. * * <p>The following are deemed to be "boolean" attributes, and will return either "true" or null: * * <p>async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, * defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, * iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, * novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, * seeking, selected, truespeed, willvalidate * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-attribute">W3C WebDriver * specification</a> for more details. * * @param name The name of the attribute. * @return The attribute's value or null if the value is not set. */ default String getDomAttribute(String name) { throw new UnsupportedOperationException("getDomAttribute"); } /** * Get the value of the given attribute of the element. Will return the current value, even if * this has been modified after the page has been loaded. * * <p>More exactly, this method will return the value of the property with the given name, if it * exists. If it does not, then the value of the attribute with the given name is returned. If * neither exists, null is returned. * * <p>The "style" attribute is converted as best can be to a text representation with a trailing * semicolon. * * <p>The following are deemed to be "boolean" attributes, and will return either "true" or null: * * <p>async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, * defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, * iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, * novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, * seeking, selected, truespeed, willvalidate * * <p>Finally, the following commonly mis-capitalized attribute/property names are evaluated as * expected: * * <ul> * <li>If the given name is "class", the "className" property is returned. * <li>If the given name is "readonly", the "readOnly" property is returned. * </ul> * * <i>Note:</i> The reason for this behavior is that users frequently confuse attributes and * properties. If you need to do something more precise, use {@link #getDomAttribute(String)} or * {@link #getDomProperty(String)} to obtain the result you desire. * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-attribute">W3C WebDriver * specification</a> for more details. * * @param name The name of the attribute. * @return The attribute/property's current value or null if the value is not set. */ String getAttribute(String name); /** * Gets result of computing the WAI-ARIA role of element. * * <p>See <a href="https://www.w3.org/TR/webdriver/#get-computed-role">W3C WebDriver * specification</a> for more details. * * @return the WAI-ARIA role of the element. */ default String getAriaRole() { throw new UnsupportedOperationException("getAriaRole"); } /** * Gets result of a Accessible Name and Description Computation for the Accessible Name of the * element. * * <p>See <a href="https://www.w3.org/TR/webdriver/#get-computed-label">W3C WebDriver * specification</a> for more details. * * @return the accessible name of the element. */ default String getAccessibleName() { throw new UnsupportedOperationException("getAccessibleName"); } /** * Determine whether this element is selected or not. This operation only applies to input * elements such as checkboxes, options in a select and radio buttons. For more information on * which elements this method supports, refer to the <a * href="https://w3c.github.io/webdriver/webdriver-spec.html#is-element-selected">specification</a>. * * <p>See <a href="https://w3c.github.io/webdriver/#is-element-selected">W3C WebDriver * specification</a> for more details. * * @return True if the element is currently selected or checked, false otherwise. */ boolean isSelected(); /** * Is the element currently enabled or not? This will generally return true for everything but * disabled input elements. * * <p>See <a href="https://w3c.github.io/webdriver/#is-element-enabled">W3C WebDriver * specification</a> for more details. * * @return True if the element is enabled, false otherwise. */ boolean isEnabled(); /** * Get the visible (i.e. not hidden by CSS) text of this element, including sub-elements. * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-text">W3C WebDriver * specification</a> for more details. * * @return The visible text of this element. */ String getText(); /** * Find all elements within the current context using the given mechanism. When using xpath be * aware that webdriver follows standard conventions: a search prefixed with "//" will search the * entire document, not just the children of this current node. Use ".//" to limit your search to * the children of this WebElement. This method is affected by the 'implicit wait' times in force * at the time of execution. When implicitly waiting, this method will return as soon as there are * more than 0 items in the found collection, or will return an empty list if the timeout is * reached. * * <p>See <a href="https://w3c.github.io/webdriver/#find-elements-from-element">W3C WebDriver * specification</a> for more details. * * @param by The locating mechanism to use * @return A list of all {@link WebElement}s, or an empty list if nothing matches. * @see org.openqa.selenium.By * @see org.openqa.selenium.WebDriver.Timeouts */ @Override List<WebElement> findElements(By by); /** * Find the first {@link WebElement} using the given method. See the note in {@link * #findElements(By)} about finding via XPath. This method is affected by the 'implicit wait' * times in force at the time of execution. The findElement(..) invocation will return a matching * row, or try again repeatedly until the configured timeout is reached. * * <p>findElement should not be used to look for non-present elements, use {@link * #findElements(By)} and assert zero length response instead. * * <p>See <a href="https://w3c.github.io/webdriver/#find-element-from-element">W3C WebDriver * specification</a> for more details. * * @param by The locating mechanism * @return The first matching element on the current context. * @throws NoSuchElementException If no matching elements are found * @see org.openqa.selenium.By * @see org.openqa.selenium.WebDriver.Timeouts */ @Override WebElement findElement(By by); /** * @return A representation of an element's shadow root for accessing the shadow DOM of a web * component. * @throws NoSuchShadowRootException If no shadow root is found */ default SearchContext getShadowRoot() { throw new UnsupportedOperationException("getShadowRoot"); } /** * Is this element displayed or not? This method avoids the problem of having to parse an * element's "style" attribute. * * @return Whether the element is displayed */ boolean isDisplayed(); /** * Where on the page is the top left-hand corner of the rendered element? * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-rect">W3C WebDriver * specification</a> for more details. * * @return A point, containing the location of the top left-hand corner of the element */ Point getLocation(); /** * What is the width and height of the rendered element? * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-rect">W3C WebDriver * specification</a> for more details. * * @return The size of the element on the page. */ Dimension getSize(); /** * @return The location and size of the rendered element * <p>See <a href="https://w3c.github.io/webdriver/#get-element-rect">W3C WebDriver * specification</a> for more details. */ Rectangle getRect(); /** * Get the value of a given CSS property. Color values could be returned as rgba or rgb strings. * This depends on whether the browser omits the implicit opacity value or not. * * <p>For example if the "background-color" property is set as "green" in the HTML source, the * returned value could be "rgba(0, 255, 0, 1)" if implicit opacity value is preserved or "rgb(0, * 255, 0)" if it is omitted. * * <p>Note that shorthand CSS properties (e.g. background, font, border, border-top, margin, * margin-top, padding, padding-top, list-style, outline, pause, cue) are not returned, in * accordance with the <a * href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration">DOM CSS2 * specification</a> - you should directly access the longhand properties (e.g. background-color) * to access the desired values. * * <p>See <a href="https://w3c.github.io/webdriver/#get-element-css-value">W3C WebDriver * specification</a> for more details. * * @param propertyName the css property name of the element * @return The current, computed value of the property. */ String getCssValue(String propertyName); }
SeleniumHQ/selenium
java/src/org/openqa/selenium/WebElement.java
39
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import io.netty.util.internal.StringUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import static java.lang.Math.*; import java.nio.ByteBuffer; final class PoolChunkList<T> implements PoolChunkListMetric { private static final Iterator<PoolChunkMetric> EMPTY_METRICS = Collections.<PoolChunkMetric>emptyList().iterator(); private final PoolArena<T> arena; private final PoolChunkList<T> nextList; private final int minUsage; private final int maxUsage; private final int maxCapacity; private PoolChunk<T> head; private final int freeMinThreshold; private final int freeMaxThreshold; // This is only update once when create the linked like list of PoolChunkList in PoolArena constructor. private PoolChunkList<T> prevList; // TODO: Test if adding padding helps under contention //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; PoolChunkList(PoolArena<T> arena, PoolChunkList<T> nextList, int minUsage, int maxUsage, int chunkSize) { assert minUsage <= maxUsage; this.arena = arena; this.nextList = nextList; this.minUsage = minUsage; this.maxUsage = maxUsage; maxCapacity = calculateMaxCapacity(minUsage, chunkSize); // the thresholds are aligned with PoolChunk.usage() logic: // 1) basic logic: usage() = 100 - freeBytes * 100L / chunkSize // so, for example: (usage() >= maxUsage) condition can be transformed in the following way: // 100 - freeBytes * 100L / chunkSize >= maxUsage // freeBytes <= chunkSize * (100 - maxUsage) / 100 // let freeMinThreshold = chunkSize * (100 - maxUsage) / 100, then freeBytes <= freeMinThreshold // // 2) usage() returns an int value and has a floor rounding during a calculation, // to be aligned absolute thresholds should be shifted for "the rounding step": // freeBytes * 100 / chunkSize < 1 // the condition can be converted to: freeBytes < 1 * chunkSize / 100 // this is why we have + 0.99999999 shifts. A example why just +1 shift cannot be used: // freeBytes = 16777216 == freeMaxThreshold: 16777216, usage = 0 < minUsage: 1, chunkSize: 16777216 // At the same time we want to have zero thresholds in case of (maxUsage == 100) and (minUsage == 100). // freeMinThreshold = (maxUsage == 100) ? 0 : (int) (chunkSize * (100.0 - maxUsage + 0.99999999) / 100L); freeMaxThreshold = (minUsage == 100) ? 0 : (int) (chunkSize * (100.0 - minUsage + 0.99999999) / 100L); } /** * Calculates the maximum capacity of a buffer that will ever be possible to allocate out of the {@link PoolChunk}s * that belong to the {@link PoolChunkList} with the given {@code minUsage} and {@code maxUsage} settings. */ private static int calculateMaxCapacity(int minUsage, int chunkSize) { minUsage = minUsage0(minUsage); if (minUsage == 100) { // If the minUsage is 100 we can not allocate anything out of this list. return 0; } // Calculate the maximum amount of bytes that can be allocated from a PoolChunk in this PoolChunkList. // // As an example: // - If a PoolChunkList has minUsage == 25 we are allowed to allocate at most 75% of the chunkSize because // this is the maximum amount available in any PoolChunk in this PoolChunkList. return (int) (chunkSize * (100L - minUsage) / 100L); } void prevList(PoolChunkList<T> prevList) { assert this.prevList == null; this.prevList = prevList; } boolean allocate(PooledByteBuf<T> buf, int reqCapacity, int sizeIdx, PoolThreadCache threadCache) { int normCapacity = arena.sizeClass.sizeIdx2size(sizeIdx); if (normCapacity > maxCapacity) { // Either this PoolChunkList is empty or the requested capacity is larger then the capacity which can // be handled by the PoolChunks that are contained in this PoolChunkList. return false; } for (PoolChunk<T> cur = head; cur != null; cur = cur.next) { if (cur.allocate(buf, reqCapacity, sizeIdx, threadCache)) { if (cur.freeBytes <= freeMinThreshold) { remove(cur); nextList.add(cur); } return true; } } return false; } boolean free(PoolChunk<T> chunk, long handle, int normCapacity, ByteBuffer nioBuffer) { chunk.free(handle, normCapacity, nioBuffer); if (chunk.freeBytes > freeMaxThreshold) { remove(chunk); // Move the PoolChunk down the PoolChunkList linked-list. return move0(chunk); } return true; } private boolean move(PoolChunk<T> chunk) { assert chunk.usage() < maxUsage; if (chunk.freeBytes > freeMaxThreshold) { // Move the PoolChunk down the PoolChunkList linked-list. return move0(chunk); } // PoolChunk fits into this PoolChunkList, adding it here. add0(chunk); return true; } /** * Moves the {@link PoolChunk} down the {@link PoolChunkList} linked-list so it will end up in the right * {@link PoolChunkList} that has the correct minUsage / maxUsage in respect to {@link PoolChunk#usage()}. */ private boolean move0(PoolChunk<T> chunk) { if (prevList == null) { // There is no previous PoolChunkList so return false which result in having the PoolChunk destroyed and // all memory associated with the PoolChunk will be released. assert chunk.usage() == 0; return false; } return prevList.move(chunk); } void add(PoolChunk<T> chunk) { if (chunk.freeBytes <= freeMinThreshold) { nextList.add(chunk); return; } add0(chunk); } /** * Adds the {@link PoolChunk} to this {@link PoolChunkList}. */ void add0(PoolChunk<T> chunk) { chunk.parent = this; if (head == null) { head = chunk; chunk.prev = null; chunk.next = null; } else { chunk.prev = null; chunk.next = head; head.prev = chunk; head = chunk; } } private void remove(PoolChunk<T> cur) { if (cur == head) { head = cur.next; if (head != null) { head.prev = null; } } else { PoolChunk<T> next = cur.next; cur.prev.next = next; if (next != null) { next.prev = cur.prev; } } } @Override public int minUsage() { return minUsage0(minUsage); } @Override public int maxUsage() { return min(maxUsage, 100); } private static int minUsage0(int value) { return max(1, value); } @Override public Iterator<PoolChunkMetric> iterator() { arena.lock(); try { if (head == null) { return EMPTY_METRICS; } List<PoolChunkMetric> metrics = new ArrayList<PoolChunkMetric>(); for (PoolChunk<T> cur = head;;) { metrics.add(cur); cur = cur.next; if (cur == null) { break; } } return metrics.iterator(); } finally { arena.unlock(); } } @Override public String toString() { StringBuilder buf = new StringBuilder(); arena.lock(); try { if (head == null) { return "none"; } for (PoolChunk<T> cur = head;;) { buf.append(cur); cur = cur.next; if (cur == null) { break; } buf.append(StringUtil.NEWLINE); } } finally { arena.unlock(); } return buf.toString(); } void destroy(PoolArena<T> arena) { PoolChunk<T> chunk = head; while (chunk != null) { arena.destroyChunk(chunk); chunk = chunk.next; } head = null; } }
netty/netty
buffer/src/main/java/io/netty/buffer/PoolChunkList.java
40
/* * Copyright 2020 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import static io.netty.buffer.PoolThreadCache.*; /** * SizeClasses requires {@code pageShifts} to be defined prior to inclusion, * and it in turn defines: * <p> * LOG2_SIZE_CLASS_GROUP: Log of size class count for each size doubling. * LOG2_MAX_LOOKUP_SIZE: Log of max size class in the lookup table. * sizeClasses: Complete table of [index, log2Group, log2Delta, nDelta, isMultiPageSize, * isSubPage, log2DeltaLookup] tuples. * index: Size class index. * log2Group: Log of group base size (no deltas added). * log2Delta: Log of delta to previous size class. * nDelta: Delta multiplier. * isMultiPageSize: 'yes' if a multiple of the page size, 'no' otherwise. * isSubPage: 'yes' if a subpage size class, 'no' otherwise. * log2DeltaLookup: Same as log2Delta if a lookup table size class, 'no' * otherwise. * <p> * nSubpages: Number of subpages size classes. * nSizes: Number of size classes. * nPSizes: Number of size classes that are multiples of pageSize. * * smallMaxSizeIdx: Maximum small size class index. * * lookupMaxClass: Maximum size class included in lookup table. * log2NormalMinClass: Log of minimum normal size class. * <p> * The first size class and spacing are 1 << LOG2_QUANTUM. * Each group has 1 << LOG2_SIZE_CLASS_GROUP of size classes. * * size = 1 << log2Group + nDelta * (1 << log2Delta) * * The first size class has an unusual encoding, because the size has to be * split between group and delta*nDelta. * * If pageShift = 13, sizeClasses looks like this: * * (index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup) * <p> * ( 0, 4, 4, 0, no, yes, 4) * ( 1, 4, 4, 1, no, yes, 4) * ( 2, 4, 4, 2, no, yes, 4) * ( 3, 4, 4, 3, no, yes, 4) * <p> * ( 4, 6, 4, 1, no, yes, 4) * ( 5, 6, 4, 2, no, yes, 4) * ( 6, 6, 4, 3, no, yes, 4) * ( 7, 6, 4, 4, no, yes, 4) * <p> * ( 8, 7, 5, 1, no, yes, 5) * ( 9, 7, 5, 2, no, yes, 5) * ( 10, 7, 5, 3, no, yes, 5) * ( 11, 7, 5, 4, no, yes, 5) * ... * ... * ( 72, 23, 21, 1, yes, no, no) * ( 73, 23, 21, 2, yes, no, no) * ( 74, 23, 21, 3, yes, no, no) * ( 75, 23, 21, 4, yes, no, no) * <p> * ( 76, 24, 22, 1, yes, no, no) */ final class SizeClasses implements SizeClassesMetric { static final int LOG2_QUANTUM = 4; private static final int LOG2_SIZE_CLASS_GROUP = 2; private static final int LOG2_MAX_LOOKUP_SIZE = 12; private static final int LOG2GROUP_IDX = 1; private static final int LOG2DELTA_IDX = 2; private static final int NDELTA_IDX = 3; private static final int PAGESIZE_IDX = 4; private static final int SUBPAGE_IDX = 5; private static final int LOG2_DELTA_LOOKUP_IDX = 6; private static final byte no = 0, yes = 1; final int pageSize; final int pageShifts; final int chunkSize; final int directMemoryCacheAlignment; final int nSizes; final int nSubpages; final int nPSizes; final int lookupMaxSize; final int smallMaxSizeIdx; private final int[] pageIdx2sizeTab; // lookup table for sizeIdx <= smallMaxSizeIdx private final int[] sizeIdx2sizeTab; // lookup table used for size <= lookupMaxClass // spacing is 1 << LOG2_QUANTUM, so the size of array is lookupMaxClass >> LOG2_QUANTUM private final int[] size2idxTab; SizeClasses(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { int group = log2(chunkSize) - LOG2_QUANTUM - LOG2_SIZE_CLASS_GROUP + 1; //generate size classes //[index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup] short[][] sizeClasses = new short[group << LOG2_SIZE_CLASS_GROUP][7]; int normalMaxSize = -1; int nSizes = 0; int size = 0; int log2Group = LOG2_QUANTUM; int log2Delta = LOG2_QUANTUM; int ndeltaLimit = 1 << LOG2_SIZE_CLASS_GROUP; //First small group, nDelta start at 0. //first size class is 1 << LOG2_QUANTUM for (int nDelta = 0; nDelta < ndeltaLimit; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = sizeOf(sizeClass, directMemoryCacheAlignment); } log2Group += LOG2_SIZE_CLASS_GROUP; //All remaining groups, nDelta start at 1. for (; size < chunkSize; log2Group++, log2Delta++) { for (int nDelta = 1; nDelta <= ndeltaLimit && size < chunkSize; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = normalMaxSize = sizeOf(sizeClass, directMemoryCacheAlignment); } } //chunkSize must be normalMaxSize assert chunkSize == normalMaxSize; int smallMaxSizeIdx = 0; int lookupMaxSize = 0; int nPSizes = 0; int nSubpages = 0; for (int idx = 0; idx < nSizes; idx++) { short[] sz = sizeClasses[idx]; if (sz[PAGESIZE_IDX] == yes) { nPSizes++; } if (sz[SUBPAGE_IDX] == yes) { nSubpages++; smallMaxSizeIdx = idx; } if (sz[LOG2_DELTA_LOOKUP_IDX] != no) { lookupMaxSize = sizeOf(sz, directMemoryCacheAlignment); } } this.smallMaxSizeIdx = smallMaxSizeIdx; this.lookupMaxSize = lookupMaxSize; this.nPSizes = nPSizes; this.nSubpages = nSubpages; this.nSizes = nSizes; this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; //generate lookup tables this.sizeIdx2sizeTab = newIdx2SizeTab(sizeClasses, nSizes, directMemoryCacheAlignment); this.pageIdx2sizeTab = newPageIdx2sizeTab(sizeClasses, nSizes, nPSizes, directMemoryCacheAlignment); this.size2idxTab = newSize2idxTab(lookupMaxSize, sizeClasses); } //calculate size class private static short[] newSizeClass(int index, int log2Group, int log2Delta, int nDelta, int pageShifts) { short isMultiPageSize; if (log2Delta >= pageShifts) { isMultiPageSize = yes; } else { int pageSize = 1 << pageShifts; int size = calculateSize(log2Group, nDelta, log2Delta); isMultiPageSize = size == size / pageSize * pageSize? yes : no; } int log2Ndelta = nDelta == 0? 0 : log2(nDelta); byte remove = 1 << log2Ndelta < nDelta? yes : no; int log2Size = log2Delta + log2Ndelta == log2Group? log2Group + 1 : log2Group; if (log2Size == log2Group) { remove = yes; } short isSubpage = log2Size < pageShifts + LOG2_SIZE_CLASS_GROUP? yes : no; int log2DeltaLookup = log2Size < LOG2_MAX_LOOKUP_SIZE || log2Size == LOG2_MAX_LOOKUP_SIZE && remove == no ? log2Delta : no; return new short[] { (short) index, (short) log2Group, (short) log2Delta, (short) nDelta, isMultiPageSize, isSubpage, (short) log2DeltaLookup }; } private static int[] newIdx2SizeTab(short[][] sizeClasses, int nSizes, int directMemoryCacheAlignment) { int[] sizeIdx2sizeTab = new int[nSizes]; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; sizeIdx2sizeTab[i] = sizeOf(sizeClass, directMemoryCacheAlignment); } return sizeIdx2sizeTab; } private static int calculateSize(int log2Group, int nDelta, int log2Delta) { return (1 << log2Group) + (nDelta << log2Delta); } private static int sizeOf(short[] sizeClass, int directMemoryCacheAlignment) { int log2Group = sizeClass[LOG2GROUP_IDX]; int log2Delta = sizeClass[LOG2DELTA_IDX]; int nDelta = sizeClass[NDELTA_IDX]; int size = calculateSize(log2Group, nDelta, log2Delta); return alignSizeIfNeeded(size, directMemoryCacheAlignment); } private static int[] newPageIdx2sizeTab(short[][] sizeClasses, int nSizes, int nPSizes, int directMemoryCacheAlignment) { int[] pageIdx2sizeTab = new int[nPSizes]; int pageIdx = 0; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; if (sizeClass[PAGESIZE_IDX] == yes) { pageIdx2sizeTab[pageIdx++] = sizeOf(sizeClass, directMemoryCacheAlignment); } } return pageIdx2sizeTab; } private static int[] newSize2idxTab(int lookupMaxSize, short[][] sizeClasses) { int[] size2idxTab = new int[lookupMaxSize >> LOG2_QUANTUM]; int idx = 0; int size = 0; for (int i = 0; size <= lookupMaxSize; i++) { int log2Delta = sizeClasses[i][LOG2DELTA_IDX]; int times = 1 << log2Delta - LOG2_QUANTUM; while (size <= lookupMaxSize && times-- > 0) { size2idxTab[idx++] = i; size = idx + 1 << LOG2_QUANTUM; } } return size2idxTab; } @Override public int sizeIdx2size(int sizeIdx) { return sizeIdx2sizeTab[sizeIdx]; } @Override public int sizeIdx2sizeCompute(int sizeIdx) { int group = sizeIdx >> LOG2_SIZE_CLASS_GROUP; int mod = sizeIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int groupSize = group == 0? 0 : 1 << LOG2_QUANTUM + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int lgDelta = shift + LOG2_QUANTUM - 1; int modSize = mod + 1 << lgDelta; return groupSize + modSize; } @Override public long pageIdx2size(int pageIdx) { return pageIdx2sizeTab[pageIdx]; } @Override public long pageIdx2sizeCompute(int pageIdx) { int group = pageIdx >> LOG2_SIZE_CLASS_GROUP; int mod = pageIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; long groupSize = group == 0? 0 : 1L << pageShifts + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int log2Delta = shift + pageShifts - 1; int modSize = mod + 1 << log2Delta; return groupSize + modSize; } @Override public int size2SizeIdx(int size) { if (size == 0) { return 0; } if (size > chunkSize) { return nSizes; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { //size-1 / MIN_TINY return size2idxTab[size - 1 >> LOG2_QUANTUM]; } int x = log2((size << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? 0 : x - (LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = size - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; return group + mod; } @Override public int pages2pageIdx(int pages) { return pages2pageIdxCompute(pages, false); } @Override public int pages2pageIdxFloor(int pages) { return pages2pageIdxCompute(pages, true); } private int pages2pageIdxCompute(int pages, boolean floor) { int pageSize = pages << pageShifts; if (pageSize > chunkSize) { return nPSizes; } int x = log2((pageSize << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + pageShifts ? 0 : x - (LOG2_SIZE_CLASS_GROUP + pageShifts); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + pageShifts + 1? pageShifts : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = pageSize - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int pageIdx = group + mod; if (floor && pageIdx2sizeTab[pageIdx] > pages << pageShifts) { pageIdx--; } return pageIdx; } // Round size up to the nearest multiple of alignment. private static int alignSizeIfNeeded(int size, int directMemoryCacheAlignment) { if (directMemoryCacheAlignment <= 0) { return size; } int delta = size & directMemoryCacheAlignment - 1; return delta == 0? size : size + directMemoryCacheAlignment - delta; } @Override public int normalizeSize(int size) { if (size == 0) { return sizeIdx2sizeTab[0]; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { int ret = sizeIdx2sizeTab[size2idxTab[size - 1 >> LOG2_QUANTUM]]; assert ret == normalizeSizeCompute(size); return ret; } return normalizeSizeCompute(size); } private static int normalizeSizeCompute(int size) { int x = log2((size << 1) - 1); int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int delta = 1 << log2Delta; int delta_mask = delta - 1; return size + delta_mask & ~delta_mask; } }
netty/netty
buffer/src/main/java/io/netty/buffer/SizeClasses.java
41
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import io.netty.util.internal.LongCounter; import io.netty.util.internal.PlatformDependent; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Deque; import java.util.PriorityQueue; import java.util.concurrent.locks.ReentrantLock; /** * Description of algorithm for PageRun/PoolSubpage allocation from PoolChunk * * Notation: The following terms are important to understand the code * > page - a page is the smallest unit of memory chunk that can be allocated * > run - a run is a collection of pages * > chunk - a chunk is a collection of runs * > in this code chunkSize = maxPages * pageSize * * To begin we allocate a byte array of size = chunkSize * Whenever a ByteBuf of given size needs to be created we search for the first position * in the byte array that has enough empty space to accommodate the requested size and * return a (long) handle that encodes this offset information, (this memory segment is then * marked as reserved so it is always used by exactly one ByteBuf and no more) * * For simplicity all sizes are normalized according to {@link PoolArena#sizeClass#size2SizeIdx(int)} method. * This ensures that when we request for memory segments of size > pageSize the normalizedCapacity * equals the next nearest size in {@link SizeClasses}. * * * A chunk has the following layout: * * /-----------------\ * | run | * | | * | | * |-----------------| * | run | * | | * |-----------------| * | unalloctated | * | (freed) | * | | * |-----------------| * | subpage | * |-----------------| * | unallocated | * | (freed) | * | ... | * | ... | * | ... | * | | * | | * | | * \-----------------/ * * * handle: * ------- * a handle is a long number, the bit layout of a run looks like: * * oooooooo ooooooos ssssssss ssssssue bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb * * o: runOffset (page offset in the chunk), 15bit * s: size (number of pages) of this run, 15bit * u: isUsed?, 1bit * e: isSubpage?, 1bit * b: bitmapIdx of subpage, zero if it's not subpage, 32bit * * runsAvailMap: * ------ * a map which manages all runs (used and not in used). * For each run, the first runOffset and last runOffset are stored in runsAvailMap. * key: runOffset * value: handle * * runsAvail: * ---------- * an array of {@link PriorityQueue}. * Each queue manages same size of runs. * Runs are sorted by offset, so that we always allocate runs with smaller offset. * * * Algorithm: * ---------- * * As we allocate runs, we update values stored in runsAvailMap and runsAvail so that the property is maintained. * * Initialization - * In the beginning we store the initial run which is the whole chunk. * The initial run: * runOffset = 0 * size = chunkSize * isUsed = no * isSubpage = no * bitmapIdx = 0 * * * Algorithm: [allocateRun(size)] * ---------- * 1) find the first avail run using in runsAvails according to size * 2) if pages of run is larger than request pages then split it, and save the tailing run * for later using * * Algorithm: [allocateSubpage(size)] * ---------- * 1) find a not full subpage according to size. * if it already exists just return, otherwise allocate a new PoolSubpage and call init() * note that this subpage object is added to subpagesPool in the PoolArena when we init() it * 2) call subpage.allocate() * * Algorithm: [free(handle, length, nioBuffer)] * ---------- * 1) if it is a subpage, return the slab back into this subpage * 2) if the subpage is not used or it is a run, then start free this run * 3) merge continuous avail runs * 4) save the merged run * */ final class PoolChunk<T> implements PoolChunkMetric { private static final int SIZE_BIT_LENGTH = 15; private static final int INUSED_BIT_LENGTH = 1; private static final int SUBPAGE_BIT_LENGTH = 1; private static final int BITMAP_IDX_BIT_LENGTH = 32; static final int IS_SUBPAGE_SHIFT = BITMAP_IDX_BIT_LENGTH; static final int IS_USED_SHIFT = SUBPAGE_BIT_LENGTH + IS_SUBPAGE_SHIFT; static final int SIZE_SHIFT = INUSED_BIT_LENGTH + IS_USED_SHIFT; static final int RUN_OFFSET_SHIFT = SIZE_BIT_LENGTH + SIZE_SHIFT; final PoolArena<T> arena; final Object base; final T memory; final boolean unpooled; /** * store the first page and last page of each avail run */ private final LongLongHashMap runsAvailMap; /** * manage all avail runs */ private final IntPriorityQueue[] runsAvail; private final ReentrantLock runsAvailLock; /** * manage all subpages in this chunk */ private final PoolSubpage<T>[] subpages; /** * Accounting of pinned memory – memory that is currently in use by ByteBuf instances. */ private final LongCounter pinnedBytes = PlatformDependent.newLongCounter(); private final int pageSize; private final int pageShifts; private final int chunkSize; // Use as cache for ByteBuffer created from the memory. These are just duplicates and so are only a container // around the memory itself. These are often needed for operations within the Pooled*ByteBuf and so // may produce extra GC, which can be greatly reduced by caching the duplicates. // // This may be null if the PoolChunk is unpooled as pooling the ByteBuffer instances does not make any sense here. private final Deque<ByteBuffer> cachedNioBuffers; int freeBytes; PoolChunkList<T> parent; PoolChunk<T> prev; PoolChunk<T> next; // TODO: Test if adding padding helps under contention //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; @SuppressWarnings("unchecked") PoolChunk(PoolArena<T> arena, Object base, T memory, int pageSize, int pageShifts, int chunkSize, int maxPageIdx) { unpooled = false; this.arena = arena; this.base = base; this.memory = memory; this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; freeBytes = chunkSize; runsAvail = newRunsAvailqueueArray(maxPageIdx); runsAvailLock = new ReentrantLock(); runsAvailMap = new LongLongHashMap(-1); subpages = new PoolSubpage[chunkSize >> pageShifts]; //insert initial run, offset = 0, pages = chunkSize / pageSize int pages = chunkSize >> pageShifts; long initHandle = (long) pages << SIZE_SHIFT; insertAvailRun(0, pages, initHandle); cachedNioBuffers = new ArrayDeque<ByteBuffer>(8); } /** Creates a special chunk that is not pooled. */ PoolChunk(PoolArena<T> arena, Object base, T memory, int size) { unpooled = true; this.arena = arena; this.base = base; this.memory = memory; pageSize = 0; pageShifts = 0; runsAvailMap = null; runsAvail = null; runsAvailLock = null; subpages = null; chunkSize = size; cachedNioBuffers = null; } private static IntPriorityQueue[] newRunsAvailqueueArray(int size) { IntPriorityQueue[] queueArray = new IntPriorityQueue[size]; for (int i = 0; i < queueArray.length; i++) { queueArray[i] = new IntPriorityQueue(); } return queueArray; } private void insertAvailRun(int runOffset, int pages, long handle) { int pageIdxFloor = arena.sizeClass.pages2pageIdxFloor(pages); IntPriorityQueue queue = runsAvail[pageIdxFloor]; assert isRun(handle); queue.offer((int) (handle >> BITMAP_IDX_BIT_LENGTH)); //insert first page of run insertAvailRun0(runOffset, handle); if (pages > 1) { //insert last page of run insertAvailRun0(lastPage(runOffset, pages), handle); } } private void insertAvailRun0(int runOffset, long handle) { long pre = runsAvailMap.put(runOffset, handle); assert pre == -1; } private void removeAvailRun(long handle) { int pageIdxFloor = arena.sizeClass.pages2pageIdxFloor(runPages(handle)); runsAvail[pageIdxFloor].remove((int) (handle >> BITMAP_IDX_BIT_LENGTH)); removeAvailRun0(handle); } private void removeAvailRun0(long handle) { int runOffset = runOffset(handle); int pages = runPages(handle); //remove first page of run runsAvailMap.remove(runOffset); if (pages > 1) { //remove last page of run runsAvailMap.remove(lastPage(runOffset, pages)); } } private static int lastPage(int runOffset, int pages) { return runOffset + pages - 1; } private long getAvailRunByOffset(int runOffset) { return runsAvailMap.get(runOffset); } @Override public int usage() { final int freeBytes; if (this.unpooled) { freeBytes = this.freeBytes; } else { runsAvailLock.lock(); try { freeBytes = this.freeBytes; } finally { runsAvailLock.unlock(); } } return usage(freeBytes); } private int usage(int freeBytes) { if (freeBytes == 0) { return 100; } int freePercentage = (int) (freeBytes * 100L / chunkSize); if (freePercentage == 0) { return 99; } return 100 - freePercentage; } boolean allocate(PooledByteBuf<T> buf, int reqCapacity, int sizeIdx, PoolThreadCache cache) { final long handle; if (sizeIdx <= arena.sizeClass.smallMaxSizeIdx) { final PoolSubpage<T> nextSub; // small // Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it. // This is need as we may add it back and so alter the linked-list structure. PoolSubpage<T> head = arena.smallSubpagePools[sizeIdx]; head.lock(); try { nextSub = head.next; if (nextSub != head) { assert nextSub.doNotDestroy && nextSub.elemSize == arena.sizeClass.sizeIdx2size(sizeIdx) : "doNotDestroy=" + nextSub.doNotDestroy + ", elemSize=" + nextSub.elemSize + ", sizeIdx=" + sizeIdx; handle = nextSub.allocate(); assert handle >= 0; assert isSubpage(handle); nextSub.chunk.initBufWithSubpage(buf, null, handle, reqCapacity, cache); return true; } handle = allocateSubpage(sizeIdx, head); if (handle < 0) { return false; } assert isSubpage(handle); } finally { head.unlock(); } } else { // normal // runSize must be multiple of pageSize int runSize = arena.sizeClass.sizeIdx2size(sizeIdx); handle = allocateRun(runSize); if (handle < 0) { return false; } assert !isSubpage(handle); } ByteBuffer nioBuffer = cachedNioBuffers != null? cachedNioBuffers.pollLast() : null; initBuf(buf, nioBuffer, handle, reqCapacity, cache); return true; } private long allocateRun(int runSize) { int pages = runSize >> pageShifts; int pageIdx = arena.sizeClass.pages2pageIdx(pages); runsAvailLock.lock(); try { //find first queue which has at least one big enough run int queueIdx = runFirstBestFit(pageIdx); if (queueIdx == -1) { return -1; } //get run with min offset in this queue IntPriorityQueue queue = runsAvail[queueIdx]; long handle = queue.poll(); assert handle != IntPriorityQueue.NO_VALUE; handle <<= BITMAP_IDX_BIT_LENGTH; assert !isUsed(handle) : "invalid handle: " + handle; removeAvailRun0(handle); handle = splitLargeRun(handle, pages); int pinnedSize = runSize(pageShifts, handle); freeBytes -= pinnedSize; return handle; } finally { runsAvailLock.unlock(); } } private int calculateRunSize(int sizeIdx) { int maxElements = 1 << pageShifts - SizeClasses.LOG2_QUANTUM; int runSize = 0; int nElements; final int elemSize = arena.sizeClass.sizeIdx2size(sizeIdx); //find lowest common multiple of pageSize and elemSize do { runSize += pageSize; nElements = runSize / elemSize; } while (nElements < maxElements && runSize != nElements * elemSize); while (nElements > maxElements) { runSize -= pageSize; nElements = runSize / elemSize; } assert nElements > 0; assert runSize <= chunkSize; assert runSize >= elemSize; return runSize; } private int runFirstBestFit(int pageIdx) { if (freeBytes == chunkSize) { return arena.sizeClass.nPSizes - 1; } for (int i = pageIdx; i < arena.sizeClass.nPSizes; i++) { IntPriorityQueue queue = runsAvail[i]; if (queue != null && !queue.isEmpty()) { return i; } } return -1; } private long splitLargeRun(long handle, int needPages) { assert needPages > 0; int totalPages = runPages(handle); assert needPages <= totalPages; int remPages = totalPages - needPages; if (remPages > 0) { int runOffset = runOffset(handle); // keep track of trailing unused pages for later use int availOffset = runOffset + needPages; long availRun = toRunHandle(availOffset, remPages, 0); insertAvailRun(availOffset, remPages, availRun); // not avail return toRunHandle(runOffset, needPages, 1); } //mark it as used handle |= 1L << IS_USED_SHIFT; return handle; } /** * Create / initialize a new PoolSubpage of normCapacity. Any PoolSubpage created / initialized here is added to * subpage pool in the PoolArena that owns this PoolChunk. * * @param sizeIdx sizeIdx of normalized size * @param head head of subpages * * @return index in memoryMap */ private long allocateSubpage(int sizeIdx, PoolSubpage<T> head) { //allocate a new run int runSize = calculateRunSize(sizeIdx); //runSize must be multiples of pageSize long runHandle = allocateRun(runSize); if (runHandle < 0) { return -1; } int runOffset = runOffset(runHandle); assert subpages[runOffset] == null; int elemSize = arena.sizeClass.sizeIdx2size(sizeIdx); PoolSubpage<T> subpage = new PoolSubpage<T>(head, this, pageShifts, runOffset, runSize(pageShifts, runHandle), elemSize); subpages[runOffset] = subpage; return subpage.allocate(); } /** * Free a subpage or a run of pages When a subpage is freed from PoolSubpage, it might be added back to subpage pool * of the owning PoolArena. If the subpage pool in PoolArena has at least one other PoolSubpage of given elemSize, * we can completely free the owning Page so it is available for subsequent allocations * * @param handle handle to free */ void free(long handle, int normCapacity, ByteBuffer nioBuffer) { if (isSubpage(handle)) { int sIdx = runOffset(handle); PoolSubpage<T> subpage = subpages[sIdx]; assert subpage != null; PoolSubpage<T> head = subpage.chunk.arena.smallSubpagePools[subpage.headIndex]; // Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it. // This is need as we may add it back and so alter the linked-list structure. head.lock(); try { assert subpage.doNotDestroy; if (subpage.free(head, bitmapIdx(handle))) { //the subpage is still used, do not free it return; } assert !subpage.doNotDestroy; // Null out slot in the array as it was freed and we should not use it anymore. subpages[sIdx] = null; } finally { head.unlock(); } } int runSize = runSize(pageShifts, handle); //start free run runsAvailLock.lock(); try { // collapse continuous runs, successfully collapsed runs // will be removed from runsAvail and runsAvailMap long finalRun = collapseRuns(handle); //set run as not used finalRun &= ~(1L << IS_USED_SHIFT); //if it is a subpage, set it to run finalRun &= ~(1L << IS_SUBPAGE_SHIFT); insertAvailRun(runOffset(finalRun), runPages(finalRun), finalRun); freeBytes += runSize; } finally { runsAvailLock.unlock(); } if (nioBuffer != null && cachedNioBuffers != null && cachedNioBuffers.size() < PooledByteBufAllocator.DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK) { cachedNioBuffers.offer(nioBuffer); } } private long collapseRuns(long handle) { return collapseNext(collapsePast(handle)); } private long collapsePast(long handle) { for (;;) { int runOffset = runOffset(handle); int runPages = runPages(handle); long pastRun = getAvailRunByOffset(runOffset - 1); if (pastRun == -1) { return handle; } int pastOffset = runOffset(pastRun); int pastPages = runPages(pastRun); //is continuous if (pastRun != handle && pastOffset + pastPages == runOffset) { //remove past run removeAvailRun(pastRun); handle = toRunHandle(pastOffset, pastPages + runPages, 0); } else { return handle; } } } private long collapseNext(long handle) { for (;;) { int runOffset = runOffset(handle); int runPages = runPages(handle); long nextRun = getAvailRunByOffset(runOffset + runPages); if (nextRun == -1) { return handle; } int nextOffset = runOffset(nextRun); int nextPages = runPages(nextRun); //is continuous if (nextRun != handle && runOffset + runPages == nextOffset) { //remove next run removeAvailRun(nextRun); handle = toRunHandle(runOffset, runPages + nextPages, 0); } else { return handle; } } } private static long toRunHandle(int runOffset, int runPages, int inUsed) { return (long) runOffset << RUN_OFFSET_SHIFT | (long) runPages << SIZE_SHIFT | (long) inUsed << IS_USED_SHIFT; } void initBuf(PooledByteBuf<T> buf, ByteBuffer nioBuffer, long handle, int reqCapacity, PoolThreadCache threadCache) { if (isSubpage(handle)) { initBufWithSubpage(buf, nioBuffer, handle, reqCapacity, threadCache); } else { int maxLength = runSize(pageShifts, handle); buf.init(this, nioBuffer, handle, runOffset(handle) << pageShifts, reqCapacity, maxLength, arena.parent.threadCache()); } } void initBufWithSubpage(PooledByteBuf<T> buf, ByteBuffer nioBuffer, long handle, int reqCapacity, PoolThreadCache threadCache) { int runOffset = runOffset(handle); int bitmapIdx = bitmapIdx(handle); PoolSubpage<T> s = subpages[runOffset]; assert s.isDoNotDestroy(); assert reqCapacity <= s.elemSize : reqCapacity + "<=" + s.elemSize; int offset = (runOffset << pageShifts) + bitmapIdx * s.elemSize; buf.init(this, nioBuffer, handle, offset, reqCapacity, s.elemSize, threadCache); } void incrementPinnedMemory(int delta) { assert delta > 0; pinnedBytes.add(delta); } void decrementPinnedMemory(int delta) { assert delta > 0; pinnedBytes.add(-delta); } @Override public int chunkSize() { return chunkSize; } @Override public int freeBytes() { if (this.unpooled) { return freeBytes; } runsAvailLock.lock(); try { return freeBytes; } finally { runsAvailLock.unlock(); } } public int pinnedBytes() { return (int) pinnedBytes.value(); } @Override public String toString() { final int freeBytes; if (this.unpooled) { freeBytes = this.freeBytes; } else { runsAvailLock.lock(); try { freeBytes = this.freeBytes; } finally { runsAvailLock.unlock(); } } return new StringBuilder() .append("Chunk(") .append(Integer.toHexString(System.identityHashCode(this))) .append(": ") .append(usage(freeBytes)) .append("%, ") .append(chunkSize - freeBytes) .append('/') .append(chunkSize) .append(')') .toString(); } void destroy() { arena.destroyChunk(this); } static int runOffset(long handle) { return (int) (handle >> RUN_OFFSET_SHIFT); } static int runSize(int pageShifts, long handle) { return runPages(handle) << pageShifts; } static int runPages(long handle) { return (int) (handle >> SIZE_SHIFT & 0x7fff); } static boolean isUsed(long handle) { return (handle >> IS_USED_SHIFT & 1) == 1L; } static boolean isRun(long handle) { return !isSubpage(handle); } static boolean isSubpage(long handle) { return (handle >> IS_SUBPAGE_SHIFT & 1) == 1L; } static int bitmapIdx(long handle) { return (int) handle; } }
netty/netty
buffer/src/main/java/io/netty/buffer/PoolChunk.java
42
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import io.netty.buffer.CompositeByteBuf.ByteWrapper; import io.netty.util.internal.ObjectUtil; import io.netty.util.CharsetUtil; import io.netty.util.internal.PlatformDependent; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.Arrays; /** * Creates a new {@link ByteBuf} by allocating new space or by wrapping * or copying existing byte arrays, byte buffers and a string. * * <h3>Use static import</h3> * This classes is intended to be used with Java 5 static import statement: * * <pre> * import static io.netty.buffer.{@link Unpooled}.*; * * {@link ByteBuf} heapBuffer = buffer(128); * {@link ByteBuf} directBuffer = directBuffer(256); * {@link ByteBuf} wrappedBuffer = wrappedBuffer(new byte[128], new byte[256]); * {@link ByteBuf} copiedBuffer = copiedBuffer({@link ByteBuffer}.allocate(128)); * </pre> * * <h3>Allocating a new buffer</h3> * * Three buffer types are provided out of the box. * * <ul> * <li>{@link #buffer(int)} allocates a new fixed-capacity heap buffer.</li> * <li>{@link #directBuffer(int)} allocates a new fixed-capacity direct buffer.</li> * </ul> * * <h3>Creating a wrapped buffer</h3> * * Wrapped buffer is a buffer which is a view of one or more existing * byte arrays and byte buffers. Any changes in the content of the original * array or buffer will be visible in the wrapped buffer. Various wrapper * methods are provided and their name is all {@code wrappedBuffer()}. * You might want to take a look at the methods that accept varargs closely if * you want to create a buffer which is composed of more than one array to * reduce the number of memory copy. * * <h3>Creating a copied buffer</h3> * * Copied buffer is a deep copy of one or more existing byte arrays, byte * buffers or a string. Unlike a wrapped buffer, there's no shared data * between the original data and the copied buffer. Various copy methods are * provided and their name is all {@code copiedBuffer()}. It is also convenient * to use this operation to merge multiple buffers into one buffer. */ public final class Unpooled { private static final ByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT; /** * Big endian byte order. */ public static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; /** * Little endian byte order. */ public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; /** * A buffer whose capacity is {@code 0}. */ @SuppressWarnings("checkstyle:StaticFinalBuffer") // EmptyByteBuf is not writeable or readable. public static final ByteBuf EMPTY_BUFFER = ALLOC.buffer(0, 0); static { assert EMPTY_BUFFER instanceof EmptyByteBuf: "EMPTY_BUFFER must be an EmptyByteBuf."; } /** * Creates a new big-endian Java heap buffer with reasonably small initial capacity, which * expands its capacity boundlessly on demand. */ public static ByteBuf buffer() { return ALLOC.heapBuffer(); } /** * Creates a new big-endian direct buffer with reasonably small initial capacity, which * expands its capacity boundlessly on demand. */ public static ByteBuf directBuffer() { return ALLOC.directBuffer(); } /** * Creates a new big-endian Java heap buffer with the specified {@code capacity}, which * expands its capacity boundlessly on demand. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ByteBuf buffer(int initialCapacity) { return ALLOC.heapBuffer(initialCapacity); } /** * Creates a new big-endian direct buffer with the specified {@code capacity}, which * expands its capacity boundlessly on demand. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ByteBuf directBuffer(int initialCapacity) { return ALLOC.directBuffer(initialCapacity); } /** * Creates a new big-endian Java heap buffer with the specified * {@code initialCapacity}, that may grow up to {@code maxCapacity} * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0}. */ public static ByteBuf buffer(int initialCapacity, int maxCapacity) { return ALLOC.heapBuffer(initialCapacity, maxCapacity); } /** * Creates a new big-endian direct buffer with the specified * {@code initialCapacity}, that may grow up to {@code maxCapacity}. * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0}. */ public static ByteBuf directBuffer(int initialCapacity, int maxCapacity) { return ALLOC.directBuffer(initialCapacity, maxCapacity); } /** * Creates a new big-endian buffer which wraps the specified {@code array}. * A modification on the specified array's content will be visible to the * returned buffer. */ public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); } /** * Creates a new big-endian buffer which wraps the sub-region of the * specified {@code array}. A modification on the specified array's * content will be visible to the returned buffer. */ public static ByteBuf wrappedBuffer(byte[] array, int offset, int length) { if (length == 0) { return EMPTY_BUFFER; } if (offset == 0 && length == array.length) { return wrappedBuffer(array); } return wrappedBuffer(array).slice(offset, length); } /** * Creates a new buffer which wraps the specified NIO buffer's current * slice. A modification on the specified buffer's content will be * visible to the returned buffer. */ public static ByteBuf wrappedBuffer(ByteBuffer buffer) { if (!buffer.hasRemaining()) { return EMPTY_BUFFER; } if (!buffer.isDirect() && buffer.hasArray()) { return wrappedBuffer( buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()).order(buffer.order()); } else if (PlatformDependent.hasUnsafe()) { if (buffer.isReadOnly()) { if (buffer.isDirect()) { return new ReadOnlyUnsafeDirectByteBuf(ALLOC, buffer); } else { return new ReadOnlyByteBufferBuf(ALLOC, buffer); } } else { return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining()); } } else { if (buffer.isReadOnly()) { return new ReadOnlyByteBufferBuf(ALLOC, buffer); } else { return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); } } } /** * Creates a new buffer which wraps the specified memory address. If {@code doFree} is true the * memoryAddress will automatically be freed once the reference count of the {@link ByteBuf} reaches {@code 0}. */ public static ByteBuf wrappedBuffer(long memoryAddress, int size, boolean doFree) { return new WrappedUnpooledUnsafeDirectByteBuf(ALLOC, memoryAddress, size, doFree); } /** * Creates a new buffer which wraps the specified buffer's readable bytes. * A modification on the specified buffer's content will be visible to the * returned buffer. * @param buffer The buffer to wrap. Reference count ownership of this variable is transferred to this method. * @return The readable portion of the {@code buffer}, or an empty buffer if there is no readable portion. * The caller is responsible for releasing this buffer. */ public static ByteBuf wrappedBuffer(ByteBuf buffer) { if (buffer.isReadable()) { return buffer.slice(); } else { buffer.release(); return EMPTY_BUFFER; } } /** * Creates a new big-endian composite buffer which wraps the specified * arrays without copying them. A modification on the specified arrays' * content will be visible to the returned buffer. */ public static ByteBuf wrappedBuffer(byte[]... arrays) { return wrappedBuffer(arrays.length, arrays); } /** * Creates a new big-endian composite buffer which wraps the readable bytes of the * specified buffers without copying them. A modification on the content * of the specified buffers will be visible to the returned buffer. * @param buffers The buffers to wrap. Reference count ownership of all variables is transferred to this method. * @return The readable portion of the {@code buffers}. The caller is responsible for releasing this buffer. */ public static ByteBuf wrappedBuffer(ByteBuf... buffers) { return wrappedBuffer(buffers.length, buffers); } /** * Creates a new big-endian composite buffer which wraps the slices of the specified * NIO buffers without copying them. A modification on the content of the * specified buffers will be visible to the returned buffer. */ public static ByteBuf wrappedBuffer(ByteBuffer... buffers) { return wrappedBuffer(buffers.length, buffers); } static <T> ByteBuf wrappedBuffer(int maxNumComponents, ByteWrapper<T> wrapper, T[] array) { switch (array.length) { case 0: break; case 1: if (!wrapper.isEmpty(array[0])) { return wrapper.wrap(array[0]); } break; default: for (int i = 0, len = array.length; i < len; i++) { T bytes = array[i]; if (bytes == null) { return EMPTY_BUFFER; } if (!wrapper.isEmpty(bytes)) { return new CompositeByteBuf(ALLOC, false, maxNumComponents, wrapper, array, i); } } } return EMPTY_BUFFER; } /** * Creates a new big-endian composite buffer which wraps the specified * arrays without copying them. A modification on the specified arrays' * content will be visible to the returned buffer. */ public static ByteBuf wrappedBuffer(int maxNumComponents, byte[]... arrays) { return wrappedBuffer(maxNumComponents, CompositeByteBuf.BYTE_ARRAY_WRAPPER, arrays); } /** * Creates a new big-endian composite buffer which wraps the readable bytes of the * specified buffers without copying them. A modification on the content * of the specified buffers will be visible to the returned buffer. * @param maxNumComponents Advisement as to how many independent buffers are allowed to exist before * consolidation occurs. * @param buffers The buffers to wrap. Reference count ownership of all variables is transferred to this method. * @return The readable portion of the {@code buffers}. The caller is responsible for releasing this buffer. */ public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuf... buffers) { switch (buffers.length) { case 0: break; case 1: ByteBuf buffer = buffers[0]; if (buffer.isReadable()) { return wrappedBuffer(buffer.order(BIG_ENDIAN)); } else { buffer.release(); } break; default: for (int i = 0; i < buffers.length; i++) { ByteBuf buf = buffers[i]; if (buf.isReadable()) { return new CompositeByteBuf(ALLOC, false, maxNumComponents, buffers, i); } buf.release(); } break; } return EMPTY_BUFFER; } /** * Creates a new big-endian composite buffer which wraps the slices of the specified * NIO buffers without copying them. A modification on the content of the * specified buffers will be visible to the returned buffer. */ public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuffer... buffers) { return wrappedBuffer(maxNumComponents, CompositeByteBuf.BYTE_BUFFER_WRAPPER, buffers); } /** * Returns a new big-endian composite buffer with no components. */ public static CompositeByteBuf compositeBuffer() { return compositeBuffer(AbstractByteBufAllocator.DEFAULT_MAX_COMPONENTS); } /** * Returns a new big-endian composite buffer with no components. */ public static CompositeByteBuf compositeBuffer(int maxNumComponents) { return new CompositeByteBuf(ALLOC, false, maxNumComponents); } /** * Creates a new big-endian buffer whose content is a copy of the * specified {@code array}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0} and {@code array.length} respectively. */ public static ByteBuf copiedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return wrappedBuffer(array.clone()); } /** * Creates a new big-endian buffer whose content is a copy of the * specified {@code array}'s sub-region. The new buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0} and * the specified {@code length} respectively. */ public static ByteBuf copiedBuffer(byte[] array, int offset, int length) { if (length == 0) { return EMPTY_BUFFER; } byte[] copy = PlatformDependent.allocateUninitializedArray(length); System.arraycopy(array, offset, copy, 0, length); return wrappedBuffer(copy); } /** * Creates a new buffer whose content is a copy of the specified * {@code buffer}'s current slice. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and {@code buffer.remaining} * respectively. */ public static ByteBuf copiedBuffer(ByteBuffer buffer) { int length = buffer.remaining(); if (length == 0) { return EMPTY_BUFFER; } byte[] copy = PlatformDependent.allocateUninitializedArray(length); // Duplicate the buffer so we not adjust the position during our get operation. // See https://github.com/netty/netty/issues/3896 ByteBuffer duplicate = buffer.duplicate(); duplicate.get(copy); return wrappedBuffer(copy).order(duplicate.order()); } /** * Creates a new buffer whose content is a copy of the specified * {@code buffer}'s readable bytes. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and {@code buffer.readableBytes} * respectively. */ public static ByteBuf copiedBuffer(ByteBuf buffer) { int readable = buffer.readableBytes(); if (readable > 0) { ByteBuf copy = buffer(readable); copy.writeBytes(buffer, buffer.readerIndex(), readable); return copy; } else { return EMPTY_BUFFER; } } /** * Creates a new big-endian buffer whose content is a merged copy of * the specified {@code arrays}. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and the sum of all arrays' * {@code length} respectively. */ public static ByteBuf copiedBuffer(byte[]... arrays) { switch (arrays.length) { case 0: return EMPTY_BUFFER; case 1: if (arrays[0].length == 0) { return EMPTY_BUFFER; } else { return copiedBuffer(arrays[0]); } } // Merge the specified arrays into one array. int length = 0; for (byte[] a: arrays) { if (Integer.MAX_VALUE - length < a.length) { throw new IllegalArgumentException( "The total length of the specified arrays is too big."); } length += a.length; } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = 0; i < arrays.length; i ++) { byte[] a = arrays[i]; System.arraycopy(a, 0, mergedArray, j, a.length); j += a.length; } return wrappedBuffer(mergedArray); } /** * Creates a new buffer whose content is a merged copy of the specified * {@code buffers}' readable bytes. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and the sum of all buffers' * {@code readableBytes} respectively. * * @throws IllegalArgumentException * if the specified buffers' endianness are different from each * other */ public static ByteBuf copiedBuffer(ByteBuf... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return copiedBuffer(buffers[0]); } // Merge the specified buffers into one buffer. ByteOrder order = null; int length = 0; for (ByteBuf b: buffers) { int bLen = b.readableBytes(); if (bLen <= 0) { continue; } if (Integer.MAX_VALUE - length < bLen) { throw new IllegalArgumentException( "The total length of the specified buffers is too big."); } length += bLen; if (order != null) { if (!order.equals(b.order())) { throw new IllegalArgumentException("inconsistent byte order"); } } else { order = b.order(); } } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = 0; i < buffers.length; i ++) { ByteBuf b = buffers[i]; int bLen = b.readableBytes(); b.getBytes(b.readerIndex(), mergedArray, j, bLen); j += bLen; } return wrappedBuffer(mergedArray).order(order); } /** * Creates a new buffer whose content is a merged copy of the specified * {@code buffers}' slices. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0} and the sum of all buffers' * {@code remaining} respectively. * * @throws IllegalArgumentException * if the specified buffers' endianness are different from each * other */ public static ByteBuf copiedBuffer(ByteBuffer... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return copiedBuffer(buffers[0]); } // Merge the specified buffers into one buffer. ByteOrder order = null; int length = 0; for (ByteBuffer b: buffers) { int bLen = b.remaining(); if (bLen <= 0) { continue; } if (Integer.MAX_VALUE - length < bLen) { throw new IllegalArgumentException( "The total length of the specified buffers is too big."); } length += bLen; if (order != null) { if (!order.equals(b.order())) { throw new IllegalArgumentException("inconsistent byte order"); } } else { order = b.order(); } } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = 0; i < buffers.length; i ++) { // Duplicate the buffer so we not adjust the position during our get operation. // See https://github.com/netty/netty/issues/3896 ByteBuffer b = buffers[i].duplicate(); int bLen = b.remaining(); b.get(mergedArray, j, bLen); j += bLen; } return wrappedBuffer(mergedArray).order(order); } /** * Creates a new big-endian buffer whose content is the specified * {@code string} encoded in the specified {@code charset}. * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and the length of the encoded string respectively. */ public static ByteBuf copiedBuffer(CharSequence string, Charset charset) { ObjectUtil.checkNotNull(string, "string"); if (CharsetUtil.UTF_8.equals(charset)) { return copiedBufferUtf8(string); } if (CharsetUtil.US_ASCII.equals(charset)) { return copiedBufferAscii(string); } if (string instanceof CharBuffer) { return copiedBuffer((CharBuffer) string, charset); } return copiedBuffer(CharBuffer.wrap(string), charset); } private static ByteBuf copiedBufferUtf8(CharSequence string) { boolean release = true; // Mimic the same behavior as other copiedBuffer implementations. ByteBuf buffer = ALLOC.heapBuffer(ByteBufUtil.utf8Bytes(string)); try { ByteBufUtil.writeUtf8(buffer, string); release = false; return buffer; } finally { if (release) { buffer.release(); } } } private static ByteBuf copiedBufferAscii(CharSequence string) { boolean release = true; // Mimic the same behavior as other copiedBuffer implementations. ByteBuf buffer = ALLOC.heapBuffer(string.length()); try { ByteBufUtil.writeAscii(buffer, string); release = false; return buffer; } finally { if (release) { buffer.release(); } } } /** * Creates a new big-endian buffer whose content is a subregion of * the specified {@code string} encoded in the specified {@code charset}. * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and the length of the encoded string respectively. */ public static ByteBuf copiedBuffer( CharSequence string, int offset, int length, Charset charset) { ObjectUtil.checkNotNull(string, "string"); if (length == 0) { return EMPTY_BUFFER; } if (string instanceof CharBuffer) { CharBuffer buf = (CharBuffer) string; if (buf.hasArray()) { return copiedBuffer( buf.array(), buf.arrayOffset() + buf.position() + offset, length, charset); } buf = buf.slice(); buf.limit(length); buf.position(offset); return copiedBuffer(buf, charset); } return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset); } /** * Creates a new big-endian buffer whose content is the specified * {@code array} encoded in the specified {@code charset}. * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and the length of the encoded string respectively. */ public static ByteBuf copiedBuffer(char[] array, Charset charset) { ObjectUtil.checkNotNull(array, "array"); return copiedBuffer(array, 0, array.length, charset); } /** * Creates a new big-endian buffer whose content is a subregion of * the specified {@code array} encoded in the specified {@code charset}. * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and the length of the encoded string respectively. */ public static ByteBuf copiedBuffer(char[] array, int offset, int length, Charset charset) { ObjectUtil.checkNotNull(array, "array"); if (length == 0) { return EMPTY_BUFFER; } return copiedBuffer(CharBuffer.wrap(array, offset, length), charset); } private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) { return ByteBufUtil.encodeString0(ALLOC, true, buffer, charset, 0); } /** * Creates a read-only buffer which disallows any modification operations * on the specified {@code buffer}. The new buffer has the same * {@code readerIndex} and {@code writerIndex} with the specified * {@code buffer}. * * @deprecated Use {@link ByteBuf#asReadOnly()}. */ @Deprecated public static ByteBuf unmodifiableBuffer(ByteBuf buffer) { ByteOrder endianness = buffer.order(); if (endianness == BIG_ENDIAN) { return new ReadOnlyByteBuf(buffer); } return new ReadOnlyByteBuf(buffer.order(BIG_ENDIAN)).order(LITTLE_ENDIAN); } /** * Creates a new 4-byte big-endian buffer that holds the specified 32-bit integer. */ public static ByteBuf copyInt(int value) { ByteBuf buf = buffer(4); buf.writeInt(value); return buf; } /** * Create a big-endian buffer that holds a sequence of the specified 32-bit integers. */ public static ByteBuf copyInt(int... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 4); for (int v: values) { buffer.writeInt(v); } return buffer; } /** * Creates a new 2-byte big-endian buffer that holds the specified 16-bit integer. */ public static ByteBuf copyShort(int value) { ByteBuf buf = buffer(2); buf.writeShort(value); return buf; } /** * Create a new big-endian buffer that holds a sequence of the specified 16-bit integers. */ public static ByteBuf copyShort(short... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 2); for (int v: values) { buffer.writeShort(v); } return buffer; } /** * Create a new big-endian buffer that holds a sequence of the specified 16-bit integers. */ public static ByteBuf copyShort(int... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 2); for (int v: values) { buffer.writeShort(v); } return buffer; } /** * Creates a new 3-byte big-endian buffer that holds the specified 24-bit integer. */ public static ByteBuf copyMedium(int value) { ByteBuf buf = buffer(3); buf.writeMedium(value); return buf; } /** * Create a new big-endian buffer that holds a sequence of the specified 24-bit integers. */ public static ByteBuf copyMedium(int... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 3); for (int v: values) { buffer.writeMedium(v); } return buffer; } /** * Creates a new 8-byte big-endian buffer that holds the specified 64-bit integer. */ public static ByteBuf copyLong(long value) { ByteBuf buf = buffer(8); buf.writeLong(value); return buf; } /** * Create a new big-endian buffer that holds a sequence of the specified 64-bit integers. */ public static ByteBuf copyLong(long... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 8); for (long v: values) { buffer.writeLong(v); } return buffer; } /** * Creates a new single-byte big-endian buffer that holds the specified boolean value. */ public static ByteBuf copyBoolean(boolean value) { ByteBuf buf = buffer(1); buf.writeBoolean(value); return buf; } /** * Create a new big-endian buffer that holds a sequence of the specified boolean values. */ public static ByteBuf copyBoolean(boolean... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length); for (boolean v: values) { buffer.writeBoolean(v); } return buffer; } /** * Creates a new 4-byte big-endian buffer that holds the specified 32-bit floating point number. */ public static ByteBuf copyFloat(float value) { ByteBuf buf = buffer(4); buf.writeFloat(value); return buf; } /** * Create a new big-endian buffer that holds a sequence of the specified 32-bit floating point numbers. */ public static ByteBuf copyFloat(float... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 4); for (float v: values) { buffer.writeFloat(v); } return buffer; } /** * Creates a new 8-byte big-endian buffer that holds the specified 64-bit floating point number. */ public static ByteBuf copyDouble(double value) { ByteBuf buf = buffer(8); buf.writeDouble(value); return buf; } /** * Create a new big-endian buffer that holds a sequence of the specified 64-bit floating point numbers. */ public static ByteBuf copyDouble(double... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 8); for (double v: values) { buffer.writeDouble(v); } return buffer; } /** * Return a unreleasable view on the given {@link ByteBuf} which will just ignore release and retain calls. */ public static ByteBuf unreleasableBuffer(ByteBuf buf) { return new UnreleasableByteBuf(buf); } /** * Wrap the given {@link ByteBuf}s in an unmodifiable {@link ByteBuf}. Be aware the returned {@link ByteBuf} will * not try to slice the given {@link ByteBuf}s to reduce GC-Pressure. * * @deprecated Use {@link #wrappedUnmodifiableBuffer(ByteBuf...)}. */ @Deprecated public static ByteBuf unmodifiableBuffer(ByteBuf... buffers) { return wrappedUnmodifiableBuffer(true, buffers); } /** * Wrap the given {@link ByteBuf}s in an unmodifiable {@link ByteBuf}. Be aware the returned {@link ByteBuf} will * not try to slice the given {@link ByteBuf}s to reduce GC-Pressure. * * The returned {@link ByteBuf} may wrap the provided array directly, and so should not be subsequently modified. */ public static ByteBuf wrappedUnmodifiableBuffer(ByteBuf... buffers) { return wrappedUnmodifiableBuffer(false, buffers); } private static ByteBuf wrappedUnmodifiableBuffer(boolean copy, ByteBuf... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return buffers[0].asReadOnly(); default: if (copy) { buffers = Arrays.copyOf(buffers, buffers.length, ByteBuf[].class); } return new FixedCompositeByteBuf(ALLOC, buffers); } } private Unpooled() { // Unused } }
netty/netty
buffer/src/main/java/io/netty/buffer/Unpooled.java
43
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import io.netty.util.internal.LongCounter; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import static io.netty.buffer.PoolChunk.isSubpage; import static java.lang.Math.max; abstract class PoolArena<T> implements PoolArenaMetric { private static final boolean HAS_UNSAFE = PlatformDependent.hasUnsafe(); enum SizeClass { Small, Normal } final PooledByteBufAllocator parent; final PoolSubpage<T>[] smallSubpagePools; private final PoolChunkList<T> q050; private final PoolChunkList<T> q025; private final PoolChunkList<T> q000; private final PoolChunkList<T> qInit; private final PoolChunkList<T> q075; private final PoolChunkList<T> q100; private final List<PoolChunkListMetric> chunkListMetrics; // Metrics for allocations and deallocations private long allocationsNormal; // We need to use the LongCounter here as this is not guarded via synchronized block. private final LongCounter allocationsSmall = PlatformDependent.newLongCounter(); private final LongCounter allocationsHuge = PlatformDependent.newLongCounter(); private final LongCounter activeBytesHuge = PlatformDependent.newLongCounter(); private long deallocationsSmall; private long deallocationsNormal; // We need to use the LongCounter here as this is not guarded via synchronized block. private final LongCounter deallocationsHuge = PlatformDependent.newLongCounter(); // Number of thread caches backed by this arena. final AtomicInteger numThreadCaches = new AtomicInteger(); // TODO: Test if adding padding helps under contention //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; private final ReentrantLock lock = new ReentrantLock(); final SizeClasses sizeClass; protected PoolArena(PooledByteBufAllocator parent, SizeClasses sizeClass) { assert null != sizeClass; this.parent = parent; this.sizeClass = sizeClass; smallSubpagePools = newSubpagePoolArray(sizeClass.nSubpages); for (int i = 0; i < smallSubpagePools.length; i ++) { smallSubpagePools[i] = newSubpagePoolHead(i); } q100 = new PoolChunkList<T>(this, null, 100, Integer.MAX_VALUE, sizeClass.chunkSize); q075 = new PoolChunkList<T>(this, q100, 75, 100, sizeClass.chunkSize); q050 = new PoolChunkList<T>(this, q075, 50, 100, sizeClass.chunkSize); q025 = new PoolChunkList<T>(this, q050, 25, 75, sizeClass.chunkSize); q000 = new PoolChunkList<T>(this, q025, 1, 50, sizeClass.chunkSize); qInit = new PoolChunkList<T>(this, q000, Integer.MIN_VALUE, 25, sizeClass.chunkSize); q100.prevList(q075); q075.prevList(q050); q050.prevList(q025); q025.prevList(q000); q000.prevList(null); qInit.prevList(qInit); List<PoolChunkListMetric> metrics = new ArrayList<PoolChunkListMetric>(6); metrics.add(qInit); metrics.add(q000); metrics.add(q025); metrics.add(q050); metrics.add(q075); metrics.add(q100); chunkListMetrics = Collections.unmodifiableList(metrics); } private PoolSubpage<T> newSubpagePoolHead(int index) { PoolSubpage<T> head = new PoolSubpage<T>(index); head.prev = head; head.next = head; return head; } @SuppressWarnings("unchecked") private PoolSubpage<T>[] newSubpagePoolArray(int size) { return new PoolSubpage[size]; } abstract boolean isDirect(); PooledByteBuf<T> allocate(PoolThreadCache cache, int reqCapacity, int maxCapacity) { PooledByteBuf<T> buf = newByteBuf(maxCapacity); allocate(cache, buf, reqCapacity); return buf; } private void allocate(PoolThreadCache cache, PooledByteBuf<T> buf, final int reqCapacity) { final int sizeIdx = sizeClass.size2SizeIdx(reqCapacity); if (sizeIdx <= sizeClass.smallMaxSizeIdx) { tcacheAllocateSmall(cache, buf, reqCapacity, sizeIdx); } else if (sizeIdx < sizeClass.nSizes) { tcacheAllocateNormal(cache, buf, reqCapacity, sizeIdx); } else { int normCapacity = sizeClass.directMemoryCacheAlignment > 0 ? sizeClass.normalizeSize(reqCapacity) : reqCapacity; // Huge allocations are never served via the cache so just call allocateHuge allocateHuge(buf, normCapacity); } } private void tcacheAllocateSmall(PoolThreadCache cache, PooledByteBuf<T> buf, final int reqCapacity, final int sizeIdx) { if (cache.allocateSmall(this, buf, reqCapacity, sizeIdx)) { // was able to allocate out of the cache so move on return; } /* * Synchronize on the head. This is needed as {@link PoolChunk#allocateSubpage(int)} and * {@link PoolChunk#free(long)} may modify the doubly linked list as well. */ final PoolSubpage<T> head = smallSubpagePools[sizeIdx]; final boolean needsNormalAllocation; head.lock(); try { final PoolSubpage<T> s = head.next; needsNormalAllocation = s == head; if (!needsNormalAllocation) { assert s.doNotDestroy && s.elemSize == sizeClass.sizeIdx2size(sizeIdx) : "doNotDestroy=" + s.doNotDestroy + ", elemSize=" + s.elemSize + ", sizeIdx=" + sizeIdx; long handle = s.allocate(); assert handle >= 0; s.chunk.initBufWithSubpage(buf, null, handle, reqCapacity, cache); } } finally { head.unlock(); } if (needsNormalAllocation) { lock(); try { allocateNormal(buf, reqCapacity, sizeIdx, cache); } finally { unlock(); } } incSmallAllocation(); } private void tcacheAllocateNormal(PoolThreadCache cache, PooledByteBuf<T> buf, final int reqCapacity, final int sizeIdx) { if (cache.allocateNormal(this, buf, reqCapacity, sizeIdx)) { // was able to allocate out of the cache so move on return; } lock(); try { allocateNormal(buf, reqCapacity, sizeIdx, cache); ++allocationsNormal; } finally { unlock(); } } private void allocateNormal(PooledByteBuf<T> buf, int reqCapacity, int sizeIdx, PoolThreadCache threadCache) { assert lock.isHeldByCurrentThread(); if (q050.allocate(buf, reqCapacity, sizeIdx, threadCache) || q025.allocate(buf, reqCapacity, sizeIdx, threadCache) || q000.allocate(buf, reqCapacity, sizeIdx, threadCache) || qInit.allocate(buf, reqCapacity, sizeIdx, threadCache) || q075.allocate(buf, reqCapacity, sizeIdx, threadCache)) { return; } // Add a new chunk. PoolChunk<T> c = newChunk(sizeClass.pageSize, sizeClass.nPSizes, sizeClass.pageShifts, sizeClass.chunkSize); boolean success = c.allocate(buf, reqCapacity, sizeIdx, threadCache); assert success; qInit.add(c); } private void incSmallAllocation() { allocationsSmall.increment(); } private void allocateHuge(PooledByteBuf<T> buf, int reqCapacity) { PoolChunk<T> chunk = newUnpooledChunk(reqCapacity); activeBytesHuge.add(chunk.chunkSize()); buf.initUnpooled(chunk, reqCapacity); allocationsHuge.increment(); } void free(PoolChunk<T> chunk, ByteBuffer nioBuffer, long handle, int normCapacity, PoolThreadCache cache) { chunk.decrementPinnedMemory(normCapacity); if (chunk.unpooled) { int size = chunk.chunkSize(); destroyChunk(chunk); activeBytesHuge.add(-size); deallocationsHuge.increment(); } else { SizeClass sizeClass = sizeClass(handle); if (cache != null && cache.add(this, chunk, nioBuffer, handle, normCapacity, sizeClass)) { // cached so not free it. return; } freeChunk(chunk, handle, normCapacity, sizeClass, nioBuffer, false); } } private static SizeClass sizeClass(long handle) { return isSubpage(handle) ? SizeClass.Small : SizeClass.Normal; } void freeChunk(PoolChunk<T> chunk, long handle, int normCapacity, SizeClass sizeClass, ByteBuffer nioBuffer, boolean finalizer) { final boolean destroyChunk; lock(); try { // We only call this if freeChunk is not called because of the PoolThreadCache finalizer as otherwise this // may fail due lazy class-loading in for example tomcat. if (!finalizer) { switch (sizeClass) { case Normal: ++deallocationsNormal; break; case Small: ++deallocationsSmall; break; default: throw new Error(); } } destroyChunk = !chunk.parent.free(chunk, handle, normCapacity, nioBuffer); } finally { unlock(); } if (destroyChunk) { // destroyChunk not need to be called while holding the synchronized lock. destroyChunk(chunk); } } void reallocate(PooledByteBuf<T> buf, int newCapacity) { assert newCapacity >= 0 && newCapacity <= buf.maxCapacity(); final int oldCapacity; final PoolChunk<T> oldChunk; final ByteBuffer oldNioBuffer; final long oldHandle; final T oldMemory; final int oldOffset; final int oldMaxLength; final PoolThreadCache oldCache; // We synchronize on the ByteBuf itself to ensure there is no "concurrent" reallocations for the same buffer. // We do this to ensure the ByteBuf internal fields that are used to allocate / free are not accessed // concurrently. This is important as otherwise we might end up corrupting our internal state of our data // structures. // // Also note we don't use a Lock here but just synchronized even tho this might seem like a bad choice for Loom. // This is done to minimize the overhead per ByteBuf. The time this would block another thread should be // relative small and so not be a problem for Loom. // See https://github.com/netty/netty/issues/13467 synchronized (buf) { oldCapacity = buf.length; if (oldCapacity == newCapacity) { return; } oldChunk = buf.chunk; oldNioBuffer = buf.tmpNioBuf; oldHandle = buf.handle; oldMemory = buf.memory; oldOffset = buf.offset; oldMaxLength = buf.maxLength; oldCache = buf.cache; // This does not touch buf's reader/writer indices allocate(parent.threadCache(), buf, newCapacity); } int bytesToCopy; if (newCapacity > oldCapacity) { bytesToCopy = oldCapacity; } else { buf.trimIndicesToCapacity(newCapacity); bytesToCopy = newCapacity; } memoryCopy(oldMemory, oldOffset, buf, bytesToCopy); free(oldChunk, oldNioBuffer, oldHandle, oldMaxLength, oldCache); } @Override public int numThreadCaches() { return numThreadCaches.get(); } @Override public int numTinySubpages() { return 0; } @Override public int numSmallSubpages() { return smallSubpagePools.length; } @Override public int numChunkLists() { return chunkListMetrics.size(); } @Override public List<PoolSubpageMetric> tinySubpages() { return Collections.emptyList(); } @Override public List<PoolSubpageMetric> smallSubpages() { return subPageMetricList(smallSubpagePools); } @Override public List<PoolChunkListMetric> chunkLists() { return chunkListMetrics; } private static List<PoolSubpageMetric> subPageMetricList(PoolSubpage<?>[] pages) { List<PoolSubpageMetric> metrics = new ArrayList<PoolSubpageMetric>(); for (PoolSubpage<?> head : pages) { if (head.next == head) { continue; } PoolSubpage<?> s = head.next; for (;;) { metrics.add(s); s = s.next; if (s == head) { break; } } } return metrics; } @Override public long numAllocations() { final long allocsNormal; lock(); try { allocsNormal = allocationsNormal; } finally { unlock(); } return allocationsSmall.value() + allocsNormal + allocationsHuge.value(); } @Override public long numTinyAllocations() { return 0; } @Override public long numSmallAllocations() { return allocationsSmall.value(); } @Override public long numNormalAllocations() { lock(); try { return allocationsNormal; } finally { unlock(); } } @Override public long numDeallocations() { final long deallocs; lock(); try { deallocs = deallocationsSmall + deallocationsNormal; } finally { unlock(); } return deallocs + deallocationsHuge.value(); } @Override public long numTinyDeallocations() { return 0; } @Override public long numSmallDeallocations() { lock(); try { return deallocationsSmall; } finally { unlock(); } } @Override public long numNormalDeallocations() { lock(); try { return deallocationsNormal; } finally { unlock(); } } @Override public long numHugeAllocations() { return allocationsHuge.value(); } @Override public long numHugeDeallocations() { return deallocationsHuge.value(); } @Override public long numActiveAllocations() { long val = allocationsSmall.value() + allocationsHuge.value() - deallocationsHuge.value(); lock(); try { val += allocationsNormal - (deallocationsSmall + deallocationsNormal); } finally { unlock(); } return max(val, 0); } @Override public long numActiveTinyAllocations() { return 0; } @Override public long numActiveSmallAllocations() { return max(numSmallAllocations() - numSmallDeallocations(), 0); } @Override public long numActiveNormalAllocations() { final long val; lock(); try { val = allocationsNormal - deallocationsNormal; } finally { unlock(); } return max(val, 0); } @Override public long numActiveHugeAllocations() { return max(numHugeAllocations() - numHugeDeallocations(), 0); } @Override public long numActiveBytes() { long val = activeBytesHuge.value(); lock(); try { for (int i = 0; i < chunkListMetrics.size(); i++) { for (PoolChunkMetric m: chunkListMetrics.get(i)) { val += m.chunkSize(); } } } finally { unlock(); } return max(0, val); } /** * Return an estimate of the number of bytes that are currently pinned to buffer instances, by the arena. The * pinned memory is not accessible for use by any other allocation, until the buffers using have all been released. */ public long numPinnedBytes() { long val = activeBytesHuge.value(); // Huge chunks are exact-sized for the buffers they were allocated to. for (int i = 0; i < chunkListMetrics.size(); i++) { for (PoolChunkMetric m: chunkListMetrics.get(i)) { val += ((PoolChunk<?>) m).pinnedBytes(); } } return max(0, val); } protected abstract PoolChunk<T> newChunk(int pageSize, int maxPageIdx, int pageShifts, int chunkSize); protected abstract PoolChunk<T> newUnpooledChunk(int capacity); protected abstract PooledByteBuf<T> newByteBuf(int maxCapacity); protected abstract void memoryCopy(T src, int srcOffset, PooledByteBuf<T> dst, int length); protected abstract void destroyChunk(PoolChunk<T> chunk); @Override public String toString() { lock(); try { StringBuilder buf = new StringBuilder() .append("Chunk(s) at 0~25%:") .append(StringUtil.NEWLINE) .append(qInit) .append(StringUtil.NEWLINE) .append("Chunk(s) at 0~50%:") .append(StringUtil.NEWLINE) .append(q000) .append(StringUtil.NEWLINE) .append("Chunk(s) at 25~75%:") .append(StringUtil.NEWLINE) .append(q025) .append(StringUtil.NEWLINE) .append("Chunk(s) at 50~100%:") .append(StringUtil.NEWLINE) .append(q050) .append(StringUtil.NEWLINE) .append("Chunk(s) at 75~100%:") .append(StringUtil.NEWLINE) .append(q075) .append(StringUtil.NEWLINE) .append("Chunk(s) at 100%:") .append(StringUtil.NEWLINE) .append(q100) .append(StringUtil.NEWLINE) .append("small subpages:"); appendPoolSubPages(buf, smallSubpagePools); buf.append(StringUtil.NEWLINE); return buf.toString(); } finally { unlock(); } } private static void appendPoolSubPages(StringBuilder buf, PoolSubpage<?>[] subpages) { for (int i = 0; i < subpages.length; i ++) { PoolSubpage<?> head = subpages[i]; if (head.next == head || head.next == null) { continue; } buf.append(StringUtil.NEWLINE) .append(i) .append(": "); PoolSubpage<?> s = head.next; while (s != null) { buf.append(s); s = s.next; if (s == head) { break; } } } } @Override protected final void finalize() throws Throwable { try { super.finalize(); } finally { destroyPoolSubPages(smallSubpagePools); destroyPoolChunkLists(qInit, q000, q025, q050, q075, q100); } } private static void destroyPoolSubPages(PoolSubpage<?>[] pages) { for (PoolSubpage<?> page : pages) { page.destroy(); } } private void destroyPoolChunkLists(PoolChunkList<T>... chunkLists) { for (PoolChunkList<T> chunkList: chunkLists) { chunkList.destroy(this); } } static final class HeapArena extends PoolArena<byte[]> { HeapArena(PooledByteBufAllocator parent, SizeClasses sizeClass) { super(parent, sizeClass); } private static byte[] newByteArray(int size) { return PlatformDependent.allocateUninitializedArray(size); } @Override boolean isDirect() { return false; } @Override protected PoolChunk<byte[]> newChunk(int pageSize, int maxPageIdx, int pageShifts, int chunkSize) { return new PoolChunk<byte[]>( this, null, newByteArray(chunkSize), pageSize, pageShifts, chunkSize, maxPageIdx); } @Override protected PoolChunk<byte[]> newUnpooledChunk(int capacity) { return new PoolChunk<byte[]>(this, null, newByteArray(capacity), capacity); } @Override protected void destroyChunk(PoolChunk<byte[]> chunk) { // Rely on GC. } @Override protected PooledByteBuf<byte[]> newByteBuf(int maxCapacity) { return HAS_UNSAFE ? PooledUnsafeHeapByteBuf.newUnsafeInstance(maxCapacity) : PooledHeapByteBuf.newInstance(maxCapacity); } @Override protected void memoryCopy(byte[] src, int srcOffset, PooledByteBuf<byte[]> dst, int length) { if (length == 0) { return; } System.arraycopy(src, srcOffset, dst.memory, dst.offset, length); } } static final class DirectArena extends PoolArena<ByteBuffer> { DirectArena(PooledByteBufAllocator parent, SizeClasses sizeClass) { super(parent, sizeClass); } @Override boolean isDirect() { return true; } @Override protected PoolChunk<ByteBuffer> newChunk(int pageSize, int maxPageIdx, int pageShifts, int chunkSize) { if (sizeClass.directMemoryCacheAlignment == 0) { ByteBuffer memory = allocateDirect(chunkSize); return new PoolChunk<ByteBuffer>(this, memory, memory, pageSize, pageShifts, chunkSize, maxPageIdx); } final ByteBuffer base = allocateDirect(chunkSize + sizeClass.directMemoryCacheAlignment); final ByteBuffer memory = PlatformDependent.alignDirectBuffer(base, sizeClass.directMemoryCacheAlignment); return new PoolChunk<ByteBuffer>(this, base, memory, pageSize, pageShifts, chunkSize, maxPageIdx); } @Override protected PoolChunk<ByteBuffer> newUnpooledChunk(int capacity) { if (sizeClass.directMemoryCacheAlignment == 0) { ByteBuffer memory = allocateDirect(capacity); return new PoolChunk<ByteBuffer>(this, memory, memory, capacity); } final ByteBuffer base = allocateDirect(capacity + sizeClass.directMemoryCacheAlignment); final ByteBuffer memory = PlatformDependent.alignDirectBuffer(base, sizeClass.directMemoryCacheAlignment); return new PoolChunk<ByteBuffer>(this, base, memory, capacity); } private static ByteBuffer allocateDirect(int capacity) { return PlatformDependent.useDirectBufferNoCleaner() ? PlatformDependent.allocateDirectNoCleaner(capacity) : ByteBuffer.allocateDirect(capacity); } @Override protected void destroyChunk(PoolChunk<ByteBuffer> chunk) { if (PlatformDependent.useDirectBufferNoCleaner()) { PlatformDependent.freeDirectNoCleaner((ByteBuffer) chunk.base); } else { PlatformDependent.freeDirectBuffer((ByteBuffer) chunk.base); } } @Override protected PooledByteBuf<ByteBuffer> newByteBuf(int maxCapacity) { if (HAS_UNSAFE) { return PooledUnsafeDirectByteBuf.newInstance(maxCapacity); } else { return PooledDirectByteBuf.newInstance(maxCapacity); } } @Override protected void memoryCopy(ByteBuffer src, int srcOffset, PooledByteBuf<ByteBuffer> dstBuf, int length) { if (length == 0) { return; } if (HAS_UNSAFE) { PlatformDependent.copyMemory( PlatformDependent.directBufferAddress(src) + srcOffset, PlatformDependent.directBufferAddress(dstBuf.memory) + dstBuf.offset, length); } else { // We must duplicate the NIO buffers because they may be accessed by other Netty buffers. src = src.duplicate(); ByteBuffer dst = dstBuf.internalNioBuffer(); src.position(srcOffset).limit(srcOffset + length); dst.position(dstBuf.offset); dst.put(src); } } } void lock() { lock.lock(); } void unlock() { lock.unlock(); } @Override public int sizeIdx2size(int sizeIdx) { return sizeClass.sizeIdx2size(sizeIdx); } @Override public int sizeIdx2sizeCompute(int sizeIdx) { return sizeClass.sizeIdx2sizeCompute(sizeIdx); } @Override public long pageIdx2size(int pageIdx) { return sizeClass.pageIdx2size(pageIdx); } @Override public long pageIdx2sizeCompute(int pageIdx) { return sizeClass.pageIdx2sizeCompute(pageIdx); } @Override public int size2SizeIdx(int size) { return sizeClass.size2SizeIdx(size); } @Override public int pages2pageIdx(int pages) { return sizeClass.pages2pageIdx(pages); } @Override public int pages2pageIdxFloor(int pages) { return sizeClass.pages2pageIdxFloor(pages); } @Override public int normalizeSize(int size) { return sizeClass.normalizeSize(size); } }
netty/netty
buffer/src/main/java/io/netty/buffer/PoolArena.java
44
// Companion Code to the paper "Generative Trees: Adversarial and Copycat" by R. Nock and M. // Guillame-Bert, in ICML'22 import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Generator_Tree *****/ class Generator_Tree implements Debuggable { public static boolean IMPUTATION_AT_MAXIMUM_LIKELIHOOD = true; public static int DISPLAY_TREE_TYPE = 1; // 1: does not display leaves support, just list leaves int name, depth; Generator_Node root; // root of the tree HashSet<Generator_Node> leaves; // list of leaves of the tree (potential growth here) Boost myBoost; int max_depth; int number_nodes; // includes leaves double entropy; // entropy at the leaves Vector<Histogram> gt_histograms; public static void SAVE_GENERATOR_TREE(Generator_Tree gt, String nameSave, String saveString) { // saves a generator in a proper format int i; FileWriter f = null; try { f = new FileWriter(nameSave); f.write(saveString); f.write("\n// Tree description (do not change)\n\n"); if (gt.root == null) { f.write(Dataset.KEY_NODES + "\n"); f.write("null\n"); } else { // saving tree architecture f.write(Dataset.KEY_NODES + "\n"); gt.root.recursive_write_nodes(f); // saving arcs features f.write("\n" + Dataset.KEY_ARCS + "\n"); gt.root.recursive_write_arcs(f); } f.close(); } catch (IOException e) { Dataset.perror("Generator_Tree.class :: Saving results error in file " + nameSave); } } Generator_Tree(int nn, Boost bb, int maxs) { name = nn; root = null; myBoost = bb; max_depth = maxs; depth = -1; // Generator empty gt_histograms = null; } public void compute_generator_histograms() { gt_histograms = new Vector<>(); Vector<Example> ex_for_histogram = generate_sample(Dataset.NUMBER_GENERATED_EXAMPLES_DEFAULT_HISTOGRAMS); Histogram h; int i; boolean ok; for (i = 0; i < myBoost.myDomain.myDS.number_domain_features(); i++) { h = myBoost.myDomain.myDS.from_histogram(i); ok = h.fill_histogram(ex_for_histogram, true); if (!ok) Dataset.perror( "Dataset.class :: not a single domain example with non UNKNOWN feature value for" + " feature #" + i); gt_histograms.addElement(h); } } public Generator_Tree surrogate() { boolean tr; Generator_Tree gt = new Generator_Tree(-1, myBoost, max_depth); gt.init(); if (leaves.size() > 1) { tr = gt.leaves.remove(gt.root); if (!tr) Dataset.perror("Generator_Tree.class :: only one leaf but root not inside"); } gt.root.recursive_copy(root, null); gt.depth = depth; gt.number_nodes = number_nodes; gt.entropy = entropy; int i; gt.gt_histograms = new Vector<>(); for (i = 0; i < myBoost.myDomain.myDS.number_domain_features(); i++) gt.gt_histograms.addElement(Histogram.copyOf(gt_histograms.elementAt(i))); return gt; } public Generator_Node find_leaf(Generator_Node model_leaf) { // find in this the *leaf* whose name matches model.name Generator_Node v = null, cur; Iterator<Generator_Node> it = leaves.iterator(); while (it.hasNext()) { cur = it.next(); if ((cur.name == model_leaf.name) && (v != null)) Dataset.perror("Generator_Tree.class :: find_leaf found >1 matching leaves"); else if (cur.name == model_leaf.name) v = cur; } return v; } public Vector<Generator_Node> all_leaves_that_could_generate(Example e) { Vector<Generator_Node> ret = new Vector<Generator_Node>(); Generator_Node gn; Iterator<Generator_Node> it = leaves.iterator(); while (it.hasNext()) { gn = it.next(); if (Generator_Node.LEAF_COULD_GENERATE_EXAMPLE(gn, e)) ret.addElement(gn); } if (ret.size() == 0) Dataset.perror("Generator_Tree.class :: no leaf to generate example " + e); return ret; } public void impute_all_values_from_one_leaf(Example e) { Vector<Generator_Node> dumgn = all_leaves_that_could_generate(e); double[] all_ps = new double[dumgn.size()]; int i, j, index, nmax, index_chosen, count; double tot_weight = 0.0, dindex; for (i = 0; i < dumgn.size(); i++) { all_ps[i] = dumgn.elementAt(i).p_node; tot_weight += all_ps[i]; } if (Statistics.APPROXIMATELY_EQUAL(tot_weight, 0.0, EPS4)) Dataset.perror( "Generator_Tree.class :: sum of generating nodes p_node = " + tot_weight + " approx 0.0"); for (i = 0; i < dumgn.size(); i++) all_ps[i] /= tot_weight; double cp = all_ps[0]; double p = Algorithm.R.nextDouble(); boolean[] is_max = new boolean[dumgn.size()]; if (Generator_Tree.IMPUTATION_AT_MAXIMUM_LIKELIHOOD) { for (i = 0; i < dumgn.size(); i++) all_ps[i] /= dumgn.elementAt(i).node_volume(); index = 0; for (i = 0; i < dumgn.size(); i++) if (all_ps[i] >= all_ps[index]) index = i; // picks a leaf at random among *all* maxes nmax = 0; count = -1; for (i = 0; i < dumgn.size(); i++) if (all_ps[i] == all_ps[index]) { is_max[i] = true; nmax++; } else is_max[i] = false; index_chosen = Math.abs(Algorithm.R.nextInt()) % nmax; i = 0; do { if (all_ps[i] == all_ps[index]) count++; if (count < index_chosen) i++; } while (count < index_chosen); if (all_ps[i] != all_ps[index]) Dataset.perror("Genrator_Tree.class :: not a max chosen in index " + i); } else { i = 0; while (p > cp) { i++; cp += all_ps[i]; } } Feature f; if (dumgn.elementAt(i).all_features_domain == null) Dataset.perror( "Generator_Node.class :: GT leaf " + dumgn.elementAt(i).name + " has all_features_domain == null"); Vector<Feature> v = dumgn.elementAt(i).all_features_domain; // contains all domains used to impute e; for (j = 0; j < e.typed_features.size(); j++) if (Unknown_Feature_Value.IS_UNKNOWN(e.typed_features.elementAt(j))) { f = v.elementAt(j); if (Feature.IS_NOMINAL(f.type)) { index = (Math.abs(Algorithm.R.nextInt())) % f.modalities.size(); e.typed_features.setElementAt(new String(f.modalities.elementAt(index)), j); } else if (Feature.IS_INTEGER(f.type)) { index = (Math.abs(Algorithm.R.nextInt())) % (f.imax - f.imin + 1); e.typed_features.setElementAt(new Integer(f.imin + index), j); } else if (Feature.IS_CONTINUOUS(f.type)) { dindex = (Algorithm.R.nextDouble()) * (f.dmax - f.dmin); e.typed_features.setElementAt(new Double(f.dmin + dindex), j); } else Dataset.perror("Generator_Tree.class :: Feature " + f + "'s type not known"); } } public Object impute_value(Example e, int feature_index) { // returns a possible imputed value given the gt for feature feature_index in e if (!Example.FEATURE_IS_UNKNOWN(e, feature_index)) Dataset.perror( "Generator_Tree.class :: Example (" + e + ")[" + feature_index + "] != " + Unknown_Feature_Value.S_UNKNOWN); Vector<Generator_Node> dumgn = all_leaves_that_could_generate(e); double[] all_ps = new double[dumgn.size()]; int i, j, index; double tot_weight = 0.0, dindex; for (i = 0; i < dumgn.size(); i++) { all_ps[i] = dumgn.elementAt(i).p_node; tot_weight += all_ps[i]; } if (Statistics.APPROXIMATELY_EQUAL(tot_weight, 0.0, EPS4)) Dataset.perror( "Generator_Tree.class :: sum of generating nodes p_node = " + tot_weight + " approx 0.0"); for (i = 0; i < dumgn.size(); i++) all_ps[i] /= tot_weight; double cp = all_ps[0]; double p = Algorithm.R.nextDouble(); i = 0; while (p > cp) { i++; cp += all_ps[i]; } if (dumgn.elementAt(i).all_features_domain == null) Dataset.perror( "Generator_Node.class :: GT leaf " + dumgn.elementAt(i).name + " has all_features_domain == null"); Vector<Feature> v = dumgn.elementAt(i).all_features_domain; Feature f = v.elementAt(feature_index); if (Feature.IS_NOMINAL(f.type)) { index = (Math.abs(Algorithm.R.nextInt())) % f.modalities.size(); return new String(f.modalities.elementAt(index)); } else if (Feature.IS_INTEGER(f.type)) { index = (Math.abs(Algorithm.R.nextInt())) % (f.imax - f.imin + 1); return new Integer(f.imin + index); } else if (Feature.IS_CONTINUOUS(f.type)) { dindex = (Algorithm.R.nextDouble()) * (f.dmax - f.dmin); return new Double(f.dmin + dindex); } else Dataset.perror("Generator_Tree.class :: Feature " + f + "'s type not known"); return null; } public double[] probability_vector(Example e, Histogram domain_histo, int feature_index) { // returns P[F|e,h] where F = feature at feature_index, h = domain_histo provides a binning for // continuous / integers if (!myBoost.myDomain.myDS.domain_feature(feature_index).name.equals(domain_histo.name)) Dataset.perror( "Generator_Tree.class :: name mismatch to compute probability_vector (" + myBoost.myDomain.myDS.domain_feature(feature_index).name + " != " + domain_histo.name + ")"); int i, j; double[] ret = new double[domain_histo.histogram_features.size()]; double[] fprop; double[] all_ps; double tot_weight = 0.0; Vector<Generator_Node> dumgn = all_leaves_that_could_generate(e); all_ps = new double[dumgn.size()]; for (i = 0; i < dumgn.size(); i++) { all_ps[i] = dumgn.elementAt(i).p_node; tot_weight += all_ps[i]; } if (Statistics.APPROXIMATELY_EQUAL(tot_weight, 0.0, EPS4)) Dataset.perror( "Generator_Tree.class :: sum of generating nodes p_node = " + tot_weight + " approx 0.0"); for (i = 0; i < dumgn.size(); i++) all_ps[i] /= tot_weight; Vector<Feature> dumf = new Vector<>(); for (i = 0; i < dumgn.size(); i++) dumf.addElement( Generator_Node.ALL_FEATURES_DOMAINS_AT_SAMPLING_NODE(this, dumgn.elementAt(i)) .elementAt(feature_index)); for (i = 0; i < dumgn.size(); i++) { fprop = domain_histo.normalized_domain_intersection_with(dumf.elementAt(i)); for (j = 0; j < fprop.length; j++) ret[j] += (all_ps[i] * fprop[j]); } return ret; } public void update_generator_tree( Generator_Node leaf, Generator_Node[] created_leaves, Discriminator_Tree dt) { // used e.g. in split_leaf to update the GT after a split has been found at leaf leaf and the // new leaves are in created_leaves // multi_p must have been computed if ((leaf.multi_p == null) || (!Statistics.APPROXIMATELY_EQUAL(leaf.multi_p[0] + leaf.multi_p[1], 1.0, EPS2))) Dataset.perror( "Generator_Tree.class :: leaf to be split has multi_p not yet computed or badly" + " computed"); boolean tr; int i, base_depth = -1; // update leaves set + p_nodes leaf.is_leaf = false; leaf.all_features_domain = null; tr = leaves.remove(leaf); if (!tr) Dataset.perror("Generator_Tree.class :: leaf not found"); for (i = 0; i < created_leaves.length; i++) { // check depth if (i == 0) base_depth = created_leaves[i].depth; else if (base_depth != created_leaves[i].depth) Dataset.perror("Generator_Tree.class :: non-consistant depth in new nodes"); tr = leaves.add(created_leaves[i]); if (!tr) Dataset.perror("Generator_Tree.class :: duplicated leaf found"); created_leaves[i].p_node = leaf.p_node * leaf.multi_p[i]; created_leaves[i].compute_all_features_domain(); } // update depth, number_nodes if (base_depth == -1) Dataset.perror("Generator_Tree.class :: no base depth computed"); if (depth < base_depth) depth = base_depth; number_nodes += created_leaves.length; } public Generator_Node get_leaf_to_be_split( Discriminator_Tree dt, Discriminator_Node node_just_split) { // WARNING: make sure names of nodes are 1-1 between DT and GT // find the corresponding leaf to split in GT and returns it if (node_just_split.is_leaf) Dataset.perror( "Generator_Tree.class :: copycat DT node is a leaf, while it should be a stump"); Iterator<Generator_Node> it = leaves.iterator(); Generator_Node target_gt = null, candidate_gt; boolean found = false; while ((it.hasNext()) && (!found)) { candidate_gt = it.next(); if (candidate_gt.name == node_just_split.name) { target_gt = candidate_gt; found = true; } } if (!found) Dataset.perror( "Generator_Tree.class :: copycat does not find node #" + node_just_split.name + " in the leaves of " + this); return target_gt; } public String one_step_grow_copycat( Discriminator_Tree dt, Discriminator_Node node_just_split, Generator_Node leaf_to_be_split) { // WARNING: make sure names of nodes are 1-1 between DT and GT // find the corresponding leaf to split in GT if (node_just_split.is_leaf) Dataset.perror( "Generator_Tree.class :: copycat DT node is a leaf, while it should be a stump"); int findex; Vector<Feature> cv; Feature gt_leaf_feature; Generator_Node[] created_leaves; double p_final; Generator_Node target_gt = leaf_to_be_split; // makes sure that both leaves attached to node_just_split have positive examples reaching them if ((!Boost.AUTHORISE_REAL_PURE_LEAVES) && ((node_just_split.left_child.w_real == 0.0) || (node_just_split.right_child.w_real == 0.0))) Dataset.perror( "Generator_Tree.class :: copycat stump " + node_just_split + " in tree " + dt + " has at least one real-pure leaf"); // test features at the nodes of the stump at node_just_split if ((node_just_split.support_at_classification_node.size() != myBoost.myDomain.myDS.number_domain_features()) || (node_just_split.left_child.support_at_classification_node.size() != myBoost.myDomain.myDS.number_domain_features()) || (node_just_split.right_child.support_at_classification_node.size() != myBoost.myDomain.myDS.number_domain_features())) Dataset.perror( "Generator_Tree.class :: copycat stump has at non-valid feature domain vector sizes"); findex = node_just_split.feature_node_index; gt_leaf_feature = Generator_Node.FEATURE_DOMAIN_AT_SAMPLING_NODE(this, target_gt, findex); cv = new Vector<>(); cv.addElement( (Feature) node_just_split.left_child.support_at_classification_node.elementAt(findex)); cv.addElement( (Feature) node_just_split.right_child.support_at_classification_node.elementAt(findex)); p_final = node_just_split.right_child.w_real / (node_just_split.left_child.w_real + node_just_split.right_child.w_real); created_leaves = target_gt.split(findex, gt_leaf_feature, p_final, cv); // changing names eventually for the new leaves to match the DT's names created_leaves[0].name = node_just_split.left_child.name; created_leaves[1].name = node_just_split.right_child.name; root.check_names(new HashSet<Integer>()); update_generator_tree(target_gt, created_leaves, dt); gt_leaf_feature = null; cv = null; created_leaves = null; return Algorithm.GT_SPLIT_OK; } public void check_recursive(Generator_Node gn) { int i; if (!gn.is_leaf) { if ((gn.children_arcs == null) || (gn.children_arcs.length < 2)) Dataset.perror("Generator_Tree.class :: " + gn + " not a leaf but without children"); for (i = 0; i < gn.children_arcs.length; i++) check_recursive(gn.children_arcs[i].end_node); } else { if (!leaves.contains(gn)) Dataset.perror("Generator_Tree.class :: " + gn + " a leaf but not in *leaves*"); } } public void init() { number_nodes = 1; boolean tr; root = new Generator_Node(this, null, number_nodes, 0, -1); root.compute_all_features_domain(); depth = 0; leaves = new HashSet<>(); tr = leaves.add(root); if (!tr) Dataset.perror("Generator_Tree.class :: adding root failed"); } public boolean has_root(Generator_Node gn) { // simple implementation if ((gn.myParentGenerator_Node_children_number == -1) && (gn.name != 1)) Dataset.perror("Generator_Tree.class :: bad root IDs"); if (gn.myParentGenerator_Node_children_number == -1) return true; return false; } public String toString() { boolean leaf_as_well = true, compute_support_for_leaf = true; if (Generator_Tree.DISPLAY_TREE_TYPE == 1) leaf_as_well = compute_support_for_leaf = false; int i, j; String v = "(name = #" + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")"; boolean stop = false; Generator_Node n = root; Vector<Generator_Node> cur_nodes = new Vector<>(); cur_nodes.addElement(n); Vector<Generator_Node> next_nodes; Iterator it; v += root.display(new HashSet()); if (!leaf_as_well) { v += "\nSampling Leaves: "; it = leaves.iterator(); while (it.hasNext()) { n = (Generator_Node) it.next(); v += "(#" + n.name + ":" + n.depth + ":" + DF4.format(n.p_node) + ") "; } v += "\n"; } return v; } public Generator_Node sample_leaf() { return sample_leaf(root); } public Generator_Node sample_leaf(Generator_Node cn) { // same as sample_leaf but starts from cn; double p, cp; int i; while (!cn.is_leaf) { cp = cn.multi_p[0]; p = Algorithm.R.nextDouble(); i = 0; while (p > cp) { i++; cp += cn.multi_p[i]; } if (i >= cn.children_arcs.length) Dataset.perror( "Generator_Tree.class :: children index " + i + " >= max = " + cn.children_arcs.length); cn = cn.children_arcs[i].end_node; } return cn; } public Vector sample_leaf_with_density() { double p, cp, densval = 1.0; Generator_Node cn = root; Vector ret = new Vector(); int i; while (!cn.is_leaf) { cp = cn.multi_p[0]; p = Algorithm.R.nextDouble(); i = 0; while (p > cp) { i++; cp += cn.multi_p[i]; } if (i >= cn.children_arcs.length) Dataset.perror( "Generator_Tree.class :: children index " + i + " >= max = " + cn.children_arcs.length); densval *= cn.multi_p[i]; cn = cn.children_arcs[i].end_node; } ret.addElement(cn); ret.addElement(new Double(densval)); return ret; } public Vector<Example> generate_sample(int nex) { int i; Vector<Example> set = new Vector<>(); Generator_Node sample_leaf; Example e; for (i = 0; i < nex; i++) { sample_leaf = sample_leaf(); e = sample_leaf.one_example(i); if ((!SAVE_TIME) || (Math.abs(Algorithm.R.nextInt()) % 1000 == 0)) { // makes a random "quality" check on generated examples if (!Generator_Node.LEAF_COULD_GENERATE_EXAMPLE(sample_leaf, e)) Dataset.perror("Generator_Tree.class :: leaf " + sample_leaf + " cannot generate " + e); } set.addElement(e); } return set; } public void replace_sample(Vector<Example> generated_examples, Generator_Node gn) { if (gn.is_leaf) Dataset.perror("Generator_Tree.class :: node " + gn + " should not be a leaf"); int i, findex; Vector<Example> set = new Vector<>(); Generator_Node sample_leaf; Example e; for (i = 0; i < generated_examples.size(); i++) { e = generated_examples.elementAt(i); if (e.generating_leaf.name == gn.name) { // We replace the feature of the example now at the split in gn findex = gn.feature_node_index; sample_leaf = sample_leaf(gn); sample_leaf.resample_feature_in_generated_example(e, findex); } } } public Vector<Example> generate_sample_with_density(int nex) { int i; Vector<Example> set = new Vector<>(); Vector bundle; Generator_Node sample_leaf; Example e; for (i = 0; i < nex; i++) { bundle = sample_leaf_with_density(); sample_leaf = (Generator_Node) bundle.elementAt(0); e = sample_leaf.one_example(i); e.local_density = ((Double) bundle.elementAt(1)).doubleValue(); if (!Generator_Node.LEAF_COULD_GENERATE_EXAMPLE(sample_leaf, e)) Dataset.perror("Generator_Tree.class :: leaf " + sample_leaf + " cannot generate " + e); set.addElement(e); } return set; } }
google-research/google-research
generative_trees/src/Generator_Tree.java
45
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.InternalThreadLocalMap; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.PlatformDependent; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import static io.netty.util.internal.MathUtil.isOutOfBounds; import static io.netty.util.internal.ObjectUtil.checkNotNull; /** * A string which has been encoded into a character encoding whose character always takes a single byte, similarly to * ASCII. It internally keeps its content in a byte array unlike {@link String}, which uses a character array, for * reduced memory footprint and faster data transfer from/to byte-based data structures such as a byte array and * {@link ByteBuffer}. It is often used in conjunction with {@code Headers} that require a {@link CharSequence}. * <p> * This class was designed to provide an immutable array of bytes, and caches some internal state based upon the value * of this array. However underlying access to this byte array is provided via not copying the array on construction or * {@link #array()}. If any changes are made to the underlying byte array it is the user's responsibility to call * {@link #arrayChanged()} so the state of this class can be reset. */ public final class AsciiString implements CharSequence, Comparable<CharSequence> { public static final AsciiString EMPTY_STRING = cached(""); private static final char MAX_CHAR_VALUE = 255; public static final int INDEX_NOT_FOUND = -1; /** * If this value is modified outside the constructor then call {@link #arrayChanged()}. */ private final byte[] value; /** * Offset into {@link #value} that all operations should use when acting upon {@link #value}. */ private final int offset; /** * Length in bytes for {@link #value} that we care about. This is independent from {@code value.length} * because we may be looking at a subsection of the array. */ private final int length; /** * The hash code is cached after it is first computed. It can be reset with {@link #arrayChanged()}. */ private int hash; /** * Used to cache the {@link #toString()} value. */ private String string; /** * Initialize this byte string based upon a byte array. A copy will be made. */ public AsciiString(byte[] value) { this(value, true); } /** * Initialize this byte string based upon a byte array. * {@code copy} determines if a copy is made or the array is shared. */ public AsciiString(byte[] value, boolean copy) { this(value, 0, value.length, copy); } /** * Construct a new instance from a {@code byte[]} array. * @param copy {@code true} then a copy of the memory will be made. {@code false} the underlying memory * will be shared. */ public AsciiString(byte[] value, int start, int length, boolean copy) { if (copy) { final byte[] rangedCopy = new byte[length]; System.arraycopy(value, start, rangedCopy, 0, rangedCopy.length); this.value = rangedCopy; this.offset = 0; } else { if (isOutOfBounds(start, length, value.length)) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= start + length(" + length + ") <= " + "value.length(" + value.length + ')'); } this.value = value; this.offset = start; } this.length = length; } /** * Create a copy of the underlying storage from {@code value}. * The copy will start at {@link ByteBuffer#position()} and copy {@link ByteBuffer#remaining()} bytes. */ public AsciiString(ByteBuffer value) { this(value, true); } /** * Initialize an instance based upon the underlying storage from {@code value}. * There is a potential to share the underlying array storage if {@link ByteBuffer#hasArray()} is {@code true}. * if {@code copy} is {@code true} a copy will be made of the memory. * if {@code copy} is {@code false} the underlying storage will be shared, if possible. */ public AsciiString(ByteBuffer value, boolean copy) { this(value, value.position(), value.remaining(), copy); } /** * Initialize an {@link AsciiString} based upon the underlying storage from {@code value}. * There is a potential to share the underlying array storage if {@link ByteBuffer#hasArray()} is {@code true}. * if {@code copy} is {@code true} a copy will be made of the memory. * if {@code copy} is {@code false} the underlying storage will be shared, if possible. */ public AsciiString(ByteBuffer value, int start, int length, boolean copy) { if (isOutOfBounds(start, length, value.capacity())) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= start + length(" + length + ") <= " + "value.capacity(" + value.capacity() + ')'); } if (value.hasArray()) { if (copy) { final int bufferOffset = value.arrayOffset() + start; this.value = Arrays.copyOfRange(value.array(), bufferOffset, bufferOffset + length); offset = 0; } else { this.value = value.array(); this.offset = start; } } else { this.value = PlatformDependent.allocateUninitializedArray(length); int oldPos = value.position(); value.get(this.value, 0, length); value.position(oldPos); this.offset = 0; } this.length = length; } /** * Create a copy of {@code value} into this instance assuming ASCII encoding. */ public AsciiString(char[] value) { this(value, 0, value.length); } /** * Create a copy of {@code value} into this instance assuming ASCII encoding. * The copy will start at index {@code start} and copy {@code length} bytes. */ public AsciiString(char[] value, int start, int length) { if (isOutOfBounds(start, length, value.length)) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= start + length(" + length + ") <= " + "value.length(" + value.length + ')'); } this.value = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = start; i < length; i++, j++) { this.value[i] = c2b(value[j]); } this.offset = 0; this.length = length; } /** * Create a copy of {@code value} into this instance using the encoding type of {@code charset}. */ public AsciiString(char[] value, Charset charset) { this(value, charset, 0, value.length); } /** * Create a copy of {@code value} into a this instance using the encoding type of {@code charset}. * The copy will start at index {@code start} and copy {@code length} bytes. */ public AsciiString(char[] value, Charset charset, int start, int length) { CharBuffer cbuf = CharBuffer.wrap(value, start, length); CharsetEncoder encoder = CharsetUtil.encoder(charset); ByteBuffer nativeBuffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * length)); encoder.encode(cbuf, nativeBuffer, true); final int bufferOffset = nativeBuffer.arrayOffset(); this.value = Arrays.copyOfRange(nativeBuffer.array(), bufferOffset, bufferOffset + nativeBuffer.position()); this.offset = 0; this.length = this.value.length; } /** * Create a copy of {@code value} into this instance assuming ASCII encoding. */ public AsciiString(CharSequence value) { this(value, 0, value.length()); } /** * Create a copy of {@code value} into this instance assuming ASCII encoding. * The copy will start at index {@code start} and copy {@code length} bytes. */ public AsciiString(CharSequence value, int start, int length) { if (isOutOfBounds(start, length, value.length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= start + length(" + length + ") <= " + "value.length(" + value.length() + ')'); } this.value = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = start; i < length; i++, j++) { this.value[i] = c2b(value.charAt(j)); } this.offset = 0; this.length = length; } /** * Create a copy of {@code value} into this instance using the encoding type of {@code charset}. */ public AsciiString(CharSequence value, Charset charset) { this(value, charset, 0, value.length()); } /** * Create a copy of {@code value} into this instance using the encoding type of {@code charset}. * The copy will start at index {@code start} and copy {@code length} bytes. */ public AsciiString(CharSequence value, Charset charset, int start, int length) { CharBuffer cbuf = CharBuffer.wrap(value, start, start + length); CharsetEncoder encoder = CharsetUtil.encoder(charset); ByteBuffer nativeBuffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * length)); encoder.encode(cbuf, nativeBuffer, true); final int offset = nativeBuffer.arrayOffset(); this.value = Arrays.copyOfRange(nativeBuffer.array(), offset, offset + nativeBuffer.position()); this.offset = 0; this.length = this.value.length; } /** * Iterates over the readable bytes of this buffer with the specified {@code processor} in ascending order. * * @return {@code -1} if the processor iterated to or beyond the end of the readable bytes. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public int forEachByte(ByteProcessor visitor) throws Exception { return forEachByte0(0, length(), visitor); } /** * Iterates over the specified area of this buffer with the specified {@code processor} in ascending order. * (i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}). * * @return {@code -1} if the processor iterated to or beyond the end of the specified area. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public int forEachByte(int index, int length, ByteProcessor visitor) throws Exception { if (isOutOfBounds(index, length, length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= index(" + index + ") <= start + length(" + length + ") <= " + "length(" + length() + ')'); } return forEachByte0(index, length, visitor); } private int forEachByte0(int index, int length, ByteProcessor visitor) throws Exception { final int len = offset + index + length; for (int i = offset + index; i < len; ++i) { if (!visitor.process(value[i])) { return i - offset; } } return -1; } /** * Iterates over the readable bytes of this buffer with the specified {@code processor} in descending order. * * @return {@code -1} if the processor iterated to or beyond the beginning of the readable bytes. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public int forEachByteDesc(ByteProcessor visitor) throws Exception { return forEachByteDesc0(0, length(), visitor); } /** * Iterates over the specified area of this buffer with the specified {@code processor} in descending order. * (i.e. {@code (index + length - 1)}, {@code (index + length - 2)}, ... {@code index}). * * @return {@code -1} if the processor iterated to or beyond the beginning of the specified area. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ public int forEachByteDesc(int index, int length, ByteProcessor visitor) throws Exception { if (isOutOfBounds(index, length, length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= index(" + index + ") <= start + length(" + length + ") <= " + "length(" + length() + ')'); } return forEachByteDesc0(index, length, visitor); } private int forEachByteDesc0(int index, int length, ByteProcessor visitor) throws Exception { final int end = offset + index; for (int i = offset + index + length - 1; i >= end; --i) { if (!visitor.process(value[i])) { return i - offset; } } return -1; } public byte byteAt(int index) { // We must do a range check here to enforce the access does not go outside our sub region of the array. // We rely on the array access itself to pick up the array out of bounds conditions if (index < 0 || index >= length) { throw new IndexOutOfBoundsException("index: " + index + " must be in the range [0," + length + ")"); } // Try to use unsafe to avoid double checking the index bounds if (PlatformDependent.hasUnsafe()) { return PlatformDependent.getByte(value, index + offset); } return value[index + offset]; } /** * Determine if this instance has 0 length. */ public boolean isEmpty() { return length == 0; } /** * The length in bytes of this instance. */ @Override public int length() { return length; } /** * During normal use cases the {@link AsciiString} should be immutable, but if the underlying array is shared, * and changes then this needs to be called. */ public void arrayChanged() { string = null; hash = 0; } /** * This gives direct access to the underlying storage array. * The {@link #toByteArray()} should be preferred over this method. * If the return value is changed then {@link #arrayChanged()} must be called. * @see #arrayOffset() * @see #isEntireArrayUsed() */ public byte[] array() { return value; } /** * The offset into {@link #array()} for which data for this ByteString begins. * @see #array() * @see #isEntireArrayUsed() */ public int arrayOffset() { return offset; } /** * Determine if the storage represented by {@link #array()} is entirely used. * @see #array() */ public boolean isEntireArrayUsed() { return offset == 0 && length == value.length; } /** * Converts this string to a byte array. */ public byte[] toByteArray() { return toByteArray(0, length()); } /** * Converts a subset of this string to a byte array. * The subset is defined by the range [{@code start}, {@code end}). */ public byte[] toByteArray(int start, int end) { return Arrays.copyOfRange(value, start + offset, end + offset); } /** * Copies the content of this string to a byte array. * * @param srcIdx the starting offset of characters to copy. * @param dst the destination byte array. * @param dstIdx the starting offset in the destination byte array. * @param length the number of characters to copy. */ public void copy(int srcIdx, byte[] dst, int dstIdx, int length) { if (isOutOfBounds(srcIdx, length, length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length(" + length + ") <= srcLen(" + length() + ')'); } System.arraycopy(value, srcIdx + offset, checkNotNull(dst, "dst"), dstIdx, length); } @Override public char charAt(int index) { return b2c(byteAt(index)); } /** * Determines if this {@code String} contains the sequence of characters in the {@code CharSequence} passed. * * @param cs the character sequence to search for. * @return {@code true} if the sequence of characters are contained in this string, otherwise {@code false}. */ public boolean contains(CharSequence cs) { return indexOf(cs) >= 0; } /** * Compares the specified string to this string using the ASCII values of the characters. Returns 0 if the strings * contain the same characters in the same order. Returns a negative integer if the first non-equal character in * this string has an ASCII value which is less than the ASCII value of the character at the same position in the * specified string, or if this string is a prefix of the specified string. Returns a positive integer if the first * non-equal character in this string has a ASCII value which is greater than the ASCII value of the character at * the same position in the specified string, or if the specified string is a prefix of this string. * * @param string the string to compare. * @return 0 if the strings are equal, a negative integer if this string is before the specified string, or a * positive integer if this string is after the specified string. * @throws NullPointerException if {@code string} is {@code null}. */ @Override public int compareTo(CharSequence string) { if (this == string) { return 0; } int result; int length1 = length(); int length2 = string.length(); int minLength = Math.min(length1, length2); for (int i = 0, j = arrayOffset(); i < minLength; i++, j++) { result = b2c(value[j]) - string.charAt(i); if (result != 0) { return result; } } return length1 - length2; } /** * Concatenates this string and the specified string. * * @param string the string to concatenate * @return a new string which is the concatenation of this string and the specified string. */ public AsciiString concat(CharSequence string) { int thisLen = length(); int thatLen = string.length(); if (thatLen == 0) { return this; } if (string instanceof AsciiString) { AsciiString that = (AsciiString) string; if (isEmpty()) { return that; } byte[] newValue = PlatformDependent.allocateUninitializedArray(thisLen + thatLen); System.arraycopy(value, arrayOffset(), newValue, 0, thisLen); System.arraycopy(that.value, that.arrayOffset(), newValue, thisLen, thatLen); return new AsciiString(newValue, false); } if (isEmpty()) { return new AsciiString(string); } byte[] newValue = PlatformDependent.allocateUninitializedArray(thisLen + thatLen); System.arraycopy(value, arrayOffset(), newValue, 0, thisLen); for (int i = thisLen, j = 0; i < newValue.length; i++, j++) { newValue[i] = c2b(string.charAt(j)); } return new AsciiString(newValue, false); } /** * Compares the specified string to this string to determine if the specified string is a suffix. * * @param suffix the suffix to look for. * @return {@code true} if the specified string is a suffix of this string, {@code false} otherwise. * @throws NullPointerException if {@code suffix} is {@code null}. */ public boolean endsWith(CharSequence suffix) { int suffixLen = suffix.length(); return regionMatches(length() - suffixLen, suffix, 0, suffixLen); } /** * Compares the specified string to this string ignoring the case of the characters and returns true if they are * equal. * * @param string the string to compare. * @return {@code true} if the specified string is equal to this string, {@code false} otherwise. */ public boolean contentEqualsIgnoreCase(CharSequence string) { if (this == string) { return true; } if (string == null || string.length() != length()) { return false; } if (string instanceof AsciiString) { AsciiString other = (AsciiString) string; byte[] value = this.value; if (offset == 0 && other.offset == 0 && length == value.length) { byte[] otherValue = other.value; for (int i = 0; i < value.length; ++i) { if (!equalsIgnoreCase(value[i], otherValue[i])) { return false; } } return true; } return misalignedEqualsIgnoreCase(other); } byte[] value = this.value; for (int i = offset, j = 0; j < string.length(); ++i, ++j) { if (!equalsIgnoreCase(b2c(value[i]), string.charAt(j))) { return false; } } return true; } private boolean misalignedEqualsIgnoreCase(AsciiString other) { byte[] value = this.value; byte[] otherValue = other.value; for (int i = offset, j = other.offset, end = offset + length; i < end; ++i, ++j) { if (!equalsIgnoreCase(value[i], otherValue[j])) { return false; } } return true; } /** * Copies the characters in this string to a character array. * * @return a character array containing the characters of this string. */ public char[] toCharArray() { return toCharArray(0, length()); } /** * Copies the characters in this string to a character array. * * @return a character array containing the characters of this string. */ public char[] toCharArray(int start, int end) { int length = end - start; if (length == 0) { return EmptyArrays.EMPTY_CHARS; } if (isOutOfBounds(start, length, length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= srcIdx + length(" + length + ") <= srcLen(" + length() + ')'); } final char[] buffer = new char[length]; for (int i = 0, j = start + arrayOffset(); i < length; i++, j++) { buffer[i] = b2c(value[j]); } return buffer; } /** * Copied the content of this string to a character array. * * @param srcIdx the starting offset of characters to copy. * @param dst the destination character array. * @param dstIdx the starting offset in the destination byte array. * @param length the number of characters to copy. */ public void copy(int srcIdx, char[] dst, int dstIdx, int length) { ObjectUtil.checkNotNull(dst, "dst"); if (isOutOfBounds(srcIdx, length, length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length(" + length + ") <= srcLen(" + length() + ')'); } final int dstEnd = dstIdx + length; for (int i = dstIdx, j = srcIdx + arrayOffset(); i < dstEnd; i++, j++) { dst[i] = b2c(value[j]); } } /** * Copies a range of characters into a new string. * @param start the offset of the first character (inclusive). * @return a new string containing the characters from start to the end of the string. * @throws IndexOutOfBoundsException if {@code start < 0} or {@code start > length()}. */ public AsciiString subSequence(int start) { return subSequence(start, length()); } /** * Copies a range of characters into a new string. * @param start the offset of the first character (inclusive). * @param end The index to stop at (exclusive). * @return a new string containing the characters from start to the end of the string. * @throws IndexOutOfBoundsException if {@code start < 0} or {@code start > length()}. */ @Override public AsciiString subSequence(int start, int end) { return subSequence(start, end, true); } /** * Either copy or share a subset of underlying sub-sequence of bytes. * @param start the offset of the first character (inclusive). * @param end The index to stop at (exclusive). * @param copy If {@code true} then a copy of the underlying storage will be made. * If {@code false} then the underlying storage will be shared. * @return a new string containing the characters from start to the end of the string. * @throws IndexOutOfBoundsException if {@code start < 0} or {@code start > length()}. */ public AsciiString subSequence(int start, int end, boolean copy) { if (isOutOfBounds(start, end - start, length())) { throw new IndexOutOfBoundsException("expected: 0 <= start(" + start + ") <= end (" + end + ") <= length(" + length() + ')'); } if (start == 0 && end == length()) { return this; } if (end == start) { return EMPTY_STRING; } return new AsciiString(value, start + offset, end - start, copy); } /** * Searches in this string for the first index of the specified string. The search for the string starts at the * beginning and moves towards the end of this string. * * @param string the string to find. * @return the index of the first character of the specified string in this string, -1 if the specified string is * not a substring. * @throws NullPointerException if {@code string} is {@code null}. */ public int indexOf(CharSequence string) { return indexOf(string, 0); } /** * Searches in this string for the index of the specified string. The search for the string starts at the specified * offset and moves towards the end of this string. * * @param subString the string to find. * @param start the starting offset. * @return the index of the first character of the specified string in this string, -1 if the specified string is * not a substring. * @throws NullPointerException if {@code subString} is {@code null}. */ public int indexOf(CharSequence subString, int start) { final int subCount = subString.length(); if (start < 0) { start = 0; } if (subCount <= 0) { return start < length ? start : length; } if (subCount > length - start) { return INDEX_NOT_FOUND; } final char firstChar = subString.charAt(0); if (firstChar > MAX_CHAR_VALUE) { return INDEX_NOT_FOUND; } final byte firstCharAsByte = c2b0(firstChar); final int len = offset + length - subCount; for (int i = start + offset; i <= len; ++i) { if (value[i] == firstCharAsByte) { int o1 = i, o2 = 0; while (++o2 < subCount && b2c(value[++o1]) == subString.charAt(o2)) { // Intentionally empty } if (o2 == subCount) { return i - offset; } } } return INDEX_NOT_FOUND; } /** * Searches in this string for the index of the specified char {@code ch}. * The search for the char starts at the specified offset {@code start} and moves towards the end of this string. * * @param ch the char to find. * @param start the starting offset. * @return the index of the first occurrence of the specified char {@code ch} in this string, * -1 if found no occurrence. */ public int indexOf(char ch, int start) { if (ch > MAX_CHAR_VALUE) { return INDEX_NOT_FOUND; } if (start < 0) { start = 0; } final byte chAsByte = c2b0(ch); final int len = offset + length; for (int i = start + offset; i < len; ++i) { if (value[i] == chAsByte) { return i - offset; } } return INDEX_NOT_FOUND; } /** * Searches in this string for the last index of the specified string. The search for the string starts at the end * and moves towards the beginning of this string. * * @param string the string to find. * @return the index of the first character of the specified string in this string, -1 if the specified string is * not a substring. * @throws NullPointerException if {@code string} is {@code null}. */ public int lastIndexOf(CharSequence string) { // Use count instead of count - 1 so lastIndexOf("") answers count return lastIndexOf(string, length); } /** * Searches in this string for the index of the specified string. The search for the string starts at the specified * offset and moves towards the beginning of this string. * * @param subString the string to find. * @param start the starting offset. * @return the index of the first character of the specified string in this string , -1 if the specified string is * not a substring. * @throws NullPointerException if {@code subString} is {@code null}. */ public int lastIndexOf(CharSequence subString, int start) { final int subCount = subString.length(); start = Math.min(start, length - subCount); if (start < 0) { return INDEX_NOT_FOUND; } if (subCount == 0) { return start; } final char firstChar = subString.charAt(0); if (firstChar > MAX_CHAR_VALUE) { return INDEX_NOT_FOUND; } final byte firstCharAsByte = c2b0(firstChar); for (int i = offset + start; i >= offset; --i) { if (value[i] == firstCharAsByte) { int o1 = i, o2 = 0; while (++o2 < subCount && b2c(value[++o1]) == subString.charAt(o2)) { // Intentionally empty } if (o2 == subCount) { return i - offset; } } } return INDEX_NOT_FOUND; } /** * Compares the specified string to this string and compares the specified range of characters to determine if they * are the same. * * @param thisStart the starting offset in this string. * @param string the string to compare. * @param start the starting offset in the specified string. * @param length the number of characters to compare. * @return {@code true} if the ranges of characters are equal, {@code false} otherwise * @throws NullPointerException if {@code string} is {@code null}. */ public boolean regionMatches(int thisStart, CharSequence string, int start, int length) { ObjectUtil.checkNotNull(string, "string"); if (start < 0 || string.length() - start < length) { return false; } final int thisLen = length(); if (thisStart < 0 || thisLen - thisStart < length) { return false; } if (length <= 0) { return true; } final int thatEnd = start + length; for (int i = start, j = thisStart + arrayOffset(); i < thatEnd; i++, j++) { if (b2c(value[j]) != string.charAt(i)) { return false; } } return true; } /** * Compares the specified string to this string and compares the specified range of characters to determine if they * are the same. When ignoreCase is true, the case of the characters is ignored during the comparison. * * @param ignoreCase specifies if case should be ignored. * @param thisStart the starting offset in this string. * @param string the string to compare. * @param start the starting offset in the specified string. * @param length the number of characters to compare. * @return {@code true} if the ranges of characters are equal, {@code false} otherwise. * @throws NullPointerException if {@code string} is {@code null}. */ public boolean regionMatches(boolean ignoreCase, int thisStart, CharSequence string, int start, int length) { if (!ignoreCase) { return regionMatches(thisStart, string, start, length); } ObjectUtil.checkNotNull(string, "string"); final int thisLen = length(); if (thisStart < 0 || length > thisLen - thisStart) { return false; } if (start < 0 || length > string.length() - start) { return false; } thisStart += arrayOffset(); final int thisEnd = thisStart + length; while (thisStart < thisEnd) { if (!equalsIgnoreCase(b2c(value[thisStart++]), string.charAt(start++))) { return false; } } return true; } /** * Copies this string replacing occurrences of the specified character with another character. * * @param oldChar the character to replace. * @param newChar the replacement character. * @return a new string with occurrences of oldChar replaced by newChar. */ public AsciiString replace(char oldChar, char newChar) { if (oldChar > MAX_CHAR_VALUE) { return this; } final byte oldCharAsByte = c2b0(oldChar); final byte newCharAsByte = c2b(newChar); final int len = offset + length; for (int i = offset; i < len; ++i) { if (value[i] == oldCharAsByte) { byte[] buffer = PlatformDependent.allocateUninitializedArray(length()); System.arraycopy(value, offset, buffer, 0, i - offset); buffer[i - offset] = newCharAsByte; ++i; for (; i < len; ++i) { byte oldValue = value[i]; buffer[i - offset] = oldValue != oldCharAsByte ? oldValue : newCharAsByte; } return new AsciiString(buffer, false); } } return this; } /** * Compares the specified string to this string to determine if the specified string is a prefix. * * @param prefix the string to look for. * @return {@code true} if the specified string is a prefix of this string, {@code false} otherwise * @throws NullPointerException if {@code prefix} is {@code null}. */ public boolean startsWith(CharSequence prefix) { return startsWith(prefix, 0); } /** * Compares the specified string to this string, starting at the specified offset, to determine if the specified * string is a prefix. * * @param prefix the string to look for. * @param start the starting offset. * @return {@code true} if the specified string occurs in this string at the specified offset, {@code false} * otherwise. * @throws NullPointerException if {@code prefix} is {@code null}. */ public boolean startsWith(CharSequence prefix, int start) { return regionMatches(start, prefix, 0, prefix.length()); } /** * Converts the characters in this string to lowercase, using the default Locale. * * @return a new string containing the lowercase characters equivalent to the characters in this string. */ public AsciiString toLowerCase() { return AsciiStringUtil.toLowerCase(this); } /** * Converts the characters in this string to uppercase, using the default Locale. * * @return a new string containing the uppercase characters equivalent to the characters in this string. */ public AsciiString toUpperCase() { return AsciiStringUtil.toUpperCase(this); } /** * Copies this string removing white space characters from the beginning and end of the string, and tries not to * copy if possible. * * @param c The {@link CharSequence} to trim. * @return a new string with characters {@code <= \\u0020} removed from the beginning and the end. */ public static CharSequence trim(CharSequence c) { if (c instanceof AsciiString) { return ((AsciiString) c).trim(); } if (c instanceof String) { return ((String) c).trim(); } int start = 0, last = c.length() - 1; int end = last; while (start <= end && c.charAt(start) <= ' ') { start++; } while (end >= start && c.charAt(end) <= ' ') { end--; } if (start == 0 && end == last) { return c; } return c.subSequence(start, end); } /** * Duplicates this string removing white space characters from the beginning and end of the * string, without copying. * * @return a new string with characters {@code <= \\u0020} removed from the beginning and the end. */ public AsciiString trim() { int start = arrayOffset(), last = arrayOffset() + length() - 1; int end = last; while (start <= end && value[start] <= ' ') { start++; } while (end >= start && value[end] <= ' ') { end--; } if (start == 0 && end == last) { return this; } return new AsciiString(value, start, end - start + 1, false); } /** * Compares a {@code CharSequence} to this {@code String} to determine if their contents are equal. * * @param a the character sequence to compare to. * @return {@code true} if equal, otherwise {@code false} */ public boolean contentEquals(CharSequence a) { if (this == a) { return true; } if (a == null || a.length() != length()) { return false; } if (a instanceof AsciiString) { return equals(a); } for (int i = arrayOffset(), j = 0; j < a.length(); ++i, ++j) { if (b2c(value[i]) != a.charAt(j)) { return false; } } return true; } /** * Determines whether this string matches a given regular expression. * * @param expr the regular expression to be matched. * @return {@code true} if the expression matches, otherwise {@code false}. * @throws PatternSyntaxException if the syntax of the supplied regular expression is not valid. * @throws NullPointerException if {@code expr} is {@code null}. */ public boolean matches(String expr) { return Pattern.matches(expr, this); } /** * Splits this string using the supplied regular expression {@code expr}. The parameter {@code max} controls the * behavior how many times the pattern is applied to the string. * * @param expr the regular expression used to divide the string. * @param max the number of entries in the resulting array. * @return an array of Strings created by separating the string along matches of the regular expression. * @throws NullPointerException if {@code expr} is {@code null}. * @throws PatternSyntaxException if the syntax of the supplied regular expression is not valid. * @see Pattern#split(CharSequence, int) */ public AsciiString[] split(String expr, int max) { return toAsciiStringArray(Pattern.compile(expr).split(this, max)); } /** * Splits the specified {@link String} with the specified delimiter.. */ public AsciiString[] split(char delim) { final List<AsciiString> res = InternalThreadLocalMap.get().arrayList(); int start = 0; final int length = length(); for (int i = start; i < length; i++) { if (charAt(i) == delim) { if (start == i) { res.add(EMPTY_STRING); } else { res.add(new AsciiString(value, start + arrayOffset(), i - start, false)); } start = i + 1; } } if (start == 0) { // If no delimiter was found in the value res.add(this); } else { if (start != length) { // Add the last element if it's not empty. res.add(new AsciiString(value, start + arrayOffset(), length - start, false)); } else { // Truncate trailing empty elements. for (int i = res.size() - 1; i >= 0; i--) { if (res.get(i).isEmpty()) { res.remove(i); } else { break; } } } } return res.toArray(EmptyArrays.EMPTY_ASCII_STRINGS); } /** * {@inheritDoc} * <p> * Provides a case-insensitive hash code for Ascii like byte strings. */ @Override public int hashCode() { int h = hash; if (h == 0) { h = PlatformDependent.hashCodeAscii(value, offset, length); hash = h; } return h; } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != AsciiString.class) { return false; } if (this == obj) { return true; } AsciiString other = (AsciiString) obj; return length() == other.length() && hashCode() == other.hashCode() && PlatformDependent.equals(array(), arrayOffset(), other.array(), other.arrayOffset(), length()); } /** * Translates the entire byte string to a {@link String}. * @see #toString(int) */ @Override public String toString() { String cache = string; if (cache == null) { cache = toString(0); string = cache; } return cache; } /** * Translates the entire byte string to a {@link String} using the {@code charset} encoding. * @see #toString(int, int) */ public String toString(int start) { return toString(start, length()); } /** * Translates the [{@code start}, {@code end}) range of this byte string to a {@link String}. */ public String toString(int start, int end) { int length = end - start; if (length == 0) { return ""; } if (isOutOfBounds(start, length, length())) { throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= srcIdx + length(" + length + ") <= srcLen(" + length() + ')'); } @SuppressWarnings("deprecation") final String str = new String(value, 0, start + offset, length); return str; } public boolean parseBoolean() { return length >= 1 && value[offset] != 0; } public char parseChar() { return parseChar(0); } public char parseChar(int start) { if (start + 1 >= length()) { throw new IndexOutOfBoundsException("2 bytes required to convert to character. index " + start + " would go out of bounds."); } final int startWithOffset = start + offset; return (char) ((b2c(value[startWithOffset]) << 8) | b2c(value[startWithOffset + 1])); } public short parseShort() { return parseShort(0, length(), 10); } public short parseShort(int radix) { return parseShort(0, length(), radix); } public short parseShort(int start, int end) { return parseShort(start, end, 10); } public short parseShort(int start, int end, int radix) { int intValue = parseInt(start, end, radix); short result = (short) intValue; if (result != intValue) { throw new NumberFormatException(subSequence(start, end, false).toString()); } return result; } public int parseInt() { return parseInt(0, length(), 10); } public int parseInt(int radix) { return parseInt(0, length(), radix); } public int parseInt(int start, int end) { return parseInt(start, end, 10); } public int parseInt(int start, int end, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException(); } if (start == end) { throw new NumberFormatException(); } int i = start; boolean negative = byteAt(i) == '-'; if (negative && ++i == end) { throw new NumberFormatException(subSequence(start, end, false).toString()); } return parseInt(i, end, radix, negative); } private int parseInt(int start, int end, int radix, boolean negative) { int max = Integer.MIN_VALUE / radix; int result = 0; int currOffset = start; while (currOffset < end) { int digit = Character.digit((char) (value[currOffset++ + offset] & 0xFF), radix); if (digit == -1) { throw new NumberFormatException(subSequence(start, end, false).toString()); } if (max > result) { throw new NumberFormatException(subSequence(start, end, false).toString()); } int next = result * radix - digit; if (next > result) { throw new NumberFormatException(subSequence(start, end, false).toString()); } result = next; } if (!negative) { result = -result; if (result < 0) { throw new NumberFormatException(subSequence(start, end, false).toString()); } } return result; } public long parseLong() { return parseLong(0, length(), 10); } public long parseLong(int radix) { return parseLong(0, length(), radix); } public long parseLong(int start, int end) { return parseLong(start, end, 10); } public long parseLong(int start, int end, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException(); } if (start == end) { throw new NumberFormatException(); } int i = start; boolean negative = byteAt(i) == '-'; if (negative && ++i == end) { throw new NumberFormatException(subSequence(start, end, false).toString()); } return parseLong(i, end, radix, negative); } private long parseLong(int start, int end, int radix, boolean negative) { long max = Long.MIN_VALUE / radix; long result = 0; int currOffset = start; while (currOffset < end) { int digit = Character.digit((char) (value[currOffset++ + offset] & 0xFF), radix); if (digit == -1) { throw new NumberFormatException(subSequence(start, end, false).toString()); } if (max > result) { throw new NumberFormatException(subSequence(start, end, false).toString()); } long next = result * radix - digit; if (next > result) { throw new NumberFormatException(subSequence(start, end, false).toString()); } result = next; } if (!negative) { result = -result; if (result < 0) { throw new NumberFormatException(subSequence(start, end, false).toString()); } } return result; } public float parseFloat() { return parseFloat(0, length()); } public float parseFloat(int start, int end) { return Float.parseFloat(toString(start, end)); } public double parseDouble() { return parseDouble(0, length()); } public double parseDouble(int start, int end) { return Double.parseDouble(toString(start, end)); } public static final HashingStrategy<CharSequence> CASE_INSENSITIVE_HASHER = new HashingStrategy<CharSequence>() { @Override public int hashCode(CharSequence o) { return AsciiString.hashCode(o); } @Override public boolean equals(CharSequence a, CharSequence b) { return AsciiString.contentEqualsIgnoreCase(a, b); } }; public static final HashingStrategy<CharSequence> CASE_SENSITIVE_HASHER = new HashingStrategy<CharSequence>() { @Override public int hashCode(CharSequence o) { return AsciiString.hashCode(o); } @Override public boolean equals(CharSequence a, CharSequence b) { return AsciiString.contentEquals(a, b); } }; /** * Returns an {@link AsciiString} containing the given character sequence. If the given string is already a * {@link AsciiString}, just returns the same instance. */ public static AsciiString of(CharSequence string) { return string instanceof AsciiString ? (AsciiString) string : new AsciiString(string); } /** * Returns an {@link AsciiString} containing the given string and retains/caches the input * string for later use in {@link #toString()}. * Used for the constants (which already stored in the JVM's string table) and in cases * where the guaranteed use of the {@link #toString()} method. */ public static AsciiString cached(String string) { AsciiString asciiString = new AsciiString(string); asciiString.string = string; return asciiString; } /** * Returns the case-insensitive hash code of the specified string. Note that this method uses the same hashing * algorithm with {@link #hashCode()} so that you can put both {@link AsciiString}s and arbitrary * {@link CharSequence}s into the same headers. */ public static int hashCode(CharSequence value) { if (value == null) { return 0; } if (value instanceof AsciiString) { return value.hashCode(); } return PlatformDependent.hashCodeAscii(value); } /** * Determine if {@code a} contains {@code b} in a case sensitive manner. */ public static boolean contains(CharSequence a, CharSequence b) { return contains(a, b, DefaultCharEqualityComparator.INSTANCE); } /** * Determine if {@code a} contains {@code b} in a case insensitive manner. */ public static boolean containsIgnoreCase(CharSequence a, CharSequence b) { return contains(a, b, AsciiCaseInsensitiveCharEqualityComparator.INSTANCE); } /** * Returns {@code true} if both {@link CharSequence}'s are equals when ignore the case. This only supports 8-bit * ASCII. */ public static boolean contentEqualsIgnoreCase(CharSequence a, CharSequence b) { if (a == null || b == null) { return a == b; } if (a instanceof AsciiString) { return ((AsciiString) a).contentEqualsIgnoreCase(b); } if (b instanceof AsciiString) { return ((AsciiString) b).contentEqualsIgnoreCase(a); } if (a.length() != b.length()) { return false; } for (int i = 0; i < a.length(); ++i) { if (!equalsIgnoreCase(a.charAt(i), b.charAt(i))) { return false; } } return true; } /** * Determine if {@code collection} contains {@code value} and using * {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values. * @param collection The collection to look for and equivalent element as {@code value}. * @param value The value to look for in {@code collection}. * @return {@code true} if {@code collection} contains {@code value} according to * {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)}. {@code false} otherwise. * @see #contentEqualsIgnoreCase(CharSequence, CharSequence) */ public static boolean containsContentEqualsIgnoreCase(Collection<CharSequence> collection, CharSequence value) { for (CharSequence v : collection) { if (contentEqualsIgnoreCase(value, v)) { return true; } } return false; } /** * Determine if {@code a} contains all of the values in {@code b} using * {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values. * @param a The collection under test. * @param b The values to test for. * @return {@code true} if {@code a} contains all of the values in {@code b} using * {@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values. {@code false} otherwise. * @see #contentEqualsIgnoreCase(CharSequence, CharSequence) */ public static boolean containsAllContentEqualsIgnoreCase(Collection<CharSequence> a, Collection<CharSequence> b) { for (CharSequence v : b) { if (!containsContentEqualsIgnoreCase(a, v)) { return false; } } return true; } /** * Returns {@code true} if the content of both {@link CharSequence}'s are equals. This only supports 8-bit ASCII. */ public static boolean contentEquals(CharSequence a, CharSequence b) { if (a == null || b == null) { return a == b; } if (a instanceof AsciiString) { return ((AsciiString) a).contentEquals(b); } if (b instanceof AsciiString) { return ((AsciiString) b).contentEquals(a); } if (a.length() != b.length()) { return false; } for (int i = 0; i < a.length(); ++i) { if (a.charAt(i) != b.charAt(i)) { return false; } } return true; } private static AsciiString[] toAsciiStringArray(String[] jdkResult) { AsciiString[] res = new AsciiString[jdkResult.length]; for (int i = 0; i < jdkResult.length; i++) { res[i] = new AsciiString(jdkResult[i]); } return res; } private interface CharEqualityComparator { boolean equals(char a, char b); } private static final class DefaultCharEqualityComparator implements CharEqualityComparator { static final DefaultCharEqualityComparator INSTANCE = new DefaultCharEqualityComparator(); private DefaultCharEqualityComparator() { } @Override public boolean equals(char a, char b) { return a == b; } } private static final class AsciiCaseInsensitiveCharEqualityComparator implements CharEqualityComparator { static final AsciiCaseInsensitiveCharEqualityComparator INSTANCE = new AsciiCaseInsensitiveCharEqualityComparator(); private AsciiCaseInsensitiveCharEqualityComparator() { } @Override public boolean equals(char a, char b) { return equalsIgnoreCase(a, b); } } private static final class GeneralCaseInsensitiveCharEqualityComparator implements CharEqualityComparator { static final GeneralCaseInsensitiveCharEqualityComparator INSTANCE = new GeneralCaseInsensitiveCharEqualityComparator(); private GeneralCaseInsensitiveCharEqualityComparator() { } @Override public boolean equals(char a, char b) { //For motivation, why we need two checks, see comment in String#regionMatches return Character.toUpperCase(a) == Character.toUpperCase(b) || Character.toLowerCase(a) == Character.toLowerCase(b); } } private static boolean contains(CharSequence a, CharSequence b, CharEqualityComparator cmp) { if (a == null || b == null || a.length() < b.length()) { return false; } if (b.length() == 0) { return true; } int bStart = 0; for (int i = 0; i < a.length(); ++i) { if (cmp.equals(b.charAt(bStart), a.charAt(i))) { // If b is consumed then true. if (++bStart == b.length()) { return true; } } else if (a.length() - i < b.length()) { // If there are not enough characters left in a for b to be contained, then false. return false; } else { bStart = 0; } } return false; } private static boolean regionMatchesCharSequences(final CharSequence cs, final int csStart, final CharSequence string, final int start, final int length, CharEqualityComparator charEqualityComparator) { //general purpose implementation for CharSequences if (csStart < 0 || length > cs.length() - csStart) { return false; } if (start < 0 || length > string.length() - start) { return false; } int csIndex = csStart; int csEnd = csIndex + length; int stringIndex = start; while (csIndex < csEnd) { char c1 = cs.charAt(csIndex++); char c2 = string.charAt(stringIndex++); if (!charEqualityComparator.equals(c1, c2)) { return false; } } return true; } /** * This methods make regionMatches operation correctly for any chars in strings * @param cs the {@code CharSequence} to be processed * @param ignoreCase specifies if case should be ignored. * @param csStart the starting offset in the {@code cs} CharSequence * @param string the {@code CharSequence} to compare. * @param start the starting offset in the specified {@code string}. * @param length the number of characters to compare. * @return {@code true} if the ranges of characters are equal, {@code false} otherwise. */ public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int csStart, final CharSequence string, final int start, final int length) { if (cs == null || string == null) { return false; } if (cs instanceof String && string instanceof String) { return ((String) cs).regionMatches(ignoreCase, csStart, (String) string, start, length); } if (cs instanceof AsciiString) { return ((AsciiString) cs).regionMatches(ignoreCase, csStart, string, start, length); } return regionMatchesCharSequences(cs, csStart, string, start, length, ignoreCase ? GeneralCaseInsensitiveCharEqualityComparator.INSTANCE : DefaultCharEqualityComparator.INSTANCE); } /** * This is optimized version of regionMatches for string with ASCII chars only * @param cs the {@code CharSequence} to be processed * @param ignoreCase specifies if case should be ignored. * @param csStart the starting offset in the {@code cs} CharSequence * @param string the {@code CharSequence} to compare. * @param start the starting offset in the specified {@code string}. * @param length the number of characters to compare. * @return {@code true} if the ranges of characters are equal, {@code false} otherwise. */ public static boolean regionMatchesAscii(final CharSequence cs, final boolean ignoreCase, final int csStart, final CharSequence string, final int start, final int length) { if (cs == null || string == null) { return false; } if (!ignoreCase && cs instanceof String && string instanceof String) { //we don't call regionMatches from String for ignoreCase==true. It's a general purpose method, //which make complex comparison in case of ignoreCase==true, which is useless for ASCII-only strings. //To avoid applying this complex ignore-case comparison, we will use regionMatchesCharSequences return ((String) cs).regionMatches(false, csStart, (String) string, start, length); } if (cs instanceof AsciiString) { return ((AsciiString) cs).regionMatches(ignoreCase, csStart, string, start, length); } return regionMatchesCharSequences(cs, csStart, string, start, length, ignoreCase ? AsciiCaseInsensitiveCharEqualityComparator.INSTANCE : DefaultCharEqualityComparator.INSTANCE); } /** * <p>Case in-sensitive find of the first index within a CharSequence * from the specified position.</p> * * <p>A {@code null} CharSequence will return {@code -1}. * A negative start position is treated as zero. * An empty ("") search CharSequence always matches. * A start position greater than the string length only matches * an empty search CharSequence.</p> * * <pre> * AsciiString.indexOfIgnoreCase(null, *, *) = -1 * AsciiString.indexOfIgnoreCase(*, null, *) = -1 * AsciiString.indexOfIgnoreCase("", "", 0) = 0 * AsciiString.indexOfIgnoreCase("aabaabaa", "A", 0) = 0 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", 0) = 2 * AsciiString.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", 3) = 5 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", 9) = -1 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", -1) = 2 * AsciiString.indexOfIgnoreCase("aabaabaa", "", 2) = 2 * AsciiString.indexOfIgnoreCase("abc", "", 9) = -1 * </pre> * * @param str the CharSequence to check, may be null * @param searchStr the CharSequence to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search CharSequence (always &ge; startPos), * -1 if no match or {@code null} string input */ public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } if (startPos < 0) { startPos = 0; } int searchStrLen = searchStr.length(); final int endLimit = str.length() - searchStrLen + 1; if (startPos > endLimit) { return INDEX_NOT_FOUND; } if (searchStrLen == 0) { return startPos; } for (int i = startPos; i < endLimit; i++) { if (regionMatches(str, true, i, searchStr, 0, searchStrLen)) { return i; } } return INDEX_NOT_FOUND; } /** * <p>Case in-sensitive find of the first index within a CharSequence * from the specified position. This method optimized and works correctly for ASCII CharSequences only</p> * * <p>A {@code null} CharSequence will return {@code -1}. * A negative start position is treated as zero. * An empty ("") search CharSequence always matches. * A start position greater than the string length only matches * an empty search CharSequence.</p> * * <pre> * AsciiString.indexOfIgnoreCase(null, *, *) = -1 * AsciiString.indexOfIgnoreCase(*, null, *) = -1 * AsciiString.indexOfIgnoreCase("", "", 0) = 0 * AsciiString.indexOfIgnoreCase("aabaabaa", "A", 0) = 0 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", 0) = 2 * AsciiString.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", 3) = 5 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", 9) = -1 * AsciiString.indexOfIgnoreCase("aabaabaa", "B", -1) = 2 * AsciiString.indexOfIgnoreCase("aabaabaa", "", 2) = 2 * AsciiString.indexOfIgnoreCase("abc", "", 9) = -1 * </pre> * * @param str the CharSequence to check, may be null * @param searchStr the CharSequence to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search CharSequence (always &ge; startPos), * -1 if no match or {@code null} string input */ public static int indexOfIgnoreCaseAscii(final CharSequence str, final CharSequence searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } if (startPos < 0) { startPos = 0; } int searchStrLen = searchStr.length(); final int endLimit = str.length() - searchStrLen + 1; if (startPos > endLimit) { return INDEX_NOT_FOUND; } if (searchStrLen == 0) { return startPos; } for (int i = startPos; i < endLimit; i++) { if (regionMatchesAscii(str, true, i, searchStr, 0, searchStrLen)) { return i; } } return INDEX_NOT_FOUND; } /** * <p>Finds the first index in the {@code CharSequence} that matches the * specified character.</p> * * @param cs the {@code CharSequence} to be processed, not null * @param searchChar the char to be searched for * @param start the start index, negative starts at the string start * @return the index where the search char was found, * -1 if char {@code searchChar} is not found or {@code cs == null} */ //----------------------------------------------------------------------- public static int indexOf(final CharSequence cs, final char searchChar, int start) { if (cs instanceof String) { return ((String) cs).indexOf(searchChar, start); } else if (cs instanceof AsciiString) { return ((AsciiString) cs).indexOf(searchChar, start); } if (cs == null) { return INDEX_NOT_FOUND; } final int sz = cs.length(); for (int i = start < 0 ? 0 : start; i < sz; i++) { if (cs.charAt(i) == searchChar) { return i; } } return INDEX_NOT_FOUND; } private static boolean equalsIgnoreCase(byte a, byte b) { return a == b || AsciiStringUtil.toLowerCase(a) == AsciiStringUtil.toLowerCase(b); } private static boolean equalsIgnoreCase(char a, char b) { return a == b || toLowerCase(a) == toLowerCase(b); } /** * If the character is uppercase - converts the character to lowercase, * otherwise returns the character as it is. Only for ASCII characters. * * @return lowercase ASCII character equivalent */ public static char toLowerCase(char c) { return isUpperCase(c) ? (char) (c + 32) : c; } private static byte toUpperCase(byte b) { return AsciiStringUtil.toUpperCase(b); } public static boolean isUpperCase(byte value) { return AsciiStringUtil.isUpperCase(value); } public static boolean isUpperCase(char value) { return value >= 'A' && value <= 'Z'; } public static byte c2b(char c) { return (byte) ((c > MAX_CHAR_VALUE) ? '?' : c); } private static byte c2b0(char c) { return (byte) c; } public static char b2c(byte b) { return (char) (b & 0xFF); } }
netty/netty
common/src/main/java/io/netty/util/AsciiString.java
46
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.util; import java.util.Arrays; public final class FnvHash { public static final long BASIC = 0xcbf29ce484222325L; public static final long PRIME = 0x100000001b3L; public static long fnv1a_64(String input) { if (input == null) { return 0; } long hash = BASIC; for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(StringBuilder input) { if (input == null) { return 0; } long hash = BASIC; for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(String input, int offset, int end) { if (input == null) { return 0; } if (input.length() < end) { end = input.length(); } long hash = BASIC; for (int i = offset; i < end; ++i) { char c = input.charAt(i); hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(byte[] input, int offset, int end) { if (input == null) { return 0; } if (input.length < end) { end = input.length; } long hash = BASIC; for (int i = offset; i < end; ++i) { byte c = input[i]; hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(char[] chars) { if (chars == null) { return 0; } long hash = BASIC; for (int i = 0; i < chars.length; ++i) { char c = chars[i]; hash ^= c; hash *= PRIME; } return hash; } /** * lower and normalized and fnv_1a_64 * * @param name the string to calculate the hash code for * @return the 64-bit hash code of the string */ public static long hashCode64(String name) { if (name == null) { return 0; } boolean quote = false; int len = name.length(); if (len > 2) { char c0 = name.charAt(0); char c1 = name.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } if (quote) { return FnvHash.hashCode64(name, 1, len - 1); } else { return FnvHash.hashCode64(name, 0, len); } } public static long fnv1a_64_lower(String key) { long hashCode = BASIC; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long fnv1a_64_lower(StringBuilder key) { long hashCode = BASIC; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long fnv1a_64_lower(long basic, StringBuilder key) { long hashCode = basic; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long hashCode64(String key, int offset, int end) { long hashCode = BASIC; for (int i = offset; i < end; ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long hashCode64(long basic, String name) { if (name == null) { return basic; } boolean quote = false; int len = name.length(); if (len > 2) { char c0 = name.charAt(0); char c1 = name.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } if (quote) { int offset = 1; int end = len - 1; for (int i = end - 1; i >= 0; --i) { char ch = name.charAt(i); if (ch == ' ') { end--; } else { break; } } return FnvHash.hashCode64(basic, name, offset, end); } else { return FnvHash.hashCode64(basic, name, 0, len); } } public static long hashCode64(long basic, String key, int offset, int end) { long hashCode = basic; for (int i = offset; i < end; ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long fnv_32_lower(String key) { long hashCode = 0x811c9dc5; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch == '_' || ch == '-') { continue; } if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= 0x01000193; } return hashCode; } public static long[] fnv1a_64_lower(String[] strings, boolean sort) { long[] hashCodes = new long[strings.length]; for (int i = 0; i < strings.length; i++) { hashCodes[i] = fnv1a_64_lower(strings[i]); } if (sort) { Arrays.sort(hashCodes); } return hashCodes; } /** * normalized and lower and fnv1a_64_hash * * @param owner the owner string to include in the hash code calculation (can be null) * @param name the name string to include in the hash code calculation (can be null) * @return the 64-bit hash code calculated from the owner and name strings */ public static long hashCode64(String owner, String name) { long hashCode = BASIC; if (owner != null) { String item = owner; boolean quote = false; int len = item.length(); if (len > 2) { char c0 = item.charAt(0); char c1 = item.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } int start = quote ? 1 : 0; int end = quote ? len - 1 : len; for (int j = start; j < end; ++j) { char ch = item.charAt(j); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } hashCode ^= '.'; hashCode *= PRIME; } if (name != null) { String item = name; boolean quote = false; int len = item.length(); if (len > 2) { char c0 = item.charAt(0); char c1 = item.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } int start = quote ? 1 : 0; int end = quote ? len - 1 : len; for (int j = start; j < end; ++j) { char ch = item.charAt(j); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } } return hashCode; } public static interface Constants { long HIGH_PRIORITY = fnv1a_64_lower("HIGH_PRIORITY"); long DISTINCTROW = fnv1a_64_lower("DISTINCTROW"); long STRAIGHT = fnv1a_64_lower("STRAIGHT"); long STRAIGHT_JOIN = fnv1a_64_lower("STRAIGHT_JOIN"); long SQL_SMALL_RESULT = fnv1a_64_lower("SQL_SMALL_RESULT"); long SQL_BIG_RESULT = fnv1a_64_lower("SQL_BIG_RESULT"); long SQL_BUFFER_RESULT = fnv1a_64_lower("SQL_BUFFER_RESULT"); long CACHE = fnv1a_64_lower("CACHE"); long SQL_CACHE = fnv1a_64_lower("SQL_CACHE"); long SQL_NO_CACHE = fnv1a_64_lower("SQL_NO_CACHE"); long SQL_CALC_FOUND_ROWS = fnv1a_64_lower("SQL_CALC_FOUND_ROWS"); long TOP = fnv1a_64_lower("TOP"); long OUTFILE = fnv1a_64_lower("OUTFILE"); long SETS = fnv1a_64_lower("SETS"); long REGEXP = fnv1a_64_lower("REGEXP"); long RLIKE = fnv1a_64_lower("RLIKE"); long USING = fnv1a_64_lower("USING"); long MATCHED = fnv1a_64_lower("MATCHED"); long IGNORE = fnv1a_64_lower("IGNORE"); long FORCE = fnv1a_64_lower("FORCE"); long CROSS = fnv1a_64_lower("CROSS"); long NATURAL = fnv1a_64_lower("NATURAL"); long APPLY = fnv1a_64_lower("APPLY"); long CONNECT = fnv1a_64_lower("CONNECT"); long START = fnv1a_64_lower("START"); long BTREE = fnv1a_64_lower("BTREE"); long HASH = fnv1a_64_lower("HASH"); long DUPLICATE = fnv1a_64_lower("DUPLICATE"); long LIST = fnv1a_64_lower("LIST"); long NO_WAIT = fnv1a_64_lower("NO_WAIT"); long WAIT = fnv1a_64_lower("WAIT"); long NOWAIT = fnv1a_64_lower("NOWAIT"); long ERRORS = fnv1a_64_lower("ERRORS"); long VALUE = fnv1a_64_lower("VALUE"); long OBJECT = fnv1a_64_lower("OBJECT"); long NEXT = fnv1a_64_lower("NEXT"); long NEXTVAL = fnv1a_64_lower("NEXTVAL"); long CURRVAL = fnv1a_64_lower("CURRVAL"); long PREVVAL = fnv1a_64_lower("PREVVAL"); long PREVIOUS = fnv1a_64_lower("PREVIOUS"); long LOW_PRIORITY = fnv1a_64_lower("LOW_PRIORITY"); long COMMIT_ON_SUCCESS = fnv1a_64_lower("COMMIT_ON_SUCCESS"); long ROLLBACK_ON_FAIL = fnv1a_64_lower("ROLLBACK_ON_FAIL"); long QUEUE_ON_PK = fnv1a_64_lower("QUEUE_ON_PK"); long TARGET_AFFECT_ROW = fnv1a_64_lower("TARGET_AFFECT_ROW"); long COLLATE = fnv1a_64_lower("COLLATE"); long BOOLEAN = fnv1a_64_lower("BOOLEAN"); long SMALLINT = fnv1a_64_lower("SMALLINT"); long MEDIUMINT = fnv1a_64_lower("MEDIUMINT"); long SHORT = fnv1a_64_lower("SHORT"); long TINY = fnv1a_64_lower("TINY"); long TINYINT = fnv1a_64_lower("TINYINT"); long CHARSET = fnv1a_64_lower("CHARSET"); long SEMI = fnv1a_64_lower("SEMI"); long ANTI = fnv1a_64_lower("ANTI"); long PRIOR = fnv1a_64_lower("PRIOR"); long NOCYCLE = fnv1a_64_lower("NOCYCLE"); long CYCLE = fnv1a_64_lower("CYCLE"); long CONNECT_BY_ROOT = fnv1a_64_lower("CONNECT_BY_ROOT"); long DATE = fnv1a_64_lower("DATE"); long GSON = fnv1a_64_lower("GSON"); long NEW = fnv1a_64_lower("NEW"); long NEWDATE = fnv1a_64_lower("NEWDATE"); long DATETIME = fnv1a_64_lower("DATETIME"); long TIME = fnv1a_64_lower("TIME"); long ZONE = fnv1a_64_lower("ZONE"); long JSON = fnv1a_64_lower("JSON"); long TIMESTAMP = fnv1a_64_lower("TIMESTAMP"); long TIMESTAMPTZ = fnv1a_64_lower("TIMESTAMPTZ"); long CLOB = fnv1a_64_lower("CLOB"); long NCLOB = fnv1a_64_lower("NCLOB"); long TINYBLOB = fnv1a_64_lower("TINYBLOB"); long BLOB = fnv1a_64_lower("BLOB"); long XMLTYPE = fnv1a_64_lower("XMLTYPE"); long BFILE = fnv1a_64_lower("BFILE"); long UROWID = fnv1a_64_lower("UROWID"); long ROWID = fnv1a_64_lower("ROWID"); long REF = fnv1a_64_lower("REF"); long INTEGER = fnv1a_64_lower("INTEGER"); long INT = fnv1a_64_lower("INT"); long INT24 = fnv1a_64_lower("INT24"); long BINARY_FLOAT = fnv1a_64_lower("BINARY_FLOAT"); long BINARY_DOUBLE = fnv1a_64_lower("BINARY_DOUBLE"); long FLOAT = fnv1a_64_lower("FLOAT"); long REAL = fnv1a_64_lower("REAL"); long NUMBER = fnv1a_64_lower("NUMBER"); long NUMERIC = fnv1a_64_lower("NUMERIC"); long DEC = fnv1a_64_lower("DEC"); long DECIMAL = fnv1a_64_lower("DECIMAL"); long CURRENT = fnv1a_64_lower("CURRENT"); long COUNT = fnv1a_64_lower("COUNT"); long ROW_NUMBER = fnv1a_64_lower("ROW_NUMBER"); long FIRST_VALUE = fnv1a_64_lower("FIRST_VALUE"); long LAST_VALUE = fnv1a_64_lower("LAST_VALUE"); long WM_CONCAT = fnv1a_64_lower("WM_CONCAT"); long AVG = fnv1a_64_lower("AVG"); long MAX = fnv1a_64_lower("MAX"); long MIN = fnv1a_64_lower("MIN"); long STDDEV = fnv1a_64_lower("STDDEV"); long RANK = fnv1a_64_lower("RANK"); long SUM = fnv1a_64_lower("SUM"); long ARBITRARY = fnv1a_64_lower("ARBITRARY"); long GROUP_CONCAT = fnv1a_64_lower("GROUP_CONCAT"); long CONVERT_TZ = fnv1a_64_lower("CONVERT_TZ"); long DEDUPLICATION = fnv1a_64_lower("DEDUPLICATION"); long CONVERT = fnv1a_64_lower("CONVERT"); long CHAR = fnv1a_64_lower("CHAR"); long ENUM = fnv1a_64_lower("ENUM"); long STRING = fnv1a_64_lower("STRING"); long VARCHAR = fnv1a_64_lower("VARCHAR"); long VARCHAR2 = fnv1a_64_lower("VARCHAR2"); long NCHAR = fnv1a_64_lower("NCHAR"); long NVARCHAR = fnv1a_64_lower("NVARCHAR"); long NVARCHAR2 = fnv1a_64_lower("NVARCHAR2"); long NCHAR_VARYING = fnv1a_64_lower("nchar varying"); long VARBINARY = fnv1a_64_lower("VARBINARY"); long TINYTEXT = fnv1a_64_lower("TINYTEXT"); long TEXT = fnv1a_64_lower("TEXT"); long MEDIUMTEXT = fnv1a_64_lower("MEDIUMTEXT"); long LONGTEXT = fnv1a_64_lower("LONGTEXT"); long TRIM = fnv1a_64_lower("TRIM"); long LEADING = fnv1a_64_lower("LEADING"); long BOTH = fnv1a_64_lower("BOTH"); long TRAILING = fnv1a_64_lower("TRAILING"); long MOD = fnv1a_64_lower("MOD"); long MATCH = fnv1a_64_lower("MATCH"); long AGAINST = fnv1a_64_lower("AGAINST"); long EXTRACT = fnv1a_64_lower("EXTRACT"); long POLYGON = fnv1a_64_lower("POLYGON"); long CIRCLE = fnv1a_64_lower("CIRCLE"); long LSEG = fnv1a_64_lower("LSEG"); long POINT = fnv1a_64_lower("POINT"); long E = fnv1a_64_lower("E"); long BOX = fnv1a_64_lower("BOX"); long MACADDR = fnv1a_64_lower("MACADDR"); long INET = fnv1a_64_lower("INET"); long CIDR = fnv1a_64_lower("CIDR"); long POSITION = fnv1a_64_lower("POSITION"); long DUAL = fnv1a_64_lower("DUAL"); long LEVEL = fnv1a_64_lower("LEVEL"); long CONNECT_BY_ISCYCLE = fnv1a_64_lower("CONNECT_BY_ISCYCLE"); long CURRENT_TIMESTAMP = fnv1a_64_lower("CURRENT_TIMESTAMP"); long LOCALTIMESTAMP = fnv1a_64_lower("LOCALTIMESTAMP"); long LOCALTIME = fnv1a_64_lower("LOCALTIME"); long SESSIONTIMEZONE = fnv1a_64_lower("SESSIONTIMEZONE"); long DBTIMEZONE = fnv1a_64_lower("DBTIMEZONE"); long CURRENT_DATE = fnv1a_64_lower("CURRENT_DATE"); long CURRENT_TIME = fnv1a_64_lower("CURRENT_TIME"); long CURTIME = fnv1a_64_lower("CURTIME"); long CURRENT_USER = fnv1a_64_lower("CURRENT_USER"); long FALSE = fnv1a_64_lower("FALSE"); long TRUE = fnv1a_64_lower("TRUE"); long LESS = fnv1a_64_lower("LESS"); long MAXVALUE = fnv1a_64_lower("MAXVALUE"); long OFFSET = fnv1a_64_lower("OFFSET"); long LIMIT = fnv1a_64_lower("LIMIT"); long RAW = fnv1a_64_lower("RAW"); long LONG_RAW = fnv1a_64_lower("LONG RAW"); long LONG = fnv1a_64_lower("LONG"); long BYTE = fnv1a_64_lower("BYTE"); long ROWNUM = fnv1a_64_lower("ROWNUM"); long SYSDATE = fnv1a_64_lower("SYSDATE"); long NOW = fnv1a_64_lower("NOW"); long ADDTIME = fnv1a_64_lower("ADDTIME"); long SUBTIME = fnv1a_64_lower("SUBTIME"); long TIMEDIFF = fnv1a_64_lower("TIMEDIFF"); long SQLCODE = fnv1a_64_lower("SQLCODE"); long PRECISION = fnv1a_64_lower("PRECISION"); long DOUBLE = fnv1a_64_lower("DOUBLE"); long DOUBLE_PRECISION = fnv1a_64_lower("DOUBLE PRECISION"); long WITHOUT = fnv1a_64_lower("WITHOUT"); long BITAND = fnv1a_64_lower("BITAND"); long DEFINER = fnv1a_64_lower("DEFINER"); long EVENT = fnv1a_64_lower("EVENT"); long RESOURCE = fnv1a_64_lower("RESOURCE"); long RESOURCES = fnv1a_64_lower("RESOURCES"); long FILE = fnv1a_64_lower("FILE"); long JAR = fnv1a_64_lower("JAR"); long PY = fnv1a_64_lower("PY"); long ARCHIVE = fnv1a_64_lower("archive"); long DETERMINISTIC = fnv1a_64_lower("DETERMINISTIC"); long CONTAINS = fnv1a_64_lower("CONTAINS"); long SQL = fnv1a_64_lower("SQL"); long CALL = fnv1a_64_lower("CALL"); long CHARACTER = fnv1a_64_lower("CHARACTER"); long UNNEST = fnv1a_64_lower("UNNEST"); long VALIDATE = fnv1a_64_lower("VALIDATE"); long NOVALIDATE = fnv1a_64_lower("NOVALIDATE"); long SIMILAR = fnv1a_64_lower("SIMILAR"); long CASCADE = fnv1a_64_lower("CASCADE"); long RELY = fnv1a_64_lower("RELY"); long NORELY = fnv1a_64_lower("NORELY"); long ROW = fnv1a_64_lower("ROW"); long ROWS = fnv1a_64_lower("ROWS"); long RANGE = fnv1a_64_lower("RANGE"); long PRECEDING = fnv1a_64_lower("PRECEDING"); long FOLLOWING = fnv1a_64_lower("FOLLOWING"); long UNBOUNDED = fnv1a_64_lower("UNBOUNDED"); long SIBLINGS = fnv1a_64_lower("SIBLINGS"); long RESPECT = fnv1a_64_lower("RESPECT"); long NULLS = fnv1a_64_lower("NULLS"); long FIRST = fnv1a_64_lower("FIRST"); long LAST = fnv1a_64_lower("LAST"); long AUTO_INCREMENT = fnv1a_64_lower("AUTO_INCREMENT"); long STORAGE = fnv1a_64_lower("STORAGE"); long STORED = fnv1a_64_lower("STORED"); long VIRTUAL = fnv1a_64_lower("VIRTUAL"); long SIGNED = fnv1a_64_lower("SIGNED"); long UNSIGNED = fnv1a_64_lower("UNSIGNED"); long ZEROFILL = fnv1a_64_lower("ZEROFILL"); long GLOBAL = fnv1a_64_lower("GLOBAL"); long LOCAL = fnv1a_64_lower("LOCAL"); long TEMPORARY = fnv1a_64_lower("TEMPORARY"); long NONCLUSTERED = fnv1a_64_lower("NONCLUSTERED"); long SESSION = fnv1a_64_lower("SESSION"); long NAMES = fnv1a_64_lower("NAMES"); long PARTIAL = fnv1a_64_lower("PARTIAL"); long SIMPLE = fnv1a_64_lower("SIMPLE"); long RESTRICT = fnv1a_64_lower("RESTRICT"); long ON = fnv1a_64_lower("ON"); long ACTION = fnv1a_64_lower("ACTION"); long SEPARATOR = fnv1a_64_lower("SEPARATOR"); long DATA = fnv1a_64_lower("DATA"); long MIGRATE = fnv1a_64_lower("MIGRATE"); long MAX_ROWS = fnv1a_64_lower("MAX_ROWS"); long MIN_ROWS = fnv1a_64_lower("MIN_ROWS"); long PACK_KEYS = fnv1a_64_lower("PACK_KEYS"); long ENGINE = fnv1a_64_lower("ENGINE"); long SKIP = fnv1a_64_lower("SKIP"); long RECURSIVE = fnv1a_64_lower("RECURSIVE"); long ROLLUP = fnv1a_64_lower("ROLLUP"); long CUBE = fnv1a_64_lower("CUBE"); long YEAR = fnv1a_64_lower("YEAR"); long QUARTER = fnv1a_64_lower("QUARTER"); long MONTH = fnv1a_64_lower("MONTH"); long WEEK = fnv1a_64_lower("WEEK"); long WEEKDAY = fnv1a_64_lower("WEEKDAY"); long WEEKOFYEAR = fnv1a_64_lower("WEEKOFYEAR"); long YEARWEEK = fnv1a_64_lower("YEARWEEK"); long YEAR_OF_WEEK = fnv1a_64_lower("YEAR_OF_WEEK"); long YOW = fnv1a_64_lower("YOW"); long YEARMONTH = fnv1a_64_lower("YEARMONTH"); long TO_TIMESTAMP = fnv1a_64_lower("TO_TIMESTAMP"); long DAY = fnv1a_64_lower("DAY"); long DAYOFMONTH = fnv1a_64_lower("DAYOFMONTH"); long DAYOFWEEK = fnv1a_64_lower("DAYOFWEEK"); long DATE_TRUNC = fnv1a_64_lower("DATE_TRUNC"); long DAYOFYEAR = fnv1a_64_lower("DAYOFYEAR"); long MONTH_BETWEEN = fnv1a_64_lower("MONTH_BETWEEN"); long TIMESTAMPADD = fnv1a_64_lower("TIMESTAMPADD"); long HOUR = fnv1a_64_lower("HOUR"); long MINUTE = fnv1a_64_lower("MINUTE"); long SECOND = fnv1a_64_lower("SECOND"); long MICROSECOND = fnv1a_64_lower("MICROSECOND"); long CURDATE = fnv1a_64_lower("CURDATE"); long CUR_DATE = fnv1a_64_lower("CUR_DATE"); long DATE_DIFF = fnv1a_64_lower("DATE_DIFF"); long SECONDS = fnv1a_64_lower("SECONDS"); long MINUTES = fnv1a_64_lower("MINUTES"); long HOURS = fnv1a_64_lower("HOURS"); long DAYS = fnv1a_64_lower("DAYS"); long MONTHS = fnv1a_64_lower("MONTHS"); long YEARS = fnv1a_64_lower("YEARS"); long BEFORE = fnv1a_64_lower("BEFORE"); long AFTER = fnv1a_64_lower("AFTER"); long INSTEAD = fnv1a_64_lower("INSTEAD"); long DEFERRABLE = fnv1a_64_lower("DEFERRABLE"); long AS = fnv1a_64_lower("AS"); long DELAYED = fnv1a_64_lower("DELAYED"); long GO = fnv1a_64_lower("GO"); long WAITFOR = fnv1a_64_lower("WAITFOR"); long EXEC = fnv1a_64_lower("EXEC"); long EXECUTE = fnv1a_64_lower("EXECUTE"); long SOURCE = fnv1a_64_lower("SOURCE"); long STAR = fnv1a_64_lower("*"); long TO_CHAR = fnv1a_64_lower("TO_CHAR"); long UNIX_TIMESTAMP = fnv1a_64_lower("UNIX_TIMESTAMP"); long FROM_UNIXTIME = fnv1a_64_lower("FROM_UNIXTIME"); long TO_UNIXTIME = fnv1a_64_lower("TO_UNIXTIME"); long SYS_GUID = fnv1a_64_lower("SYS_GUID"); long LAST_DAY = fnv1a_64_lower("LAST_DAY"); long MAKEDATE = fnv1a_64_lower("MAKEDATE"); long ASCII = fnv1a_64_lower("ASCII"); long DAYNAME = fnv1a_64_lower("DAYNAME"); long STATISTICS = fnv1a_64_lower("STATISTICS"); long TRANSACTION = fnv1a_64_lower("TRANSACTION"); long OFF = fnv1a_64_lower("OFF"); long IDENTITY_INSERT = fnv1a_64_lower("IDENTITY_INSERT"); long PASSWORD = fnv1a_64_lower("PASSWORD"); long SOCKET = fnv1a_64_lower("SOCKET"); long OWNER = fnv1a_64_lower("OWNER"); long PORT = fnv1a_64_lower("PORT"); long PUBLIC = fnv1a_64_lower("PUBLIC"); long SYNONYM = fnv1a_64_lower("SYNONYM"); long MATERIALIZED = fnv1a_64_lower("MATERIALIZED"); long BITMAP = fnv1a_64_lower("BITMAP"); long LABEL = fnv1a_64_lower("LABEL"); long PACKAGE = fnv1a_64_lower("PACKAGE"); long PACKAGES = fnv1a_64_lower("PACKAGES"); long TRUNC = fnv1a_64_lower("TRUNC"); long SYSTIMESTAMP = fnv1a_64_lower("SYSTIMESTAMP"); long TYPE = fnv1a_64_lower("TYPE"); long RECORD = fnv1a_64_lower("RECORD"); long MAP = fnv1a_64_lower("MAP"); long MAPJOIN = fnv1a_64_lower("MAPJOIN"); long MAPPED = fnv1a_64_lower("MAPPED"); long MAPPING = fnv1a_64_lower("MAPPING"); long COLPROPERTIES = fnv1a_64_lower("COLPROPERTIES"); long ONLY = fnv1a_64_lower("ONLY"); long MEMBER = fnv1a_64_lower("MEMBER"); long STATIC = fnv1a_64_lower("STATIC"); long FINAL = fnv1a_64_lower("FINAL"); long INSTANTIABLE = fnv1a_64_lower("INSTANTIABLE"); long UNSUPPORTED = fnv1a_64_lower("UNSUPPORTED"); long VARRAY = fnv1a_64_lower("VARRAY"); long WRAPPED = fnv1a_64_lower("WRAPPED"); long AUTHID = fnv1a_64_lower("AUTHID"); long UNDER = fnv1a_64_lower("UNDER"); long USERENV = fnv1a_64_lower("USERENV"); long NUMTODSINTERVAL = fnv1a_64_lower("NUMTODSINTERVAL"); long LATERAL = fnv1a_64_lower("LATERAL"); long NONE = fnv1a_64_lower("NONE"); long PARTITIONING = fnv1a_64_lower("PARTITIONING"); long VALIDPROC = fnv1a_64_lower("VALIDPROC"); long COMPRESS = fnv1a_64_lower("COMPRESS"); long YES = fnv1a_64_lower("YES"); long WMSYS = fnv1a_64_lower("WMSYS"); long DEPTH = fnv1a_64_lower("DEPTH"); long BREADTH = fnv1a_64_lower("BREADTH"); long SCHEDULE = fnv1a_64_lower("SCHEDULE"); long COMPLETION = fnv1a_64_lower("COMPLETION"); long RENAME = fnv1a_64_lower("RENAME"); long AT = fnv1a_64_lower("AT"); long LANGUAGE = fnv1a_64_lower("LANGUAGE"); long LOGFILE = fnv1a_64_lower("LOGFILE"); long LOG = fnv1a_64_lower("LOG"); long INITIAL_SIZE = fnv1a_64_lower("INITIAL_SIZE"); long MAX_SIZE = fnv1a_64_lower("MAX_SIZE"); long NODEGROUP = fnv1a_64_lower("NODEGROUP"); long EXTENT_SIZE = fnv1a_64_lower("EXTENT_SIZE"); long AUTOEXTEND_SIZE = fnv1a_64_lower("AUTOEXTEND_SIZE"); long FILE_BLOCK_SIZE = fnv1a_64_lower("FILE_BLOCK_SIZE"); long BLOCK_SIZE = fnv1a_64_lower("BLOCK_SIZE"); long REPLICA_NUM = fnv1a_64_lower("REPLICA_NUM"); long TABLET_SIZE = fnv1a_64_lower("TABLET_SIZE"); long PCTFREE = fnv1a_64_lower("PCTFREE"); long USE_BLOOM_FILTER = fnv1a_64_lower("USE_BLOOM_FILTER"); long SERVER = fnv1a_64_lower("SERVER"); long HOST = fnv1a_64_lower("HOST"); long ADD = fnv1a_64_lower("ADD"); long REMOVE = fnv1a_64_lower("REMOVE"); long MOVE = fnv1a_64_lower("MOVE"); long ALGORITHM = fnv1a_64_lower("ALGORITHM"); long LINEAR = fnv1a_64_lower("LINEAR"); long EVERY = fnv1a_64_lower("EVERY"); long STARTS = fnv1a_64_lower("STARTS"); long ENDS = fnv1a_64_lower("ENDS"); long BINARY = fnv1a_64_lower("BINARY"); long GEOMETRY = fnv1a_64_lower("GEOMETRY"); long ISOPEN = fnv1a_64_lower("ISOPEN"); long CONFLICT = fnv1a_64_lower("CONFLICT"); long NOTHING = fnv1a_64_lower("NOTHING"); long COMMIT = fnv1a_64_lower("COMMIT"); long DESCRIBE = fnv1a_64_lower("DESCRIBE"); long SQLXML = fnv1a_64_lower("SQLXML"); long BIT = fnv1a_64_lower("BIT"); long LONGBLOB = fnv1a_64_lower("LONGBLOB"); long RS = fnv1a_64_lower("RS"); long RR = fnv1a_64_lower("RR"); long CS = fnv1a_64_lower("CS"); long UR = fnv1a_64_lower("UR"); long INT4 = fnv1a_64_lower("INT4"); long VARBIT = fnv1a_64_lower("VARBIT"); long DECODE = fnv1a_64_lower("DECODE"); long IF = fnv1a_64_lower("IF"); long FUNCTION = fnv1a_64_lower("FUNCTION"); long EXTERNAL = fnv1a_64_lower("EXTERNAL"); long SORTED = fnv1a_64_lower("SORTED"); long CLUSTERED = fnv1a_64_lower("CLUSTERED"); long LIFECYCLE = fnv1a_64_lower("LIFECYCLE"); long LOCATION = fnv1a_64_lower("LOCATION"); long PARTITIONS = fnv1a_64_lower("PARTITIONS"); long FORMAT = fnv1a_64_lower("FORMAT"); long ENCODE = fnv1a_64_lower("ENCODE"); long SELECT = fnv1a_64_lower("SELECT"); long DELETE = fnv1a_64_lower("DELETE"); long UPDATE = fnv1a_64_lower("UPDATE"); long INSERT = fnv1a_64_lower("INSERT"); long REPLACE = fnv1a_64_lower("REPLACE"); long TRUNCATE = fnv1a_64_lower("TRUNCATE"); long CREATE = fnv1a_64_lower("CREATE"); long MERGE = fnv1a_64_lower("MERGE"); long SHOW = fnv1a_64_lower("SHOW"); long ALTER = fnv1a_64_lower("ALTER"); long DESC = fnv1a_64_lower("DESC"); long SET = fnv1a_64_lower("SET"); long KILL = fnv1a_64_lower("KILL"); long MSCK = fnv1a_64_lower("MSCK"); long USE = fnv1a_64_lower("USE"); long ROLLBACK = fnv1a_64_lower("ROLLBACK"); long GRANT = fnv1a_64_lower("GRANT"); long REVOKE = fnv1a_64_lower("REVOKE"); long DROP = fnv1a_64_lower("DROP"); long USER = fnv1a_64_lower("USER"); long USAGE = fnv1a_64_lower("USAGE"); long PCTUSED = fnv1a_64_lower("PCTUSED"); long OPAQUE = fnv1a_64_lower("OPAQUE"); long INHERITS = fnv1a_64_lower("INHERITS"); long DELIMITED = fnv1a_64_lower("DELIMITED"); long ARRAY = fnv1a_64_lower("ARRAY"); long SCALAR = fnv1a_64_lower("SCALAR"); long STRUCT = fnv1a_64_lower("STRUCT"); long TABLE = fnv1a_64_lower("TABLE"); long UNIONTYPE = fnv1a_64_lower("UNIONTYPE"); long TDDL = fnv1a_64_lower("TDDL"); long CONCURRENTLY = fnv1a_64_lower("CONCURRENTLY"); long TABLES = fnv1a_64_lower("TABLES"); long ROLES = fnv1a_64_lower("ROLES"); long NOCACHE = fnv1a_64_lower("NOCACHE"); long NOPARALLEL = fnv1a_64_lower("NOPARALLEL"); long EXIST = fnv1a_64_lower("EXIST"); long EXISTS = fnv1a_64_lower("EXISTS"); long SOUNDS = fnv1a_64_lower("SOUNDS"); long TBLPROPERTIES = fnv1a_64_lower("TBLPROPERTIES"); long TABLEGROUP = fnv1a_64_lower("TABLEGROUP"); long TABLEGROUPS = fnv1a_64_lower("TABLEGROUPS"); long DIMENSION = fnv1a_64_lower("DIMENSION"); long OPTIONS = fnv1a_64_lower("OPTIONS"); long OPTIMIZER = fnv1a_64_lower("OPTIMIZER"); long FULLTEXT = fnv1a_64_lower("FULLTEXT"); long SPATIAL = fnv1a_64_lower("SPATIAL"); long SUBPARTITION_AVAILABLE_PARTITION_NUM = fnv1a_64_lower("SUBPARTITION_AVAILABLE_PARTITION_NUM"); long EXTRA = fnv1a_64_lower("EXTRA"); long DATABASES = fnv1a_64_lower("DATABASES"); long COLUMNS = fnv1a_64_lower("COLUMNS"); long PROCESS = fnv1a_64_lower("PROCESS"); long PROCESSLIST = fnv1a_64_lower("PROCESSLIST"); long MPP = fnv1a_64_lower("MPP"); long SERDE = fnv1a_64_lower("SERDE"); long SORT = fnv1a_64_lower("SORT"); long ZORDER = fnv1a_64_lower("ZORDER"); long FIELDS = fnv1a_64_lower("FIELDS"); long COLLECTION = fnv1a_64_lower("COLLECTION"); long SKEWED = fnv1a_64_lower("SKEWED"); long SYMBOL = fnv1a_64_lower("SYMBOL"); long LOAD = fnv1a_64_lower("LOAD"); long VIEWS = fnv1a_64_lower("VIEWS"); long SUBSTR = fnv1a_64_lower("SUBSTR"); long TO_BASE64 = fnv1a_64_lower("TO_BASE64"); long REGEXP_SUBSTR = fnv1a_64_lower("REGEXP_SUBSTR"); long REGEXP_COUNT = fnv1a_64_lower("REGEXP_COUNT"); long REGEXP_EXTRACT = fnv1a_64_lower("REGEXP_EXTRACT"); long REGEXP_EXTRACT_ALL = fnv1a_64_lower("REGEXP_EXTRACT_ALL"); long REGEXP_LIKE = fnv1a_64_lower("REGEXP_LIKE"); long REGEXP_REPLACE = fnv1a_64_lower("REGEXP_REPLACE"); long REGEXP_SPLIT = fnv1a_64_lower("REGEXP_SPLIT"); long CONCAT = fnv1a_64_lower("CONCAT"); long LCASE = fnv1a_64_lower("LCASE"); long UCASE = fnv1a_64_lower("UCASE"); long LOWER = fnv1a_64_lower("LOWER"); long UPPER = fnv1a_64_lower("UPPER"); long LENGTH = fnv1a_64_lower("LENGTH"); long LOCATE = fnv1a_64_lower("LOCATE"); long UDF_SYS_ROWCOUNT = fnv1a_64_lower("UDF_SYS_ROWCOUNT"); long CHAR_LENGTH = fnv1a_64_lower("CHAR_LENGTH"); long CHARACTER_LENGTH = fnv1a_64_lower("CHARACTER_LENGTH"); long SUBSTRING = fnv1a_64_lower("SUBSTRING"); long SUBSTRING_INDEX = fnv1a_64_lower("SUBSTRING_INDEX"); long LEFT = fnv1a_64_lower("LEFT"); long RIGHT = fnv1a_64_lower("RIGHT"); long RTRIM = fnv1a_64_lower("RTRIM"); long LEN = fnv1a_64_lower("LEN"); long GREAST = fnv1a_64_lower("GREAST"); long LEAST = fnv1a_64_lower("LEAST"); long IFNULL = fnv1a_64_lower("IFNULL"); long NULLIF = fnv1a_64_lower("NULLIF"); long GREATEST = fnv1a_64_lower("GREATEST"); long COALESCE = fnv1a_64_lower("COALESCE"); long ISNULL = fnv1a_64_lower("ISNULL"); long NVL = fnv1a_64_lower("NVL"); long NVL2 = fnv1a_64_lower("NVL2"); long TO_DATE = fnv1a_64_lower("TO_DATE"); long DATEADD = fnv1a_64_lower("DATEADD"); long DATE_ADD = fnv1a_64_lower("DATE_ADD"); long ADDDATE = fnv1a_64_lower("ADDDATE"); long DATE_SUB = fnv1a_64_lower("DATE_SUB"); long SUBDATE = fnv1a_64_lower("SUBDATE"); long DATE_PARSE = fnv1a_64_lower("DATE_PARSE"); long STR_TO_DATE = fnv1a_64_lower("STR_TO_DATE"); long CLOTHES_FEATURE_EXTRACT_V1 = fnv1a_64_lower("CLOTHES_FEATURE_EXTRACT_V1"); long CLOTHES_ATTRIBUTE_EXTRACT_V1 = fnv1a_64_lower("CLOTHES_ATTRIBUTE_EXTRACT_V1"); long GENERIC_FEATURE_EXTRACT_V1 = fnv1a_64_lower("GENERIC_FEATURE_EXTRACT_V1"); long FACE_FEATURE_EXTRACT_V1 = fnv1a_64_lower("FACE_FEATURE_EXTRACT_V1"); long TEXT_FEATURE_EXTRACT_V1 = fnv1a_64_lower("TEXT_FEATURE_EXTRACT_V1"); long JSON_TABLE = fnv1a_64_lower("JSON_TABLE"); long JSON_EXTRACT = fnv1a_64_lower("JSON_EXTRACT"); long JSON_EXTRACT_SCALAR = fnv1a_64_lower("json_extract_scalar"); long JSON_ARRAY_GET = fnv1a_64_lower("JSON_ARRAY_GET"); long ADD_MONTHS = fnv1a_64_lower("ADD_MONTHS"); long ABS = fnv1a_64_lower("ABS"); long ACOS = fnv1a_64_lower("ACOS"); long ASIN = fnv1a_64_lower("ASIN"); long ATAN = fnv1a_64_lower("ATAN"); long ATAN2 = fnv1a_64_lower("ATAN2"); long COS = fnv1a_64_lower("COS"); long FLOOR = fnv1a_64_lower("FLOOR"); long CEIL = fnv1a_64_lower("CEIL"); long SQRT = fnv1a_64_lower("SQRT"); long LEAD = fnv1a_64_lower("LEAD"); long LAG = fnv1a_64_lower("LAG"); long CEILING = fnv1a_64_lower("CEILING"); long POWER = fnv1a_64_lower("POWER"); long EXP = fnv1a_64_lower("EXP"); long LN = fnv1a_64_lower("LN"); long LOG10 = fnv1a_64_lower("LOG10"); long INTERVAL = fnv1a_64_lower("INTERVAL"); long FROM_DAYS = fnv1a_64_lower("FROM_DAYS"); long TO_DAYS = fnv1a_64_lower("TO_DAYS"); long BIGINT = fnv1a_64_lower("BIGINT"); long LONGLONG = fnv1a_64_lower("LONGLONG"); long DISCARD = fnv1a_64_lower("DISCARD"); long EXCHANGE = fnv1a_64_lower("EXCHANGE"); long ROLE = fnv1a_64_lower("ROLE"); long OVERWRITE = fnv1a_64_lower("OVERWRITE"); long NO = fnv1a_64_lower("NO"); long CATALOG = fnv1a_64_lower("CATALOG"); long CATALOGS = fnv1a_64_lower("CATALOGS"); long FUNCTIONS = fnv1a_64_lower("FUNCTIONS"); long SCHEMAS = fnv1a_64_lower("SCHEMAS"); long CHANGE = fnv1a_64_lower("CHANGE"); long MODIFY = fnv1a_64_lower("MODIFY"); long BEGIN = fnv1a_64_lower("BEGIN"); long PATH = fnv1a_64_lower("PATH"); long ENCRYPTION = fnv1a_64_lower("ENCRYPTION"); long COMPRESSION = fnv1a_64_lower("COMPRESSION"); long KEY_BLOCK_SIZE = fnv1a_64_lower("KEY_BLOCK_SIZE"); long CHECKSUM = fnv1a_64_lower("CHECKSUM"); long CONNECTION = fnv1a_64_lower("CONNECTION"); long DATASOURCES = fnv1a_64_lower("DATASOURCES"); long NODE = fnv1a_64_lower("NODE"); long HELP = fnv1a_64_lower("HELP"); long BROADCASTS = fnv1a_64_lower("BROADCASTS"); long MASTER = fnv1a_64_lower("MASTER"); long SLAVE = fnv1a_64_lower("SLAVE"); long SQL_DELAY_CUTOFF = fnv1a_64_lower("SQL_DELAY_CUTOFF"); long SOCKET_TIMEOUT = fnv1a_64_lower("SOCKET_TIMEOUT"); long FORBID_EXECUTE_DML_ALL = fnv1a_64_lower("FORBID_EXECUTE_DML_ALL"); long SCAN = fnv1a_64_lower("SCAN"); long NOLOGFILE = fnv1a_64_lower("NOLOGFILE"); long NOBADFILE = fnv1a_64_lower("NOBADFILE"); long TERMINATED = fnv1a_64_lower("TERMINATED"); long LTRIM = fnv1a_64_lower("LTRIM"); long MISSING = fnv1a_64_lower("MISSING"); long SUBPARTITION = fnv1a_64_lower("SUBPARTITION"); long SUBPARTITIONS = fnv1a_64_lower("SUBPARTITIONS"); long GENERATED = fnv1a_64_lower("GENERATED"); long ALWAYS = fnv1a_64_lower("ALWAYS"); long VISIBLE = fnv1a_64_lower("VISIBLE"); long INCLUDING = fnv1a_64_lower("INCLUDING"); long EXCLUDE = fnv1a_64_lower("EXCLUDE"); long EXCLUDING = fnv1a_64_lower("EXCLUDING"); long ROUTINE = fnv1a_64_lower("ROUTINE"); long IDENTIFIED = fnv1a_64_lower("IDENTIFIED"); long DELIMITER = fnv1a_64_lower("DELIMITER"); long UNKNOWN = fnv1a_64_lower("UNKNOWN"); long WEIGHT_STRING = fnv1a_64_lower("WEIGHT_STRING"); long REVERSE = fnv1a_64_lower("REVERSE"); long DATE_FORMAT = fnv1a_64_lower("DATE_FORMAT"); long DAY_OF_WEEK = fnv1a_64_lower("DAY_OF_WEEK"); long DATEDIFF = fnv1a_64_lower("DATEDIFF"); long GET_FORMAT = fnv1a_64_lower("GET_FORMAT"); long TIMESTAMPDIFF = fnv1a_64_lower("TIMESTAMPDIFF"); long MONTHNAME = fnv1a_64_lower("MONTHNAME"); long PERIOD_ADD = fnv1a_64_lower("PERIOD_ADD"); long PERIOD_DIFF = fnv1a_64_lower("PERIOD_DIFF"); long ROUND = fnv1a_64_lower("ROUND"); long DBPARTITION = fnv1a_64_lower("DBPARTITION"); long TBPARTITION = fnv1a_64_lower("TBPARTITION"); long EXTPARTITION = fnv1a_64_lower("EXTPARTITION"); long STARTWITH = fnv1a_64_lower("STARTWITH"); long TBPARTITIONS = fnv1a_64_lower("TBPARTITIONS"); long DBPARTITIONS = fnv1a_64_lower("DBPARTITIONS"); long PARTITIONED = fnv1a_64_lower("PARTITIONED"); long PARALLEL = fnv1a_64_lower("PARALLEL"); long ALLOW = fnv1a_64_lower("ALLOW"); long DISALLOW = fnv1a_64_lower("DISALLOW"); long PIVOT = fnv1a_64_lower("PIVOT"); long MODEL = fnv1a_64_lower("MODEL"); long KEEP = fnv1a_64_lower("KEEP"); long REFERENCE = fnv1a_64_lower("REFERENCE"); long RETURN = fnv1a_64_lower("RETURN"); long RETURNS = fnv1a_64_lower("RETURNS"); long ROWTYPE = fnv1a_64_lower("ROWTYPE"); long WINDOW = fnv1a_64_lower("WINDOW"); long QUALIFY = fnv1a_64_lower("QUALIFY"); long MULTIVALUE = fnv1a_64_lower("MULTIVALUE"); long OPTIONALLY = fnv1a_64_lower("OPTIONALLY"); long ENCLOSED = fnv1a_64_lower("ENCLOSED"); long ESCAPED = fnv1a_64_lower("ESCAPED"); long ESCAPE = fnv1a_64_lower("ESCAPE"); long LINES = fnv1a_64_lower("LINES"); long STARTING = fnv1a_64_lower("STARTING"); long DISTRIBUTE = fnv1a_64_lower("DISTRIBUTE"); long DISTRIBUTED = fnv1a_64_lower("DISTRIBUTED"); long CLUSTER = fnv1a_64_lower("CLUSTER"); long RUNNING = fnv1a_64_lower("RUNNING"); long CLUSTERING = fnv1a_64_lower("CLUSTERING"); long PCTVERSION = fnv1a_64_lower("PCTVERSION"); long IDENTITY = fnv1a_64_lower("IDENTITY"); long INCREMENT = fnv1a_64_lower("INCREMENT"); long MINVALUE = fnv1a_64_lower("MINVALUE"); long ANN = fnv1a_64_lower("ANN"); long ANN_DISTANCE = fnv1a_64_lower("ANN_DISTANCE"); long SUPPLEMENTAL = fnv1a_64_lower("SUPPLEMENTAL"); long SUBSTITUTABLE = fnv1a_64_lower("SUBSTITUTABLE"); long BASICFILE = fnv1a_64_lower("BASICFILE"); long IN_MEMORY_METADATA = fnv1a_64_lower("IN_MEMORY_METADATA"); long CURSOR_SPECIFIC_SEGMENT = fnv1a_64_lower("CURSOR_SPECIFIC_SEGMENT"); long DEFER = fnv1a_64_lower("DEFER"); long UNDO_LOG_LIMIT = fnv1a_64_lower("UNDO_LOG_LIMIT"); long DBPROPERTIES = fnv1a_64_lower("DBPROPERTIES"); long ANNINDEX = fnv1a_64_lower("ANNINDEX"); long RTTYPE = fnv1a_64_lower("RTTYPE"); long DISTANCE = fnv1a_64_lower("DISTANCE"); long IDXPROPERTIES = fnv1a_64_lower("IDXPROPERTIES"); long RECOVER = fnv1a_64_lower("RECOVER"); long BACKUP = fnv1a_64_lower("BACKUP"); long RESTORE = fnv1a_64_lower("RESTORE"); long EXSTORE = fnv1a_64_lower("EXSTORE"); long UNDO = fnv1a_64_lower("UNDO"); long NOSCAN = fnv1a_64_lower("NOSCAN"); long EXTENDED = fnv1a_64_lower("EXTENDED"); long FORMATTED = fnv1a_64_lower("FORMATTED"); long DEPENDENCY = fnv1a_64_lower("DEPENDENCY"); long AUTHORIZATION = fnv1a_64_lower("AUTHORIZATION"); long ANALYZE = fnv1a_64_lower("ANALYZE"); long EXPORT = fnv1a_64_lower("EXPORT"); long IMPORT = fnv1a_64_lower("IMPORT"); long TABLESAMPLE = fnv1a_64_lower("TABLESAMPLE"); long BUCKET = fnv1a_64_lower("BUCKET"); long BUCKETS = fnv1a_64_lower("BUCKETS"); long UNARCHIVE = fnv1a_64_lower("UNARCHIVE"); long SEQUENCES = fnv1a_64_lower("SEQUENCES"); long OUTLINE = fnv1a_64_lower("OUTLINE"); long ORD = fnv1a_64_lower("ORD"); long SPACE = fnv1a_64_lower("SPACE"); long REPEAT = fnv1a_64_lower("REPEAT"); long SLOW = fnv1a_64_lower("SLOW"); long PLAN = fnv1a_64_lower("PLAN"); long PLANCACHE = fnv1a_64_lower("PLANCACHE"); long RECYCLEBIN = fnv1a_64_lower("RECYCLEBIN"); long PURGE = fnv1a_64_lower("PURGE"); long FLASHBACK = fnv1a_64_lower("FLASHBACK"); long INPUTFORMAT = fnv1a_64_lower("INPUTFORMAT"); long OUTPUTFORMAT = fnv1a_64_lower("OUTPUTFORMAT"); long DUMP = fnv1a_64_lower("DUMP"); long BROADCAST = fnv1a_64_lower("BROADCAST"); long GROUP = fnv1a_64_lower("GROUP"); long GROUPING = fnv1a_64_lower("GROUPING"); long WITH = fnv1a_64_lower("WITH"); long FROM = fnv1a_64_lower("FROM"); long WHO = fnv1a_64_lower("WHO"); long WHOAMI = fnv1a_64_lower("WHOAMI"); long GRANTS = fnv1a_64_lower("GRANTS"); long STATISTIC = fnv1a_64_lower("STATISTIC"); long STATISTIC_LIST = fnv1a_64_lower("STATISTIC_LIST"); long STATUS = fnv1a_64_lower("STATUS"); long FULL = fnv1a_64_lower("FULL"); long STATS = fnv1a_64_lower("STATS"); long OUTLINES = fnv1a_64_lower("OUTLINES"); long VERSION = fnv1a_64_lower("VERSION"); long CONFIG = fnv1a_64_lower("CONFIG"); long USERS = fnv1a_64_lower("USERS"); long PHYSICAL_PROCESSLIST = fnv1a_64_lower("PHYSICAL_PROCESSLIST"); long PHYSICAL = fnv1a_64_lower("PHYSICAL"); long DISTANCEMEASURE = fnv1a_64_lower("DISTANCEMEASURE"); long UNIT = fnv1a_64_lower("UNIT"); long DB = fnv1a_64_lower("DB"); long STEP = fnv1a_64_lower("STEP"); long HEX = fnv1a_64_lower("HEX"); long UNHEX = fnv1a_64_lower("UNHEX"); long POLICY = fnv1a_64_lower("POLICY"); long QUERY_TASK = fnv1a_64_lower("QUERY_TASK"); long UUID = fnv1a_64_lower("UUID"); long PCTTHRESHOLD = fnv1a_64_lower("PCTTHRESHOLD"); long UNUSABLE = fnv1a_64_lower("UNUSABLE"); long FILTER = fnv1a_64_lower("FILTER"); long BIT_COUNT = fnv1a_64_lower("BIT_COUNT"); long STDDEV_SAMP = fnv1a_64_lower("STDDEV_SAMP"); long PERCENT_RANK = fnv1a_64_lower("PERCENT_RANK"); long DENSE_RANK = fnv1a_64_lower("DENSE_RANK"); long CUME_DIST = fnv1a_64_lower("CUME_DIST"); long CARDINALITY = fnv1a_64_lower("CARDINALITY"); long TRY_CAST = fnv1a_64_lower("TRY_CAST"); long COVERING = fnv1a_64_lower("COVERING"); long CHARFILTER = fnv1a_64_lower("CHARFILTER"); long CHARFILTERS = fnv1a_64_lower("CHARFILTERS"); long TOKENIZER = fnv1a_64_lower("TOKENIZER"); long TOKENIZERS = fnv1a_64_lower("TOKENIZERS"); long TOKENFILTER = fnv1a_64_lower("TOKENFILTER"); long TOKENFILTERS = fnv1a_64_lower("TOKENFILTERS"); long ANALYZER = fnv1a_64_lower("ANALYZER"); long ANALYZERS = fnv1a_64_lower("ANALYZERS"); long DICTIONARY = fnv1a_64_lower("DICTIONARY"); long DICTIONARIES = fnv1a_64_lower("DICTIONARIES"); long QUERY = fnv1a_64_lower("QUERY"); long META = fnv1a_64_lower("META"); long TRY = fnv1a_64_lower("TRY"); long D = fnv1a_64_lower("D"); long T = fnv1a_64_lower("T"); long TS = fnv1a_64_lower("TS"); long FN = fnv1a_64_lower("FN"); long COPY = fnv1a_64_lower("COPY"); long CREDENTIALS = fnv1a_64_lower("CREDENTIALS"); long ACCESS_KEY_ID = fnv1a_64_lower("ACCESS_KEY_ID"); long ACCESS_KEY_SECRET = fnv1a_64_lower("ACCESS_KEY_SECRET"); long BERNOULLI = fnv1a_64_lower("BERNOULLI"); long SYSTEM = fnv1a_64_lower("SYSTEM"); long SYNC = fnv1a_64_lower("SYNC"); long INIT = fnv1a_64_lower("INIT"); long BD = fnv1a_64_lower("BD"); long FORMAT_DATETIME = fnv1a_64_lower("FORMAT_DATETIME"); long WITHIN = fnv1a_64_lower("WITHIN"); long RULE = fnv1a_64_lower("RULE"); long EXPLAIN = fnv1a_64_lower("EXPLAIN"); long ISOLATION = fnv1a_64_lower("ISOLATION"); long READ = fnv1a_64_lower("READ"); long UNCOMMITTED = fnv1a_64_lower("UNCOMMITTED"); long COMMITTED = fnv1a_64_lower("COMMITTED"); long REPEATABLE = fnv1a_64_lower("REPEATABLE"); long SERIALIZABLE = fnv1a_64_lower("SERIALIZABLE"); long _LATIN1 = fnv1a_64_lower("_LATIN1"); long _GBK = fnv1a_64_lower("_GBK"); long _BIG5 = fnv1a_64_lower("_BIG5"); long _UTF8 = fnv1a_64_lower("_UTF8"); long _UTF8MB4 = fnv1a_64_lower("_UTF8MB4"); long _UTF16 = fnv1a_64_lower("_UTF16"); long _UTF16LE = fnv1a_64_lower("_UTF16LE"); long _UTF32 = fnv1a_64_lower("_UTF32"); long _UCS2 = fnv1a_64_lower("_UCS2"); long _UJIS = fnv1a_64_lower("_UJIS"); long X = fnv1a_64_lower("X"); long TRANSFORM = fnv1a_64_lower("TRANSFORM"); long NESTED = fnv1a_64_lower("NESTED"); long RESTART = fnv1a_64_lower("RESTART"); long ASOF = fnv1a_64_lower("ASOF"); long JSON_SET = fnv1a_64_lower("JSON_SET"); long JSONB_SET = fnv1a_64_lower("JSONB_SET"); long TUNNEL = fnv1a_64_lower("TUNNEL"); long DOWNLOAD = fnv1a_64_lower("DOWNLOAD"); long UPLOAD = fnv1a_64_lower("UPLOAD"); long CLONE = fnv1a_64_lower("CLONE"); long INSTALL = fnv1a_64_lower("INSTALL"); long UNLOAD = fnv1a_64_lower("UNLOAD"); long AGGREGATE = fnv1a_64_lower("AGGREGATE"); long UNIQUE = fnv1a_64_lower("UNIQUE"); long PRIMARY = fnv1a_64_lower("PRIMARY"); long THAN = fnv1a_64_lower("THAN"); long PROPERTIES = fnv1a_64_lower("PROPERTIES"); long SINGLE = fnv1a_64_lower("SINGLE"); } }
alibaba/druid
core/src/main/java/com/alibaba/druid/util/FnvHash.java
47
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents the known and supported Platforms that WebDriver runs on. This is pretty close to the * Operating System, but differs slightly, because this class is used to extract information such as * program locations and line endings. */ // Useful URLs: // http://hg.openjdk.java.net/jdk7/modules/jdk/file/a37326fa7f95/src/windows/native/java/lang/java_props_md.c public enum Platform { /** Never returned, but can be used to request a browser running on any version of Windows. */ WINDOWS("") { @Override public Platform family() { return null; } @Override public String toString() { return "windows"; } }, /** * For versions of Windows that "feel like" Windows XP. These are ones that store files in * "\Program Files\" and documents under "\\documents and settings\\username" */ XP("Windows Server 2003", "xp", "windows", "winnt", "windows_nt", "windows nt") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows XP"; } }, /** For versions of Windows that "feel like" Windows Vista. */ VISTA("windows vista", "Windows Server 2008") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows Vista"; } }, WIN7("windows 7", "win7") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows 7"; } }, /** For versions of Windows that "feel like" Windows 8. */ WIN8("Windows Server 2012", "windows 8", "win8") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows 8"; } }, WIN8_1("windows 8.1", "win8.1") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows 8.1"; } }, WIN10("windows 10", "win10") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows 10"; } }, WIN11("windows 11", "win11") { @Override public Platform family() { return WINDOWS; } @Override public String toString() { return "Windows 11"; } }, MAC("mac", "darwin", "macOS", "mac os x", "os x") { @Override public Platform family() { return null; } @Override public String toString() { return "mac"; } }, SNOW_LEOPARD("snow leopard", "os x 10.6", "macos 10.6") { @Override public Platform family() { return MAC; } @Override public String toString() { return "OS X 10.6"; } }, MOUNTAIN_LION("mountain lion", "os x 10.8", "macos 10.8") { @Override public Platform family() { return MAC; } @Override public String toString() { return "OS X 10.8"; } }, MAVERICKS("mavericks", "os x 10.9", "macos 10.9") { @Override public Platform family() { return MAC; } @Override public String toString() { return "OS X 10.9"; } }, YOSEMITE("yosemite", "os x 10.10", "macos 10.10") { @Override public Platform family() { return MAC; } @Override public String toString() { return "OS X 10.10"; } }, EL_CAPITAN("el capitan", "os x 10.11", "macos 10.11") { @Override public Platform family() { return MAC; } @Override public String toString() { return "OS X 10.11"; } }, SIERRA("sierra", "os x 10.12", "macos 10.12") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 10.12"; } }, HIGH_SIERRA("high sierra", "os x 10.13", "macos 10.13") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 10.13"; } }, MOJAVE("mojave", "os x 10.14", "macos 10.14") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 10.14"; } }, CATALINA("catalina", "os x 10.15", "macos 10.15") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 10.15"; } }, BIG_SUR("big sur", "os x 11.0", "macos 11.0") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 11.0"; } }, MONTEREY("monterey", "os x 12.0", "macos 12.0") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 12.0"; } }, VENTURA("ventura", "os x 13.0", "macos 13.0") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 13.0"; } }, SONOMA("sonoma", "os x 14.0", "macos 14.0") { @Override public Platform family() { return MAC; } @Override public String toString() { return "macOS 14.0"; } }, /** Many platforms have UNIX traits, amongst them LINUX, Solaris and BSD. */ UNIX("solaris", "bsd") { @Override public Platform family() { return null; } }, LINUX("linux") { @Override public Platform family() { return UNIX; } @Override public String toString() { return "linux"; } }, ANDROID("android", "dalvik") { @Override public Platform family() { return null; } }, IOS("iOS") { @Override public Platform family() { return null; } }, /** Never returned, but can be used to request a browser running on any operating system. */ ANY("") { @Override public Platform family() { return ANY; } @Override public boolean is(Platform compareWith) { return this == compareWith; } @Override public String toString() { return "any"; } }; private static Platform current; private final String[] partOfOsName; private int minorVersion = 0; private int majorVersion = 0; Platform(String... partOfOsName) { this.partOfOsName = partOfOsName; } /** * Get current platform (not necessarily the same as operating system). * * @return current platform */ public static Platform getCurrent() { if (current == null) { current = extractFromSysProperty(System.getProperty("os.name")); String version = System.getProperty("os.version", "0.0.0"); int major = 0; int min = 0; Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+).*"); Matcher matcher = pattern.matcher(version); if (matcher.matches()) { try { major = Integer.parseInt(matcher.group(1)); min = Integer.parseInt(matcher.group(2)); } catch (NumberFormatException e) { // These things happen } } current.majorVersion = major; current.minorVersion = min; } return current; } /** * Extracts platforms based on system properties in Java and uses a heuristic to determine the * most likely operating system. If unable to determine the operating system, it will default to * UNIX. * * @param osName the operating system name to determine the platform of * @return the most likely platform based on given operating system name */ public static Platform extractFromSysProperty(String osName) { return extractFromSysProperty(osName, System.getProperty("os.version")); } /** * Extracts platforms based on system properties in Java and uses a heuristic to determine the * most likely operating system. If unable to determine the operating system, it will default to * UNIX. * * @param osName the operating system name to determine the platform of * @param osVersion the operating system version to determine the platform of * @return the most likely platform based on given operating system name and version */ public static Platform extractFromSysProperty(String osName, String osVersion) { osName = osName.toLowerCase(); // os.name for android is linux if ("dalvik".equalsIgnoreCase(System.getProperty("java.vm.name"))) { return Platform.ANDROID; } // Windows 8 can't be detected by osName alone if (osVersion.equals("6.2") && osName.startsWith("windows nt")) { return WIN8; } // Windows 8 can't be detected by osName alone if (osVersion.equals("6.3") && osName.startsWith("windows nt")) { return WIN8_1; } Platform mostLikely = UNIX; String previousMatch = null; for (Platform os : Platform.values()) { for (String matcher : os.partOfOsName) { if ("".equals(matcher)) { continue; } matcher = matcher.toLowerCase(); if (os.isExactMatch(osName, matcher)) { return os; } if (os.isCurrentPlatform(osName, matcher) && isBetterMatch(previousMatch, matcher)) { previousMatch = matcher; mostLikely = os; } } } // Default to assuming we're on a UNIX variant (including LINUX) return mostLikely; } /** * Gets a platform with the name matching the parameter. * * @param name the platform name * @return the Platform enum value matching the parameter */ public static Platform fromString(String name) { for (Platform platform : values()) { if (platform.toString().equalsIgnoreCase(name)) { return platform; } } for (Platform os : Platform.values()) { for (String matcher : os.partOfOsName) { if (name.equalsIgnoreCase(matcher)) { return os; } } } throw new WebDriverException("Unrecognized platform: " + name); } /** * Decides whether the previous match is better or not than the current match. If previous match * is null, the newer match is always better. * * @param previous the previous match * @param matcher the newer match * @return true if newer match is better, false otherwise */ private static boolean isBetterMatch(String previous, String matcher) { return previous == null || matcher.length() >= previous.length(); } public String[] getPartOfOsName() { return Arrays.copyOf(partOfOsName, partOfOsName.length); } /** * Heuristic for comparing two platforms. If platforms (which is not the same thing as operating * systems) are found to be approximately similar in nature, this will return true. For instance * the LINUX platform is similar to UNIX, and will give a positive result if compared. * * @param compareWith the platform to compare with * @return true if platforms are approximately similar, false otherwise */ public boolean is(Platform compareWith) { return // Any platform is itself this == compareWith || // Any platform is also ANY platform compareWith == ANY || // And any Platform which is not a platform type belongs to the same family (this.family() != null && this.family().is(compareWith)); } /** * Returns a platform that represents a family for the current platform. For instance the LINUX if * a part of the UNIX family, the XP is a part of the WINDOWS family. * * @return the family platform for the current one, or {@code null} if this {@code Platform} * represents a platform family (such as Windows, or MacOS) */ public abstract Platform family(); private boolean isCurrentPlatform(String osName, String matchAgainst) { return osName.contains(matchAgainst); } private boolean isExactMatch(String osName, String matchAgainst) { return matchAgainst.equals(osName); } /** * Returns the major version of this platform. * * @return the major version of specified platform */ public int getMajorVersion() { return majorVersion; } /** * Returns the minor version of this platform. * * @return the minor version of specified platform */ public int getMinorVersion() { return minorVersion; } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/Platform.java
48
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util; import static io.netty.util.internal.ObjectUtil.checkInRange; import static io.netty.util.internal.ObjectUtil.checkPositive; import static io.netty.util.internal.ObjectUtil.checkNotNull; import io.netty.util.concurrent.ImmediateExecutor; import io.netty.util.internal.MathUtil; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.Collections; import java.util.HashSet; import java.util.Queue; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLong; import static io.netty.util.internal.StringUtil.simpleClassName; /** * A {@link Timer} optimized for approximated I/O timeout scheduling. * * <h3>Tick Duration</h3> * * As described with 'approximated', this timer does not execute the scheduled * {@link TimerTask} on time. {@link HashedWheelTimer}, on every tick, will * check if there are any {@link TimerTask}s behind the schedule and execute * them. * <p> * You can increase or decrease the accuracy of the execution timing by * specifying smaller or larger tick duration in the constructor. In most * network applications, I/O timeout does not need to be accurate. Therefore, * the default tick duration is 100 milliseconds and you will not need to try * different configurations in most cases. * * <h3>Ticks per Wheel (Wheel Size)</h3> * * {@link HashedWheelTimer} maintains a data structure called 'wheel'. * To put simply, a wheel is a hash table of {@link TimerTask}s whose hash * function is 'dead line of the task'. The default number of ticks per wheel * (i.e. the size of the wheel) is 512. You could specify a larger value * if you are going to schedule a lot of timeouts. * * <h3>Do not create many instances.</h3> * * {@link HashedWheelTimer} creates a new thread whenever it is instantiated and * started. Therefore, you should make sure to create only one instance and * share it across your application. One of the common mistakes, that makes * your application unresponsive, is to create a new instance for every connection. * * <h3>Implementation Details</h3> * * {@link HashedWheelTimer} is based on * <a href="https://cseweb.ucsd.edu/users/varghese/">George Varghese</a> and * Tony Lauck's paper, * <a href="https://cseweb.ucsd.edu/users/varghese/PAPERS/twheel.ps.Z">'Hashed * and Hierarchical Timing Wheels: data structures to efficiently implement a * timer facility'</a>. More comprehensive slides are located * <a href="https://www.cse.wustl.edu/~cdgill/courses/cs6874/TimingWheels.ppt">here</a>. */ public class HashedWheelTimer implements Timer { static final InternalLogger logger = InternalLoggerFactory.getInstance(HashedWheelTimer.class); private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger(); private static final AtomicBoolean WARNED_TOO_MANY_INSTANCES = new AtomicBoolean(); private static final int INSTANCE_COUNT_LIMIT = 64; private static final long MILLISECOND_NANOS = TimeUnit.MILLISECONDS.toNanos(1); private static final ResourceLeakDetector<HashedWheelTimer> leakDetector = ResourceLeakDetectorFactory.instance() .newResourceLeakDetector(HashedWheelTimer.class, 1); private static final AtomicIntegerFieldUpdater<HashedWheelTimer> WORKER_STATE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState"); private final ResourceLeakTracker<HashedWheelTimer> leak; private final Worker worker = new Worker(); private final Thread workerThread; public static final int WORKER_STATE_INIT = 0; public static final int WORKER_STATE_STARTED = 1; public static final int WORKER_STATE_SHUTDOWN = 2; @SuppressWarnings({"unused", "FieldMayBeFinal"}) private volatile int workerState; // 0 - init, 1 - started, 2 - shut down private final long tickDuration; private final HashedWheelBucket[] wheel; private final int mask; private final CountDownLatch startTimeInitialized = new CountDownLatch(1); private final Queue<HashedWheelTimeout> timeouts = PlatformDependent.newMpscQueue(); private final Queue<HashedWheelTimeout> cancelledTimeouts = PlatformDependent.newMpscQueue(); private final AtomicLong pendingTimeouts = new AtomicLong(0); private final long maxPendingTimeouts; private final Executor taskExecutor; private volatile long startTime; /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}), default tick duration, and * default number of ticks per wheel. */ public HashedWheelTimer() { this(Executors.defaultThreadFactory()); } /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}) and default number of ticks * per wheel. * * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @throws NullPointerException if {@code unit} is {@code null} * @throws IllegalArgumentException if {@code tickDuration} is &lt;= 0 */ public HashedWheelTimer(long tickDuration, TimeUnit unit) { this(Executors.defaultThreadFactory(), tickDuration, unit); } /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}). * * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @throws NullPointerException if {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) { this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel); } /** * Creates a new timer with the default tick duration and default number of * ticks per wheel. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @throws NullPointerException if {@code threadFactory} is {@code null} */ public HashedWheelTimer(ThreadFactory threadFactory) { this(threadFactory, 100, TimeUnit.MILLISECONDS); } /** * Creates a new timer with the default number of ticks per wheel. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if {@code tickDuration} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit) { this(threadFactory, tickDuration, unit, 512); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) { this(threadFactory, tickDuration, unit, ticksPerWheel, true); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @param leakDetection {@code true} if leak detection should be enabled always, * if false it will only be enabled if the worker thread is not * a daemon thread. * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection) { this(threadFactory, tickDuration, unit, ticksPerWheel, leakDetection, -1); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @param leakDetection {@code true} if leak detection should be enabled always, * if false it will only be enabled if the worker thread is not * a daemon thread. * @param maxPendingTimeouts The maximum number of pending timeouts after which call to * {@code newTimeout} will result in * {@link java.util.concurrent.RejectedExecutionException} * being thrown. No maximum pending timeouts limit is assumed if * this value is 0 or negative. * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection, long maxPendingTimeouts) { this(threadFactory, tickDuration, unit, ticksPerWheel, leakDetection, maxPendingTimeouts, ImmediateExecutor.INSTANCE); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @param leakDetection {@code true} if leak detection should be enabled always, * if false it will only be enabled if the worker thread is not * a daemon thread. * @param maxPendingTimeouts The maximum number of pending timeouts after which call to * {@code newTimeout} will result in * {@link java.util.concurrent.RejectedExecutionException} * being thrown. No maximum pending timeouts limit is assumed if * this value is 0 or negative. * @param taskExecutor The {@link Executor} that is used to execute the submitted {@link TimerTask}s. * The caller is responsible to shutdown the {@link Executor} once it is not needed * anymore. * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection, long maxPendingTimeouts, Executor taskExecutor) { checkNotNull(threadFactory, "threadFactory"); checkNotNull(unit, "unit"); checkPositive(tickDuration, "tickDuration"); checkPositive(ticksPerWheel, "ticksPerWheel"); this.taskExecutor = checkNotNull(taskExecutor, "taskExecutor"); // Normalize ticksPerWheel to power of two and initialize the wheel. wheel = createWheel(ticksPerWheel); mask = wheel.length - 1; // Convert tickDuration to nanos. long duration = unit.toNanos(tickDuration); // Prevent overflow. if (duration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException(String.format( "tickDuration: %d (expected: 0 < tickDuration in nanos < %d", tickDuration, Long.MAX_VALUE / wheel.length)); } if (duration < MILLISECOND_NANOS) { logger.warn("Configured tickDuration {} smaller than {}, using 1ms.", tickDuration, MILLISECOND_NANOS); this.tickDuration = MILLISECOND_NANOS; } else { this.tickDuration = duration; } workerThread = threadFactory.newThread(worker); leak = leakDetection || !workerThread.isDaemon() ? leakDetector.track(this) : null; this.maxPendingTimeouts = maxPendingTimeouts; if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT && WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { reportTooManyInstances(); } } @Override protected void finalize() throws Throwable { try { super.finalize(); } finally { // This object is going to be GCed and it is assumed the ship has sailed to do a proper shutdown. If // we have not yet shutdown then we want to make sure we decrement the active instance count. if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) { INSTANCE_COUNTER.decrementAndGet(); } } } private static HashedWheelBucket[] createWheel(int ticksPerWheel) { ticksPerWheel = MathUtil.findNextPositivePowerOfTwo(ticksPerWheel); HashedWheelBucket[] wheel = new HashedWheelBucket[ticksPerWheel]; for (int i = 0; i < wheel.length; i ++) { wheel[i] = new HashedWheelBucket(); } return wheel; } /** * Starts the background thread explicitly. The background thread will * start automatically on demand even if you did not call this method. * * @throws IllegalStateException if this timer has been * {@linkplain #stop() stopped} already */ public void start() { switch (WORKER_STATE_UPDATER.get(this)) { case WORKER_STATE_INIT: if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) { workerThread.start(); } break; case WORKER_STATE_STARTED: break; case WORKER_STATE_SHUTDOWN: throw new IllegalStateException("cannot be started once stopped"); default: throw new Error("Invalid WorkerState"); } // Wait until the startTime is initialized by the worker. while (startTime == 0) { try { startTimeInitialized.await(); } catch (InterruptedException ignore) { // Ignore - it will be ready very soon. } } } @Override public Set<Timeout> stop() { if (Thread.currentThread() == workerThread) { throw new IllegalStateException( HashedWheelTimer.class.getSimpleName() + ".stop() cannot be called from " + TimerTask.class.getSimpleName()); } if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) { // workerState can be 0 or 2 at this moment - let it always be 2. if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) { INSTANCE_COUNTER.decrementAndGet(); if (leak != null) { boolean closed = leak.close(this); assert closed; } } return Collections.emptySet(); } try { boolean interrupted = false; while (workerThread.isAlive()) { workerThread.interrupt(); try { workerThread.join(100); } catch (InterruptedException ignored) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } finally { INSTANCE_COUNTER.decrementAndGet(); if (leak != null) { boolean closed = leak.close(this); assert closed; } } return worker.unprocessedTimeouts(); } @Override public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { checkNotNull(task, "task"); checkNotNull(unit, "unit"); long pendingTimeoutsCount = pendingTimeouts.incrementAndGet(); if (maxPendingTimeouts > 0 && pendingTimeoutsCount > maxPendingTimeouts) { pendingTimeouts.decrementAndGet(); throw new RejectedExecutionException("Number of pending timeouts (" + pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending " + "timeouts (" + maxPendingTimeouts + ")"); } start(); // Add the timeout to the timeout queue which will be processed on the next tick. // During processing all the queued HashedWheelTimeouts will be added to the correct HashedWheelBucket. long deadline = System.nanoTime() + unit.toNanos(delay) - startTime; // Guard against overflow. if (delay > 0 && deadline < 0) { deadline = Long.MAX_VALUE; } HashedWheelTimeout timeout = new HashedWheelTimeout(this, task, deadline); timeouts.add(timeout); return timeout; } /** * Returns the number of pending timeouts of this {@link Timer}. */ public long pendingTimeouts() { return pendingTimeouts.get(); } private static void reportTooManyInstances() { if (logger.isErrorEnabled()) { String resourceType = simpleClassName(HashedWheelTimer.class); logger.error("You are creating too many " + resourceType + " instances. " + resourceType + " is a shared resource that must be reused across the JVM, " + "so that only a few instances are created."); } } private final class Worker implements Runnable { private final Set<Timeout> unprocessedTimeouts = new HashSet<Timeout>(); private long tick; @Override public void run() { // Initialize the startTime. startTime = System.nanoTime(); if (startTime == 0) { // We use 0 as an indicator for the uninitialized value here, so make sure it's not 0 when initialized. startTime = 1; } // Notify the other threads waiting for the initialization at start(). startTimeInitialized.countDown(); do { final long deadline = waitForNextTick(); if (deadline > 0) { int idx = (int) (tick & mask); processCancelledTasks(); HashedWheelBucket bucket = wheel[idx]; transferTimeoutsToBuckets(); bucket.expireTimeouts(deadline); tick++; } } while (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_STARTED); // Fill the unprocessedTimeouts so we can return them from stop() method. for (HashedWheelBucket bucket: wheel) { bucket.clearTimeouts(unprocessedTimeouts); } for (;;) { HashedWheelTimeout timeout = timeouts.poll(); if (timeout == null) { break; } if (!timeout.isCancelled()) { unprocessedTimeouts.add(timeout); } } processCancelledTasks(); } private void transferTimeoutsToBuckets() { // transfer only max. 100000 timeouts per tick to prevent a thread to stale the workerThread when it just // adds new timeouts in a loop. for (int i = 0; i < 100000; i++) { HashedWheelTimeout timeout = timeouts.poll(); if (timeout == null) { // all processed break; } if (timeout.state() == HashedWheelTimeout.ST_CANCELLED) { // Was cancelled in the meantime. continue; } long calculated = timeout.deadline / tickDuration; timeout.remainingRounds = (calculated - tick) / wheel.length; final long ticks = Math.max(calculated, tick); // Ensure we don't schedule for past. int stopIndex = (int) (ticks & mask); HashedWheelBucket bucket = wheel[stopIndex]; bucket.addTimeout(timeout); } } private void processCancelledTasks() { for (;;) { HashedWheelTimeout timeout = cancelledTimeouts.poll(); if (timeout == null) { // all processed break; } try { timeout.remove(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("An exception was thrown while process a cancellation task", t); } } } } /** * calculate goal nanoTime from startTime and current tick number, * then wait until that goal has been reached. * @return Long.MIN_VALUE if received a shutdown request, * current time otherwise (with Long.MIN_VALUE changed by +1) */ private long waitForNextTick() { long deadline = tickDuration * (tick + 1); for (;;) { final long currentTime = System.nanoTime() - startTime; long sleepTimeMs = (deadline - currentTime + 999999) / 1000000; if (sleepTimeMs <= 0) { if (currentTime == Long.MIN_VALUE) { return -Long.MAX_VALUE; } else { return currentTime; } } // Check if we run on windows, as if thats the case we will need // to round the sleepTime as workaround for a bug that only affect // the JVM if it runs on windows. // // See https://github.com/netty/netty/issues/356 if (PlatformDependent.isWindows()) { sleepTimeMs = sleepTimeMs / 10 * 10; if (sleepTimeMs == 0) { sleepTimeMs = 1; } } try { Thread.sleep(sleepTimeMs); } catch (InterruptedException ignored) { if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) { return Long.MIN_VALUE; } } } } public Set<Timeout> unprocessedTimeouts() { return Collections.unmodifiableSet(unprocessedTimeouts); } } private static final class HashedWheelTimeout implements Timeout, Runnable { private static final int ST_INIT = 0; private static final int ST_CANCELLED = 1; private static final int ST_EXPIRED = 2; private static final AtomicIntegerFieldUpdater<HashedWheelTimeout> STATE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state"); private final HashedWheelTimer timer; private final TimerTask task; private final long deadline; @SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization" }) private volatile int state = ST_INIT; // remainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the // HashedWheelTimeout will be added to the correct HashedWheelBucket. long remainingRounds; // This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list. // As only the workerThread will act on it there is no need for synchronization / volatile. HashedWheelTimeout next; HashedWheelTimeout prev; // The bucket to which the timeout was added HashedWheelBucket bucket; HashedWheelTimeout(HashedWheelTimer timer, TimerTask task, long deadline) { this.timer = timer; this.task = task; this.deadline = deadline; } @Override public Timer timer() { return timer; } @Override public TimerTask task() { return task; } @Override public boolean cancel() { // only update the state it will be removed from HashedWheelBucket on next tick. if (!compareAndSetState(ST_INIT, ST_CANCELLED)) { return false; } // If a task should be canceled we put this to another queue which will be processed on each tick. // So this means that we will have a GC latency of max. 1 tick duration which is good enough. This way // we can make again use of our MpscLinkedQueue and so minimize the locking / overhead as much as possible. timer.cancelledTimeouts.add(this); return true; } void remove() { HashedWheelBucket bucket = this.bucket; if (bucket != null) { bucket.remove(this); } else { timer.pendingTimeouts.decrementAndGet(); } } public boolean compareAndSetState(int expected, int state) { return STATE_UPDATER.compareAndSet(this, expected, state); } public int state() { return state; } @Override public boolean isCancelled() { return state() == ST_CANCELLED; } @Override public boolean isExpired() { return state() == ST_EXPIRED; } public void expire() { if (!compareAndSetState(ST_INIT, ST_EXPIRED)) { return; } try { timer.taskExecutor.execute(this); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("An exception was thrown while submit " + TimerTask.class.getSimpleName() + " for execution.", t); } } } @Override public void run() { try { task.run(this); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t); } } } @Override public String toString() { final long currentTime = System.nanoTime(); long remaining = deadline - currentTime + timer.startTime; StringBuilder buf = new StringBuilder(192) .append(simpleClassName(this)) .append('(') .append("deadline: "); if (remaining > 0) { buf.append(remaining) .append(" ns later"); } else if (remaining < 0) { buf.append(-remaining) .append(" ns ago"); } else { buf.append("now"); } if (isCancelled()) { buf.append(", cancelled"); } return buf.append(", task: ") .append(task()) .append(')') .toString(); } } /** * Bucket that stores HashedWheelTimeouts. These are stored in a linked-list like datastructure to allow easy * removal of HashedWheelTimeouts in the middle. Also the HashedWheelTimeout act as nodes themself and so no * extra object creation is needed. */ private static final class HashedWheelBucket { // Used for the linked-list datastructure private HashedWheelTimeout head; private HashedWheelTimeout tail; /** * Add {@link HashedWheelTimeout} to this bucket. */ public void addTimeout(HashedWheelTimeout timeout) { assert timeout.bucket == null; timeout.bucket = this; if (head == null) { head = tail = timeout; } else { tail.next = timeout; timeout.prev = tail; tail = timeout; } } /** * Expire all {@link HashedWheelTimeout}s for the given {@code deadline}. */ public void expireTimeouts(long deadline) { HashedWheelTimeout timeout = head; // process all timeouts while (timeout != null) { HashedWheelTimeout next = timeout.next; if (timeout.remainingRounds <= 0) { next = remove(timeout); if (timeout.deadline <= deadline) { timeout.expire(); } else { // The timeout was placed into a wrong slot. This should never happen. throw new IllegalStateException(String.format( "timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline)); } } else if (timeout.isCancelled()) { next = remove(timeout); } else { timeout.remainingRounds --; } timeout = next; } } public HashedWheelTimeout remove(HashedWheelTimeout timeout) { HashedWheelTimeout next = timeout.next; // remove timeout that was either processed or cancelled by updating the linked-list if (timeout.prev != null) { timeout.prev.next = next; } if (timeout.next != null) { timeout.next.prev = timeout.prev; } if (timeout == head) { // if timeout is also the tail we need to adjust the entry too if (timeout == tail) { tail = null; head = null; } else { head = next; } } else if (timeout == tail) { // if the timeout is the tail modify the tail to be the prev node. tail = timeout.prev; } // null out prev, next and bucket to allow for GC. timeout.prev = null; timeout.next = null; timeout.bucket = null; timeout.timer.pendingTimeouts.decrementAndGet(); return next; } /** * Clear this bucket and return all not expired / cancelled {@link Timeout}s. */ public void clearTimeouts(Set<Timeout> set) { for (;;) { HashedWheelTimeout timeout = pollTimeout(); if (timeout == null) { return; } if (timeout.isExpired() || timeout.isCancelled()) { continue; } set.add(timeout); } } private HashedWheelTimeout pollTimeout() { HashedWheelTimeout head = this.head; if (head == null) { return null; } HashedWheelTimeout next = head.next; if (next == null) { tail = this.head = null; } else { this.head = next; next.prev = null; } // null out prev and next to allow for GC. head.next = null; head.prev = null; head.bucket = null; return head; } } }
netty/netty
common/src/main/java/io/netty/util/HashedWheelTimer.java
49
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufInputStream; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; import io.netty.util.AttributeMap; import io.netty.util.DefaultAttributeMap; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.PlatformDependent; import java.io.BufferedInputStream; import java.security.Provider; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.crypto.Cipher; import javax.crypto.EncryptedPrivateKeyInfo; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyException; import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; /** * A secure socket protocol implementation which acts as a factory for {@link SSLEngine} and {@link SslHandler}. * Internally, it is implemented via JDK's {@link SSLContext} or OpenSSL's {@code SSL_CTX}. * * <h3>Making your server support SSL/TLS</h3> * <pre> * // In your {@link ChannelInitializer}: * {@link ChannelPipeline} p = channel.pipeline(); * {@link SslContext} sslCtx = {@link SslContextBuilder#forServer(File, File) SslContextBuilder.forServer(...)}.build(); * p.addLast("ssl", {@link #newHandler(ByteBufAllocator) sslCtx.newHandler(channel.alloc())}); * ... * </pre> * * <h3>Making your client support SSL/TLS</h3> * <pre> * // In your {@link ChannelInitializer}: * {@link ChannelPipeline} p = channel.pipeline(); * {@link SslContext} sslCtx = {@link SslContextBuilder#forClient() SslContextBuilder.forClient()}.build(); * p.addLast("ssl", {@link #newHandler(ByteBufAllocator, String, int) sslCtx.newHandler(channel.alloc(), host, port)}); * ... * </pre> */ public abstract class SslContext { static final String ALIAS = "key"; static final CertificateFactory X509_CERT_FACTORY; static { try { X509_CERT_FACTORY = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new IllegalStateException("unable to instance X.509 CertificateFactory", e); } } private final boolean startTls; private final AttributeMap attributes = new DefaultAttributeMap(); private static final String OID_PKCS5_PBES2 = "1.2.840.113549.1.5.13"; private static final String PBES2 = "PBES2"; /** * Returns the default server-side implementation provider currently in use. * * @return {@link SslProvider#OPENSSL} if OpenSSL is available. {@link SslProvider#JDK} otherwise. */ public static SslProvider defaultServerProvider() { return defaultProvider(); } /** * Returns the default client-side implementation provider currently in use. * * @return {@link SslProvider#OPENSSL} if OpenSSL is available. {@link SslProvider#JDK} otherwise. */ public static SslProvider defaultClientProvider() { return defaultProvider(); } private static SslProvider defaultProvider() { if (OpenSsl.isAvailable()) { return SslProvider.OPENSSL; } else { return SslProvider.JDK; } } /** * Creates a new server-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext(File certChainFile, File keyFile) throws SSLException { return newServerContext(certChainFile, keyFile, null); } /** * Creates a new server-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( File certChainFile, File keyFile, String keyPassword) throws SSLException { return newServerContext(null, certChainFile, keyFile, keyPassword); } /** * Creates a new server-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param nextProtocols the application layer protocols to accept, in the order of preference. * {@code null} to disable TLS NPN/ALPN extension. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( File certChainFile, File keyFile, String keyPassword, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { return newServerContext( null, certChainFile, keyFile, keyPassword, ciphers, nextProtocols, sessionCacheSize, sessionTimeout); } /** * Creates a new server-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( File certChainFile, File keyFile, String keyPassword, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { return newServerContext( null, certChainFile, keyFile, keyPassword, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout); } /** * Creates a new server-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( SslProvider provider, File certChainFile, File keyFile) throws SSLException { return newServerContext(provider, certChainFile, keyFile, null); } /** * Creates a new server-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( SslProvider provider, File certChainFile, File keyFile, String keyPassword) throws SSLException { return newServerContext(provider, certChainFile, keyFile, keyPassword, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0); } /** * Creates a new server-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param nextProtocols the application layer protocols to accept, in the order of preference. * {@code null} to disable TLS NPN/ALPN extension. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( SslProvider provider, File certChainFile, File keyFile, String keyPassword, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { return newServerContext(provider, certChainFile, keyFile, keyPassword, ciphers, IdentityCipherSuiteFilter.INSTANCE, toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout); } /** * Creates a new server-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param nextProtocols the application layer protocols to accept, in the order of preference. * {@code null} to disable TLS NPN/ALPN extension. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( SslProvider provider, File certChainFile, File keyFile, String keyPassword, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { return newServerContext( provider, null, trustManagerFactory, certChainFile, keyFile, keyPassword, null, ciphers, IdentityCipherSuiteFilter.INSTANCE, toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout); } /** * Creates a new server-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * Only required if {@code provider} is {@link SslProvider#JDK} * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext(SslProvider provider, File certChainFile, File keyFile, String keyPassword, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { return newServerContext(provider, null, null, certChainFile, keyFile, keyPassword, null, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, KeyStore.getDefaultType()); } /** * Creates a new server-side {@link SslContext}. * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param trustCertCollectionFile an X.509 certificate collection file in PEM format. * This provides the certificate collection used for mutual authentication. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from clients. * {@code null} to use the default or the results of parsing * {@code trustCertCollectionFile}. * This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}. * @param keyCertChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s * that is used to encrypt data being sent to clients. * {@code null} to use the default or the results of parsing * {@code keyCertChainFile} and {@code keyFile}. * This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * Only required if {@code provider} is {@link SslProvider#JDK} * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @return a new server-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newServerContext( SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { return newServerContext(provider, trustCertCollectionFile, trustManagerFactory, keyCertChainFile, keyFile, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, KeyStore.getDefaultType()); } /** * Creates a new server-side {@link SslContext}. * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param trustCertCollectionFile an X.509 certificate collection file in PEM format. * This provides the certificate collection used for mutual authentication. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from clients. * {@code null} to use the default or the results of parsing * {@code trustCertCollectionFile}. * This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}. * @param keyCertChainFile an X.509 certificate chain file in PEM format * @param keyFile a PKCS#8 private key file in PEM format * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s * that is used to encrypt data being sent to clients. * {@code null} to use the default or the results of parsing * {@code keyCertChainFile} and {@code keyFile}. * This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * Only required if {@code provider} is {@link SslProvider#JDK} * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @param keyStore the keystore type that should be used * @return a new server-side {@link SslContext} */ static SslContext newServerContext( SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout, String keyStore) throws SSLException { try { return newServerContextInternal(provider, null, toX509Certificates(trustCertCollectionFile), trustManagerFactory, toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword), keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, ClientAuth.NONE, null, false, false, keyStore); } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the server-side SSL context", e); } } static SslContext newServerContextInternal( SslProvider provider, Provider sslContextProvider, X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory, X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls, boolean enableOcsp, String keyStoreType, Map.Entry<SslContextOption<?>, Object>... ctxOptions) throws SSLException { if (provider == null) { provider = defaultServerProvider(); } switch (provider) { case JDK: if (enableOcsp) { throw new IllegalArgumentException("OCSP is not supported with this SslProvider: " + provider); } return new JdkSslServerContext(sslContextProvider, trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, clientAuth, protocols, startTls, keyStoreType); case OPENSSL: verifyNullSslContextProvider(provider, sslContextProvider); return new OpenSslServerContext( trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, clientAuth, protocols, startTls, enableOcsp, keyStoreType, ctxOptions); case OPENSSL_REFCNT: verifyNullSslContextProvider(provider, sslContextProvider); return new ReferenceCountedOpenSslServerContext( trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, clientAuth, protocols, startTls, enableOcsp, keyStoreType, ctxOptions); default: throw new Error(provider.toString()); } } private static void verifyNullSslContextProvider(SslProvider provider, Provider sslContextProvider) { if (sslContextProvider != null) { throw new IllegalArgumentException("Java Security Provider unsupported for SslProvider: " + provider); } } /** * Creates a new client-side {@link SslContext}. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext() throws SSLException { return newClientContext(null, null, null); } /** * Creates a new client-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext(File certChainFile) throws SSLException { return newClientContext(null, certChainFile); } /** * Creates a new client-side {@link SslContext}. * * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext(TrustManagerFactory trustManagerFactory) throws SSLException { return newClientContext(null, null, trustManagerFactory); } /** * Creates a new client-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException { return newClientContext(null, certChainFile, trustManagerFactory); } /** * Creates a new client-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param nextProtocols the application layer protocols to accept, in the order of preference. * {@code null} to disable TLS NPN/ALPN extension. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { return newClientContext( null, certChainFile, trustManagerFactory, ciphers, nextProtocols, sessionCacheSize, sessionTimeout); } /** * Creates a new client-side {@link SslContext}. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { return newClientContext( null, certChainFile, trustManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout); } /** * Creates a new client-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext(SslProvider provider) throws SSLException { return newClientContext(provider, null, null); } /** * Creates a new client-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext(SslProvider provider, File certChainFile) throws SSLException { return newClientContext(provider, certChainFile, null); } /** * Creates a new client-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( SslProvider provider, TrustManagerFactory trustManagerFactory) throws SSLException { return newClientContext(provider, null, trustManagerFactory); } /** * Creates a new client-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( SslProvider provider, File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException { return newClientContext(provider, certChainFile, trustManagerFactory, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0); } /** * Creates a new client-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param nextProtocols the application layer protocols to accept, in the order of preference. * {@code null} to disable TLS NPN/ALPN extension. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( SslProvider provider, File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { return newClientContext( provider, certChainFile, trustManagerFactory, null, null, null, null, ciphers, IdentityCipherSuiteFilter.INSTANCE, toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout); } /** * Creates a new client-side {@link SslContext}. * * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( SslProvider provider, File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { return newClientContext( provider, certChainFile, trustManagerFactory, null, null, null, null, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout); } /** * Creates a new client-side {@link SslContext}. * @param provider the {@link SslContext} implementation to use. * {@code null} to use the current default one. * @param trustCertCollectionFile an X.509 certificate collection file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default or the results of parsing * {@code trustCertCollectionFile}. * This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}. * @param keyCertChainFile an X.509 certificate chain file in PEM format. * This provides the public key for mutual authentication. * {@code null} to use the system default * @param keyFile a PKCS#8 private key file in PEM format. * This provides the private key for mutual authentication. * {@code null} for no mutual authentication. * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * Ignored if {@code keyFile} is {@code null}. * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s * that is used to encrypt data being sent to servers. * {@code null} to use the default or the results of parsing * {@code keyCertChainFile} and {@code keyFile}. * This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * * @return a new client-side {@link SslContext} * @deprecated Replaced by {@link SslContextBuilder} */ @Deprecated public static SslContext newClientContext( SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { try { return newClientContextInternal(provider, null, toX509Certificates(trustCertCollectionFile), trustManagerFactory, toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword), keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, null, sessionCacheSize, sessionTimeout, false, KeyStore.getDefaultType()); } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the client-side SSL context", e); } } static SslContext newClientContextInternal( SslProvider provider, Provider sslContextProvider, X509Certificate[] trustCert, TrustManagerFactory trustManagerFactory, X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, String[] protocols, long sessionCacheSize, long sessionTimeout, boolean enableOcsp, String keyStoreType, Map.Entry<SslContextOption<?>, Object>... options) throws SSLException { if (provider == null) { provider = defaultClientProvider(); } switch (provider) { case JDK: if (enableOcsp) { throw new IllegalArgumentException("OCSP is not supported with this SslProvider: " + provider); } return new JdkSslClientContext(sslContextProvider, trustCert, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout, keyStoreType); case OPENSSL: verifyNullSslContextProvider(provider, sslContextProvider); OpenSsl.ensureAvailability(); return new OpenSslClientContext( trustCert, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout, enableOcsp, keyStoreType, options); case OPENSSL_REFCNT: verifyNullSslContextProvider(provider, sslContextProvider); OpenSsl.ensureAvailability(); return new ReferenceCountedOpenSslClientContext( trustCert, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout, enableOcsp, keyStoreType, options); default: throw new Error(provider.toString()); } } static ApplicationProtocolConfig toApplicationProtocolConfig(Iterable<String> nextProtocols) { ApplicationProtocolConfig apn; if (nextProtocols == null) { apn = ApplicationProtocolConfig.DISABLED; } else { apn = new ApplicationProtocolConfig( Protocol.NPN_AND_ALPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedListenerFailureBehavior.ACCEPT, nextProtocols); } return apn; } /** * Creates a new instance (startTls set to {@code false}). */ protected SslContext() { this(false); } /** * Creates a new instance. */ protected SslContext(boolean startTls) { this.startTls = startTls; } /** * Returns the {@link AttributeMap} that belongs to this {@link SslContext} . */ public final AttributeMap attributes() { return attributes; } /** * Returns {@code true} if and only if this context is for server-side. */ public final boolean isServer() { return !isClient(); } /** * Returns the {@code true} if and only if this context is for client-side. */ public abstract boolean isClient(); /** * Returns the list of enabled cipher suites, in the order of preference. */ public abstract List<String> cipherSuites(); /** * Returns the size of the cache used for storing SSL session objects. */ public long sessionCacheSize() { return sessionContext().getSessionCacheSize(); } /** * Returns the timeout for the cached SSL session objects, in seconds. */ public long sessionTimeout() { return sessionContext().getSessionTimeout(); } /** * @deprecated Use {@link #applicationProtocolNegotiator()} instead. */ @Deprecated public final List<String> nextProtocols() { return applicationProtocolNegotiator().protocols(); } /** * Returns the object responsible for negotiating application layer protocols for the TLS NPN/ALPN extensions. */ public abstract ApplicationProtocolNegotiator applicationProtocolNegotiator(); /** * Creates a new {@link SSLEngine}. * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the object must be released. One way to do this is to * wrap in a {@link SslHandler} and insert it into a pipeline. See {@link #newHandler(ByteBufAllocator)}. * @return a new {@link SSLEngine} */ public abstract SSLEngine newEngine(ByteBufAllocator alloc); /** * Creates a new {@link SSLEngine} using advisory peer information. * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the object must be released. One way to do this is to * wrap in a {@link SslHandler} and insert it into a pipeline. * See {@link #newHandler(ByteBufAllocator, String, int)}. * @param peerHost the non-authoritative name of the host * @param peerPort the non-authoritative port * * @return a new {@link SSLEngine} */ public abstract SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort); /** * Returns the {@link SSLSessionContext} object held by this context. */ public abstract SSLSessionContext sessionContext(); /** * Create a new SslHandler. * @see #newHandler(ByteBufAllocator, Executor) */ public final SslHandler newHandler(ByteBufAllocator alloc) { return newHandler(alloc, startTls); } /** * Create a new SslHandler. * @see #newHandler(ByteBufAllocator) */ protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls) { return new SslHandler(newEngine(alloc), startTls); } /** * Creates a new {@link SslHandler}. * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the returned {@link SslHandler} will release the engine * that is wrapped. If the returned {@link SslHandler} is not inserted into a pipeline then you may leak native * memory! * <p><b>Beware</b>: the underlying generated {@link SSLEngine} won't have * <a href="https://wiki.openssl.org/index.php/Hostname_validation">hostname verification</a> enabled by default. * If you create {@link SslHandler} for the client side and want proper security, we advice that you configure * the {@link SSLEngine} (see {@link javax.net.ssl.SSLParameters#setEndpointIdentificationAlgorithm(String)}): * <pre> * SSLEngine sslEngine = sslHandler.engine(); * SSLParameters sslParameters = sslEngine.getSSLParameters(); * // only available since Java 7 * sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); * sslEngine.setSSLParameters(sslParameters); * </pre> * <p> * The underlying {@link SSLEngine} may not follow the restrictions imposed by the * <a href="https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html">SSLEngine javadocs</a> which * limits wrap/unwrap to operate on a single SSL/TLS packet. * @param alloc If supported by the SSLEngine then the SSLEngine will use this to allocate ByteBuf objects. * @param delegatedTaskExecutor the {@link Executor} that will be used to execute tasks that are returned by * {@link SSLEngine#getDelegatedTask()}. * @return a new {@link SslHandler} */ public SslHandler newHandler(ByteBufAllocator alloc, Executor delegatedTaskExecutor) { return newHandler(alloc, startTls, delegatedTaskExecutor); } /** * Create a new SslHandler. * @see #newHandler(ByteBufAllocator, String, int, boolean, Executor) */ protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls, Executor executor) { return new SslHandler(newEngine(alloc), startTls, executor); } /** * Creates a new {@link SslHandler} * * @see #newHandler(ByteBufAllocator, String, int, Executor) */ public final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort) { return newHandler(alloc, peerHost, peerPort, startTls); } /** * Create a new SslHandler. * @see #newHandler(ByteBufAllocator, String, int, boolean, Executor) */ protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls) { return new SslHandler(newEngine(alloc, peerHost, peerPort), startTls); } /** * Creates a new {@link SslHandler} with advisory peer information. * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the returned {@link SslHandler} will release the engine * that is wrapped. If the returned {@link SslHandler} is not inserted into a pipeline then you may leak native * memory! * <p><b>Beware</b>: the underlying generated {@link SSLEngine} won't have * <a href="https://wiki.openssl.org/index.php/Hostname_validation">hostname verification</a> enabled by default. * If you create {@link SslHandler} for the client side and want proper security, we advice that you configure * the {@link SSLEngine} (see {@link javax.net.ssl.SSLParameters#setEndpointIdentificationAlgorithm(String)}): * <pre> * SSLEngine sslEngine = sslHandler.engine(); * SSLParameters sslParameters = sslEngine.getSSLParameters(); * // only available since Java 7 * sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); * sslEngine.setSSLParameters(sslParameters); * </pre> * <p> * The underlying {@link SSLEngine} may not follow the restrictions imposed by the * <a href="https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html">SSLEngine javadocs</a> which * limits wrap/unwrap to operate on a single SSL/TLS packet. * @param alloc If supported by the SSLEngine then the SSLEngine will use this to allocate ByteBuf objects. * @param peerHost the non-authoritative name of the host * @param peerPort the non-authoritative port * @param delegatedTaskExecutor the {@link Executor} that will be used to execute tasks that are returned by * {@link SSLEngine#getDelegatedTask()}. * * @return a new {@link SslHandler} */ public SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, Executor delegatedTaskExecutor) { return newHandler(alloc, peerHost, peerPort, startTls, delegatedTaskExecutor); } protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls, Executor delegatedTaskExecutor) { return new SslHandler(newEngine(alloc, peerHost, peerPort), startTls, delegatedTaskExecutor); } /** * Generates a key specification for an (encrypted) private key. * * @param password characters, if {@code null} an unencrypted key is assumed * @param key bytes of the DER encoded private key * * @return a key specification * * @throws IOException if parsing {@code key} fails * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unknown * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unknown * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt * {@code key} * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty */ @Deprecated protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException { if (password == null) { return new PKCS8EncodedKeySpec(key); } EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key); String pbeAlgorithm = getPBEAlgorithm(encryptedPrivateKeyInfo); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(pbeAlgorithm); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(pbeAlgorithm); cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters()); return encryptedPrivateKeyInfo.getKeySpec(cipher); } private static String getPBEAlgorithm(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) { AlgorithmParameters parameters = encryptedPrivateKeyInfo.getAlgParameters(); String algName = encryptedPrivateKeyInfo.getAlgName(); // Java 8 ~ 16 returns OID_PKCS5_PBES2 // Java 17+ returns PBES2 if (PlatformDependent.javaVersion() >= 8 && parameters != null && (OID_PKCS5_PBES2.equals(algName) || PBES2.equals(algName))) { /* * This should be "PBEWith<prf>And<encryption>". * Relying on the toString() implementation is potentially * fragile but acceptable in this case since the JRE depends on * the toString() implementation as well. * In the future, if necessary, we can parse the value of * parameters.getEncoded() but the associated complexity and * unlikeliness of the JRE implementation changing means that * Tomcat will use to toString() approach for now. */ return parameters.toString(); } return encryptedPrivateKeyInfo.getAlgName(); } /** * Generates a new {@link KeyStore}. * * @param certChain an X.509 certificate chain * @param key a PKCS#8 private key * @param keyPasswordChars the password of the {@code keyFile}. * {@code null} if it's not password-protected. * @param keyStoreType The KeyStore Type you want to use * @return generated {@link KeyStore}. */ protected static KeyStore buildKeyStore(X509Certificate[] certChain, PrivateKey key, char[] keyPasswordChars, String keyStoreType) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(null, null); ks.setKeyEntry(ALIAS, key, keyPasswordChars, certChain); return ks; } protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, KeyException, IOException { return toPrivateKey(keyFile, keyPassword, true); } static PrivateKey toPrivateKey(File keyFile, String keyPassword, boolean tryBouncyCastle) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, KeyException, IOException { if (keyFile == null) { return null; } // try BC first, if this fail fallback to original key extraction process if (tryBouncyCastle && BouncyCastlePemReader.isAvailable()) { PrivateKey pk = BouncyCastlePemReader.getPrivateKey(keyFile, keyPassword); if (pk != null) { return pk; } } return getPrivateKeyFromByteBuffer(PemReader.readPrivateKey(keyFile), keyPassword); } protected static PrivateKey toPrivateKey(InputStream keyInputStream, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, KeyException, IOException { if (keyInputStream == null) { return null; } // try BC first, if this fail fallback to original key extraction process if (BouncyCastlePemReader.isAvailable()) { if (!keyInputStream.markSupported()) { // We need an input stream that supports resetting, in case BouncyCastle fails to read. keyInputStream = new BufferedInputStream(keyInputStream); } keyInputStream.mark(1048576); // Be able to reset up to 1 MiB of data. PrivateKey pk = BouncyCastlePemReader.getPrivateKey(keyInputStream, keyPassword); if (pk != null) { return pk; } // BouncyCastle could not read the key. Reset the input stream in case the input position changed. keyInputStream.reset(); } return getPrivateKeyFromByteBuffer(PemReader.readPrivateKey(keyInputStream), keyPassword); } private static PrivateKey getPrivateKeyFromByteBuffer(ByteBuf encodedKeyBuf, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, KeyException, IOException { byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()]; encodedKeyBuf.readBytes(encodedKey).release(); PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec( keyPassword == null ? null : keyPassword.toCharArray(), encodedKey); try { return KeyFactory.getInstance("RSA").generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException ignore) { try { return KeyFactory.getInstance("DSA").generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException ignore2) { try { return KeyFactory.getInstance("EC").generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeySpecException("Neither RSA, DSA nor EC worked", e); } } } } /** * Build a {@link TrustManagerFactory} from a certificate chain file. * @param certChainFile The certificate file to build from. * @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not {@code null}. * @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile} */ @Deprecated protected static TrustManagerFactory buildTrustManagerFactory( File certChainFile, TrustManagerFactory trustManagerFactory) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { return buildTrustManagerFactory(certChainFile, trustManagerFactory, null); } /** * Build a {@link TrustManagerFactory} from a certificate chain file. * @param certChainFile The certificate file to build from. * @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not {@code null}. * @param keyType The KeyStore Type you want to use * @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile} */ protected static TrustManagerFactory buildTrustManagerFactory( File certChainFile, TrustManagerFactory trustManagerFactory, String keyType) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { X509Certificate[] x509Certs = toX509Certificates(certChainFile); return buildTrustManagerFactory(x509Certs, trustManagerFactory, keyType); } protected static X509Certificate[] toX509Certificates(File file) throws CertificateException { if (file == null) { return null; } return getCertificatesFromBuffers(PemReader.readCertificates(file)); } protected static X509Certificate[] toX509Certificates(InputStream in) throws CertificateException { if (in == null) { return null; } return getCertificatesFromBuffers(PemReader.readCertificates(in)); } private static X509Certificate[] getCertificatesFromBuffers(ByteBuf[] certs) throws CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate[] x509Certs = new X509Certificate[certs.length]; try { for (int i = 0; i < certs.length; i++) { InputStream is = new ByteBufInputStream(certs[i], false); try { x509Certs[i] = (X509Certificate) cf.generateCertificate(is); } finally { try { is.close(); } catch (IOException e) { // This is not expected to happen, but re-throw in case it does. throw new RuntimeException(e); } } } } finally { for (ByteBuf buf: certs) { buf.release(); } } return x509Certs; } protected static TrustManagerFactory buildTrustManagerFactory( X509Certificate[] certCollection, TrustManagerFactory trustManagerFactory, String keyStoreType) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } final KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(null, null); int i = 1; for (X509Certificate cert: certCollection) { String alias = Integer.toString(i); ks.setCertificateEntry(alias, cert); i++; } // Set up trust manager factory to use our key store. if (trustManagerFactory == null) { trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); } trustManagerFactory.init(ks); return trustManagerFactory; } static PrivateKey toPrivateKeyInternal(File keyFile, String keyPassword) throws SSLException { try { return toPrivateKey(keyFile, keyPassword); } catch (Exception e) { throw new SSLException(e); } } static X509Certificate[] toX509CertificatesInternal(File file) throws SSLException { try { return toX509Certificates(file); } catch (CertificateException e) { throw new SSLException(e); } } protected static KeyManagerFactory buildKeyManagerFactory(X509Certificate[] certChainFile, String keyAlgorithm, PrivateKey key, String keyPassword, KeyManagerFactory kmf, String keyStore) throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException, UnrecoverableKeyException { if (keyAlgorithm == null) { keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); } char[] keyPasswordChars = keyStorePassword(keyPassword); KeyStore ks = buildKeyStore(certChainFile, key, keyPasswordChars, keyStore); return buildKeyManagerFactory(ks, keyAlgorithm, keyPasswordChars, kmf); } static KeyManagerFactory buildKeyManagerFactory(KeyStore ks, String keyAlgorithm, char[] keyPasswordChars, KeyManagerFactory kmf) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { // Set up key manager factory to use our key store if (kmf == null) { if (keyAlgorithm == null) { keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); } kmf = KeyManagerFactory.getInstance(keyAlgorithm); } kmf.init(ks, keyPasswordChars); return kmf; } static char[] keyStorePassword(String keyPassword) { return keyPassword == null ? EmptyArrays.EMPTY_CHARS : keyPassword.toCharArray(); } }
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslContext.java
50
/* * Copyright 2012-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.build; import org.antora.gradle.AntoraPlugin; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.JavaBasePlugin; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; /** * Plugin to apply conventions to projects that are part of Spring Boot's build. * Conventions are applied in response to various plugins being applied. * * When the {@link JavaBasePlugin} is applied, the conventions in {@link JavaConventions} * are applied. * * When the {@link MavenPublishPlugin} is applied, the conventions in * {@link MavenPublishingConventions} are applied. * * When the {@link AntoraPlugin} is applied, the conventions in {@link AntoraConventions} * are applied. * * @author Andy Wilkinson * @author Christoph Dreis * @author Mike Smithson */ public class ConventionsPlugin implements Plugin<Project> { @Override public void apply(Project project) { new NoHttpConventions().apply(project); new JavaConventions().apply(project); new MavenPublishingConventions().apply(project); new AntoraConventions().apply(project); new KotlinConventions().apply(project); new WarConventions().apply(project); new EclipseConventions().apply(project); } }
spring-projects/spring-boot
buildSrc/src/main/java/org/springframework/boot/build/ConventionsPlugin.java
51
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.socket.ChannelOutputShutdownEvent; import io.netty.channel.socket.ChannelOutputShutdownException; import io.netty.util.DefaultAttributeMap; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.ClosedChannelException; import java.nio.channels.NotYetConnectedException; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; /** * A skeletal {@link Channel} implementation. */ public abstract class AbstractChannel extends DefaultAttributeMap implements Channel { private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class); private final Channel parent; private final ChannelId id; private final Unsafe unsafe; private final DefaultChannelPipeline pipeline; private final VoidChannelPromise unsafeVoidPromise = new VoidChannelPromise(this, false); private final CloseFuture closeFuture = new CloseFuture(this); private volatile SocketAddress localAddress; private volatile SocketAddress remoteAddress; private volatile EventLoop eventLoop; private volatile boolean registered; private boolean closeInitiated; private Throwable initialCloseCause; /** Cache for the string representation of this channel */ private boolean strValActive; private String strVal; /** * Creates a new instance. * * @param parent * the parent of this channel. {@code null} if there's no parent. */ protected AbstractChannel(Channel parent) { this.parent = parent; id = newId(); unsafe = newUnsafe(); pipeline = newChannelPipeline(); } /** * Creates a new instance. * * @param parent * the parent of this channel. {@code null} if there's no parent. */ protected AbstractChannel(Channel parent, ChannelId id) { this.parent = parent; this.id = id; unsafe = newUnsafe(); pipeline = newChannelPipeline(); } protected final int maxMessagesPerWrite() { ChannelConfig config = config(); if (config instanceof DefaultChannelConfig) { return ((DefaultChannelConfig) config).getMaxMessagesPerWrite(); } Integer value = config.getOption(ChannelOption.MAX_MESSAGES_PER_WRITE); if (value == null) { return Integer.MAX_VALUE; } return value; } @Override public final ChannelId id() { return id; } /** * Returns a new {@link DefaultChannelId} instance. Subclasses may override this method to assign custom * {@link ChannelId}s to {@link Channel}s that use the {@link AbstractChannel#AbstractChannel(Channel)} constructor. */ protected ChannelId newId() { return DefaultChannelId.newInstance(); } /** * Returns a new {@link DefaultChannelPipeline} instance. */ protected DefaultChannelPipeline newChannelPipeline() { return new DefaultChannelPipeline(this); } @Override public boolean isWritable() { ChannelOutboundBuffer buf = unsafe.outboundBuffer(); return buf != null && buf.isWritable(); } @Override public long bytesBeforeUnwritable() { ChannelOutboundBuffer buf = unsafe.outboundBuffer(); // isWritable() is currently assuming if there is no outboundBuffer then the channel is not writable. // We should be consistent with that here. return buf != null ? buf.bytesBeforeUnwritable() : 0; } @Override public long bytesBeforeWritable() { ChannelOutboundBuffer buf = unsafe.outboundBuffer(); // isWritable() is currently assuming if there is no outboundBuffer then the channel is not writable. // We should be consistent with that here. return buf != null ? buf.bytesBeforeWritable() : Long.MAX_VALUE; } @Override public Channel parent() { return parent; } @Override public ChannelPipeline pipeline() { return pipeline; } @Override public ByteBufAllocator alloc() { return config().getAllocator(); } @Override public EventLoop eventLoop() { EventLoop eventLoop = this.eventLoop; if (eventLoop == null) { throw new IllegalStateException("channel not registered to an event loop"); } return eventLoop; } @Override public SocketAddress localAddress() { SocketAddress localAddress = this.localAddress; if (localAddress == null) { try { this.localAddress = localAddress = unsafe().localAddress(); } catch (Error e) { throw e; } catch (Throwable t) { // Sometimes fails on a closed socket in Windows. return null; } } return localAddress; } /** * @deprecated no use-case for this. */ @Deprecated protected void invalidateLocalAddress() { localAddress = null; } @Override public SocketAddress remoteAddress() { SocketAddress remoteAddress = this.remoteAddress; if (remoteAddress == null) { try { this.remoteAddress = remoteAddress = unsafe().remoteAddress(); } catch (Error e) { throw e; } catch (Throwable t) { // Sometimes fails on a closed socket in Windows. return null; } } return remoteAddress; } /** * @deprecated no use-case for this. */ @Deprecated protected void invalidateRemoteAddress() { remoteAddress = null; } @Override public boolean isRegistered() { return registered; } @Override public ChannelFuture bind(SocketAddress localAddress) { return pipeline.bind(localAddress); } @Override public ChannelFuture connect(SocketAddress remoteAddress) { return pipeline.connect(remoteAddress); } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { return pipeline.connect(remoteAddress, localAddress); } @Override public ChannelFuture disconnect() { return pipeline.disconnect(); } @Override public ChannelFuture close() { return pipeline.close(); } @Override public ChannelFuture deregister() { return pipeline.deregister(); } @Override public Channel flush() { pipeline.flush(); return this; } @Override public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { return pipeline.bind(localAddress, promise); } @Override public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { return pipeline.connect(remoteAddress, promise); } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { return pipeline.connect(remoteAddress, localAddress, promise); } @Override public ChannelFuture disconnect(ChannelPromise promise) { return pipeline.disconnect(promise); } @Override public ChannelFuture close(ChannelPromise promise) { return pipeline.close(promise); } @Override public ChannelFuture deregister(ChannelPromise promise) { return pipeline.deregister(promise); } @Override public Channel read() { pipeline.read(); return this; } @Override public ChannelFuture write(Object msg) { return pipeline.write(msg); } @Override public ChannelFuture write(Object msg, ChannelPromise promise) { return pipeline.write(msg, promise); } @Override public ChannelFuture writeAndFlush(Object msg) { return pipeline.writeAndFlush(msg); } @Override public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { return pipeline.writeAndFlush(msg, promise); } @Override public ChannelPromise newPromise() { return pipeline.newPromise(); } @Override public ChannelProgressivePromise newProgressivePromise() { return pipeline.newProgressivePromise(); } @Override public ChannelFuture newSucceededFuture() { return pipeline.newSucceededFuture(); } @Override public ChannelFuture newFailedFuture(Throwable cause) { return pipeline.newFailedFuture(cause); } @Override public ChannelFuture closeFuture() { return closeFuture; } @Override public Unsafe unsafe() { return unsafe; } /** * Create a new {@link AbstractUnsafe} instance which will be used for the life-time of the {@link Channel} */ protected abstract AbstractUnsafe newUnsafe(); /** * Returns the ID of this channel. */ @Override public final int hashCode() { return id.hashCode(); } /** * Returns {@code true} if and only if the specified object is identical * with this channel (i.e: {@code this == o}). */ @Override public final boolean equals(Object o) { return this == o; } @Override public final int compareTo(Channel o) { if (this == o) { return 0; } return id().compareTo(o.id()); } /** * Returns the {@link String} representation of this channel. The returned * string contains the {@linkplain #hashCode() ID}, {@linkplain #localAddress() local address}, * and {@linkplain #remoteAddress() remote address} of this channel for * easier identification. */ @Override public String toString() { boolean active = isActive(); if (strValActive == active && strVal != null) { return strVal; } SocketAddress remoteAddr = remoteAddress(); SocketAddress localAddr = localAddress(); if (remoteAddr != null) { StringBuilder buf = new StringBuilder(96) .append("[id: 0x") .append(id.asShortText()) .append(", L:") .append(localAddr) .append(active? " - " : " ! ") .append("R:") .append(remoteAddr) .append(']'); strVal = buf.toString(); } else if (localAddr != null) { StringBuilder buf = new StringBuilder(64) .append("[id: 0x") .append(id.asShortText()) .append(", L:") .append(localAddr) .append(']'); strVal = buf.toString(); } else { StringBuilder buf = new StringBuilder(16) .append("[id: 0x") .append(id.asShortText()) .append(']'); strVal = buf.toString(); } strValActive = active; return strVal; } @Override public final ChannelPromise voidPromise() { return pipeline.voidPromise(); } /** * {@link Unsafe} implementation which sub-classes must extend and use. */ protected abstract class AbstractUnsafe implements Unsafe { private volatile ChannelOutboundBuffer outboundBuffer = new ChannelOutboundBuffer(AbstractChannel.this); private RecvByteBufAllocator.Handle recvHandle; private boolean inFlush0; /** true if the channel has never been registered, false otherwise */ private boolean neverRegistered = true; private void assertEventLoop() { assert !registered || eventLoop.inEventLoop(); } @Override public RecvByteBufAllocator.Handle recvBufAllocHandle() { if (recvHandle == null) { recvHandle = config().getRecvByteBufAllocator().newHandle(); } return recvHandle; } @Override public final ChannelOutboundBuffer outboundBuffer() { return outboundBuffer; } @Override public final SocketAddress localAddress() { return localAddress0(); } @Override public final SocketAddress remoteAddress() { return remoteAddress0(); } @Override public final void register(EventLoop eventLoop, final ChannelPromise promise) { ObjectUtil.checkNotNull(eventLoop, "eventLoop"); if (isRegistered()) { promise.setFailure(new IllegalStateException("registered to an event loop already")); return; } if (!isCompatible(eventLoop)) { promise.setFailure( new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName())); return; } AbstractChannel.this.eventLoop = eventLoop; if (eventLoop.inEventLoop()) { register0(promise); } else { try { eventLoop.execute(new Runnable() { @Override public void run() { register0(promise); } }); } catch (Throwable t) { logger.warn( "Force-closing a channel whose registration task was not accepted by an event loop: {}", AbstractChannel.this, t); closeForcibly(); closeFuture.setClosed(); safeSetFailure(promise, t); } } } private void register0(ChannelPromise promise) { try { // check if the channel is still open as it could be closed in the mean time when the register // call was outside of the eventLoop if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } boolean firstRegistration = neverRegistered; doRegister(); neverRegistered = false; registered = true; // Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the // user may already fire events through the pipeline in the ChannelFutureListener. pipeline.invokeHandlerAddedIfNeeded(); safeSetSuccess(promise); pipeline.fireChannelRegistered(); // Only fire a channelActive if the channel has never been registered. This prevents firing // multiple channel actives if the channel is deregistered and re-registered. if (isActive()) { if (firstRegistration) { pipeline.fireChannelActive(); } else if (config().isAutoRead()) { // This channel was registered before and autoRead() is set. This means we need to begin read // again so that we process inbound data. // // See https://github.com/netty/netty/issues/4805 beginRead(); } } } catch (Throwable t) { // Close the channel directly to avoid FD leak. closeForcibly(); closeFuture.setClosed(); safeSetFailure(promise, t); } } @Override public final void bind(final SocketAddress localAddress, final ChannelPromise promise) { assertEventLoop(); if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } // See: https://github.com/netty/netty/issues/576 if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) && localAddress instanceof InetSocketAddress && !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() && !PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) { // Warn a user about the fact that a non-root user can't receive a // broadcast packet on *nix if the socket is bound on non-wildcard address. logger.warn( "A non-root user can't receive a broadcast packet if the socket " + "is not bound to a wildcard address; binding to a non-wildcard " + "address (" + localAddress + ") anyway as requested."); } boolean wasActive = isActive(); try { doBind(localAddress); } catch (Throwable t) { safeSetFailure(promise, t); closeIfClosed(); return; } if (!wasActive && isActive()) { invokeLater(new Runnable() { @Override public void run() { pipeline.fireChannelActive(); } }); } safeSetSuccess(promise); } @Override public final void disconnect(final ChannelPromise promise) { assertEventLoop(); if (!promise.setUncancellable()) { return; } boolean wasActive = isActive(); try { doDisconnect(); // Reset remoteAddress and localAddress remoteAddress = null; localAddress = null; } catch (Throwable t) { safeSetFailure(promise, t); closeIfClosed(); return; } if (wasActive && !isActive()) { invokeLater(new Runnable() { @Override public void run() { pipeline.fireChannelInactive(); } }); } safeSetSuccess(promise); closeIfClosed(); // doDisconnect() might have closed the channel } @Override public void close(final ChannelPromise promise) { assertEventLoop(); ClosedChannelException closedChannelException = StacklessClosedChannelException.newInstance(AbstractChannel.class, "close(ChannelPromise)"); close(promise, closedChannelException, closedChannelException, false); } /** * Shutdown the output portion of the corresponding {@link Channel}. * For example this will clean up the {@link ChannelOutboundBuffer} and not allow any more writes. */ @UnstableApi public final void shutdownOutput(final ChannelPromise promise) { assertEventLoop(); shutdownOutput(promise, null); } /** * Shutdown the output portion of the corresponding {@link Channel}. * For example this will clean up the {@link ChannelOutboundBuffer} and not allow any more writes. * @param cause The cause which may provide rational for the shutdown. */ private void shutdownOutput(final ChannelPromise promise, Throwable cause) { if (!promise.setUncancellable()) { return; } final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { promise.setFailure(new ClosedChannelException()); return; } this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. final Throwable shutdownCause = cause == null ? new ChannelOutputShutdownException("Channel output shutdown") : new ChannelOutputShutdownException("Channel output shutdown", cause); // When a side enables SO_LINGER and calls showdownOutput(...) to start TCP half-closure // we can not call doDeregister here because we should ensure this side in fin_wait2 state // can still receive and process the data which is send by another side in the close_wait state。 // See https://github.com/netty/netty/issues/11981 try { // The shutdown function does not block regardless of the SO_LINGER setting on the socket // so we don't need to use GlobalEventExecutor to execute the shutdown doShutdownOutput(); promise.setSuccess(); } catch (Throwable err) { promise.setFailure(err); } finally { closeOutboundBufferForShutdown(pipeline, outboundBuffer, shutdownCause); } } private void closeOutboundBufferForShutdown( ChannelPipeline pipeline, ChannelOutboundBuffer buffer, Throwable cause) { buffer.failFlushed(cause, false); buffer.close(cause, true); pipeline.fireUserEventTriggered(ChannelOutputShutdownEvent.INSTANCE); } private void close(final ChannelPromise promise, final Throwable cause, final ClosedChannelException closeCause, final boolean notify) { if (!promise.setUncancellable()) { return; } if (closeInitiated) { if (closeFuture.isDone()) { // Closed already. safeSetSuccess(promise); } else if (!(promise instanceof VoidChannelPromise)) { // Only needed if no VoidChannelPromise. // This means close() was called before so we just register a listener and return closeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { promise.setSuccess(); } }); } return; } closeInitiated = true; final boolean wasActive = isActive(); final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. Executor closeExecutor = prepareToClose(); if (closeExecutor != null) { closeExecutor.execute(new Runnable() { @Override public void run() { try { // Execute the close. doClose0(promise); } finally { // Call invokeLater so closeAndDeregister is executed in the EventLoop again! invokeLater(new Runnable() { @Override public void run() { if (outboundBuffer != null) { // Fail all the queued messages outboundBuffer.failFlushed(cause, notify); outboundBuffer.close(closeCause); } fireChannelInactiveAndDeregister(wasActive); } }); } } }); } else { try { // Close the channel and fail the queued messages in all cases. doClose0(promise); } finally { if (outboundBuffer != null) { // Fail all the queued messages. outboundBuffer.failFlushed(cause, notify); outboundBuffer.close(closeCause); } } if (inFlush0) { invokeLater(new Runnable() { @Override public void run() { fireChannelInactiveAndDeregister(wasActive); } }); } else { fireChannelInactiveAndDeregister(wasActive); } } } private void doClose0(ChannelPromise promise) { try { doClose(); closeFuture.setClosed(); safeSetSuccess(promise); } catch (Throwable t) { closeFuture.setClosed(); safeSetFailure(promise, t); } } private void fireChannelInactiveAndDeregister(final boolean wasActive) { deregister(voidPromise(), wasActive && !isActive()); } @Override public final void closeForcibly() { assertEventLoop(); try { doClose(); } catch (Exception e) { logger.warn("Failed to close a channel.", e); } } @Override public final void deregister(final ChannelPromise promise) { assertEventLoop(); deregister(promise, false); } private void deregister(final ChannelPromise promise, final boolean fireChannelInactive) { if (!promise.setUncancellable()) { return; } if (!registered) { safeSetSuccess(promise); return; } // As a user may call deregister() from within any method while doing processing in the ChannelPipeline, // we need to ensure we do the actual deregister operation later. This is needed as for example, // we may be in the ByteToMessageDecoder.callDecode(...) method and so still try to do processing in // the old EventLoop while the user already registered the Channel to a new EventLoop. Without delay, // the deregister operation this could lead to have a handler invoked by different EventLoop and so // threads. // // See: // https://github.com/netty/netty/issues/4435 invokeLater(new Runnable() { @Override public void run() { try { doDeregister(); } catch (Throwable t) { logger.warn("Unexpected exception occurred while deregistering a channel.", t); } finally { if (fireChannelInactive) { pipeline.fireChannelInactive(); } // Some transports like local and AIO does not allow the deregistration of // an open channel. Their doDeregister() calls close(). Consequently, // close() calls deregister() again - no need to fire channelUnregistered, so check // if it was registered. if (registered) { registered = false; pipeline.fireChannelUnregistered(); } safeSetSuccess(promise); } } }); } @Override public final void beginRead() { assertEventLoop(); try { doBeginRead(); } catch (final Exception e) { invokeLater(new Runnable() { @Override public void run() { pipeline.fireExceptionCaught(e); } }); close(voidPromise()); } } @Override public final void write(Object msg, ChannelPromise promise) { assertEventLoop(); ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { try { // release message now to prevent resource-leak ReferenceCountUtil.release(msg); } finally { // If the outboundBuffer is null we know the channel was closed and so // need to fail the future right away. If it is not null the handling of the rest // will be done in flush0() // See https://github.com/netty/netty/issues/2362 safeSetFailure(promise, newClosedChannelException(initialCloseCause, "write(Object, ChannelPromise)")); } return; } int size; try { msg = filterOutboundMessage(msg); size = pipeline.estimatorHandle().size(msg); if (size < 0) { size = 0; } } catch (Throwable t) { try { ReferenceCountUtil.release(msg); } finally { safeSetFailure(promise, t); } return; } outboundBuffer.addMessage(msg, size, promise); } @Override public final void flush() { assertEventLoop(); ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { return; } outboundBuffer.addFlush(); flush0(); } @SuppressWarnings("deprecation") protected void flush0() { if (inFlush0) { // Avoid re-entrance return; } final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null || outboundBuffer.isEmpty()) { return; } inFlush0 = true; // Mark all pending write requests as failure if the channel is inactive. if (!isActive()) { try { // Check if we need to generate the exception at all. if (!outboundBuffer.isEmpty()) { if (isOpen()) { outboundBuffer.failFlushed(new NotYetConnectedException(), true); } else { // Do not trigger channelWritabilityChanged because the channel is closed already. outboundBuffer.failFlushed(newClosedChannelException(initialCloseCause, "flush0()"), false); } } } finally { inFlush0 = false; } return; } try { doWrite(outboundBuffer); } catch (Throwable t) { handleWriteError(t); } finally { inFlush0 = false; } } protected final void handleWriteError(Throwable t) { if (t instanceof IOException && config().isAutoClose()) { /** * Just call {@link #close(ChannelPromise, Throwable, boolean)} here which will take care of * failing all flushed messages and also ensure the actual close of the underlying transport * will happen before the promises are notified. * * This is needed as otherwise {@link #isActive()} , {@link #isOpen()} and {@link #isWritable()} * may still return {@code true} even if the channel should be closed as result of the exception. */ initialCloseCause = t; close(voidPromise(), t, newClosedChannelException(t, "flush0()"), false); } else { try { shutdownOutput(voidPromise(), t); } catch (Throwable t2) { initialCloseCause = t; close(voidPromise(), t2, newClosedChannelException(t, "flush0()"), false); } } } private ClosedChannelException newClosedChannelException(Throwable cause, String method) { ClosedChannelException exception = StacklessClosedChannelException.newInstance(AbstractChannel.AbstractUnsafe.class, method); if (cause != null) { exception.initCause(cause); } return exception; } @Override public final ChannelPromise voidPromise() { assertEventLoop(); return unsafeVoidPromise; } protected final boolean ensureOpen(ChannelPromise promise) { if (isOpen()) { return true; } safeSetFailure(promise, newClosedChannelException(initialCloseCause, "ensureOpen(ChannelPromise)")); return false; } /** * Marks the specified {@code promise} as success. If the {@code promise} is done already, log a message. */ protected final void safeSetSuccess(ChannelPromise promise) { if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) { logger.warn("Failed to mark a promise as success because it is done already: {}", promise); } } /** * Marks the specified {@code promise} as failure. If the {@code promise} is done already, log a message. */ protected final void safeSetFailure(ChannelPromise promise, Throwable cause) { if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); } } protected final void closeIfClosed() { if (isOpen()) { return; } close(voidPromise()); } private void invokeLater(Runnable task) { try { // This method is used by outbound operation implementations to trigger an inbound event later. // They do not trigger an inbound event immediately because an outbound operation might have been // triggered by another inbound event handler method. If fired immediately, the call stack // will look like this for example: // // handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection. // -> handlerA.ctx.close() // -> channel.unsafe.close() // -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet // // which means the execution of two inbound handler methods of the same handler overlap undesirably. eventLoop().execute(task); } catch (RejectedExecutionException e) { logger.warn("Can't invoke task later as EventLoop rejected it", e); } } /** * Appends the remote address to the message of the exceptions caused by connection attempt failure. */ protected final Throwable annotateConnectException(Throwable cause, SocketAddress remoteAddress) { if (cause instanceof ConnectException) { return new AnnotatedConnectException((ConnectException) cause, remoteAddress); } if (cause instanceof NoRouteToHostException) { return new AnnotatedNoRouteToHostException((NoRouteToHostException) cause, remoteAddress); } if (cause instanceof SocketException) { return new AnnotatedSocketException((SocketException) cause, remoteAddress); } return cause; } /** * Prepares to close the {@link Channel}. If this method returns an {@link Executor}, the * caller must call the {@link Executor#execute(Runnable)} method with a task that calls * {@link #doClose()} on the returned {@link Executor}. If this method returns {@code null}, * {@link #doClose()} must be called from the caller thread. (i.e. {@link EventLoop}) */ protected Executor prepareToClose() { return null; } } /** * Return {@code true} if the given {@link EventLoop} is compatible with this instance. */ protected abstract boolean isCompatible(EventLoop loop); /** * Returns the {@link SocketAddress} which is bound locally. */ protected abstract SocketAddress localAddress0(); /** * Return the {@link SocketAddress} which the {@link Channel} is connected to. */ protected abstract SocketAddress remoteAddress0(); /** * Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process. * * Sub-classes may override this method */ protected void doRegister() throws Exception { // NOOP } /** * Bind the {@link Channel} to the {@link SocketAddress} */ protected abstract void doBind(SocketAddress localAddress) throws Exception; /** * Disconnect this {@link Channel} from its remote peer */ protected abstract void doDisconnect() throws Exception; /** * Close the {@link Channel} */ protected abstract void doClose() throws Exception; /** * Called when conditions justify shutting down the output portion of the channel. This may happen if a write * operation throws an exception. */ @UnstableApi protected void doShutdownOutput() throws Exception { doClose(); } /** * Deregister the {@link Channel} from its {@link EventLoop}. * * Sub-classes may override this method */ protected void doDeregister() throws Exception { // NOOP } /** * Schedule a read operation. */ protected abstract void doBeginRead() throws Exception; /** * Flush the content of the given buffer to the remote peer. */ protected abstract void doWrite(ChannelOutboundBuffer in) throws Exception; /** * Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that * the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer) */ protected Object filterOutboundMessage(Object msg) throws Exception { return msg; } protected void validateFileRegion(DefaultFileRegion region, long position) throws IOException { DefaultFileRegion.validate(region, position); } static final class CloseFuture extends DefaultChannelPromise { CloseFuture(AbstractChannel ch) { super(ch); } @Override public ChannelPromise setSuccess() { throw new IllegalStateException(); } @Override public ChannelPromise setFailure(Throwable cause) { throw new IllegalStateException(); } @Override public boolean trySuccess() { throw new IllegalStateException(); } @Override public boolean tryFailure(Throwable cause) { throw new IllegalStateException(); } boolean setClosed() { return super.trySuccess(); } } private static final class AnnotatedConnectException extends ConnectException { private static final long serialVersionUID = 3901958112696433556L; AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); } // Suppress a warning since this method doesn't need synchronization @Override public Throwable fillInStackTrace() { return this; } } private static final class AnnotatedNoRouteToHostException extends NoRouteToHostException { private static final long serialVersionUID = -6801433937592080623L; AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); } // Suppress a warning since this method doesn't need synchronization @Override public Throwable fillInStackTrace() { return this; } } private static final class AnnotatedSocketException extends SocketException { private static final long serialVersionUID = 3896743275010454039L; AnnotatedSocketException(SocketException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); } // Suppress a warning since this method doesn't need synchronization @Override public Throwable fillInStackTrace() { return this; } } }
netty/netty
transport/src/main/java/io/netty/channel/AbstractChannel.java
52
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.common; import com.facebook.infer.annotation.Nullsafe; /** Object wrapping an auto-expanding long[]. Like an ArrayList<Long> but without the autoboxing. */ @Nullsafe(Nullsafe.Mode.LOCAL) public class LongArray { private static final double INNER_ARRAY_GROWTH_FACTOR = 1.8; private long[] mArray; private int mLength; public static LongArray createWithInitialCapacity(int initialCapacity) { return new LongArray(initialCapacity); } private LongArray(int initialCapacity) { mArray = new long[initialCapacity]; mLength = 0; } public void add(long value) { growArrayIfNeeded(); mArray[mLength++] = value; } public long get(int index) { if (index >= mLength) { throw new IndexOutOfBoundsException("" + index + " >= " + mLength); } return mArray[index]; } public void set(int index, long value) { if (index >= mLength) { throw new IndexOutOfBoundsException("" + index + " >= " + mLength); } mArray[index] = value; } public int size() { return mLength; } public boolean isEmpty() { return mLength == 0; } /** Removes the *last* n items of the array all at once. */ public void dropTail(int n) { if (n > mLength) { throw new IndexOutOfBoundsException( "Trying to drop " + n + " items from array of length " + mLength); } mLength -= n; } private void growArrayIfNeeded() { if (mLength == mArray.length) { // If the initial capacity was 1 we need to ensure it at least grows by 1. int newSize = Math.max(mLength + 1, (int) (mLength * INNER_ARRAY_GROWTH_FACTOR)); long[] newArray = new long[newSize]; System.arraycopy(mArray, 0, newArray, 0, mLength); mArray = newArray; } } }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/LongArray.java
53
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.api.java; import java.io.Serializable; import java.util.Objects; import com.google.common.base.Preconditions; /** * <p>Like {@code java.util.Optional} in Java 8, {@code scala.Option} in Scala, and * {@code com.google.common.base.Optional} in Google Guava, this class represents a * value of a given type that may or may not exist. It is used in methods that wish * to optionally return a value, in preference to returning {@code null}.</p> * * <p>In fact, the class here is a reimplementation of the essential API of both * {@code java.util.Optional} and {@code com.google.common.base.Optional}. From * {@code java.util.Optional}, it implements:</p> * * <ul> * <li>{@link #empty()}</li> * <li>{@link #of(Object)}</li> * <li>{@link #ofNullable(Object)}</li> * <li>{@link #get()}</li> * <li>{@link #orElse(Object)}</li> * <li>{@link #isPresent()}</li> * </ul> * * <p>From {@code com.google.common.base.Optional} it implements:</p> * * <ul> * <li>{@link #absent()}</li> * <li>{@link #of(Object)}</li> * <li>{@link #fromNullable(Object)}</li> * <li>{@link #get()}</li> * <li>{@link #or(Object)}</li> * <li>{@link #orNull()}</li> * <li>{@link #isPresent()}</li> * </ul> * * <p>{@code java.util.Optional} itself was not used because at the time, the * project did not require Java 8. Using {@code com.google.common.base.Optional} * has in the past caused serious library version conflicts with Guava that can't * be resolved by shading. Hence this work-alike clone.</p> * * @param <T> type of value held inside */ public final class Optional<T> implements Serializable { private static final Optional<?> EMPTY = new Optional<>(); private final T value; private Optional() { this.value = null; } private Optional(T value) { Preconditions.checkNotNull(value); this.value = value; } // java.util.Optional API (subset) /** * @return an empty {@code Optional} */ public static <T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; } /** * @param value non-null value to wrap * @return {@code Optional} wrapping this value * @throws NullPointerException if value is null */ public static <T> Optional<T> of(T value) { return new Optional<>(value); } /** * @param value value to wrap, which may be null * @return {@code Optional} wrapping this value, which may be empty */ public static <T> Optional<T> ofNullable(T value) { if (value == null) { return empty(); } else { return of(value); } } /** * @return the value wrapped by this {@code Optional} * @throws NullPointerException if this is empty (contains no value) */ public T get() { Preconditions.checkNotNull(value); return value; } /** * @param other value to return if this is empty * @return this {@code Optional}'s value if present, or else the given value */ public T orElse(T other) { return value != null ? value : other; } /** * @return true iff this {@code Optional} contains a value (non-empty) */ public boolean isPresent() { return value != null; } // Guava API (subset) // of(), get() and isPresent() are identically present in the Guava API /** * @return an empty {@code Optional} */ public static <T> Optional<T> absent() { return empty(); } /** * @param value value to wrap, which may be null * @return {@code Optional} wrapping this value, which may be empty */ public static <T> Optional<T> fromNullable(T value) { return ofNullable(value); } /** * @param other value to return if this is empty * @return this {@code Optional}'s value if present, or else the given value */ public T or(T other) { return value != null ? value : other; } /** * @return this {@code Optional}'s value if present, or else null */ public T orNull() { return value; } // Common methods @Override public boolean equals(Object obj) { if (!(obj instanceof Optional<?> other)) { return false; } return Objects.equals(value, other.value); } @Override public int hashCode() { return value == null ? 0 : value.hashCode(); } @Override public String toString() { return value == null ? "Optional.empty" : String.format("Optional[%s]", value); } }
apache/spark
core/src/main/java/org/apache/spark/api/java/Optional.java
54
/* Part of the Processing project - http://processing.org Copyright (c) 2004-06 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import static processing.app.I18n.format; import static processing.app.I18n.tr; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.SystemColor; import java.awt.Toolkit; import java.awt.font.TextAttribute; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.swing.text.StyleContext; import org.apache.batik.transcoder.Transcoder; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.lang3.StringUtils; import processing.app.helpers.OSUtils; import processing.app.helpers.PreferencesHelper; import processing.app.helpers.PreferencesMap; /** * Storage class for theme settings. This was separated from the Preferences * class for 1.0 so that the coloring wouldn't conflict with previous releases * and to make way for future ability to customize. */ public class Theme { static final String THEME_DIR = "theme/"; static final String THEME_FILE_NAME = "theme.txt"; static final String NAMESPACE_APP = "app:"; static final String NAMESPACE_USER = "user:"; /** * A theme resource, this is returned instead of {@link File} so that we can * support zip-packaged resources as well as files in the file system */ public static class Resource { // Priority levels used to determine whether one resource should override // another static public final int PRIORITY_DEFAULT = 0; static public final int PRIORITY_USER_ZIP = 1; static public final int PRIORITY_USER_FILE = 2; /** * Priority of this resource. */ private final int priority; /** * Resource name (original name of requested resource, relative path only). */ private final String name; /** * File if this resource represents a file, can be null. */ private final File file; /** * Zip theme if the resource is contained within a zipped theme */ private final ZippedTheme theme; /** * Zip entry if this resource represents a zip entry, can be null. */ private final ZipEntry zipEntry; /** * URL of this resource regardless of type, theoretically shouldn't ever be * null though it might be if a particular resource path can't be * successfully transformed into a URL (eg. {@link Theme#getUrl} traps a * <tt>MalformedURLException</tt>). */ private final URL url; /** * If this resource supercedes a resource with a lower priority, this field * stores a reference to the superceded resource. This allows consumers to * traverse the resource hierarchy if required. */ private Resource parent; /** * ctor for file resources */ Resource(int priority, String name, URL url, File file) { this(priority, name, url, file, null, null); } /** * ctor for zip resources */ Resource(int priority, String name, URL url, ZippedTheme theme, ZipEntry entry) { this(priority, name, url, null, theme, entry); } private Resource(int priority, String name, URL url, File file, ZippedTheme theme, ZipEntry zipEntry) { this.priority = priority; this.name = name; this.file = file; this.theme = theme; this.zipEntry = zipEntry; this.url = url; } public Resource getParent() { return this.parent; } public String getName() { return this.name; } public URL getUrl() { return this.url; } public int getPriority() { return this.priority; } public boolean isUserDefined() { return this.priority > PRIORITY_DEFAULT; } public boolean exists() { return this.zipEntry != null || this.file == null || this.file.exists(); } public InputStream getInputStream() throws IOException { if (this.file != null) { return new FileInputStream(this.file); } if (this.zipEntry != null) { return this.theme.getZip().getInputStream(this.zipEntry); } if (this.url != null) { return this.url.openStream(); } throw new FileNotFoundException(this.name); } public String toString() { return this.name; } Resource withParent(Resource parent) { this.parent = parent; return this; } } /** * Struct which keeps information about a discovered .zip theme file */ public static class ZippedTheme { /** * Configuration key, this key consists of a "namespace" which determines * the root folder the theme was found in without actually storing the path * itself, followed by the file name. */ private final String key; /** * File containing the theme */ private final File file; /** * Zip file handle for retrieving entries */ private final ZipFile zip; /** * Display name, defaulted to filename but can be read from metadata */ private final String name; /** * Version number, plain text string read from metadata */ private final String version; private ZippedTheme(String namespace, File file, ZipFile zip, String name, String version) { this.key = namespace + file.getName(); this.file = file; this.zip = zip; this.name = name; this.version = version; } public String getKey() { return this.key; } public File getFile() { return this.file; } public ZipFile getZip() { return this.zip; } public String getName() { return this.name; } public String getVersion() { return this.version; } public String toString() { String description = String.format("%s %s (%s)", this.getName(), this.getVersion(), this.file.getName()); return StringUtils.abbreviate(description, 40); } /** * Attempts to parse the supplied zip file as a theme file. This is largely * determined by the file being readable and containing a theme.txt entry. * Returns null if the file is unreadable or doesn't contain theme.txt */ static ZippedTheme load(String namespace, File file) { ZipFile zip = null; try { zip = new ZipFile(file); ZipEntry themeTxtEntry = zip.getEntry(THEME_FILE_NAME); if (themeTxtEntry != null) { String name = file.getName().substring(0, file.getName().length() - 4); String version = ""; ZipEntry themePropsEntry = zip.getEntry("theme.properties"); if (themePropsEntry != null) { Properties themeProperties = new Properties(); themeProperties.load(zip.getInputStream(themePropsEntry)); name = themeProperties.getProperty("name", name); version = themeProperties.getProperty("version", version); } return new ZippedTheme(namespace, file, zip, name, version); } } catch (Exception ex) { System.err.println(format(tr("Error loading theme {0}: {1}"), file.getAbsolutePath(), ex.getMessage())); IOUtils.closeQuietly(zip); } return null; } } /** * Copy of the defaults in case the user mangles a preference. */ static PreferencesMap defaults; /** * Table of attributes/values for the theme. */ static PreferencesMap table = new PreferencesMap(); /** * Available zipped themes */ static private final Map<String, ZippedTheme> availableThemes = new TreeMap<>(); /** * Zip file containing user-defined theme elements */ static private ZippedTheme zipTheme; static protected void init() { zipTheme = openZipTheme(); try { loadFromResource(table, THEME_DIR + THEME_FILE_NAME); } catch (Exception te) { Base.showError(null, tr("Could not read color theme settings.\n" + "You'll need to reinstall Arduino."), te); } // other things that have to be set explicitly for the defaults setColor("run.window.bgcolor", SystemColor.control); // clone the hash table defaults = new PreferencesMap(table); } static private ZippedTheme openZipTheme() { refreshAvailableThemes(); String selectedTheme = PreferencesData.get("theme.file", ""); synchronized(availableThemes) { return availableThemes.get(selectedTheme); } } static private void refreshAvailableThemes() { Map<String, ZippedTheme> discoveredThemes = new TreeMap<>(); refreshAvailableThemes(discoveredThemes, NAMESPACE_APP, new File(BaseNoGui.getContentFile("lib"), THEME_DIR)); refreshAvailableThemes(discoveredThemes, NAMESPACE_USER, new File(BaseNoGui.getSketchbookFolder(), THEME_DIR)); synchronized (availableThemes) { availableThemes.clear(); availableThemes.putAll(discoveredThemes); } } static private void refreshAvailableThemes(Map<String, ZippedTheme> discoveredThemes, String namespace, File folder) { if (!folder.isDirectory()) { return; } for (File zipFile : folder.listFiles((dir, name) -> name.endsWith(".zip"))) { ZippedTheme theme = ZippedTheme.load(namespace, zipFile); if (theme != null) { discoveredThemes.put(theme.getKey(), theme); } } } public static Collection<ZippedTheme> getAvailablethemes() { refreshAvailableThemes(); return Collections.unmodifiableCollection(availableThemes.values()); } static public String get(String attribute) { return table.get(attribute); } static public String getDefault(String attribute) { return defaults.get(attribute); } static public void set(String attribute, String value) { table.put(attribute, value); } static public boolean getBoolean(String attribute) { return table.getBoolean(attribute); } static public void setBoolean(String attribute, boolean value) { table.putBoolean(attribute, value); } static public int getInteger(String attribute) { return Integer.parseInt(get(attribute)); } static public void setInteger(String key, int value) { set(key, String.valueOf(value)); } static public int getScale() { try { int scale = PreferencesData.getInteger("gui.scale", -1); if (scale != -1) return scale; } catch (NumberFormatException ignore) { } return BaseNoGui.getPlatform().getSystemDPI() * 100 / 96; } static public int scale(int size) { return size * getScale() / 100; } static public Dimension scale(Dimension dim) { return new Dimension(scale(dim.width), scale(dim.height)); } static public Font scale(Font font) { float size = scale(font.getSize()); // size must be float to call the correct Font.deriveFont(float) // method that is different from Font.deriveFont(int)! Font scaled = font.deriveFont(size); return scaled; } static public Rectangle scale(Rectangle rect) { Rectangle res = new Rectangle(rect); res.x = scale(res.x); res.y = scale(res.y); res.width = scale(res.width); res.height = scale(res.height); return res; } static public Color getColorCycleColor(String name, int i) { int cycleSize = getInteger(name + ".size"); name = String.format("%s.%02d", name, i % cycleSize); return PreferencesHelper.parseColor(get(name)); } static public void setColorCycleColor(String name, int i, Color color) { name = String.format("%s.%02d", name, i); PreferencesHelper.putColor(table, name, color); int cycleSize = getInteger(name + ".size"); setInteger(name + ".size", (i + 1) > cycleSize ? (i + 1) : cycleSize); } static public Color getColor(String name) { return PreferencesHelper.parseColor(get(name)); } static public void setColor(String attr, Color color) { PreferencesHelper.putColor(table, attr, color); } static public Font getFont(String attr) { Font font = PreferencesHelper.getFont(table, attr); if (font == null) { String value = getDefault(attr); set(attr, value); font = PreferencesHelper.getFont(table, attr); if (font == null) { return null; } } return font.deriveFont((float) scale(font.getSize())); } /** * Returns the default font for text areas. * * @return The default font. */ public static final Font getDefaultFont() { // Use StyleContext to get a composite font for better Asian language // support; see Sun bug S282887. StyleContext sc = StyleContext.getDefaultStyleContext(); Font font = null; if (OSUtils.isMacOS()) { // Snow Leopard (1.6) uses Menlo as default monospaced font, // pre-Snow Leopard used Monaco. font = sc.getFont("Menlo", Font.PLAIN, 12); if (!"Menlo".equals(font.getFamily())) { font = sc.getFont("Monaco", Font.PLAIN, 12); if (!"Monaco".equals(font.getFamily())) { // Shouldn't happen font = sc.getFont("Monospaced", Font.PLAIN, 13); } } } else { // Consolas added in Vista, used by VS2010+. font = sc.getFont("Consolas", Font.PLAIN, 13); if (!"Consolas".equals(font.getFamily())) { font = sc.getFont("Monospaced", Font.PLAIN, 13); } } // System.out.println(font.getFamily() + ", " + font.getName()); return font; } public static Map<String, Object> getStyledFont(String what, Font font) { String split[] = get("editor." + what + ".style").split(","); Color color = PreferencesHelper.parseColor(split[0]); String style = split[1]; boolean bold = style.contains("bold"); boolean italic = style.contains("italic"); boolean underlined = style.contains("underlined"); Font styledFont = new Font(font.getFamily(), (bold ? Font.BOLD : 0) | (italic ? Font.ITALIC : 0), font.getSize()); if (underlined) { Map<TextAttribute, Object> attr = new Hashtable<>(); attr.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); styledFont = styledFont.deriveFont(attr); } Map<String, Object> result = new HashMap<>(); result.put("color", color); result.put("font", styledFont); return result; } /** * Return an Image object from inside the Processing lib folder. */ static public Image getLibImage(String filename, Component who, int width, int height) { Image image = null; // Use vector image when available Resource vectorFile = getThemeResource(filename + ".svg"); if (vectorFile.exists()) { try { image = imageFromSVG(vectorFile.getUrl(), width, height); } catch (Exception e) { System.err.println("Failed to load " + vectorFile + ": " + e.getMessage()); } } Resource bitmapFile = getThemeResource(filename + ".png"); // Otherwise fall-back to PNG bitmaps, allowing user-defined bitmaps to // override built-in svgs if (image == null || bitmapFile.getPriority() > vectorFile.getPriority()) { Resource bitmap2xFile = getThemeResource(filename + "@2x.png"); Resource imageFile; if (((getScale() > 125 && bitmap2xFile.exists()) || !bitmapFile.exists()) && (bitmapFile.isUserDefined() && bitmap2xFile.isUserDefined())) { imageFile = bitmap2xFile; } else { imageFile = bitmapFile; } Toolkit tk = Toolkit.getDefaultToolkit(); image = tk.getImage(imageFile.getUrl()); } MediaTracker tracker = new MediaTracker(who); try { tracker.addImage(image, 0); tracker.waitForAll(); } catch (InterruptedException e) { } if (image.getWidth(null) != width || image.getHeight(null) != height) { image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); try { tracker.addImage(image, 1); tracker.waitForAll(); } catch (InterruptedException e) { } } return image; } /** * Get an image associated with the current color theme. */ static public Image getThemeImage(String name, Component who, int width, int height) { return getLibImage(THEME_DIR + name, who, width, height); } private static Image imageFromSVG(URL url, int width, int height) throws TranscoderException { Transcoder t = new PNGTranscoder(); t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(width)); t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(height)); TranscoderInput input = new TranscoderInput(url.toString()); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); TranscoderOutput output = new TranscoderOutput(ostream); t.transcode(input, output); byte[] imgData = ostream.toByteArray(); return Toolkit.getDefaultToolkit().createImage(imgData); } static public Graphics2D setupGraphics2D(Graphics graphics) { Graphics2D g = (Graphics2D) graphics; if (PreferencesData.getBoolean("editor.antialias")) { g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } return g; } /** * Loads the supplied {@link PreferencesMap} from the specified resource, * recursively loading parent resources such that entries are loaded in order * of priority (lowest first). * * @param map preference map to populate * @param name name of resource to load */ static public PreferencesMap loadFromResource(PreferencesMap map, String name) throws IOException { return loadFromResource(map, getThemeResource(name)); } static private PreferencesMap loadFromResource(PreferencesMap map, Resource resource) throws IOException { if (resource != null) { loadFromResource(map, resource.getParent()); map.load(resource.getInputStream()); } return map; } /** * @param name * @return */ static public Resource getThemeResource(String name) { File defaultfile = getDefaultFile(name); Resource resource = new Resource(Resource.PRIORITY_DEFAULT, name, getUrl(defaultfile), defaultfile); ZipEntry themeZipEntry = getThemeZipEntry(name); if (themeZipEntry != null) { resource = new Resource(Resource.PRIORITY_USER_ZIP, name, getUrl(themeZipEntry), zipTheme, themeZipEntry).withParent(resource); } File themeFile = getThemeFile(name); if (themeFile != null) { resource = new Resource(Resource.PRIORITY_USER_FILE, name, getUrl(themeFile), themeFile).withParent(resource); } return resource; } static private File getThemeFile(String name) { File sketchBookThemeFolder = new File(BaseNoGui.getSketchbookFolder(), THEME_DIR); File themeFile = new File(sketchBookThemeFolder, name); if (themeFile.exists()) { return themeFile; } if (name.startsWith(THEME_DIR)) { themeFile = new File(sketchBookThemeFolder, name.substring(THEME_DIR.length())); if (themeFile.exists()) { return themeFile; } } return null; } static private ZipEntry getThemeZipEntry(String name) { if (zipTheme == null) { return null; } if (name.startsWith(THEME_DIR)) { name = name.substring(THEME_DIR.length()); } return zipTheme.getZip().getEntry(name); } static private File getDefaultFile(String name) { return new File(BaseNoGui.getContentFile("lib"), name); } static URL getUrl(File file) { try { return file.toURI().toURL(); } catch (MalformedURLException ex) { return null; } } static URL getUrl(ZipEntry entry) { try { // Adjust file name for URL format on Windows String zipFile = zipTheme.getZip().getName().replace('\\', '/'); if (!zipFile.startsWith("/")) { zipFile = "/" + zipFile; } // Construct a URL which points to the internal resource URI uri = new URI("jar", "file:" + zipFile + "!/" + entry.getName(), null); return uri.toURL(); } catch (MalformedURLException | URISyntaxException ex) { return null; } } }
roboard/86Duino
app/src/processing/app/Theme.java
55
/* * Copyright 2012-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.build; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import com.gradle.develocity.agent.gradle.test.DevelocityTestConfiguration; import com.gradle.develocity.agent.gradle.test.PredictiveTestSelectionConfiguration; import com.gradle.develocity.agent.gradle.test.TestRetryConfiguration; import io.spring.javaformat.gradle.SpringJavaFormatPlugin; import io.spring.javaformat.gradle.tasks.CheckFormat; import io.spring.javaformat.gradle.tasks.Format; import org.gradle.api.JavaVersion; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.ConfigurationContainer; import org.gradle.api.artifacts.Dependency; import org.gradle.api.artifacts.DependencySet; import org.gradle.api.plugins.JavaBasePlugin; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.plugins.quality.Checkstyle; import org.gradle.api.plugins.quality.CheckstyleExtension; import org.gradle.api.plugins.quality.CheckstylePlugin; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.bundling.Jar; import org.gradle.api.tasks.compile.JavaCompile; import org.gradle.api.tasks.javadoc.Javadoc; import org.gradle.api.tasks.testing.Test; import org.gradle.external.javadoc.CoreJavadocOptions; import org.springframework.boot.build.architecture.ArchitecturePlugin; import org.springframework.boot.build.classpath.CheckClasspathForProhibitedDependencies; import org.springframework.boot.build.optional.OptionalDependenciesPlugin; import org.springframework.boot.build.testing.TestFailuresPlugin; import org.springframework.boot.build.toolchain.ToolchainPlugin; import org.springframework.util.StringUtils; /** * Conventions that are applied in the presence of the {@link JavaBasePlugin}. When the * plugin is applied: * * <ul> * <li>The project is configured with source and target compatibility of 17 * <li>{@link SpringJavaFormatPlugin Spring Java Format}, {@link CheckstylePlugin * Checkstyle}, {@link TestFailuresPlugin Test Failures}, and {@link ArchitecturePlugin * Architecture} plugins are applied * <li>{@link Test} tasks are configured: * <ul> * <li>to use JUnit Platform * <li>with a max heap of 1024M * <li>to run after any Checkstyle and format checking tasks * <li>to enable retries with a maximum of three attempts when running on CI * <li>to use predictive test selection when the value of the * {@code ENABLE_PREDICTIVE_TEST_SELECTION} environment variable is {@code true} * </ul> * <li>A {@code testRuntimeOnly} dependency upon * {@code org.junit.platform:junit-platform-launcher} is added to projects with the * {@link JavaPlugin} applied * <li>{@link JavaCompile}, {@link Javadoc}, and {@link Format} tasks are configured to * use UTF-8 encoding * <li>{@link JavaCompile} tasks are configured to: * <ul> * <li>Use {@code -parameters}. * <li>Treat warnings as errors * <li>Enable {@code unchecked}, {@code deprecation}, {@code rawtypes}, and * {@code varargs} warnings * </ul> * <li>{@link Jar} tasks are configured to produce jars with LICENSE.txt and NOTICE.txt * files and the following manifest entries: * <ul> * <li>{@code Automatic-Module-Name} * <li>{@code Build-Jdk-Spec} * <li>{@code Built-By} * <li>{@code Implementation-Title} * <li>{@code Implementation-Version} * </ul> * <li>{@code spring-boot-parent} is used for dependency management</li> * </ul> * * <p/> * * @author Andy Wilkinson * @author Christoph Dreis * @author Mike Smithson * @author Scott Frederick */ class JavaConventions { private static final String SOURCE_AND_TARGET_COMPATIBILITY = "17"; void apply(Project project) { project.getPlugins().withType(JavaBasePlugin.class, (java) -> { project.getPlugins().apply(TestFailuresPlugin.class); project.getPlugins().apply(ArchitecturePlugin.class); configureSpringJavaFormat(project); configureJavaConventions(project); configureJavadocConventions(project); configureTestConventions(project); configureJarManifestConventions(project); configureDependencyManagement(project); configureToolchain(project); configureProhibitedDependencyChecks(project); }); } private void configureJarManifestConventions(Project project) { ExtractResources extractLegalResources = project.getTasks() .create("extractLegalResources", ExtractResources.class); extractLegalResources.getDestinationDirectory().set(project.getLayout().getBuildDirectory().dir("legal")); extractLegalResources.setResourcesNames(Arrays.asList("LICENSE.txt", "NOTICE.txt")); extractLegalResources.property("version", project.getVersion().toString()); SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class); Set<String> sourceJarTaskNames = sourceSets.stream() .map(SourceSet::getSourcesJarTaskName) .collect(Collectors.toSet()); Set<String> javadocJarTaskNames = sourceSets.stream() .map(SourceSet::getJavadocJarTaskName) .collect(Collectors.toSet()); project.getTasks().withType(Jar.class, (jar) -> project.afterEvaluate((evaluated) -> { jar.metaInf((metaInf) -> metaInf.from(extractLegalResources)); jar.manifest((manifest) -> { Map<String, Object> attributes = new TreeMap<>(); attributes.put("Automatic-Module-Name", project.getName().replace("-", ".")); attributes.put("Build-Jdk-Spec", SOURCE_AND_TARGET_COMPATIBILITY); attributes.put("Built-By", "Spring"); attributes.put("Implementation-Title", determineImplementationTitle(project, sourceJarTaskNames, javadocJarTaskNames, jar)); attributes.put("Implementation-Version", project.getVersion()); manifest.attributes(attributes); }); })); } private String determineImplementationTitle(Project project, Set<String> sourceJarTaskNames, Set<String> javadocJarTaskNames, Jar jar) { if (sourceJarTaskNames.contains(jar.getName())) { return "Source for " + project.getName(); } if (javadocJarTaskNames.contains(jar.getName())) { return "Javadoc for " + project.getName(); } return project.getDescription(); } private void configureTestConventions(Project project) { project.getTasks().withType(Test.class, (test) -> { test.useJUnitPlatform(); test.setMaxHeapSize("1024M"); project.getTasks().withType(Checkstyle.class, test::mustRunAfter); project.getTasks().withType(CheckFormat.class, test::mustRunAfter); configureTestRetries(test); configurePredictiveTestSelection(test); }); project.getPlugins() .withType(JavaPlugin.class, (javaPlugin) -> project.getDependencies() .add(JavaPlugin.TEST_RUNTIME_ONLY_CONFIGURATION_NAME, "org.junit.platform:junit-platform-launcher")); } private void configureTestRetries(Test test) { TestRetryConfiguration testRetry = test.getExtensions() .getByType(DevelocityTestConfiguration.class) .getTestRetry(); testRetry.getFailOnPassedAfterRetry().set(false); testRetry.getMaxRetries().set(isCi() ? 3 : 0); } private boolean isCi() { return Boolean.parseBoolean(System.getenv("CI")); } private void configurePredictiveTestSelection(Test test) { if (isPredictiveTestSelectionEnabled()) { PredictiveTestSelectionConfiguration predictiveTestSelection = test.getExtensions() .getByType(DevelocityTestConfiguration.class) .getPredictiveTestSelection(); predictiveTestSelection.getEnabled().convention(true); } } private boolean isPredictiveTestSelectionEnabled() { return Boolean.parseBoolean(System.getenv("ENABLE_PREDICTIVE_TEST_SELECTION")); } private void configureJavadocConventions(Project project) { project.getTasks().withType(Javadoc.class, (javadoc) -> { CoreJavadocOptions options = (CoreJavadocOptions) javadoc.getOptions(); options.source("17"); options.encoding("UTF-8"); options.addStringOption("Xdoclint:none", "-quiet"); }); } private void configureJavaConventions(Project project) { if (!project.hasProperty("toolchainVersion")) { JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class); javaPluginExtension.setSourceCompatibility(JavaVersion.toVersion(SOURCE_AND_TARGET_COMPATIBILITY)); } project.getTasks().withType(JavaCompile.class, (compile) -> { compile.getOptions().setEncoding("UTF-8"); List<String> args = compile.getOptions().getCompilerArgs(); if (!args.contains("-parameters")) { args.add("-parameters"); } if (project.hasProperty("toolchainVersion")) { compile.setSourceCompatibility(SOURCE_AND_TARGET_COMPATIBILITY); compile.setTargetCompatibility(SOURCE_AND_TARGET_COMPATIBILITY); } else if (buildingWithJava17(project)) { args.addAll(Arrays.asList("-Werror", "-Xlint:unchecked", "-Xlint:deprecation", "-Xlint:rawtypes", "-Xlint:varargs")); } }); } private boolean buildingWithJava17(Project project) { return !project.hasProperty("toolchainVersion") && JavaVersion.current() == JavaVersion.VERSION_17; } private void configureSpringJavaFormat(Project project) { project.getPlugins().apply(SpringJavaFormatPlugin.class); project.getTasks().withType(Format.class, (Format) -> Format.setEncoding("UTF-8")); project.getPlugins().apply(CheckstylePlugin.class); CheckstyleExtension checkstyle = project.getExtensions().getByType(CheckstyleExtension.class); checkstyle.setToolVersion("10.12.4"); checkstyle.getConfigDirectory().set(project.getRootProject().file("src/checkstyle")); String version = SpringJavaFormatPlugin.class.getPackage().getImplementationVersion(); DependencySet checkstyleDependencies = project.getConfigurations().getByName("checkstyle").getDependencies(); checkstyleDependencies .add(project.getDependencies().create("com.puppycrawl.tools:checkstyle:" + checkstyle.getToolVersion())); checkstyleDependencies .add(project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version)); } private void configureDependencyManagement(Project project) { ConfigurationContainer configurations = project.getConfigurations(); Configuration dependencyManagement = configurations.create("dependencyManagement", (configuration) -> { configuration.setVisible(false); configuration.setCanBeConsumed(false); configuration.setCanBeResolved(false); }); configurations .matching((configuration) -> (configuration.getName().endsWith("Classpath") || JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME.equals(configuration.getName())) && (!configuration.getName().contains("dokkatoo"))) .all((configuration) -> configuration.extendsFrom(dependencyManagement)); Dependency springBootParent = project.getDependencies() .enforcedPlatform(project.getDependencies() .project(Collections.singletonMap("path", ":spring-boot-project:spring-boot-parent"))); dependencyManagement.getDependencies().add(springBootParent); project.getPlugins() .withType(OptionalDependenciesPlugin.class, (optionalDependencies) -> configurations .getByName(OptionalDependenciesPlugin.OPTIONAL_CONFIGURATION_NAME) .extendsFrom(dependencyManagement)); } private void configureToolchain(Project project) { project.getPlugins().apply(ToolchainPlugin.class); } private void configureProhibitedDependencyChecks(Project project) { SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class); sourceSets.all((sourceSet) -> createProhibitedDependenciesChecks(project, sourceSet.getCompileClasspathConfigurationName(), sourceSet.getRuntimeClasspathConfigurationName())); } private void createProhibitedDependenciesChecks(Project project, String... configurationNames) { ConfigurationContainer configurations = project.getConfigurations(); for (String configurationName : configurationNames) { Configuration configuration = configurations.getByName(configurationName); createProhibitedDependenciesCheck(configuration, project); } } private void createProhibitedDependenciesCheck(Configuration classpath, Project project) { CheckClasspathForProhibitedDependencies checkClasspathForProhibitedDependencies = project.getTasks() .create("check" + StringUtils.capitalize(classpath.getName() + "ForProhibitedDependencies"), CheckClasspathForProhibitedDependencies.class); checkClasspathForProhibitedDependencies.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForProhibitedDependencies); } }
spring-projects/spring-boot
buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java
56
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react; import android.app.Application; import androidx.annotation.Nullable; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.JSExceptionHandler; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.UIManagerProvider; import com.facebook.react.common.LifecycleState; import com.facebook.react.common.SurfaceDelegate; import com.facebook.react.common.SurfaceDelegateFactory; import com.facebook.react.common.annotations.DeprecatedInNewArchitecture; import com.facebook.react.devsupport.DevSupportManagerFactory; import com.facebook.react.devsupport.interfaces.DevLoadingViewManager; import com.facebook.react.devsupport.interfaces.PausedInDebuggerOverlayManager; import com.facebook.react.devsupport.interfaces.RedBoxHandler; import com.facebook.react.internal.ChoreographerProvider; import java.util.List; /** * Simple class that holds an instance of {@link ReactInstanceManager}. This can be used in your * {@link Application class} (see {@link ReactApplication}), or as a static field. */ @DeprecatedInNewArchitecture( message = "This class will be replaced by com.facebook.react.ReactHost in the new architecture of" + " React Native.") public abstract class ReactNativeHost { private final Application mApplication; private @Nullable ReactInstanceManager mReactInstanceManager; protected ReactNativeHost(Application application) { mApplication = application; } /** Get the current {@link ReactInstanceManager} instance, or create one. */ public ReactInstanceManager getReactInstanceManager() { if (mReactInstanceManager == null) { ReactMarker.logMarker(ReactMarkerConstants.INIT_REACT_RUNTIME_START); ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_START); mReactInstanceManager = createReactInstanceManager(); ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_END); } return mReactInstanceManager; } /** * Get whether this holder contains a {@link ReactInstanceManager} instance, or not. I.e. if * {@link #getReactInstanceManager()} has been called at least once since this object was created * or {@link #clear()} was called. */ public boolean hasInstance() { return mReactInstanceManager != null; } /** * Destroy the current instance and release the internal reference to it, allowing it to be GCed. */ public void clear() { if (mReactInstanceManager != null) { mReactInstanceManager.destroy(); mReactInstanceManager = null; } } protected ReactInstanceManager createReactInstanceManager() { ReactMarker.logMarker(ReactMarkerConstants.BUILD_REACT_INSTANCE_MANAGER_START); ReactInstanceManagerBuilder builder = getBaseReactInstanceManagerBuilder(); ReactMarker.logMarker(ReactMarkerConstants.BUILD_REACT_INSTANCE_MANAGER_END); return builder.build(); } protected ReactInstanceManagerBuilder getBaseReactInstanceManagerBuilder() { ReactInstanceManagerBuilder builder = ReactInstanceManager.builder() .setApplication(mApplication) .setJSMainModulePath(getJSMainModuleName()) .setUseDeveloperSupport(getUseDeveloperSupport()) .setDevSupportManagerFactory(getDevSupportManagerFactory()) .setDevLoadingViewManager(getDevLoadingViewManager()) .setRequireActivity(getShouldRequireActivity()) .setSurfaceDelegateFactory(getSurfaceDelegateFactory()) .setJSExceptionHandler(getJSExceptionHandler()) .setLazyViewManagersEnabled(getLazyViewManagersEnabled()) .setRedBoxHandler(getRedBoxHandler()) .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory()) .setUIManagerProvider(getUIManagerProvider()) .setInitialLifecycleState(LifecycleState.BEFORE_CREATE) .setReactPackageTurboModuleManagerDelegateBuilder( getReactPackageTurboModuleManagerDelegateBuilder()) .setJSEngineResolutionAlgorithm(getJSEngineResolutionAlgorithm()) .setChoreographerProvider(getChoreographerProvider()) .setPausedInDebuggerOverlayManager(getPausedInDebuggerOverlayManager()); for (ReactPackage reactPackage : getPackages()) { builder.addPackage(reactPackage); } String jsBundleFile = getJSBundleFile(); if (jsBundleFile != null) { builder.setJSBundleFile(jsBundleFile); } else { builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName())); } return builder; } /** Get the {@link RedBoxHandler} to send RedBox-related callbacks to. */ protected @Nullable RedBoxHandler getRedBoxHandler() { return null; } protected @Nullable JSExceptionHandler getJSExceptionHandler() { return null; } /** Get the {@link JavaScriptExecutorFactory}. Override this to use a custom Executor. */ protected @Nullable JavaScriptExecutorFactory getJavaScriptExecutorFactory() { return null; } protected @Nullable ReactPackageTurboModuleManagerDelegate.Builder getReactPackageTurboModuleManagerDelegateBuilder() { return null; } protected final Application getApplication() { return mApplication; } protected @Nullable UIManagerProvider getUIManagerProvider() { return reactApplicationContext -> null; } /** Returns whether or not to treat it as normal if Activity is null. */ public boolean getShouldRequireActivity() { return true; } /** * Returns whether view managers should be created lazily. See {@link * ViewManagerOnDemandReactPackage} for details. * * @experimental */ public boolean getLazyViewManagersEnabled() { return false; } /** * Return the {@link SurfaceDelegateFactory} used by NativeModules to get access to a {@link * SurfaceDelegate} to interact with a surface. By default in the mobile platform the {@link * SurfaceDelegate} it returns is null, and the NativeModule needs to implement its own {@link * SurfaceDelegate} to decide how it would interact with its own container surface. */ public SurfaceDelegateFactory getSurfaceDelegateFactory() { return new SurfaceDelegateFactory() { @Override public @Nullable SurfaceDelegate createSurfaceDelegate(String moduleName) { return null; } }; } /** * Get the {@link DevLoadingViewManager}. Override this to use a custom dev loading view manager */ protected @Nullable DevLoadingViewManager getDevLoadingViewManager() { return null; } protected @Nullable PausedInDebuggerOverlayManager getPausedInDebuggerOverlayManager() { return null; } /** * Returns the name of the main module. Determines the URL used to fetch the JS bundle from Metro. * It is only used when dev support is enabled. This is the first file to be executed once the * {@link ReactInstanceManager} is created. e.g. "index.android" */ protected String getJSMainModuleName() { return "index.android"; } /** * Returns a custom path of the bundle file. This is used in cases the bundle should be loaded * from a custom path. By default it is loaded from Android assets, from a path specified by * {@link getBundleAssetName}. e.g. "file://sdcard/myapp_cache/index.android.bundle" */ protected @Nullable String getJSBundleFile() { return null; } /** * Returns the name of the bundle in assets. If this is null, and no file path is specified for * the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will always * try to load the JS bundle from Metro. e.g. "index.android.bundle" */ protected @Nullable String getBundleAssetName() { return "index.android.bundle"; } /** Returns whether dev mode should be enabled. This enables e.g. the dev menu. */ public abstract boolean getUseDeveloperSupport(); /** Get the {@link DevSupportManagerFactory}. Override this to use a custom dev support manager */ protected @Nullable DevSupportManagerFactory getDevSupportManagerFactory() { return null; } /** * Returns a list of {@link ReactPackage} used by the app. You'll most likely want to return at * least the {@code MainReactPackage}. If your app uses additional views or modules besides the * default ones, you'll want to include more packages here. */ protected abstract List<ReactPackage> getPackages(); /** * Returns the {@link JSEngineResolutionAlgorithm} to be used when loading the JS engine. If null, * will try to load JSC first and fallback to Hermes if JSC is not available. */ protected @Nullable JSEngineResolutionAlgorithm getJSEngineResolutionAlgorithm() { return null; } /** * Returns a custom implementation of ChoreographerProvider to be used this host. If null - React * will use default direct android.view.Choreographer-based provider. */ protected @Nullable ChoreographerProvider getChoreographerProvider() { return null; } }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java
57
/* * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.build; import org.apache.maven.artifact.repository.MavenArtifactRepository; import org.gradle.api.Project; import org.gradle.api.attributes.Usage; import org.gradle.api.component.AdhocComponentWithVariants; import org.gradle.api.component.ConfigurationVariantDetails; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.VariantVersionMappingStrategy; import org.gradle.api.publish.maven.MavenPom; import org.gradle.api.publish.maven.MavenPomDeveloperSpec; import org.gradle.api.publish.maven.MavenPomIssueManagement; import org.gradle.api.publish.maven.MavenPomLicenseSpec; import org.gradle.api.publish.maven.MavenPomOrganization; import org.gradle.api.publish.maven.MavenPomScm; import org.gradle.api.publish.maven.MavenPublication; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; /** * Conventions that are applied in the presence of the {@link MavenPublishPlugin}. When * the plugin is applied: * * <ul> * <li>If the {@code deploymentRepository} property has been set, a * {@link MavenArtifactRepository Maven artifact repository} is configured to publish to * it. * <li>The poms of all {@link MavenPublication Maven publications} are customized to meet * Maven Central's requirements. * <li>If the {@link JavaPlugin Java plugin} has also been applied: * <ul> * <li>Creation of Javadoc and source jars is enabled. * <li>Publication metadata (poms and Gradle module metadata) is configured to use * resolved versions. * </ul> * </ul> * * @author Andy Wilkinson * @author Christoph Dreis * @author Mike Smithson */ class MavenPublishingConventions { void apply(Project project) { project.getPlugins().withType(MavenPublishPlugin.class).all((mavenPublish) -> { PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class); if (project.hasProperty("deploymentRepository")) { publishing.getRepositories().maven((mavenRepository) -> { mavenRepository.setUrl(project.property("deploymentRepository")); mavenRepository.setName("deployment"); }); } publishing.getPublications() .withType(MavenPublication.class) .all((mavenPublication) -> customizeMavenPublication(mavenPublication, project)); project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> { JavaPluginExtension extension = project.getExtensions().getByType(JavaPluginExtension.class); extension.withJavadocJar(); extension.withSourcesJar(); }); }); } private void customizeMavenPublication(MavenPublication publication, Project project) { customizePom(publication.getPom(), project); project.getPlugins() .withType(JavaPlugin.class) .all((javaPlugin) -> customizeJavaMavenPublication(publication, project)); } private void customizePom(MavenPom pom, Project project) { pom.getUrl().set("https://spring.io/projects/spring-boot"); pom.getName().set(project.provider(project::getName)); pom.getDescription().set(project.provider(project::getDescription)); if (!isUserInherited(project)) { pom.organization(this::customizeOrganization); } pom.licenses(this::customizeLicences); pom.developers(this::customizeDevelopers); pom.scm((scm) -> customizeScm(scm, project)); if (!isUserInherited(project)) { pom.issueManagement(this::customizeIssueManagement); } } private void customizeJavaMavenPublication(MavenPublication publication, Project project) { addMavenOptionalFeature(publication, project); if (publication.getName().equals("pluginMaven")) { return; } publication.versionMapping((strategy) -> strategy.usage(Usage.JAVA_API, (mappingStrategy) -> mappingStrategy .fromResolutionOf(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))); publication.versionMapping( (strategy) -> strategy.usage(Usage.JAVA_RUNTIME, VariantVersionMappingStrategy::fromResolutionResult)); } /** * Add a feature that allows maven plugins to declare optional dependencies that * appear in the POM. This is required to make m2e in Eclipse happy. * @param publication the project's Maven publication * @param project the project to add the feature to */ private void addMavenOptionalFeature(MavenPublication publication, Project project) { JavaPluginExtension extension = project.getExtensions().getByType(JavaPluginExtension.class); extension.registerFeature("mavenOptional", (feature) -> feature.usingSourceSet(extension.getSourceSets().getByName("main"))); AdhocComponentWithVariants javaComponent = (AdhocComponentWithVariants) project.getComponents() .findByName("java"); javaComponent.addVariantsFromConfiguration( project.getConfigurations().findByName("mavenOptionalRuntimeElements"), ConfigurationVariantDetails::mapToOptional); suppressMavenOptionalFeatureWarnings(publication); } private void suppressMavenOptionalFeatureWarnings(MavenPublication publication) { publication.suppressPomMetadataWarningsFor("mavenOptionalApiElements"); publication.suppressPomMetadataWarningsFor("mavenOptionalRuntimeElements"); } private void customizeOrganization(MavenPomOrganization organization) { organization.getName().set("VMware, Inc."); organization.getUrl().set("https://spring.io"); } private void customizeLicences(MavenPomLicenseSpec licences) { licences.license((licence) -> { licence.getName().set("Apache License, Version 2.0"); licence.getUrl().set("https://www.apache.org/licenses/LICENSE-2.0"); }); } private void customizeDevelopers(MavenPomDeveloperSpec developers) { developers.developer((developer) -> { developer.getName().set("Spring"); developer.getEmail().set("[email protected]"); developer.getOrganization().set("VMware, Inc."); developer.getOrganizationUrl().set("https://www.spring.io"); }); } private void customizeScm(MavenPomScm scm, Project project) { if (!isUserInherited(project)) { scm.getConnection().set("scm:git:git://github.com/spring-projects/spring-boot.git"); scm.getDeveloperConnection().set("scm:git:ssh://[email protected]/spring-projects/spring-boot.git"); } scm.getUrl().set("https://github.com/spring-projects/spring-boot"); } private void customizeIssueManagement(MavenPomIssueManagement issueManagement) { issueManagement.getSystem().set("GitHub"); issueManagement.getUrl().set("https://github.com/spring-projects/spring-boot/issues"); } private boolean isUserInherited(Project project) { return "spring-boot-starter-parent".equals(project.getName()) || "spring-boot-dependencies".equals(project.getName()); } }
spring-projects/spring-boot
buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java
58
/* * Copyright (C) 2007 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotates methods of a {@linkplain Module module} to create a provider method binding. The * method's return type is bound to its returned value. The {@linkplain Component component} * implementation will pass dependencies to the method as parameters. * * <h3>Nullability</h3> * * <p>Dagger forbids injecting {@code null} by default. Component implementations that invoke * {@code @Provides} methods that return {@code null} will throw a {@link NullPointerException} * immediately thereafter. {@code @Provides} methods may opt into allowing {@code null} by * annotating the method with any {@code @Nullable} annotation like {@code * javax.annotation.Nullable} or {@code androidx.annotation.Nullable}. * * <p>If a {@code @Provides} method is marked {@code @Nullable}, Dagger will <em>only</em> allow * injection into sites that are marked {@code @Nullable} as well. A component that attempts to pair * a {@code @Nullable} provision with a non-{@code @Nullable} injection site will fail to compile. */ @Documented @Target(METHOD) @Retention(RUNTIME) public @interface Provides {}
google/dagger
java/dagger/Provides.java
59
/* * Copyright (C) 2014 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Qualifier; import javax.inject.Scope; import javax.inject.Singleton; /** * Annotates an interface or abstract class for which a fully-formed, dependency-injected * implementation is to be generated from a set of {@linkplain #modules}. The generated class will * have the name of the type annotated with {@code @Component} prepended with {@code Dagger}. For * example, {@code @Component interface MyComponent {...}} will produce an implementation named * {@code DaggerMyComponent}. * * <p><a id="component-methods"></a> * * <h2>Component methods</h2> * * <p>Every type annotated with {@code @Component} must contain at least one abstract component * method. Component methods may have any name, but must have signatures that conform to either * {@linkplain Provider provision} or {@linkplain MembersInjector members-injection} contracts. * * <p><a id="provision-methods"></a> * * <h3>Provision methods</h3> * * <p>Provision methods have no parameters and return an {@link Inject injected} or {@link Provides * provided} type. Each method may have a {@link Qualifier} annotation as well. The following are * all valid provision method declarations: * * <pre><code> * SomeType getSomeType(); * {@literal Set<SomeType>} getSomeTypes(); * {@literal @PortNumber} int getPortNumber(); * </code></pre> * * <p>Provision methods, like typical {@link Inject injection} sites, may use {@link Provider} or * {@link Lazy} to more explicitly control provision requests. A {@link Provider} allows the user of * the component to request provision any number of times by calling {@link Provider#get}. A {@link * Lazy} will only ever request a single provision, but will defer it until the first call to {@link * Lazy#get}. The following provision methods all request provision of the same type, but each * implies different semantics: * * <pre><code> * SomeType getSomeType(); * {@literal Provider<SomeType>} getSomeTypeProvider(); * {@literal Lazy<SomeType>} getLazySomeType(); * </code></pre> * * <a id="members-injection-methods"></a> * * <h3>Members-injection methods</h3> * * <p>Members-injection methods have a single parameter and inject dependencies into each of the * {@link Inject}-annotated fields and methods of the passed instance. A members-injection method * may be void or return its single parameter as a convenience for chaining. The following are all * valid members-injection method declarations: * * <pre><code> * void injectSomeType(SomeType someType); * SomeType injectAndReturnSomeType(SomeType someType); * </code></pre> * * <p>A method with no parameters that returns a {@link MembersInjector} is equivalent to a members * injection method. Calling {@link MembersInjector#injectMembers} on the returned object will * perform the same work as a members injection method. For example: * * <pre><code> * {@literal MembersInjector<SomeType>} getSomeTypeMembersInjector(); * </code></pre> * * <h4>A note about covariance</h4> * * <p>While a members-injection method for a type will accept instances of its subtypes, only {@link * Inject}-annotated members of the parameter type and its supertypes will be injected; members of * subtypes will not. For example, given the following types, only {@code a} and {@code b} will be * injected into an instance of {@code Child} when it is passed to the members-injection method * {@code injectSelf(Self instance)}: * * <pre><code> * class Parent { * {@literal @}Inject A a; * } * * class Self extends Parent { * {@literal @}Inject B b; * } * * class Child extends Self { * {@literal @}Inject C c; * } * </code></pre> * * <a id="instantiation"></a> * * <h2>Instantiation</h2> * * <p>Component implementations are primarily instantiated via a generated <a * href="http://en.wikipedia.org/wiki/Builder_pattern">builder</a> or <a * href="https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)">factory</a>. * * <p>If a nested {@link Builder @Component.Builder} or {@link Factory @Component.Factory} type * exists in the component, Dagger will generate an implementation of that type. If neither exists, * Dagger will generate a builder type that has a method to set each of the {@linkplain #modules} * and component {@linkplain #dependencies} named with the <a * href="http://en.wikipedia.org/wiki/CamelCase">lower camel case</a> version of the module or * dependency type. * * <p>In either case, the Dagger-generated component type will have a static method, named either * {@code builder()} or {@code factory()}, that returns a builder or factory instance. * * <p>Example of using a builder: * * <pre>{@code * public static void main(String[] args) { * OtherComponent otherComponent = ...; * MyComponent component = DaggerMyComponent.builder() * // required because component dependencies must be set * .otherComponent(otherComponent) * // required because FlagsModule has constructor parameters * .flagsModule(new FlagsModule(args)) * // may be elided because a no-args constructor is visible * .myApplicationModule(new MyApplicationModule()) * .build(); * } * }</pre> * * <p>Example of using a factory: * * <pre>{@code * public static void main(String[] args) { * OtherComponent otherComponent = ...; * MyComponent component = DaggerMyComponent.factory() * .create(otherComponent, new FlagsModule(args), new MyApplicationModule()); * // Note that all parameters to a factory method are required, even if one is for a module * // that Dagger could instantiate. The only case where null is legal is for a * // @BindsInstance @Nullable parameter. * } * }</pre> * * <p>In the case that a component has no component dependencies and only no-arg modules, the * generated component will also have a factory method {@code create()}. {@code * SomeComponent.create()} and {@code SomeComponent.builder().build()} are both valid and * equivalent. * * <p><a id="scope"></a> * * <h2>Scope</h2> * * <p>Each Dagger component can be associated with a scope by annotating it with the {@linkplain * Scope scope annotation}. The component implementation ensures that there is only one provision of * each scoped binding per instance of the component. If the component declares a scope, it may only * contain unscoped bindings or bindings of that scope anywhere in the graph. For example: * * <pre><code> * {@literal @}Singleton {@literal @}Component * interface MyApplicationComponent { * // this component can only inject types using unscoped or {@literal @}Singleton bindings * } * </code></pre> * * <p>In order to get the proper behavior associated with a scope annotation, it is the caller's * responsibility to instantiate new component instances when appropriate. A {@link Singleton} * component, for instance, should only be instantiated once per application, while a {@code * RequestScoped} component should be instantiated once per request. Because components are * self-contained implementations, exiting a scope is as simple as dropping all references to the * component instance. * * <p><a id="component-relationships"></a> * * <h2>Component relationships</h2> * * <p>While there is much utility in isolated components with purely unscoped bindings, many * applications will call for multiple components with multiple scopes to interact. Dagger provides * two mechanisms for relating components. * * <p><a id="subcomponents"></a> * * <h3>Subcomponents</h3> * * <p>The simplest way to relate two components is by declaring a {@link Subcomponent}. A * subcomponent behaves exactly like a component, but has its implementation generated within a * parent component or subcomponent. That relationship allows the subcomponent implementation to * inherit the <em>entire</em> binding graph from its parent when it is declared. For that reason, a * subcomponent isn't evaluated for completeness until it is associated with a parent. * * <p>Subcomponents are declared by listing the class in the {@link Module#subcomponents()} * attribute of one of the parent component's modules. This binds the {@link Subcomponent.Builder} * or {@link Subcomponent.Factory} for that subcomponent within the parent component. * * <p>Subcomponents may also be declared via a factory method on a parent component or subcomponent. * The method may have any name, but must return the subcomponent. The factory method's parameters * may be any number of the subcomponent's modules, but must at least include those without visible * no-arg constructors. The following is an example of a factory method that creates a * request-scoped subcomponent from a singleton-scoped parent: * * <pre><code> * {@literal @}Singleton {@literal @}Component * interface ApplicationComponent { * // component methods... * * RequestComponent newRequestComponent(RequestModule requestModule); * } * </code></pre> * * <a id="component-dependencies"></a> * * <h3>Component dependencies</h3> * * <p>While subcomponents are the simplest way to compose subgraphs of bindings, subcomponents are * tightly coupled with the parents; they may use any binding defined by their ancestor component * and subcomponents. As an alternative, components can use bindings only from another <em>component * interface</em> by declaring a {@linkplain #dependencies component dependency}. When a type is * used as a component dependency, each <a href="#provision-methods">provision method</a> on the * dependency is bound as a provider. Note that <em>only</em> the bindings exposed as provision * methods are available through component dependencies. * * @since 2.0 */ @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger. @Target(TYPE) @Documented public @interface Component { /** * A list of classes annotated with {@link Module} whose bindings are used to generate the * component implementation. Note that through the use of {@link Module#includes} the full set of * modules used to implement the component may include more modules that just those listed here. */ Class<?>[] modules() default {}; /** * A list of types that are to be used as <a href="#component-dependencies">component * dependencies</a>. */ Class<?>[] dependencies() default {}; /** * A builder for a component. * * <p>A builder is a type with setter methods for the {@linkplain Component#modules modules}, * {@linkplain Component#dependencies dependencies} and {@linkplain BindsInstance bound instances} * required by the component and a single no-argument build method that creates a new component * instance. * * <p>Components may have a single nested {@code static abstract class} or {@code interface} * annotated with {@code @Component.Builder}. If they do, then Dagger will generate a builder * class that implements that type. Note that a component with a {@code @Component.Builder} may * not also have a {@code @Component.Factory}. * * <p>Builder types must follow some rules: * * <ul> * <li>There <i>must</i> be exactly one abstract no-argument method that returns the component * type or one of its supertypes, called the "build method". * <li>There <i>may</i> be other other abstract methods, called "setter methods". * <li>Setter methods <i>must</i> take a single argument and return {@code void}, the builder * type or a supertype of the builder type. * <li>There <i>must</i> be a setter method for each {@linkplain Component#dependencies * component dependency}. * <li>There <i>must</i> be a setter method for each non-{@code abstract} {@linkplain * Component#modules module} that has non-{@code static} binding methods, unless Dagger can * instantiate that module with a visible no-argument constructor. * <li>There <i>may</i> be setter methods for modules that Dagger can instantiate or does not * need to instantiate. * <li>There <i>may</i> be setter methods annotated with {@code @BindsInstance}. These methods * bind the instance passed to them within the component. See {@link * BindsInstance @BindsInstance} for more information. * <li>There <i>may</i> be non-{@code abstract} methods, but they are ignored as far as * validation and builder generation are concerned. * </ul> * * For example, this could be a valid {@code Component} with a {@code Builder}: * * <pre><code> * {@literal @}Component(modules = {BackendModule.class, FrontendModule.class}) * interface MyComponent { * MyWidget myWidget(); * * {@literal @}Component.Builder * interface Builder { * Builder backendModule(BackendModule bm); * Builder frontendModule(FrontendModule fm); * {@literal @}BindsInstance * Builder foo(Foo foo); * MyComponent build(); * } * }</code></pre> */ @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger. @Target(TYPE) @Documented @interface Builder {} /** * A factory for a component. * * <p>A factory is a type with a single method that returns a new component instance each time it * is called. The parameters of that method allow the caller to provide the {@linkplain * Component#modules modules}, {@linkplain Component#dependencies dependencies} and {@linkplain * BindsInstance bound instances} required by the component. * * <p>Components may have a single nested {@code static abstract class} or {@code interface} * annotated with {@code @Component.Factory}. If they do, then Dagger will generate a factory * class that will implement that type. Note that a component with a {@code @Component.Factory} * may not also have a {@code @Component.Builder}. * * <p>Factory types must follow some rules: * * <ul> * <li>There <i>must</i> be exactly one abstract method, which must return the component type or * one of its supertypes. * <li>The method <i>must</i> have a parameter for each {@linkplain Component#dependencies * component dependency}. * <li>The method <i>must</i> have a parameter for each non-{@code abstract} {@linkplain * Component#modules module} that has non-{@code static} binding methods, unless Dagger can * instantiate that module with a visible no-argument constructor. * <li>The method <i>may</i> have parameters for modules that Dagger can instantiate or does not * need to instantiate. * <li>The method <i>may</i> have parameters annotated with {@code @BindsInstance}. These * parameters bind the instance passed for that parameter within the component. See {@link * BindsInstance @BindsInstance} for more information. * <li>There <i>may</i> be non-{@code abstract} methods, but they are ignored as far as * validation and factory generation are concerned. * </ul> * * For example, this could be a valid {@code Component} with a {@code Factory}: * * <pre><code> * {@literal @}Component(modules = {BackendModule.class, FrontendModule.class}) * interface MyComponent { * MyWidget myWidget(); * * {@literal @}Component.Factory * interface Factory { * MyComponent newMyComponent( * BackendModule bm, FrontendModule fm, {@literal @}BindsInstance Foo foo); * } * }</code></pre> * * <p>For a root component, if a {@code @Component.Factory} is defined, the generated component * type will have a {@code static} method named {@code factory()} that returns an instance of that * factory. * * @since 2.22 */ @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger. @Target(TYPE) @Documented @interface Factory {} }
google/dagger
java/dagger/Component.java
60
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.grid.data; import static java.util.Collections.unmodifiableMap; import java.io.Serializable; import java.net.URI; import java.time.Instant; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.internal.Require; import org.openqa.selenium.json.JsonInput; import org.openqa.selenium.remote.SessionId; /** * Represents a running instance of a WebDriver session. It is identified by a {@link SessionId}. * The serialized form is designed to mimic that of the return value of the New Session command, but * an additional {@code uri} field must also be present. */ public class Session implements Serializable { private final SessionId id; private final URI uri; private final Capabilities stereotype; private final Capabilities capabilities; private final Instant startTime; public Session( SessionId id, URI uri, Capabilities stereotype, Capabilities capabilities, Instant startTime) { this.id = Require.nonNull("Session ID", id); this.uri = Require.nonNull("Where the session is running", uri); this.startTime = Require.nonNull("Start time", startTime); this.stereotype = ImmutableCapabilities.copyOf(Require.nonNull("Stereotype", stereotype)); this.capabilities = ImmutableCapabilities.copyOf(Require.nonNull("Session capabilities", capabilities)); } public SessionId getId() { return id; } public URI getUri() { return uri; } public Capabilities getStereotype() { return stereotype; } public Capabilities getCapabilities() { return capabilities; } public Instant getStartTime() { return startTime; } private Map<String, Object> toJson() { // Deliberately shaped like the return value for the W3C New Session command's return value. Map<String, Object> toReturn = new TreeMap<>(); toReturn.put("capabilities", getCapabilities()); toReturn.put("sessionId", getId().toString()); toReturn.put("stereotype", getStereotype()); toReturn.put("start", getStartTime()); toReturn.put("uri", getUri()); return unmodifiableMap(toReturn); } private static Session fromJson(JsonInput input) { SessionId id = null; URI uri = null; Capabilities caps = null; Capabilities stereotype = null; Instant start = null; input.beginObject(); while (input.hasNext()) { switch (input.nextName()) { case "capabilities": caps = ImmutableCapabilities.copyOf(input.read(Capabilities.class)); break; case "sessionId": id = input.read(SessionId.class); break; case "start": start = input.read(Instant.class); break; case "stereotype": stereotype = input.read(Capabilities.class); break; case "uri": uri = input.read(URI.class); break; default: input.skipValue(); break; } } input.endObject(); return new Session(id, uri, stereotype, caps, start); } @Override public boolean equals(Object that) { if (!(that instanceof Session)) { return false; } Session session = (Session) that; return Objects.equals(id, session.getId()) && Objects.equals(uri, session.getUri()); } @Override public int hashCode() { return Objects.hash(id, uri); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/grid/data/Session.java
61
/* * Copyright (C) 2016 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import dagger.internal.Beta; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Marks a method on a {@linkplain Component.Builder component builder} or a parameter on a * {@linkplain Component.Factory component factory} as binding an instance to some key within the * component. * * <p>For example: * * <pre> * {@literal @Component.Builder} * interface Builder { * {@literal @BindsInstance} Builder foo(Foo foo); * {@literal @BindsInstance} Builder bar({@literal @Blue} Bar bar); * ... * } * * // or * * {@literal @Component.Factory} * interface Factory { * MyComponent newMyComponent( * {@literal @BindsInstance} Foo foo, * {@literal @BindsInstance @Blue} Bar bar); * } * </pre> * * <p>will allow clients of the builder or factory to pass their own instances of {@code Foo} and * {@code Bar}, and those instances can be injected within the component as {@code Foo} or * {@code @Blue Bar}, respectively. It's important to note that unlike in factories, the methods in * builders should only accept and bind a single parameter each. Using the following will result in * an error: * * <pre> * {@literal @Component.Builder} * interface Builder { * // Error! Builder methods can only have one parameter * {@literal @BindsInstance} Builder fooAndBar(Foo foo, {@literal @Blue} Bar bar); * ... * } * </pre> * * <p>{@code @BindsInstance} arguments may not be {@code null} unless the parameter is annotated * with {@code @Nullable}. * * <p>For builders, {@code @BindsInstance} methods must be called before building the component, * unless their parameter is marked {@code @Nullable}, in which case the component will act as * though it was called with a {@code null} argument. Primitives, of course, may not be marked * {@code @Nullable}. * * <p>Binding an instance is equivalent to passing an instance to a module constructor and providing * that instance, but is often more efficient. When possible, binding object instances should be * preferred to using module instances. */ @Documented @Retention(RUNTIME) @Target({METHOD, PARAMETER}) @Beta public @interface BindsInstance {}
google/dagger
java/dagger/BindsInstance.java
62
package com.alibaba.fastjson; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONLexerBase; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.FieldSerializer; import com.alibaba.fastjson.serializer.JavaBeanSerializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.util.IOUtils; import com.alibaba.fastjson.util.TypeUtils; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author wenshao[[email protected]] * @since 1.2.0 */ public class JSONPath implements JSONAware { private static ConcurrentMap<String, JSONPath> pathCache = new ConcurrentHashMap<String, JSONPath>(128, 0.75f, 1); private final String path; private Segment[] segments; private boolean hasRefSegment; private SerializeConfig serializeConfig; private ParserConfig parserConfig; private boolean ignoreNullValue; public JSONPath(String path){ this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance(), true); } public JSONPath(String path, boolean ignoreNullValue){ this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance(), ignoreNullValue); } public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig, boolean ignoreNullValue){ if (path == null || path.length() == 0) { throw new JSONPathException("json-path can not be null or empty"); } this.path = path; this.serializeConfig = serializeConfig; this.parserConfig = parserConfig; this.ignoreNullValue = ignoreNullValue; } protected void init() { if (segments != null) { return; } if ("*".equals(path)) { this.segments = new Segment[] { WildCardSegment.instance }; } else { JSONPathParser parser = new JSONPathParser(path); this.segments = parser.explain(); this.hasRefSegment = parser.hasRefSegment; } } public boolean isRef() { try { init(); for (int i = 0; i < segments.length; ++i) { Segment segment = segments[i]; Class segmentType = segment.getClass(); if (segmentType == ArrayAccessSegment.class || segmentType == PropertySegment.class) { continue; } return false; } return true; } catch (JSONPathException ex) { // skip return false; } } public Object eval(Object rootObject) { if (rootObject == null) { return null; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { Segment segment = segments[i]; currentObject = segment.eval(this, rootObject, currentObject); } return currentObject; } /** * @since 1.2.76 * @param rootObject * @param clazz * @param parserConfig * @return */ public <T> T eval(Object rootObject, Type clazz, ParserConfig parserConfig) { Object obj = this.eval(rootObject); return TypeUtils.cast(obj, clazz, parserConfig); } /** * @since 1.2.76 * @param rootObject * @param clazz * @return */ public <T> T eval(Object rootObject, Type clazz) { return this.eval(rootObject, clazz, ParserConfig.getGlobalInstance()); } public Object extract(DefaultJSONParser parser) { if (parser == null) { return null; } init(); if (hasRefSegment) { Object root = parser.parse(); return this.eval(root); } if (segments.length == 0) { return parser.parse(); } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof TypeSegment || lastSegment instanceof FloorSegment || lastSegment instanceof MultiIndexSegment) { return eval( parser.parse()); } Context context = null; for (int i = 0; i < segments.length; ++i) { Segment segment = segments[i]; boolean last = i == segments.length - 1; if (context != null && context.object != null) { context.object = segment.eval(this, null, context.object); continue; } boolean eval; if (!last) { Segment nextSegment = segments[i + 1]; if (segment instanceof PropertySegment && ((PropertySegment) segment).deep && (nextSegment instanceof ArrayAccessSegment || nextSegment instanceof MultiIndexSegment || nextSegment instanceof MultiPropertySegment || nextSegment instanceof SizeSegment || nextSegment instanceof PropertySegment || nextSegment instanceof FilterSegment)) { eval = true; } else if (nextSegment instanceof ArrayAccessSegment && ((ArrayAccessSegment) nextSegment).index < 0) { eval = true; } else if (nextSegment instanceof FilterSegment) { eval = true; } else if (segment instanceof WildCardSegment) { eval = true; }else if(segment instanceof MultiIndexSegment){ eval = true; } else { eval = false; } } else { eval = true; } context = new Context(context, eval); segment.extract(this, parser, context); } return context.object; } private static class Context { final Context parent; final boolean eval; Object object; public Context(Context parent, boolean eval) { this.parent = parent; this.eval = eval; } } public boolean contains(Object rootObject) { if (rootObject == null) { return false; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { Object parentObject = currentObject; currentObject = segments[i].eval(this, rootObject, currentObject); if (currentObject == null) { return false; } if (currentObject == Collections.EMPTY_LIST && parentObject instanceof List) { return ((List) parentObject).contains(currentObject); } } return true; } @SuppressWarnings("rawtypes") public boolean containsValue(Object rootObject, Object value) { Object currentObject = eval(rootObject); if (currentObject == value) { return true; } if (currentObject == null) { return false; } if (currentObject instanceof Iterable) { Iterator it = ((Iterable) currentObject).iterator(); while (it.hasNext()) { Object item = it.next(); if (eq(item, value)) { return true; } } return false; } return eq(currentObject, value); } public int size(Object rootObject) { if (rootObject == null) { return -1; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { currentObject = segments[i].eval(this, rootObject, currentObject); } return evalSize(currentObject); } /** * Extract keySet or field names from rootObject on this JSONPath. * * @param rootObject Can be a map or custom object. Array and Collection are not supported. * @return Set of keys, or <code>null</code> if not supported. */ public Set<?> keySet(Object rootObject) { if (rootObject == null) { return null; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { currentObject = segments[i].eval(this, rootObject, currentObject); } return evalKeySet(currentObject); } public void patchAdd(Object rootObject, Object value, boolean replace) { if (rootObject == null) { return; } init(); Object currentObject = rootObject; Object parentObject = null; for (int i = 0; i < segments.length; ++i) { parentObject = currentObject; Segment segment = segments[i]; currentObject = segment.eval(this, rootObject, currentObject); if (currentObject == null && i != segments.length - 1) { if (segment instanceof PropertySegment) { currentObject = new JSONObject(); ((PropertySegment) segment).setValue(this, parentObject, currentObject); } } } Object result = currentObject; if ((!replace) && result instanceof Collection) { Collection collection = (Collection) result; collection.add(value); return; } Object newResult; if (result != null && !replace) { Class<?> resultClass = result.getClass(); if (resultClass.isArray()) { int length = Array.getLength(result); Object descArray = Array.newInstance(resultClass.getComponentType(), length + 1); System.arraycopy(result, 0, descArray, 0, length); Array.set(descArray, length, value); newResult = descArray; } else if (Map.class.isAssignableFrom(resultClass)) { newResult = value; } else { throw new JSONException("unsupported array put operation. " + resultClass); } } else { newResult = value; } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; propertySegment.setValue(this, parentObject, newResult); return; } if (lastSegment instanceof ArrayAccessSegment) { ((ArrayAccessSegment) lastSegment).setValue(this, parentObject, newResult); return; } throw new UnsupportedOperationException(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void arrayAdd(Object rootObject, Object... values) { if (values == null || values.length == 0) { return; } if (rootObject == null) { return; } init(); Object currentObject = rootObject; Object parentObject = null; for (int i = 0; i < segments.length; ++i) { if (i == segments.length - 1) { parentObject = currentObject; } currentObject = segments[i].eval(this, rootObject, currentObject); } Object result = currentObject; if (result == null) { throw new JSONPathException("value not found in path " + path); } if (result instanceof Collection) { Collection collection = (Collection) result; for (Object value : values) { collection.add(value); } return; } Class<?> resultClass = result.getClass(); Object newResult; if (resultClass.isArray()) { int length = Array.getLength(result); Object descArray = Array.newInstance(resultClass.getComponentType(), length + values.length); System.arraycopy(result, 0, descArray, 0, length); for (int i = 0; i < values.length; ++i) { Array.set(descArray, length + i, values[i]); } newResult = descArray; } else { throw new JSONException("unsupported array put operation. " + resultClass); } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; propertySegment.setValue(this, parentObject, newResult); return; } if (lastSegment instanceof ArrayAccessSegment) { ((ArrayAccessSegment) lastSegment).setValue(this, parentObject, newResult); return; } throw new UnsupportedOperationException(); } public boolean remove(Object rootObject) { if (rootObject == null) { return false; } init(); Object currentObject = rootObject; Object parentObject = null; Segment lastSegment = segments[segments.length - 1]; for (int i = 0; i < segments.length; ++i) { if (i == segments.length - 1) { parentObject = currentObject; break; } Segment segement = segments[i]; if (i == segments.length - 2 && lastSegment instanceof FilterSegment && segement instanceof PropertySegment ) { FilterSegment filterSegment = (FilterSegment) lastSegment; if (currentObject instanceof List) { PropertySegment propertySegment = (PropertySegment) segement; List list = (List) currentObject; for (Iterator it = list.iterator();it.hasNext();) { Object item = it.next(); Object result = propertySegment.eval(this, rootObject, item); if (result instanceof Iterable) { filterSegment.remove(this, rootObject, result); } else if (result instanceof Map) { if (filterSegment.filter.apply(this, rootObject, currentObject, result)) { it.remove(); } } } return true; } else if (currentObject instanceof Map) { PropertySegment propertySegment = (PropertySegment) segement; Object result = propertySegment.eval(this, rootObject, currentObject); if (result == null) { return false; } if (result instanceof Map && filterSegment.filter.apply(this, rootObject, currentObject, result)) { propertySegment.remove(this, currentObject); return true; } } } currentObject = segement.eval(this, rootObject, currentObject); if (currentObject == null) { break; } } if (parentObject == null) { return false; } if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; if (parentObject instanceof Collection) { if (segments.length > 1) { Segment parentSegment = segments[segments.length - 2]; if (parentSegment instanceof RangeSegment || parentSegment instanceof MultiIndexSegment) { Collection collection = (Collection) parentObject; boolean removedOnce = false; for (Object item : collection) { boolean removed = propertySegment.remove(this, item); if (removed) { removedOnce = true; } } return removedOnce; } } } return propertySegment.remove(this, parentObject); } if (lastSegment instanceof ArrayAccessSegment) { return ((ArrayAccessSegment) lastSegment).remove(this, parentObject); } if (lastSegment instanceof FilterSegment) { FilterSegment filterSegment = (FilterSegment) lastSegment; return filterSegment.remove(this, rootObject, parentObject); } throw new UnsupportedOperationException(); } public boolean set(Object rootObject, Object value) { return set(rootObject, value, true); } public boolean set(Object rootObject, Object value, boolean p) { if (rootObject == null) { return false; } init(); Object currentObject = rootObject; Object parentObject = null; for (int i = 0; i < segments.length; ++i) { // if (i == segments.length - 1) { // parentObject = currentObject; // break; // } // parentObject = currentObject; Segment segment = segments[i]; currentObject = segment.eval(this, rootObject, currentObject); if (currentObject == null) { Segment nextSegment = null; if (i < segments.length - 1) { nextSegment = segments[i + 1]; } Object newObj = null; if (nextSegment instanceof PropertySegment) { JavaBeanDeserializer beanDeserializer = null; Class<?> fieldClass = null; if (segment instanceof PropertySegment) { String propertyName = ((PropertySegment) segment).propertyName; Class<?> parentClass = parentObject.getClass(); JavaBeanDeserializer parentBeanDeserializer = getJavaBeanDeserializer(parentClass); if (parentBeanDeserializer != null) { FieldDeserializer fieldDeserializer = parentBeanDeserializer.getFieldDeserializer(propertyName); fieldClass = fieldDeserializer.fieldInfo.fieldClass; beanDeserializer = getJavaBeanDeserializer(fieldClass); } } if (beanDeserializer != null) { if (beanDeserializer.beanInfo.defaultConstructor != null) { newObj = beanDeserializer.createInstance(null, fieldClass); } else { return false; } } else { newObj = new JSONObject(); } } else if (nextSegment instanceof ArrayAccessSegment) { newObj = new JSONArray(); } if (newObj != null) { if (segment instanceof PropertySegment) { PropertySegment propSegement = (PropertySegment) segment; propSegement.setValue(this, parentObject, newObj); currentObject = newObj; continue; } else if (segment instanceof ArrayAccessSegment) { ArrayAccessSegment arrayAccessSegement = (ArrayAccessSegment) segment; arrayAccessSegement.setValue(this, parentObject, newObj); currentObject = newObj; continue; } } break; } } if (parentObject == null) { return false; } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; propertySegment.setValue(this, parentObject, value); return true; } if (lastSegment instanceof ArrayAccessSegment) { return ((ArrayAccessSegment) lastSegment).setValue(this, parentObject, value); } throw new UnsupportedOperationException(); } public static Object eval(Object rootObject, String path) { JSONPath jsonpath = compile(path); return jsonpath.eval(rootObject); } public static Object eval(Object rootObject, String path, boolean ignoreNullValue) { JSONPath jsonpath = compile(path, ignoreNullValue); return jsonpath.eval(rootObject); } public static int size(Object rootObject, String path) { JSONPath jsonpath = compile(path); Object result = jsonpath.eval(rootObject); return jsonpath.evalSize(result); } /** * Compile jsonPath and use it to extract keySet or field names from rootObject. * * @param rootObject Can be a map or custom object. Array and Collection are not supported. * @param path JSONPath string to be compiled. * @return Set of keys, or <code>null</code> if not supported. */ public static Set<?> keySet(Object rootObject, String path) { JSONPath jsonpath = compile(path); Object result = jsonpath.eval(rootObject); return jsonpath.evalKeySet(result); } public static boolean contains(Object rootObject, String path) { if (rootObject == null) { return false; } JSONPath jsonpath = compile(path); return jsonpath.contains(rootObject); } public static boolean containsValue(Object rootObject, String path, Object value) { JSONPath jsonpath = compile(path); return jsonpath.containsValue(rootObject, value); } public static void arrayAdd(Object rootObject, String path, Object... values) { JSONPath jsonpath = compile(path); jsonpath.arrayAdd(rootObject, values); } public static boolean set(Object rootObject, String path, Object value) { JSONPath jsonpath = compile(path); return jsonpath.set(rootObject, value); } public static boolean remove(Object root, String path) { JSONPath jsonpath = compile(path); return jsonpath.remove(root); } public static JSONPath compile(String path) { if (path == null) { throw new JSONPathException("jsonpath can not be null"); } JSONPath jsonpath = pathCache.get(path); if (jsonpath == null) { jsonpath = new JSONPath(path); if (pathCache.size() < 1024) { pathCache.putIfAbsent(path, jsonpath); jsonpath = pathCache.get(path); } } return jsonpath; } public static JSONPath compile(String path, boolean ignoreNullValue) { if (path == null) { throw new JSONPathException("jsonpath can not be null"); } JSONPath jsonpath = pathCache.get(path); if (jsonpath == null) { jsonpath = new JSONPath(path, ignoreNullValue); if (pathCache.size() < 1024) { pathCache.putIfAbsent(path, jsonpath); jsonpath = pathCache.get(path); } } return jsonpath; } /** * @since 1.2.9 * @param json * @param path * @return */ public static Object read(String json, String path) { return compile(path) .eval( JSON.parse(json) ); } /** * @since 1.2.76 * @param json * @param path * @param clazz * @param parserConfig * @return */ public static <T> T read(String json, String path, Type clazz, ParserConfig parserConfig) { return compile(path).eval(JSON.parse(json), clazz, parserConfig); } /** * @since 1.2.76 * @param json * @param path * @param clazz * @return */ public static <T> T read(String json, String path, Type clazz) { return read(json, path, clazz, null); } /** * @since 1.2.51 * @param json * @param path * @return */ public static Object extract(String json, String path, ParserConfig config, int features, Feature... optionFeatures) { features |= Feature.OrderedField.mask; DefaultJSONParser parser = new DefaultJSONParser(json, config, features); JSONPath jsonPath = compile(path); Object result = jsonPath.extract(parser); parser.lexer.close(); return result; } public static Object extract(String json, String path) { return extract(json, path, ParserConfig.global, JSON.DEFAULT_PARSER_FEATURE); } public static Map<String, Object> paths(Object javaObject) { return paths(javaObject, SerializeConfig.globalInstance); } public static Map<String, Object> paths(Object javaObject, SerializeConfig config) { Map<Object, String> values = new IdentityHashMap<Object, String>(); Map<String, Object> paths = new HashMap<String, Object>(); paths(values, paths, "/", javaObject, config); return paths; } private static void paths(Map<Object, String> values, Map<String, Object> paths, String parent, Object javaObject, SerializeConfig config) { if (javaObject == null) { return; } String p = values.put(javaObject, parent); if (p != null) { Class<?> type = javaObject.getClass(); boolean basicType = type == String.class || type == Boolean.class || type == Character.class || type == UUID.class || type.isEnum() || javaObject instanceof Number || javaObject instanceof Date ; if (!basicType) { return; } } paths.put(parent, javaObject); if (javaObject instanceof Map) { Map map = (Map) javaObject; for (Object entryObj : map.entrySet()) { Map.Entry entry = (Map.Entry) entryObj; Object key = entry.getKey(); if (key instanceof String) { String path = parent.equals("/") ? "/" + key : parent + "/" + key; paths(values, paths, path, entry.getValue(), config); } } return; } if (javaObject instanceof Collection) { Collection collection = (Collection) javaObject; int i = 0; for (Object item : collection) { String path = parent.equals("/") ? "/" + i : parent + "/" + i; paths(values, paths, path, item, config); ++i; } return; } Class<?> clazz = javaObject.getClass(); if (clazz.isArray()) { int len = Array.getLength(javaObject); for (int i = 0; i < len; ++i) { Object item = Array.get(javaObject, i); String path = parent.equals("/") ? "/" + i : parent + "/" + i; paths(values, paths, path, item, config); } return; } if (ParserConfig.isPrimitive2(clazz) || clazz.isEnum()) { return; } ObjectSerializer serializer = config.getObjectWriter(clazz); if (serializer instanceof JavaBeanSerializer) { JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) serializer; try { Map<String, Object> fieldValues = javaBeanSerializer.getFieldValuesMap(javaObject); for (Map.Entry<String, Object> entry : fieldValues.entrySet()) { String key = entry.getKey(); if (key instanceof String) { String path = parent.equals("/") ? "/" + key : parent + "/" + key; paths(values, paths, path, entry.getValue(), config); } } } catch (Exception e) { throw new JSONException("toJSON error", e); } return; } return; } public String getPath() { return path; } static class JSONPathParser { private final String path; private int pos; private char ch; private int level; private boolean hasRefSegment; private static final String strArrayRegex = "\'\\s*,\\s*\'"; private static final Pattern strArrayPatternx = Pattern.compile(strArrayRegex); public JSONPathParser(String path){ this.path = path; next(); } void next() { ch = path.charAt(pos++); } char getNextChar() { return path.charAt(pos); } boolean isEOF() { return pos >= path.length(); } Segment readSegement() { if (level == 0 && path.length() == 1) { if (isDigitFirst(ch)) { int index = ch - '0'; return new ArrayAccessSegment(index); } else if ((ch >= 'a' && ch <= 'z') || ((ch >= 'A' && ch <= 'Z'))) { return new PropertySegment(Character.toString(ch), false); } } while (!isEOF()) { skipWhitespace(); if (ch == '$') { next(); skipWhitespace(); if (ch == '?') { return new FilterSegment( (Filter) parseArrayAccessFilter(false)); } continue; } if (ch == '.' || ch == '/') { int c0 = ch; boolean deep = false; next(); if (c0 == '.' && ch == '.') { next(); deep = true; if (path.length() > pos + 3 && ch == '[' && path.charAt(pos) == '*' && path.charAt(pos + 1) == ']' && path.charAt(pos + 2) == '.') { next(); next(); next(); next(); } } if (ch == '*' || (deep && ch == '[')) { boolean objectOnly = ch == '['; if (!isEOF()) { next(); } if (deep) { if (objectOnly) { return WildCardSegment.instance_deep_objectOnly; } else { return WildCardSegment.instance_deep; } } else { return WildCardSegment.instance; } } if (isDigitFirst(ch)) { return parseArrayAccess(false); } String propertyName = readName(); if (ch == '(') { next(); if (ch == ')') { if (!isEOF()) { next(); } if ("size".equals(propertyName) || "length".equals(propertyName)) { return SizeSegment.instance; } else if ("max".equals(propertyName)) { return MaxSegment.instance; } else if ("min".equals(propertyName)) { return MinSegment.instance; } else if ("keySet".equals(propertyName)) { return KeySetSegment.instance; } else if ("type".equals(propertyName)) { return TypeSegment.instance; } else if ("floor".equals(propertyName)) { return FloorSegment.instance; } throw new JSONPathException("not support jsonpath : " + path); } throw new JSONPathException("not support jsonpath : " + path); } return new PropertySegment(propertyName, deep); } if (ch == '[') { return parseArrayAccess(true); } if (level == 0) { String propertyName = readName(); return new PropertySegment(propertyName, false); } if (ch == '?') { return new FilterSegment( (Filter) parseArrayAccessFilter(false)); } throw new JSONPathException("not support jsonpath : " + path); } return null; } public final void skipWhitespace() { for (;;) { if (ch <= ' ' && (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\b')) { next(); continue; } else { break; } } } Segment parseArrayAccess(boolean acceptBracket) { Object object = parseArrayAccessFilter(acceptBracket); if (object instanceof Segment) { return ((Segment) object); } return new FilterSegment((Filter) object); } Object parseArrayAccessFilter(boolean acceptBracket) { if (acceptBracket) { accept('['); } boolean predicateFlag = false; int lparanCount = 0; if (ch == '?') { next(); accept('('); lparanCount++; while (ch == '(') { next(); lparanCount++; } predicateFlag = true; } skipWhitespace(); if (predicateFlag || IOUtils.firstIdentifier(ch) || Character.isJavaIdentifierStart(ch) || ch == '\\' || ch == '@') { boolean self = false; if (ch == '@') { next(); accept('.'); self = true; } String propertyName = readName(); skipWhitespace(); if (predicateFlag && ch == ')') { next(); Filter filter = new NotNullSegement(propertyName, false); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } if (acceptBracket) { accept(']'); } return filter; } if (acceptBracket && ch == ']') { if (isEOF()) { if (propertyName.equals("last")) { return new MultiIndexSegment(new int[]{-1}); } } next(); Filter filter = new NotNullSegement(propertyName, false); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } boolean function = false; skipWhitespace(); if (ch == '(') { next(); accept(')'); skipWhitespace(); function = true; } Operator op = readOp(); skipWhitespace(); if (op == Operator.BETWEEN || op == Operator.NOT_BETWEEN) { final boolean not = (op == Operator.NOT_BETWEEN); Object startValue = readValue(); String name = readName(); if (!"and".equalsIgnoreCase(name)) { throw new JSONPathException(path); } Object endValue = readValue(); if (startValue == null || endValue == null) { throw new JSONPathException(path); } if (isInt(startValue.getClass()) && isInt(endValue.getClass())) { Filter filter = new IntBetweenSegement(propertyName , function , TypeUtils.longExtractValue((Number) startValue) , TypeUtils.longExtractValue((Number) endValue) , not); return filter; } throw new JSONPathException(path); } if (op == Operator.IN || op == Operator.NOT_IN) { final boolean not = (op == Operator.NOT_IN); accept('('); List<Object> valueList = new JSONArray(); { Object value = readValue(); valueList.add(value); for (;;) { skipWhitespace(); if (ch != ',') { break; } next(); value = readValue(); valueList.add(value); } } boolean isInt = true; boolean isIntObj = true; boolean isString = true; for (Object item : valueList) { if (item == null) { if (isInt) { isInt = false; } continue; } Class<?> clazz = item.getClass(); if (isInt && !(clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class)) { isInt = false; isIntObj = false; } if (isString && clazz != String.class) { isString = false; } } if (valueList.size() == 1 && valueList.get(0) == null) { Filter filter; if (not) { filter = new NotNullSegement(propertyName, function); } else { filter = new NullSegement(propertyName, function); } while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } if (isInt) { if (valueList.size() == 1) { long value = TypeUtils.longExtractValue((Number) valueList.get(0)); Operator intOp = not ? Operator.NE : Operator.EQ; Filter filter = new IntOpSegement(propertyName, function, value, intOp); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } long[] values = new long[valueList.size()]; for (int i = 0; i < values.length; ++i) { values[i] = TypeUtils.longExtractValue((Number) valueList.get(i)); } Filter filter = new IntInSegement(propertyName, function, values, not); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } if (isString) { if (valueList.size() == 1) { String value = (String) valueList.get(0); Operator intOp = not ? Operator.NE : Operator.EQ; Filter filter = new StringOpSegement(propertyName, function, value, intOp); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } String[] values = new String[valueList.size()]; valueList.toArray(values); Filter filter = new StringInSegement(propertyName, function, values, not); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } if (isIntObj) { Long[] values = new Long[valueList.size()]; for (int i = 0; i < values.length; ++i) { Number item = (Number) valueList.get(i); if (item != null) { values[i] = TypeUtils.longExtractValue(item); } } Filter filter = new IntObjInSegement(propertyName, function, values, not); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } throw new UnsupportedOperationException(); } if (ch == '\'' || ch == '"') { String strValue = readString(); Filter filter = null; if (op == Operator.RLIKE) { filter = new RlikeSegement(propertyName, function, strValue, false); } else if (op == Operator.NOT_RLIKE) { filter = new RlikeSegement(propertyName, function, strValue, true); } else if (op == Operator.LIKE || op == Operator.NOT_LIKE) { while (strValue.indexOf("%%") != -1) { strValue = strValue.replaceAll("%%", "%"); } final boolean not = (op == Operator.NOT_LIKE); int p0 = strValue.indexOf('%'); if (p0 == -1) { if (op == Operator.LIKE) { op = Operator.EQ; } else { op = Operator.NE; } filter = new StringOpSegement(propertyName, function, strValue, op); } else { String[] items = strValue.split("%"); String startsWithValue = null; String endsWithValue = null; String[] containsValues = null; if (p0 == 0) { if (strValue.charAt(strValue.length() - 1) == '%') { containsValues = new String[items.length - 1]; System.arraycopy(items, 1, containsValues, 0, containsValues.length); } else { endsWithValue = items[items.length - 1]; if (items.length > 2) { containsValues = new String[items.length - 2]; System.arraycopy(items, 1, containsValues, 0, containsValues.length); } } } else if (strValue.charAt(strValue.length() - 1) == '%') { if (items.length == 1) { startsWithValue = items[0]; } else { containsValues = items; } } else { if (items.length == 1) { startsWithValue = items[0]; } else if (items.length == 2) { startsWithValue = items[0]; endsWithValue = items[1]; } else { startsWithValue = items[0]; endsWithValue = items[items.length - 1]; containsValues = new String[items.length - 2]; System.arraycopy(items, 1, containsValues, 0, containsValues.length); } } filter = new MatchSegement(propertyName, function, startsWithValue, endsWithValue, containsValues, not); } } else { filter = new StringOpSegement(propertyName, function, strValue, op); } while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } if (isDigitFirst(ch)) { long value = readLongValue(); double doubleValue = 0D; if (ch == '.') { doubleValue = readDoubleValue(value); } Filter filter; if (doubleValue == 0) { filter = new IntOpSegement(propertyName, function, value, op); } else { filter = new DoubleOpSegement(propertyName, function, doubleValue, op); } while (ch == ' ') { next(); } if (lparanCount > 1 && ch == ')') { next(); lparanCount--; } if (ch == '&' || ch == '|') { filter = filterRest(filter); } if (predicateFlag) { lparanCount--; accept(')'); } if (acceptBracket) { accept(']'); } return filter; } else if (ch == '$') { Segment segment = readSegement(); RefOpSegement filter = new RefOpSegement(propertyName, function, segment, op); hasRefSegment = true; while (ch == ' ') { next(); } if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } else if (ch == '/') { int flags = 0; StringBuilder regBuf = new StringBuilder(); for (;;) { next(); if (ch == '/') { next(); if (ch == 'i') { next(); flags |= Pattern.CASE_INSENSITIVE; } break; } if (ch == '\\') { next(); regBuf.append(ch); } else { regBuf.append(ch); } } Pattern pattern = Pattern.compile(regBuf.toString(), flags); RegMatchSegement filter = new RegMatchSegement(propertyName, function, pattern, op); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } if (ch == 'n') { String name = readName(); if ("null".equals(name)) { Filter filter = null; if (op == Operator.EQ) { filter = new NullSegement(propertyName, function); } else if (op == Operator.NE) { filter = new NotNullSegement(propertyName, function); } if (filter != null) { while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } } if (predicateFlag) { accept(')'); } accept(']'); if (filter != null) { return filter; } throw new UnsupportedOperationException(); } } else if (ch == 't') { String name = readName(); if ("true".equals(name)) { Filter filter = null; if (op == Operator.EQ) { filter = new ValueSegment(propertyName, function, Boolean.TRUE, true); } else if (op == Operator.NE) { filter = new ValueSegment(propertyName, function, Boolean.TRUE, false); } if (filter != null) { while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } } if (predicateFlag) { accept(')'); } accept(']'); if (filter != null) { return filter; } throw new UnsupportedOperationException(); } } else if (ch == 'f') { String name = readName(); if ("false".equals(name)) { Filter filter = null; if (op == Operator.EQ) { filter = new ValueSegment(propertyName, function, Boolean.FALSE, true); } else if (op == Operator.NE) { filter = new ValueSegment(propertyName, function, Boolean.FALSE, false); } if (filter != null) { while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } } if (predicateFlag) { accept(')'); } accept(']'); if (filter != null) { return filter; } throw new UnsupportedOperationException(); } } throw new UnsupportedOperationException(); // accept(')'); } int start = pos - 1; char startCh = ch; while (ch != ']' && ch != '/' && !isEOF()) { if (ch == '.' // && (!predicateFlag) // && !predicateFlag && startCh != '\'' ) { break; } if (ch == '\\') { next(); } next(); } int end; if (acceptBracket) { end = pos - 1; } else { if (ch == '/' || ch == '.') { end = pos - 1; } else { end = pos; } } String text = path.substring(start, end); if (text.indexOf('\\') != 0) { StringBuilder buf = new StringBuilder(text.length()); for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch == '\\' && i < text.length() - 1) { char c2 = text.charAt(i + 1); if (c2 == '@' || ch == '\\' || ch == '\"') { buf.append(c2); i++; continue; } } buf.append(ch); } text = buf.toString(); } if (text.indexOf("\\.") != -1) { String propName; if (startCh == '\'' && text.length() > 2 && text.charAt(text.length() - 1) == startCh) { propName = text.substring(1, text.length() - 1); } else { propName = text.replaceAll("\\\\\\.", "\\."); if (propName.indexOf("\\-") != -1) { propName = propName.replaceAll("\\\\-", "-"); } } if (predicateFlag) { accept(')'); } return new PropertySegment(propName, false); } Segment segment = buildArraySegement(text); if (acceptBracket && !isEOF()) { accept(']'); } return segment; } Filter filterRest(Filter filter) { boolean and = ch == '&'; if ((ch == '&' && getNextChar() == '&') || (ch == '|' && getNextChar() == '|')) { next(); next(); boolean paren = false; if (ch == '(') { paren = true; next(); } while (ch == ' ') { next(); } Filter right = (Filter) parseArrayAccessFilter(false); filter = new FilterGroup(filter, right, and); if (paren && ch == ')') { next(); } } return filter; } protected long readLongValue() { int beginIndex = pos - 1; if (ch == '+' || ch == '-') { next(); } while (ch >= '0' && ch <= '9') { next(); } int endIndex = pos - 1; String text = path.substring(beginIndex, endIndex); long value = Long.parseLong(text); return value; } protected double readDoubleValue(long longValue) { int beginIndex = pos - 1; next(); while (ch >= '0' && ch <= '9') { next(); } int endIndex = pos - 1; String text = path.substring(beginIndex, endIndex); double value = Double.parseDouble(text); value += longValue; return value; } protected Object readValue() { skipWhitespace(); if (isDigitFirst(ch)) { return readLongValue(); } if (ch == '"' || ch == '\'') { return readString(); } if (ch == 'n') { String name = readName(); if ("null".equals(name)) { return null; } else { throw new JSONPathException(path); } } throw new UnsupportedOperationException(); } static boolean isDigitFirst(char ch) { return ch == '-' || ch == '+' || (ch >= '0' && ch <= '9'); } protected Operator readOp() { Operator op = null; if (ch == '=') { next(); if (ch == '~') { next(); op = Operator.REG_MATCH; } else if (ch == '=') { next(); op = Operator.EQ; } else { op = Operator.EQ; } } else if (ch == '!') { next(); accept('='); op = Operator.NE; } else if (ch == '<') { next(); if (ch == '=') { next(); op = Operator.LE; } else { op = Operator.LT; } } else if (ch == '>') { next(); if (ch == '=') { next(); op = Operator.GE; } else { op = Operator.GT; } } if (op == null) { String name = readName(); if ("not".equalsIgnoreCase(name)) { skipWhitespace(); name = readName(); if ("like".equalsIgnoreCase(name)) { op = Operator.NOT_LIKE; } else if ("rlike".equalsIgnoreCase(name)) { op = Operator.NOT_RLIKE; } else if ("in".equalsIgnoreCase(name)) { op = Operator.NOT_IN; } else if ("between".equalsIgnoreCase(name)) { op = Operator.NOT_BETWEEN; } else { throw new UnsupportedOperationException(); } } else if ("nin".equalsIgnoreCase(name)) { op = Operator.NOT_IN; } else { if ("like".equalsIgnoreCase(name)) { op = Operator.LIKE; } else if ("rlike".equalsIgnoreCase(name)) { op = Operator.RLIKE; } else if ("in".equalsIgnoreCase(name)) { op = Operator.IN; } else if ("between".equalsIgnoreCase(name)) { op = Operator.BETWEEN; } else { throw new UnsupportedOperationException(); } } } return op; } String readName() { skipWhitespace(); if (ch != '\\' && !Character.isJavaIdentifierStart(ch)) { throw new JSONPathException("illeal jsonpath syntax. " + path); } StringBuilder buf = new StringBuilder(); while (!isEOF()) { if (ch == '\\') { next(); buf.append(ch); if (isEOF()) { return buf.toString(); } next(); continue; } boolean identifierFlag = Character.isJavaIdentifierPart(ch); if (!identifierFlag) { break; } buf.append(ch); next(); } if (isEOF() && Character.isJavaIdentifierPart(ch)) { buf.append(ch); } return buf.toString(); } String readString() { char quoate = ch; next(); int beginIndex = pos - 1; while (ch != quoate && !isEOF()) { next(); } String strValue = path.substring(beginIndex, isEOF() ? pos : pos - 1); accept(quoate); return strValue; } void accept(char expect) { if (ch == ' ') { next(); } if (ch != expect) { throw new JSONPathException("expect '" + expect + ", but '" + ch + "'"); } if (!isEOF()) { next(); } } public Segment[] explain() { if (path == null || path.length() == 0) { throw new IllegalArgumentException(); } Segment[] segments = new Segment[8]; for (;;) { Segment segment = readSegement(); if (segment == null) { break; } if (segment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) segment; if ((!propertySegment.deep) && propertySegment.propertyName.equals("*")) { continue; } } if (level == segments.length) { Segment[] t = new Segment[level * 3 / 2]; System.arraycopy(segments, 0, t, 0, level); segments = t; } segments[level++] = segment; } if (level == segments.length) { return segments; } Segment[] result = new Segment[level]; System.arraycopy(segments, 0, result, 0, level); return result; } Segment buildArraySegement(String indexText) { final int indexTextLen = indexText.length(); final char firstChar = indexText.charAt(0); final char lastChar = indexText.charAt(indexTextLen - 1); int commaIndex = indexText.indexOf(','); if (indexText.length() > 2 && firstChar == '\'' && lastChar == '\'') { String propertyName = indexText.substring(1, indexTextLen - 1); if (commaIndex == -1 || !strArrayPatternx.matcher(indexText).find()) { return new PropertySegment(propertyName, false); } String[] propertyNames = propertyName.split(strArrayRegex); return new MultiPropertySegment(propertyNames); } int colonIndex = indexText.indexOf(':'); if (commaIndex == -1 && colonIndex == -1) { if (TypeUtils.isNumber(indexText)) { try { int index = Integer.parseInt(indexText); return new ArrayAccessSegment(index); }catch (NumberFormatException ex){ return new PropertySegment(indexText, false); // fix ISSUE-1208 } } else { if (indexText.charAt(0) == '"' && indexText.charAt(indexText.length() - 1) == '"') { indexText = indexText.substring(1, indexText.length() - 1); } return new PropertySegment(indexText, false); } } if (commaIndex != -1) { String[] indexesText = indexText.split(","); int[] indexes = new int[indexesText.length]; for (int i = 0; i < indexesText.length; ++i) { indexes[i] = Integer.parseInt(indexesText[i]); } return new MultiIndexSegment(indexes); } if (colonIndex != -1) { String[] indexesText = indexText.split(":"); int[] indexes = new int[indexesText.length]; for (int i = 0; i < indexesText.length; ++i) { String str = indexesText[i]; if (str.length() == 0) { if (i == 0) { indexes[i] = 0; } else { throw new UnsupportedOperationException(); } } else { indexes[i] = Integer.parseInt(str); } } int start = indexes[0]; int end; if (indexes.length > 1) { end = indexes[1]; } else { end = -1; } int step; if (indexes.length == 3) { step = indexes[2]; } else { step = 1; } if (end >= 0 && end < start) { throw new UnsupportedOperationException("end must greater than or equals start. start " + start + ", end " + end); } if (step <= 0) { throw new UnsupportedOperationException("step must greater than zero : " + step); } return new RangeSegment(start, end, step); } throw new UnsupportedOperationException(); } } interface Segment { Object eval(JSONPath path, Object rootObject, Object currentObject); void extract(JSONPath path, DefaultJSONParser parser, Context context); } static class SizeSegment implements Segment { public final static SizeSegment instance = new SizeSegment(); public Integer eval(JSONPath path, Object rootObject, Object currentObject) { return path.evalSize(currentObject); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { Object object = parser.parse(); context.object = path.evalSize(object); } } static class TypeSegment implements Segment { public final static TypeSegment instance = new TypeSegment(); public String eval(JSONPath path, Object rootObject, Object currentObject) { if (currentObject == null) { return "null"; } if (currentObject instanceof Collection) { return "array"; } if (currentObject instanceof Number) { return "number"; } if (currentObject instanceof Boolean) { return "boolean"; } if (currentObject instanceof String || currentObject instanceof UUID || currentObject instanceof Enum) { return "string"; } return "object"; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class FloorSegment implements Segment { public final static FloorSegment instance = new FloorSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { if (currentObject instanceof JSONArray) { JSONArray array = ((JSONArray) ((JSONArray) currentObject).clone()); for (int i = 0; i < array.size(); i++) { Object item = array.get(i); Object newItem = floor(item); if (newItem != item) { array.set(i , newItem); } } return array; } return floor(currentObject); } private static Object floor(Object item) { if (item == null) { return null; } if (item instanceof Float) { return Math.floor((Float) item); } if (item instanceof Double) { return Math.floor((Double) item); } if (item instanceof BigDecimal) { BigDecimal decimal = (BigDecimal) item; return decimal.setScale(0, RoundingMode.FLOOR); } if (item instanceof Byte || item instanceof Short || item instanceof Integer || item instanceof Long || item instanceof BigInteger) { return item; } throw new UnsupportedOperationException(); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class MaxSegment implements Segment { public final static MaxSegment instance = new MaxSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { Object max = null; if (currentObject instanceof Collection) { Iterator iterator = ((Collection) currentObject).iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (next == null) { continue; } if (max == null) { max = next; } else if (compare(max, next) < 0) { max = next; } } } else { throw new UnsupportedOperationException(); } return max; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class MinSegment implements Segment { public final static MinSegment instance = new MinSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { Object min = null; if (currentObject instanceof Collection) { Iterator iterator = ((Collection) currentObject).iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (next == null) { continue; } if (min == null) { min = next; } else if (compare(min, next) > 0) { min = next; } } } else { throw new UnsupportedOperationException(); } return min; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static int compare(Object a, Object b) { if (a.getClass() == b.getClass()) { return ((Comparable) a).compareTo(b); } Class typeA = a.getClass(); Class typeB = b.getClass(); if (typeA == BigDecimal.class) { if (typeB == Integer.class) { b = new BigDecimal((Integer) b); } else if (typeB == Long.class) { b = new BigDecimal((Long) b); } else if (typeB == Float.class) { b = new BigDecimal((Float) b); } else if (typeB == Double.class) { b = new BigDecimal((Double) b); } } else if (typeA == Long.class) { if (typeB == Integer.class) { b = new Long((Integer) b); } else if (typeB == BigDecimal.class) { a = new BigDecimal((Long) a); } else if (typeB == Float.class) { a = new Float((Long) a); } else if (typeB == Double.class) { a = new Double((Long) a); } } else if (typeA == Integer.class) { if (typeB == Long.class) { a = new Long((Integer) a); } else if (typeB == BigDecimal.class) { a = new BigDecimal((Integer) a); } else if (typeB == Float.class) { a = new Float((Integer) a); } else if (typeB == Double.class) { a = new Double((Integer) a); } } else if (typeA == Double.class) { if (typeB == Integer.class) { b = new Double((Integer) b); } else if (typeB == Long.class) { b = new Double((Long) b); } else if (typeB == Float.class) { b = new Double((Float) b); } } else if (typeA == Float.class) { if (typeB == Integer.class) { b = new Float((Integer) b); } else if (typeB == Long.class) { b = new Float((Long) b); } else if (typeB == Double.class) { a = new Double((Float) a); } } return ((Comparable) a).compareTo(b); } static class KeySetSegment implements Segment { public final static KeySetSegment instance = new KeySetSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { return path.evalKeySet(currentObject); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class PropertySegment implements Segment { private final String propertyName; private final long propertyNameHash; private final boolean deep; public PropertySegment(String propertyName, boolean deep){ this.propertyName = propertyName; this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); this.deep = deep; } public Object eval(JSONPath path, Object rootObject, Object currentObject) { if (deep) { List<Object> results = new ArrayList<Object>(); path.deepScan(currentObject, propertyName, results); return results; } else { // return path.getPropertyValue(currentObject, propertyName, true); return path.getPropertyValue(currentObject, propertyName, propertyNameHash); } } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { JSONLexerBase lexer = (JSONLexerBase) parser.lexer; if (deep && context.object == null) { context.object = new JSONArray(); } if (lexer.token() == JSONToken.LBRACKET) { if ("*".equals(propertyName)) { return; } lexer.nextToken(); JSONArray array; if (deep) { array =(JSONArray) context.object; } else { array = new JSONArray(); } for (;;) { switch (lexer.token()) { case JSONToken.LBRACE: { if (deep) { extract(path, parser, context); break; } int matchStat = lexer.seekObjectToField(propertyNameHash, deep); if (matchStat == JSONLexer.VALUE) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(); break; default: value = parser.parse(); break; } array.add(value); if (lexer.token() == JSONToken.RBRACE) { lexer.nextToken(); continue; } else { lexer.skipObject(false); } } else if (matchStat == JSONLexer.NOT_MATCH) { continue; } else { if (deep) { throw new UnsupportedOperationException(lexer.info()); } else { lexer.skipObject(false); } } break; } case JSONToken.LBRACKET: if (deep) { extract(path, parser, context); } else { lexer.skipObject(false); } break; case JSONToken.LITERAL_STRING: case JSONToken.LITERAL_INT: case JSONToken.LITERAL_FLOAT: case JSONToken.LITERAL_ISO8601_DATE: case JSONToken.TRUE: case JSONToken.FALSE: case JSONToken.NULL: lexer.nextToken(); break; default: break; } if (lexer.token() == JSONToken.RBRACKET) { lexer.nextToken(); break; } else if (lexer.token() == JSONToken.COMMA) { lexer.nextToken(); continue; } else { throw new JSONException("illegal json : " + lexer.info()); } } if (!deep) { if (array.size() > 0) { context.object = array; } } return; } if (!deep) { int matchStat = lexer.seekObjectToField(propertyNameHash, deep); if (matchStat == JSONLexer.VALUE) { if (context.eval) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_FLOAT: value = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); break; default: value = parser.parse(); break; } if (context.eval) { context.object = value; } } } return; } // deep for (;;) { int matchStat = lexer.seekObjectToField(propertyNameHash, deep); if (matchStat == JSONLexer.NOT_MATCH) { break; } if (matchStat == JSONLexer.VALUE) { if (context.eval) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_FLOAT: value = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); break; default: value = parser.parse(); break; } if (context.eval) { if (context.object instanceof List) { List list = (List) context.object; if (list.size() == 0 && value instanceof List) { context.object = value; } else { list.add(value); } } else { context.object = value; } } } } else if (matchStat == JSONLexer.OBJECT || matchStat == JSONLexer.ARRAY) { extract(path, parser, context); } } } public void setValue(JSONPath path, Object parent, Object value) { if (deep) { path.deepSet(parent, propertyName, propertyNameHash, value); } else { path.setPropertyValue(parent, propertyName, propertyNameHash, value); } } public boolean remove(JSONPath path, Object parent) { return path.removePropertyValue(parent, propertyName, deep); } } static class MultiPropertySegment implements Segment { private final String[] propertyNames; private final long[] propertyNamesHash; public MultiPropertySegment(String[] propertyNames){ this.propertyNames = propertyNames; this.propertyNamesHash = new long[propertyNames.length]; for (int i = 0; i < propertyNamesHash.length; i++) { propertyNamesHash[i] = TypeUtils.fnv1a_64(propertyNames[i]); } } public Object eval(JSONPath path, Object rootObject, Object currentObject) { List<Object> fieldValues = new ArrayList<Object>(propertyNames.length); for (int i = 0; i < propertyNames.length; i++) { Object fieldValue = path.getPropertyValue(currentObject, propertyNames[i], propertyNamesHash[i]); fieldValues.add(fieldValue); } return fieldValues; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { JSONLexerBase lexer = (JSONLexerBase) parser.lexer; JSONArray array; if (context.object == null) { context.object = array = new JSONArray(); } else { array = (JSONArray) context.object; } for (int i = array.size(); i < propertyNamesHash.length; ++i) { array.add(null); } // if (lexer.token() == JSONToken.LBRACKET) { // lexer.nextToken(); // JSONArray array; // // array = new JSONArray(); // for (;;) { // if (lexer.token() == JSONToken.LBRACE) { // int index = lexer.seekObjectToField(propertyNamesHash); // int matchStat = lexer.matchStat; // if (matchStat == JSONLexer.VALUE) { // Object value; // switch (lexer.token()) { // case JSONToken.LITERAL_INT: // value = lexer.integerValue(); // lexer.nextToken(); // break; // case JSONToken.LITERAL_STRING: // value = lexer.stringVal(); // lexer.nextToken(); // break; // default: // value = parser.parse(); // break; // } // // array.add(index, value); // if (lexer.token() == JSONToken.RBRACE) { // lexer.nextToken(); // continue; // } else { // lexer.skipObject(); // } // } else { // lexer.skipObject(); // } // } // // if (lexer.token() == JSONToken.RBRACKET) { // break; // } else if (lexer.token() == JSONToken.COMMA) { // lexer.nextToken(); // continue; // } else { // throw new JSONException("illegal json."); // } // } // // context.object = array; // return; // } for_: for (;;) { int index = lexer.seekObjectToField(propertyNamesHash); int matchStat = lexer.matchStat; if (matchStat == JSONLexer.VALUE) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_FLOAT: value = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); break; default: value = parser.parse(); break; } array.set(index, value); if (lexer.token() == JSONToken.COMMA) { continue for_; } } break; } } } static class WildCardSegment implements Segment { private boolean deep; private boolean objectOnly; private WildCardSegment(boolean deep, boolean objectOnly) { this.deep = deep; this.objectOnly = objectOnly; } public final static WildCardSegment instance = new WildCardSegment(false, false); public final static WildCardSegment instance_deep = new WildCardSegment(true, false); public final static WildCardSegment instance_deep_objectOnly = new WildCardSegment(true, true); public Object eval(JSONPath path, Object rootObject, Object currentObject) { if (!deep) { return path.getPropertyValues(currentObject); } List<Object> values = new ArrayList<Object>(); path.deepGetPropertyValues(currentObject, values); return values; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { if (context.eval) { Object object = parser.parse(); if (deep) { List<Object> values = new ArrayList<Object>(); if (objectOnly) { path.deepGetObjects(object, values); } else { path.deepGetPropertyValues(object, values); } context.object = values; return; } if (object instanceof JSONObject) { Collection<Object> values = ((JSONObject) object).values(); JSONArray array = new JSONArray(values.size()); array.addAll(values); context.object = array; return; } else if (object instanceof JSONArray) { context.object = object; return; } } throw new JSONException("TODO"); } } static class ArrayAccessSegment implements Segment { private final int index; public ArrayAccessSegment(int index){ this.index = index; } public Object eval(JSONPath path, Object rootObject, Object currentObject) { return path.getArrayItem(currentObject, index); } public boolean setValue(JSONPath path, Object currentObject, Object value) { return path.setArrayItem(path, currentObject, index, value); } public boolean remove(JSONPath path, Object currentObject) { return path.removeArrayItem(path, currentObject, index); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { JSONLexerBase lexer = (JSONLexerBase) parser.lexer; if (lexer.seekArrayToItem(index) && context.eval) { context.object = parser.parse(); } } } static class MultiIndexSegment implements Segment { private final int[] indexes; public MultiIndexSegment(int[] indexes){ this.indexes = indexes; } public Object eval(JSONPath path, Object rootObject, Object currentObject) { List<Object> items = new JSONArray(indexes.length); for (int i = 0; i < indexes.length; ++i) { Object item = path.getArrayItem(currentObject, indexes[i]); items.add(item); } return items; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { if (context.eval) { Object object = parser.parse(); if (object instanceof List) { int[] indexes = new int[this.indexes.length]; System.arraycopy(this.indexes, 0, indexes, 0, indexes.length); boolean noneNegative = indexes[0] >= 0; List list = (List) object; if (noneNegative) { for (int i = list.size() - 1; i >= 0; i--) { if (Arrays.binarySearch(indexes, i) < 0) { list.remove(i); } } context.object = list; return; } } } throw new UnsupportedOperationException(); } } static class RangeSegment implements Segment { private final int start; private final int end; private final int step; public RangeSegment(int start, int end, int step){ this.start = start; this.end = end; this.step = step; } public Object eval(JSONPath path, Object rootObject, Object currentObject) { int size = SizeSegment.instance.eval(path, rootObject, currentObject); int start = this.start >= 0 ? this.start : this.start + size; int end = this.end >= 0 ? this.end : this.end + size; int array_size = (end - start) / step + 1; if (array_size == -1) { return null; } List<Object> items = new ArrayList<Object>(array_size); for (int i = start; i <= end && i < size; i += step) { Object item = path.getArrayItem(currentObject, i); items.add(item); } return items; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class NotNullSegement extends PropertyFilter { public NotNullSegement(String propertyName, boolean function){ super(propertyName, function); } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { return path.getPropertyValue(item, propertyName, propertyNameHash) != null; } } static class NullSegement extends PropertyFilter { public NullSegement(String propertyName, boolean function){ super(propertyName, function); } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); return propertyValue == null; } } static class ValueSegment extends PropertyFilter { private final Object value; private boolean eq = true; public ValueSegment(String propertyName,boolean function, Object value, boolean eq){ super(propertyName, function); if (value == null) { throw new IllegalArgumentException("value is null"); } this.value = value; this.eq = eq; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); boolean result = value.equals(propertyValue); if (!eq) { result = !result; } return result; } } static class IntInSegement extends PropertyFilter { private final long[] values; private final boolean not; public IntInSegement(String propertyName, boolean function, long[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); for (long value : values) { if (value == longPropertyValue) { return !not; } } } return not; } } static class IntBetweenSegement extends PropertyFilter { private final long startValue; private final long endValue; private final boolean not; public IntBetweenSegement(String propertyName, boolean function, long startValue, long endValue, boolean not){ super(propertyName, function); this.startValue = startValue; this.endValue = endValue; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); if (longPropertyValue >= startValue && longPropertyValue <= endValue) { return !not; } } return not; } } static class IntObjInSegement extends PropertyFilter { private final Long[] values; private final boolean not; public IntObjInSegement(String propertyName, boolean function, Long[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { for (Long value : values) { if (value == null) { return !not; } } return not; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); for (Long value : values) { if (value == null) { continue; } if (value.longValue() == longPropertyValue) { return !not; } } } return not; } } static class StringInSegement extends PropertyFilter { private final String[] values; private final boolean not; public StringInSegement(String propertyName, boolean function, String[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); for (String value : values) { if (value == propertyValue) { return !not; } else if (value != null && value.equals(propertyValue)) { return !not; } } return not; } } static class IntOpSegement extends PropertyFilter { private final long value; private final Operator op; private BigDecimal valueDecimal; private Float valueFloat; private Double valueDouble; public IntOpSegement(String propertyName, boolean function, long value, Operator op){ super(propertyName, function); this.value = value; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } if (propertyValue instanceof BigDecimal) { if (valueDecimal == null) { valueDecimal = BigDecimal.valueOf(value); } int result = valueDecimal.compareTo((BigDecimal) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } if (propertyValue instanceof Float) { if (valueFloat == null) { valueFloat = Float.valueOf(value); } int result = valueFloat.compareTo((Float) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } if (propertyValue instanceof Double) { if (valueDouble == null) { valueDouble = Double.valueOf(value); } int result = valueDouble.compareTo((Double) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } long longValue = TypeUtils.longExtractValue((Number) propertyValue); switch (op) { case EQ: return longValue == value; case NE: return longValue != value; case GE: return longValue >= value; case GT: return longValue > value; case LE: return longValue <= value; case LT: return longValue < value; } return false; } } static abstract class PropertyFilter implements Filter { static long TYPE = TypeUtils.fnv1a_64("type"); protected final String propertyName; protected final long propertyNameHash; protected final boolean function; protected Segment functionExpr; protected PropertyFilter(String propertyName, boolean function) { this.propertyName = propertyName; this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); this.function = function; if (function) { if (propertyNameHash == TYPE) { functionExpr = TypeSegment.instance; } else if (propertyNameHash == SIZE) { functionExpr = SizeSegment.instance; } else { throw new JSONPathException("unsupported funciton : " + propertyName); } } } protected Object get(JSONPath path, Object rootObject, Object currentObject) { if (functionExpr != null) { return functionExpr.eval(path, rootObject, currentObject); } return path.getPropertyValue(currentObject, propertyName, propertyNameHash); } } static class DoubleOpSegement extends PropertyFilter { private final double value; private final Operator op; public DoubleOpSegement(String propertyName, boolean function, double value, Operator op){ super(propertyName, function); this.value = value; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } double doubleValue = ((Number) propertyValue).doubleValue(); switch (op) { case EQ: return doubleValue == value; case NE: return doubleValue != value; case GE: return doubleValue >= value; case GT: return doubleValue > value; case LE: return doubleValue <= value; case LT: return doubleValue < value; } return false; } } static class RefOpSegement extends PropertyFilter { private final Segment refSgement; private final Operator op; public RefOpSegement(String propertyName, boolean function, Segment refSgement, Operator op){ super(propertyName, function); this.refSgement = refSgement; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } Object refValue = refSgement.eval(path, rootObject, rootObject); if (refValue instanceof Integer || refValue instanceof Long || refValue instanceof Short || refValue instanceof Byte) { long value = TypeUtils.longExtractValue((Number) refValue); if (propertyValue instanceof Integer || propertyValue instanceof Long || propertyValue instanceof Short || propertyValue instanceof Byte) { long longValue = TypeUtils.longExtractValue((Number) propertyValue); switch (op) { case EQ: return longValue == value; case NE: return longValue != value; case GE: return longValue >= value; case GT: return longValue > value; case LE: return longValue <= value; case LT: return longValue < value; } } else if (propertyValue instanceof BigDecimal) { BigDecimal valueDecimal = BigDecimal.valueOf(value); int result = valueDecimal.compareTo((BigDecimal) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } } throw new UnsupportedOperationException(); } } static class MatchSegement extends PropertyFilter { private final String startsWithValue; private final String endsWithValue; private final String[] containsValues; private final int minLength; private final boolean not; public MatchSegement( String propertyName, boolean function, String startsWithValue, String endsWithValue, String[] containsValues, boolean not) { super(propertyName, function); this.startsWithValue = startsWithValue; this.endsWithValue = endsWithValue; this.containsValues = containsValues; this.not = not; int len = 0; if (startsWithValue != null) { len += startsWithValue.length(); } if (endsWithValue != null) { len += endsWithValue.length(); } if (containsValues != null) { for (String item : containsValues) { len += item.length(); } } this.minLength = len; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } final String strPropertyValue = propertyValue.toString(); if (strPropertyValue.length() < minLength) { return not; } int start = 0; if (startsWithValue != null) { if (!strPropertyValue.startsWith(startsWithValue)) { return not; } start += startsWithValue.length(); } if (containsValues != null) { for (String containsValue : containsValues) { int index = strPropertyValue.indexOf(containsValue, start); if (index == -1) { return not; } start = index + containsValue.length(); } } if (endsWithValue != null) { if (!strPropertyValue.endsWith(endsWithValue)) { return not; } } return !not; } } static class RlikeSegement extends PropertyFilter { private final Pattern pattern; private final boolean not; public RlikeSegement(String propertyName, boolean function, String pattern, boolean not){ super(propertyName, function); this.pattern = Pattern.compile(pattern); this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } String strPropertyValue = propertyValue.toString(); Matcher m = pattern.matcher(strPropertyValue); boolean match = m.matches(); if (not) { match = !match; } return match; } } static class StringOpSegement extends PropertyFilter { private final String value; private final Operator op; public StringOpSegement(String propertyName, boolean function, String value, Operator op){ super(propertyName, function); this.value = value; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (op == Operator.EQ) { return value.equals(propertyValue); } else if (op == Operator.NE) { return !value.equals(propertyValue); } if (propertyValue == null) { return false; } int compareResult = value.compareTo(propertyValue.toString()); if (op == Operator.GE) { return compareResult <= 0; } else if (op == Operator.GT) { return compareResult < 0; } else if (op == Operator.LE) { return compareResult >= 0; } else if (op == Operator.LT) { return compareResult > 0; } return false; } } static class RegMatchSegement extends PropertyFilter { private final Pattern pattern; private final Operator op; public RegMatchSegement(String propertyName, boolean function, Pattern pattern, Operator op){ super(propertyName, function); this.pattern = pattern; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } String str = propertyValue.toString(); Matcher m = pattern.matcher(str); return m.matches(); } } enum Operator { EQ, NE, GT, GE, LT, LE, LIKE, NOT_LIKE, RLIKE, NOT_RLIKE, IN, NOT_IN, BETWEEN, NOT_BETWEEN, And, Or, REG_MATCH } static public class FilterSegment implements Segment { private final Filter filter; public FilterSegment(Filter filter){ super(); this.filter = filter; } @SuppressWarnings("rawtypes") public Object eval(JSONPath path, Object rootObject, Object currentObject) { if (currentObject == null) { return null; } List<Object> items = new JSONArray(); if (currentObject instanceof Iterable) { Iterator it = ((Iterable) currentObject).iterator(); while (it.hasNext()) { Object item = it.next(); if (filter.apply(path, rootObject, currentObject, item)) { items.add(item); } } return items; } if (filter.apply(path, rootObject, currentObject, currentObject)) { return currentObject; } return null; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { Object object = parser.parse(); context.object = eval(path, object, object); } public boolean remove(JSONPath path, Object rootObject, Object currentObject) { if (currentObject == null) { return false; } if (currentObject instanceof Iterable) { Iterator it = ((Iterable) currentObject).iterator(); while (it.hasNext()) { Object item = it.next(); if (filter.apply(path, rootObject, currentObject, item)) { it.remove(); } } return true; } return false; } } interface Filter { boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item); } static class FilterGroup implements Filter { private boolean and; private List<Filter> fitlers; public FilterGroup(Filter left, Filter right, boolean and) { fitlers = new ArrayList<Filter>(2); fitlers.add(left); fitlers.add(right); this.and = and; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { if (and) { for (Filter fitler : this.fitlers) { if (!fitler.apply(path, rootObject, currentObject, item)) { return false; } } return true; } else { for (Filter fitler : this.fitlers) { if (fitler.apply(path, rootObject, currentObject, item)) { return true; } } return false; } } } @SuppressWarnings("rawtypes") protected Object getArrayItem(final Object currentObject, int index) { if (currentObject == null) { return null; } if (currentObject instanceof List) { List list = (List) currentObject; if (index >= 0) { if (index < list.size()) { return list.get(index); } return null; } else { if (Math.abs(index) <= list.size()) { return list.get(list.size() + index); } return null; } } if (currentObject.getClass().isArray()) { int arrayLenth = Array.getLength(currentObject); if (index >= 0) { if (index < arrayLenth) { return Array.get(currentObject, index); } return null; } else { if (Math.abs(index) <= arrayLenth) { return Array.get(currentObject, arrayLenth + index); } return null; } } if (currentObject instanceof Map) { Map map = (Map) currentObject; Object value = map.get(index); if (value == null) { value = map.get(Integer.toString(index)); } return value; } if (currentObject instanceof Collection) { Collection collection = (Collection) currentObject; int i = 0; for (Object item : collection) { if (i == index) { return item; } i++; } return null; } if (index == 0) { return currentObject; } throw new UnsupportedOperationException(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public boolean setArrayItem(JSONPath path, Object currentObject, int index, Object value) { if (currentObject instanceof List) { List list = (List) currentObject; if (index >= 0) { list.set(index, value); } else { list.set(list.size() + index, value); } return true; } Class<?> clazz = currentObject.getClass(); if (clazz.isArray()) { int arrayLenth = Array.getLength(currentObject); if (index >= 0) { if (index < arrayLenth) { Array.set(currentObject, index, value); } } else { if (Math.abs(index) <= arrayLenth) { Array.set(currentObject, arrayLenth + index, value); } } return true; } throw new JSONPathException("unsupported set operation." + clazz); } @SuppressWarnings("rawtypes") public boolean removeArrayItem(JSONPath path, Object currentObject, int index) { if (currentObject instanceof List) { List list = (List) currentObject; if (index >= 0) { if (index >= list.size()) { return false; } list.remove(index); } else { int newIndex = list.size() + index; if (newIndex < 0) { return false; } list.remove(newIndex); } return true; } Class<?> clazz = currentObject.getClass(); throw new JSONPathException("unsupported set operation." + clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected Collection<Object> getPropertyValues(final Object currentObject) { if (currentObject == null) { return null; } final Class<?> currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); if (beanSerializer != null) { try { return beanSerializer.getFieldValues(currentObject); } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path, e); } } if (currentObject instanceof Map) { Map map = (Map) currentObject; return map.values(); } if (currentObject instanceof Collection) { return (Collection) currentObject; } throw new UnsupportedOperationException(); } protected void deepGetObjects(final Object currentObject, List<Object> outValues) { final Class<?> currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); Collection collection = null; if (beanSerializer != null) { try { collection = beanSerializer.getFieldValues(currentObject); outValues.add(currentObject); } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path, e); } } else if (currentObject instanceof Map) { outValues.add(currentObject); Map map = (Map) currentObject; collection = map.values(); } else if (currentObject instanceof Collection) { collection = (Collection) currentObject; } if (collection != null) { for (Object fieldValue : collection) { if (fieldValue == null || ParserConfig.isPrimitive2(fieldValue.getClass())) { // skip } else { deepGetObjects(fieldValue, outValues); } } return; } throw new UnsupportedOperationException(currentClass.getName()); } protected void deepGetPropertyValues(final Object currentObject, List<Object> outValues) { final Class<?> currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); Collection collection = null; if (beanSerializer != null) { try { collection = beanSerializer.getFieldValues(currentObject); } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path, e); } } else if (currentObject instanceof Map) { Map map = (Map) currentObject; collection = map.values(); } else if (currentObject instanceof Collection) { collection = (Collection) currentObject; } if (collection != null) { for (Object fieldValue : collection) { if (fieldValue == null || ParserConfig.isPrimitive2(fieldValue.getClass())) { outValues.add(fieldValue); } else { deepGetPropertyValues(fieldValue, outValues); } } return; } throw new UnsupportedOperationException(currentClass.getName()); } static boolean eq(Object a, Object b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.getClass() == b.getClass()) { return a.equals(b); } if (a instanceof Number) { if (b instanceof Number) { return eqNotNull((Number) a, (Number) b); } return false; } return a.equals(b); } @SuppressWarnings("rawtypes") static boolean eqNotNull(Number a, Number b) { Class clazzA = a.getClass(); boolean isIntA = isInt(clazzA); Class clazzB = b.getClass(); boolean isIntB = isInt(clazzB); if (a instanceof BigDecimal) { BigDecimal decimalA = (BigDecimal) a; if (isIntB) { return decimalA.equals(BigDecimal.valueOf(TypeUtils.longExtractValue(b))); } } if (isIntA) { if (isIntB) { return a.longValue() == b.longValue(); } if (b instanceof BigInteger) { BigInteger bigIntB = (BigInteger) a; BigInteger bigIntA = BigInteger.valueOf(a.longValue()); return bigIntA.equals(bigIntB); } } if (isIntB) { if (a instanceof BigInteger) { BigInteger bigIntA = (BigInteger) a; BigInteger bigIntB = BigInteger.valueOf(TypeUtils.longExtractValue(b)); return bigIntA.equals(bigIntB); } } boolean isDoubleA = isDouble(clazzA); boolean isDoubleB = isDouble(clazzB); if ((isDoubleA && isDoubleB) || (isDoubleA && isIntB) || (isDoubleB && isIntA)) { return a.doubleValue() == b.doubleValue(); } return false; } protected static boolean isDouble(Class<?> clazzA) { return clazzA == Float.class || clazzA == Double.class; } protected static boolean isInt(Class<?> clazzA) { return clazzA == Byte.class || clazzA == Short.class || clazzA == Integer.class || clazzA == Long.class; } final static long SIZE = 0x4dea9618e618ae3cL; // TypeUtils.fnv1a_64("size"); final static long LENGTH = 0xea11573f1af59eb5L; // TypeUtils.fnv1a_64("length"); protected Object getPropertyValue(Object currentObject, String propertyName, long propertyNameHash) { if (currentObject == null) { return null; } if (currentObject instanceof String) { try { JSONObject object = (JSONObject) JSON.parse((String) currentObject, parserConfig); currentObject = object; } catch (Exception ex) { // skip } } if (currentObject instanceof Map) { Map map = (Map) currentObject; Object val = map.get(propertyName); if (val == null && (SIZE == propertyNameHash || LENGTH == propertyNameHash)) { val = map.size(); } return val; } final Class<?> currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); if (beanSerializer != null) { try { return beanSerializer.getFieldValue(currentObject, propertyName, propertyNameHash, false); } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e); } } if (currentObject instanceof List) { List list = (List) currentObject; if (SIZE == propertyNameHash || LENGTH == propertyNameHash) { return list.size(); } List<Object> fieldValues = null; for (int i = 0; i < list.size(); ++i) { Object obj = list.get(i); // if (obj == list) { if (fieldValues == null) { fieldValues = new JSONArray(list.size()); } fieldValues.add(obj); continue; } Object itemValue = getPropertyValue(obj, propertyName, propertyNameHash); if (itemValue instanceof Collection) { Collection collection = (Collection) itemValue; if (fieldValues == null) { fieldValues = new JSONArray(list.size()); } fieldValues.addAll(collection); } else if (itemValue != null || !ignoreNullValue) { if (fieldValues == null) { fieldValues = new JSONArray(list.size()); } fieldValues.add(itemValue); } } if (fieldValues == null) { fieldValues = Collections.emptyList(); } return fieldValues; } if (currentObject instanceof Object[]) { Object[] array = (Object[]) currentObject; if (SIZE == propertyNameHash || LENGTH == propertyNameHash) { return array.length; } List<Object> fieldValues = new JSONArray(array.length); for (int i = 0; i < array.length; ++i) { Object obj = array[i]; // if (obj == array) { fieldValues.add(obj); continue; } Object itemValue = getPropertyValue(obj, propertyName, propertyNameHash); if (itemValue instanceof Collection) { Collection collection = (Collection) itemValue; fieldValues.addAll(collection); } else if (itemValue != null || !ignoreNullValue) { fieldValues.add(itemValue); } } return fieldValues; } if (currentObject instanceof Enum) { final long NAME = 0xc4bcadba8e631b86L; // TypeUtils.fnv1a_64("name"); final long ORDINAL = 0xf1ebc7c20322fc22L; //TypeUtils.fnv1a_64("ordinal"); Enum e = (Enum) currentObject; if (NAME == propertyNameHash) { return e.name(); } if (ORDINAL == propertyNameHash) { return e.ordinal(); } } if (currentObject instanceof Calendar) { final long YEAR = 0x7c64634977425edcL; //TypeUtils.fnv1a_64("year"); final long MONTH = 0xf4bdc3936faf56a5L; //TypeUtils.fnv1a_64("month"); final long DAY = 0xca8d3918f4578f1dL; // TypeUtils.fnv1a_64("day"); final long HOUR = 0x407efecc7eb5764fL; //TypeUtils.fnv1a_64("hour"); final long MINUTE = 0x5bb2f9bdf2fad1e9L; //TypeUtils.fnv1a_64("minute"); final long SECOND = 0xa49985ef4cee20bdL; //TypeUtils.fnv1a_64("second"); Calendar e = (Calendar) currentObject; if (YEAR == propertyNameHash) { return e.get(Calendar.YEAR); } if (MONTH == propertyNameHash) { return e.get(Calendar.MONTH); } if (DAY == propertyNameHash) { return e.get(Calendar.DAY_OF_MONTH); } if (HOUR == propertyNameHash) { return e.get(Calendar.HOUR_OF_DAY); } if (MINUTE == propertyNameHash) { return e.get(Calendar.MINUTE); } if (SECOND == propertyNameHash) { return e.get(Calendar.SECOND); } } return null; //throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName); } @SuppressWarnings("rawtypes") protected void deepScan(final Object currentObject, final String propertyName, List<Object> results) { if (currentObject == null) { return; } if (currentObject instanceof Map) { Map<?, ?> map = (Map<?, ?>) currentObject; for (Map.Entry entry : map.entrySet()) { Object val = entry.getValue(); if (propertyName.equals(entry.getKey())) { if (val instanceof Collection) { results.addAll((Collection) val); } else { results.add(val); } continue; } if (val == null || ParserConfig.isPrimitive2(val.getClass())) { continue; } deepScan(val, propertyName, results); } return; } if (currentObject instanceof Collection) { Iterator iterator = ((Collection) currentObject).iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (ParserConfig.isPrimitive2(next.getClass())) { continue; } deepScan(next, propertyName, results); } return; } final Class<?> currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); if (beanSerializer != null) { try { FieldSerializer fieldDeser = beanSerializer.getFieldSerializer(propertyName); if (fieldDeser != null) { try { Object val = fieldDeser.getPropertyValueDirect(currentObject); results.add(val); } catch (InvocationTargetException ex) { throw new JSONException("getFieldValue error." + propertyName, ex); } catch (IllegalAccessException ex) { throw new JSONException("getFieldValue error." + propertyName, ex); } return; } List<Object> fieldValues = beanSerializer.getFieldValues(currentObject); for (Object val : fieldValues) { deepScan(val, propertyName, results); } return; } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e); } } if (currentObject instanceof List) { List list = (List) currentObject; for (int i = 0; i < list.size(); ++i) { Object val = list.get(i); deepScan(val, propertyName, results); } return; } } protected void deepSet(final Object currentObject, final String propertyName, long propertyNameHash, Object value) { if (currentObject == null) { return; } if (currentObject instanceof Map) { Map map = (Map) currentObject; if (map.containsKey(propertyName)) { Object val = map.get(propertyName); map.put(propertyName, value); return; } for (Object val : map.values()) { deepSet(val, propertyName, propertyNameHash, value); } return; } final Class<?> currentClass = currentObject.getClass(); JavaBeanDeserializer beanDeserializer = getJavaBeanDeserializer(currentClass); if (beanDeserializer != null) { try { FieldDeserializer fieldDeser = beanDeserializer.getFieldDeserializer(propertyName); if (fieldDeser != null) { fieldDeser.setValue(currentObject, value); return; } JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); List<Object> fieldValues = beanSerializer.getObjectFieldValues(currentObject); for (Object val : fieldValues) { deepSet(val, propertyName, propertyNameHash, value); } return; } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e); } } if (currentObject instanceof List) { List list = (List) currentObject; for (int i = 0; i < list.size(); ++i) { Object val = list.get(i); deepSet(val, propertyName, propertyNameHash, value); } return; } } @SuppressWarnings({ "unchecked", "rawtypes" }) protected boolean setPropertyValue(Object parent, String name, long propertyNameHash, Object value) { if (parent instanceof Map) { ((Map) parent).put(name, value); return true; } if (parent instanceof List) { for (Object element : (List) parent) { if (element == null) { continue; } setPropertyValue(element, name, propertyNameHash, value); } return true; } ObjectDeserializer deserializer = parserConfig.getDeserializer(parent.getClass()); JavaBeanDeserializer beanDeserializer = null; if (deserializer instanceof JavaBeanDeserializer) { beanDeserializer = (JavaBeanDeserializer) deserializer; } if (beanDeserializer != null) { FieldDeserializer fieldDeserializer = beanDeserializer.getFieldDeserializer(propertyNameHash); if (fieldDeserializer == null) { return false; } if (value != null && value.getClass() != fieldDeserializer.fieldInfo.fieldClass) { value = TypeUtils.cast(value, fieldDeserializer.fieldInfo.fieldType, parserConfig); } fieldDeserializer.setValue(parent, value); return true; } throw new UnsupportedOperationException(); } @SuppressWarnings({"rawtypes" }) protected boolean removePropertyValue(Object parent, String name, boolean deep) { if (parent instanceof Map) { Object origin = ((Map) parent).remove(name); boolean found = origin != null; if (deep) { for (Object item : ((Map) parent).values()) { removePropertyValue(item, name, deep); } } return found; } ObjectDeserializer deserializer = parserConfig.getDeserializer(parent.getClass()); JavaBeanDeserializer beanDeserializer = null; if (deserializer instanceof JavaBeanDeserializer) { beanDeserializer = (JavaBeanDeserializer) deserializer; } if (beanDeserializer != null) { FieldDeserializer fieldDeserializer = beanDeserializer.getFieldDeserializer(name); boolean found = false; if (fieldDeserializer != null) { fieldDeserializer.setValue(parent, null); found = true; } if (deep) { Collection<Object> propertyValues = this.getPropertyValues(parent); for (Object item : propertyValues) { if (item == null) { continue; } removePropertyValue(item, name, deep); } } return found; } if (deep) { return false; } throw new UnsupportedOperationException(); } protected JavaBeanSerializer getJavaBeanSerializer(final Class<?> currentClass) { JavaBeanSerializer beanSerializer = null; { ObjectSerializer serializer = serializeConfig.getObjectWriter(currentClass); if (serializer instanceof JavaBeanSerializer) { beanSerializer = (JavaBeanSerializer) serializer; } } return beanSerializer; } protected JavaBeanDeserializer getJavaBeanDeserializer(final Class<?> currentClass) { JavaBeanDeserializer beanDeserializer = null; { ObjectDeserializer deserializer = parserConfig.getDeserializer(currentClass); if (deserializer instanceof JavaBeanDeserializer) { beanDeserializer = (JavaBeanDeserializer) deserializer; } } return beanDeserializer; } @SuppressWarnings("rawtypes") int evalSize(Object currentObject) { if (currentObject == null) { return -1; } if (currentObject instanceof Collection) { return ((Collection) currentObject).size(); } if (currentObject instanceof Object[]) { return ((Object[]) currentObject).length; } if (currentObject.getClass().isArray()) { return Array.getLength(currentObject); } if (currentObject instanceof Map) { int count = 0; for (Object value : ((Map) currentObject).values()) { if (value != null) { count++; } } return count; } JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentObject.getClass()); if (beanSerializer == null) { return -1; } try { return beanSerializer.getSize(currentObject); } catch (Exception e) { throw new JSONPathException("evalSize error : " + path, e); } } @SuppressWarnings({"rawtypes", "unchecked"}) Set<?> evalKeySet(Object currentObject) { if (currentObject == null) { return null; } if (currentObject instanceof Map) { // For performance reasons return keySet directly, without filtering null-value key. return ((Map)currentObject).keySet(); } if (currentObject instanceof Collection || currentObject instanceof Object[] || currentObject.getClass().isArray()) { return null; } JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentObject.getClass()); if (beanSerializer == null) { return null; } try { return beanSerializer.getFieldNames(currentObject); } catch (Exception e) { throw new JSONPathException("evalKeySet error : " + path, e); } } public String toJSONString() { return JSON.toJSONString(path); } public static Object reserveToArray(Object object, String... paths) { JSONArray reserved = new JSONArray(); if (paths == null || paths.length == 0) { return reserved; } for (String item : paths) { JSONPath path = JSONPath.compile(item); path.init(); Object value = path.eval(object); reserved.add(value); } return reserved; } public static Object reserveToObject(Object object, String... paths) { if (paths == null || paths.length == 0) { return object; } JSONObject reserved = new JSONObject(true); for (String item : paths) { JSONPath path = JSONPath.compile(item); path.init(); Segment lastSegement = path.segments[path.segments.length - 1]; if (lastSegement instanceof PropertySegment) { Object value = path.eval(object); if (value == null) { continue; } path.set(reserved, value); } else { // skip } } return reserved; } }
CyberFlameGO/fastjson
src/main/java/com/alibaba/fastjson/JSONPath.java
63
/** * Most of the times, the students of Computer Science & Engineering of BUET deal with bogus, tough and * very complex formulae. That is why, sometimes, even for a easy problem they think very hard and make * the problem much complex to solve. But, the team members of the team “BUET PESSIMISTIC” * are the only exceptions. Just like the opposite manner, they treat every hard problem as easy and so * cannot do well in any contest. Today, they try to solve a series but fail for treating it as hard. Let * them help. * Input * Just try to determine the answer for the following series * ∑ * N * i=1 * iAi * You are given the value of integers N and A (1 ≤ N ≤ 150, 0 ≤ A ≤ 15). * Output * For each line of the input, your correct program should output the integer value of the sum in separate * lines for each pair of values of N and A. * Sample Input * 3 3 * 4 4 * Sample Output * 102 * 1252 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1464 import java.math.BigInteger; import java.util.Scanner; public class VeryEasy { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { BigInteger sum = BigInteger.ZERO; int N = input.nextInt(); int A = input.nextInt(); BigInteger aAsBigInteger = BigInteger.valueOf(A); BigInteger product = BigInteger.ONE; for (int i = 1; i < N + 1; i++) { product = BigInteger.valueOf(i).multiply(aAsBigInteger.pow(i)); sum = sum.add(product); } System.out.println(sum); } } }
kdn251/interviews
uva/VeryEasy.java
64
//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } }
kdn251/interviews
leetcode/math/AddDigits.java
65
// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class CloneGraph { public HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } }
kdn251/interviews
company/uber/CloneGraph.java
66
// According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." // Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): // Any live cell with fewer than two live neighbors dies, as if caused by under-population. // Any live cell with two or three live neighbors lives on to the next generation. // Any live cell with more than three live neighbors dies, as if by over-population.. // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. // Write a function to compute the next state (after one update) of the board given its current state. // Follow up: // Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. // In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? public class GameOfLife { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } int m = board.length; int n = board[0].length; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { int lives = liveNeighbors(board, m, n, i, j); if(board[i][j] == 1 && lives >= 2 && lives <= 3) { board[i][j] = 3; } if(board[i][j] == 0 && lives == 3) { board[i][j] = 2; } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { board[i][j] >>= 1; } } } private int liveNeighbors(int[][] board, int m, int n, int i, int j) { int lives = 0; for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) { for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) { lives += board[x][y] & 1; } } lives -= board[i][j] & 1; return lives; } }
kdn251/interviews
leetcode/array/GameOfLife.java
67
// According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." // Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): // Any live cell with fewer than two live neighbors dies, as if caused by under-population. // Any live cell with two or three live neighbors lives on to the next generation. // Any live cell with more than three live neighbors dies, as if by over-population.. // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. // Write a function to compute the next state (after one update) of the board given its current state. // Follow up: // Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. // In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? public class GameOfLife { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } int m = board.length; int n = board[0].length; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { int lives = liveNeighbors(board, m, n, i, j); if(board[i][j] == 1 && lives >= 2 && lives <= 3) { board[i][j] = 3; } if(board[i][j] == 0 && lives == 3) { board[i][j] = 2; } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { board[i][j] >>= 1; } } } private int liveNeighbors(int[][] board, int m, int n, int i, int j) { int lives = 0; for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) { for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) { lives += board[x][y] & 1; } } lives -= board[i][j] & 1; return lives; } }
kdn251/interviews
company/google/GameOfLife.java
68
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; /** * The LowerBound method is used to return an index pointing to the first * element in the range [first, last) which has a value not less than val, i.e. * the index of the next smallest number just greater than or equal to that * number. If there are multiple values that are equal to val it returns the * index of the first such value. * * <p> * This is an extension of BinarySearch. * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author Pratik Padalia (https://github.com/15pratik) * @see SearchAlgorithm * @see BinarySearch */ class LowerBound implements SearchAlgorithm { // Driver Program public static void main(String[] args) { // Just generate data Random r = ThreadLocalRandom.current(); int size = 100; int maxElement = 100000; Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new); // The element for which the lower bound is to be found int val = integers[r.nextInt(size - 1)] + 1; LowerBound search = new LowerBound(); int atIndex = search.find(integers, val); System.out.printf("Val: %d. Lower Bound Found %d at index %d. An array length %d%n", val, integers[atIndex], atIndex, size); boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val; System.out.printf("Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); } /** * @param array is an array where the LowerBound value is to be found * @param key is an element for which the LowerBound is to be found * @param <T> is any comparable type * @return index of the LowerBound element */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { return search(array, key, 0, array.length - 1); } /** * This method implements the Generic Binary Search * * @param array The array to make the binary search * @param key The number you are looking for * @param left The lower bound * @param right The upper bound * @return the location of the key */ private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } // find median int median = (left + right) >>> 1; int comp = key.compareTo(array[median]); if (comp == 0) { return median; } else if (comp < 0) { // median position can be a possible solution return search(array, key, left, median); } else { // key we are looking is greater, so we must look on the right of median position return search(array, key, median + 1, right); } } }
satishppawar/Java
src/main/java/com/thealgorithms/searches/LowerBound.java
69
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; /** * The UpperBound method is used to return an index pointing to the first * element in the range [first, last) which has a value greater than val, or the * last index if no such element exists i.e. the index of the next smallest * number just greater than that number. If there are multiple values that are * equal to val it returns the index of the first such value. * * <p> * This is an extension of BinarySearch. * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author Pratik Padalia (https://github.com/15pratik) * @see SearchAlgorithm * @see BinarySearch */ class UpperBound implements SearchAlgorithm { // Driver Program public static void main(String[] args) { // Just generate data Random r = ThreadLocalRandom.current(); int size = 100; int maxElement = 100000; Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new); // The element for which the upper bound is to be found int val = integers[r.nextInt(size - 1)] + 1; UpperBound search = new UpperBound(); int atIndex = search.find(integers, val); System.out.printf("Val: %d. Upper Bound Found %d at index %d. An array length %d%n", val, integers[atIndex], atIndex, size); boolean toCheck = integers[atIndex] > val || integers[size - 1] < val; System.out.printf("Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); } /** * @param array is an array where the UpperBound value is to be found * @param key is an element for which the UpperBound is to be found * @param <T> is any comparable type * @return index of the UpperBound element */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { return search(array, key, 0, array.length - 1); } /** * This method implements the Generic Binary Search * * @param array The array to make the binary search * @param key The number you are looking for * @param left The lower bound * @param right The upper bound * @return the location of the key */ private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } // find median int median = (left + right) >>> 1; int comp = key.compareTo(array[median]); if (comp < 0) { // key is smaller, median position can be a possible solution return search(array, key, left, median); } else { // key we are looking is greater, so we must look on the right of median position return search(array, key, median + 1, right); } } }
satishppawar/Java
src/main/java/com/thealgorithms/searches/UpperBound.java
70
/** * News agency pays money for articles according to some rules. Each character has its own value (some * characters may have value equals to zero). Author gets his payment as a sum of all character’s values * in the article. You have to determine the amount of money that news agency must pay to an author. * Input * The first line contains integer N (0 < N ≤ 5), it is a number of tests. Each test describes an integer * K (0 < K ≤ 100), the number of paid characters. On next K lines there are table of paid characters * and its values (character values are written in cents). If character can not be found in the table, then * its value is equal to zero. Next, there is integer M (0 < M ≤ 150000). Next M lines contain an article * itself. Each line can be up to 10000 characters length. Be aware of a large input size, the whole input * file is about 7MB. * Output * For each test print how much money publisher must pay for an article in format ‘x.yy$’. Where x is * a number of dollars without leading zeros, and yy number of cents with one leading zero if necessary. * Examples: ‘3.32$’, ‘13.07$’, ‘71.30$’, ‘0.09$’. * Sample Input * 1 * 7 * a 3 * W 10 * A 100 * , 10 * k 7 * . 3 * I 13 * 7 * ACM International Collegiate Programming Contest (abbreviated * as ACM-ICPC or just ICPC) is an annual multi-tiered competition * among the universities of the world. The ICPC challenges students * to set ever higher standards of excellence for themselves * through competition that rewards team work, problem analysis, * and rapid software development. * From Wikipedia. * Sample Output * 3.74$ */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2315 import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Newspaper { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { Map<String, Integer> values = new HashMap<String, Integer>(); int numberOfValuableCharacters = input.nextInt(); while (numberOfValuableCharacters != 0) { values.put(input.next(), input.nextInt()); numberOfValuableCharacters--; } int numberOfLines = input.nextInt(); input.nextLine(); double sum = 0; while (numberOfLines != 0) { String textAsString = input.nextLine(); for (int i = 0; i < textAsString.length(); i++) { String c = textAsString.charAt(i) + ""; if (values.containsKey(c)) { sum = sum + values.get(c); } } numberOfLines--; } sum = sum / 100; DecimalFormat formatter = new DecimalFormat("0.00"); String sumFormatted = formatter.format(sum); System.out.println(sumFormatted + "$"); numberOfTestCases--; } } }
kdn251/interviews
uva/Newspaper.java
71
//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } }
kdn251/interviews
company/microsoft/AddDigits.java
72
// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } }
kdn251/interviews
leetcode/array/FindTheCelebrity.java
73
// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } }
kdn251/interviews
company/facebook/FindTheCelebrity.java
74
// Given an encoded string, return it's decoded string. // The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. // You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. // Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. public class DecodeString { public String decodeString(String s) { //declare empty string String decoded = ""; //initialize stack to hold counts Stack<Integer> countStack = new Stack<Integer>(); //initalize stack to hold decoded string Stack<String> decodedStack = new Stack<String>(); //initialize index to zero int index = 0; //iterate through entire string while(index < s.length()) { //if the current character is numeric... if(Character.isDigit(s.charAt(index))) { int count = 0; //determine the number while(Character.isDigit(s.charAt(index))) { count = 10 * count + (s.charAt(index) - '0'); index++; } //push the number onto the count stack countStack.push(count); } else if(s.charAt(index) == '[') { //if the current character is an opening bracket decodedStack.push(decoded); decoded = ""; index++; } else if(s.charAt(index) == ']') { //if the current character is a closing bracket StringBuilder temp = new StringBuilder(decodedStack.pop()); int repeatTimes = countStack.pop(); for(int i = 0; i < repeatTimes; i++) { temp.append(decoded); } decoded = temp.toString(); index++; } else { //otherwise, append the current character to the decoded string decoded += s.charAt(index); index++; } } //return the decoded string return decoded; } }
kdn251/interviews
leetcode/stack/DecodeString.java
75
// Given an encoded string, return it's decoded string. // The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. // You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. // Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. public class DecodeString { public String decodeString(String s) { //declare empty string String decoded = ""; //initialize stack to hold counts Stack<Integer> countStack = new Stack<Integer>(); //initalize stack to hold decoded string Stack<String> decodedStack = new Stack<String>(); //initialize index to zero int index = 0; //iterate through entire string while(index < s.length()) { //if the current character is numeric... if(Character.isDigit(s.charAt(index))) { int count = 0; //determine the number while(Character.isDigit(s.charAt(index))) { count = 10 * count + (s.charAt(index) - '0'); index++; } //push the number onto the count stack countStack.push(count); } else if(s.charAt(index) == '[') { //if the current character is an opening bracket decodedStack.push(decoded); decoded = ""; index++; } else if(s.charAt(index) == ']') { //if the current character is a closing bracket StringBuilder temp = new StringBuilder(decodedStack.pop()); int repeatTimes = countStack.pop(); for(int i = 0; i < repeatTimes; i++) { temp.append(decoded); } decoded = temp.toString(); index++; } else { //otherwise, append the current character to the decoded string decoded += s.charAt(index); index++; } } //return the decoded string return decoded; } }
kdn251/interviews
company/google/DecodeString.java
76
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.recipes; import java.io.IOException; import java.security.cert.X509Certificate; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.tls.Certificates; import okhttp3.tls.HandshakeCertificates; public final class CustomTrust { // PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view // https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren't // sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com. // Typically developers will need to get a PEM file from their organization's TLS administrator. final X509Certificate comodoRsaCertificationAuthority = Certificates.decodeCertificatePem("" + "-----BEGIN CERTIFICATE-----\n" + "MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\n" + "hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\n" + "A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV\n" + "BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5\n" + "MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT\n" + "EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR\n" + "Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh\n" + "dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR\n" + "6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X\n" + "pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC\n" + "9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV\n" + "/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf\n" + "Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z\n" + "+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w\n" + "qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah\n" + "SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC\n" + "u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf\n" + "Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq\n" + "crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E\n" + "FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB\n" + "/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl\n" + "wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM\n" + "4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV\n" + "2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna\n" + "FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ\n" + "CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK\n" + "boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke\n" + "jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL\n" + "S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb\n" + "QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl\n" + "0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB\n" + "NVOFBkpdn627G190\n" + "-----END CERTIFICATE-----\n"); final X509Certificate entrustRootCertificateAuthority = Certificates.decodeCertificatePem("" + "-----BEGIN CERTIFICATE-----\n" + "MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC\n" + "VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0\n" + "Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW\n" + "KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl\n" + "cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw\n" + "NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw\n" + "NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy\n" + "ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV\n" + "BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ\n" + "KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo\n" + "Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4\n" + "4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9\n" + "KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI\n" + "rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi\n" + "94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB\n" + "sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi\n" + "gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo\n" + "kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE\n" + "vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA\n" + "A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t\n" + "O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua\n" + "AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP\n" + "9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/\n" + "eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m\n" + "0vdXcDazv/wor3ElhVsT/h5/WrQ8\n" + "-----END CERTIFICATE-----\n"); final X509Certificate letsEncryptCertificateAuthority = Certificates.decodeCertificatePem("" + "-----BEGIN CERTIFICATE-----\n" + "MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" + "MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" + "DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" + "SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" + "GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" + "AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" + "q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" + "SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" + "Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" + "a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" + "/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" + "AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" + "CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" + "bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" + "c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" + "VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" + "ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" + "MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" + "Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" + "AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" + "uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" + "wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" + "X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" + "PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" + "KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" + "-----END CERTIFICATE-----"); private final OkHttpClient client; public CustomTrust() { // This implementation just embeds the PEM files in Java strings; most applications will // instead read this from a resource file that gets bundled with the application. HandshakeCertificates certificates = new HandshakeCertificates.Builder() .addTrustedCertificate(letsEncryptCertificateAuthority) .addTrustedCertificate(entrustRootCertificateAuthority) .addTrustedCertificate(comodoRsaCertificationAuthority) // Uncomment if standard certificates are also required. //.addPlatformTrustedCertificates() .build(); client = new OkHttpClient.Builder() .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager()) .build(); } public void run() throws Exception { Request request = new Request.Builder() .url("https://publicobject.com/helloworld.txt") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } throw new IOException("Unexpected code " + response); } System.out.println(response.body().string()); } } public static void main(String... args) throws Exception { new CustomTrust().run(); } }
gesellix/okhttp
samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java
77
/** * In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in * which he made the following conjecture: * Every number greater than 2 can be written as the sum of three prime numbers. * Goldbach was considering 1 as a primer number, a convention that is no longer followed. Later on, * Euler re-expressed the conjecture as: * Every even number greater than or equal to 4 can be expressed as the sum of two prime * numbers. * For example: * • 8 = 3 + 5. Both 3 and 5 are odd prime numbers. * • 20 = 3 + 17 = 7 + 13. * • 42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23. * Today it is still unproven whether the conjecture is right. (Oh wait, I have the proof of course, but * it is too long to write it on the margin of this page.) * Anyway, your task is now to verify Goldbach’s conjecture as expressed by Euler for all even numbers * less than a million. * Input * The input file will contain one or more test cases. * Each test case consists of one even integer n with 6 ≤ n < 1000000. * Input will be terminated by a value of 0 for n. * Output * For each test case, print one line of the form n = a + b, where a and b are odd primes. Numbers and * operators should be separated by exactly one blank like in the sample output below. If there is more * than one pair of odd primes adding up to n, choose the pair where the difference b − a is maximized. * If there is no such pair, print a line saying ‘Goldbach's conjecture is wrong.’ * Sample Input * 8 * 20 * 42 * 0 * Sample Output * 8 = 3 + 5 * 20 = 3 + 17 * 42 = 5 + 37 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=484 import java.util.Scanner; public class GoldbachConjecture { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean[] isPrime = sieveOfEratosthenes(1000000); int number = input.nextInt(); while (number != 0) { boolean found = false; for (int i = 3; i < number && !found; i++) { if (isPrime[i]) { int currentPrime = i; int j = number - currentPrime; if (isPrime[j]) { System.out.println(number + " = " + currentPrime + " + " + j); found = true; } } } if (!found) { System.out.println("Goldbach's conjecture is wrong."); } number = input.nextInt(); } } private static boolean[] sieveOfEratosthenes(int number) { boolean[] isPrime = new boolean[number + 1]; for (int i = 2; i < number + 1; i++) { isPrime[i] = true; } for (int factor = 2; factor * factor <= number; factor++) { if (isPrime[factor]) { for (int j = factor; factor * j <= number; j++) { isPrime[factor * j] = false; } } } return isPrime; } }
kdn251/interviews
uva/GoldbachConjecture.java
78
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Helper class for loading the TensorFlow Java native library. * * <p>The Java TensorFlow bindings require a native (JNI) library. This library * (libtensorflow_jni.so on Linux, libtensorflow_jni.dylib on OS X, tensorflow_jni.dll on Windows) * can be made available to the JVM using the java.library.path System property (e.g., using * -Djava.library.path command-line argument). However, doing so requires an additional step of * configuration. * * <p>Alternatively, the native libraries can be packaed in a .jar, making them easily usable from * build systems like Maven. However, in such cases, the native library has to be extracted from the * .jar archive. * * <p>NativeLibrary.load() takes care of this. First looking for the library in java.library.path * and failing that, it tries to find the OS and architecture specific version of the library in the * set of ClassLoader resources (under org/tensorflow/native/OS-ARCH). The resources paths used for * lookup must be consistent with any packaging (such as on Maven Central) of the TensorFlow Java * native libraries. */ final class NativeLibrary { private static final boolean DEBUG = System.getProperty("org.tensorflow.NativeLibrary.DEBUG") != null; private static final String JNI_LIBNAME = "tensorflow_jni"; public static void load() { if (isLoaded() || tryLoadLibrary()) { // Either: // (1) The native library has already been statically loaded, OR // (2) The required native code has been statically linked (through a custom launcher), OR // (3) The native code is part of another library (such as an application-level library) // that has already been loaded. For example, tensorflow/tools/android/test and // tensorflow/tools/android/inference_interface include the required native code in // differently named libraries. // // Doesn't matter how, but it seems the native code is loaded, so nothing else to do. return; } // Native code is not present, perhaps it has been packaged into the .jar file containing this. // Extract the JNI library itself final String jniLibName = System.mapLibraryName(JNI_LIBNAME); final String jniResourceName = makeResourceName(jniLibName); log("jniResourceName: " + jniResourceName); final InputStream jniResource = NativeLibrary.class.getClassLoader().getResourceAsStream(jniResourceName); // Extract the JNI's dependency final String frameworkLibName = getVersionedLibraryName(System.mapLibraryName("tensorflow_framework")); final String frameworkResourceName = makeResourceName(frameworkLibName); log("frameworkResourceName: " + frameworkResourceName); final InputStream frameworkResource = NativeLibrary.class.getClassLoader().getResourceAsStream(frameworkResourceName); // Do not complain if the framework resource wasn't found. This may just mean that we're // building with --config=monolithic (in which case it's not needed and not included). if (jniResource == null) { throw new UnsatisfiedLinkError( String.format( "Cannot find TensorFlow native library for OS: %s, architecture: %s. See " + "https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md" + " for possible solutions (such as building the library from source). Additional" + " information on attempts to find the native library can be obtained by adding" + " org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.", os(), architecture())); } try { // Create a temporary directory for the extracted resource and its dependencies. final File tempPath = createTemporaryDirectory(); // Deletions are in the reverse order of requests, so we need to request that the directory be // deleted first, so that it is empty when the request is fulfilled. tempPath.deleteOnExit(); final String tempDirectory = tempPath.getCanonicalPath(); if (frameworkResource != null) { extractResource(frameworkResource, frameworkLibName, tempDirectory); } else { log( frameworkResourceName + " not found. This is fine assuming " + jniResourceName + " is not built to depend on it."); } System.load(extractResource(jniResource, jniLibName, tempDirectory)); } catch (IOException e) { throw new UnsatisfiedLinkError( String.format( "Unable to extract native library into a temporary file (%s)", e.toString())); } } private static boolean tryLoadLibrary() { try { System.loadLibrary(JNI_LIBNAME); return true; } catch (UnsatisfiedLinkError e) { log("tryLoadLibraryFailed: " + e.getMessage()); return false; } } private static boolean isLoaded() { try { TensorFlow.version(); log("isLoaded: true"); return true; } catch (UnsatisfiedLinkError e) { return false; } } private static boolean resourceExists(String baseName) { return NativeLibrary.class.getClassLoader().getResource(makeResourceName(baseName)) != null; } private static String getVersionedLibraryName(String libFilename) { final String versionName = getMajorVersionNumber(); // If we're on darwin, the versioned libraries look like blah.1.dylib. final String darwinSuffix = ".dylib"; if (libFilename.endsWith(darwinSuffix)) { final String prefix = libFilename.substring(0, libFilename.length() - darwinSuffix.length()); if (versionName != null) { final String darwinVersionedLibrary = prefix + "." + versionName + darwinSuffix; if (resourceExists(darwinVersionedLibrary)) { return darwinVersionedLibrary; } } else { // If we're here, we're on darwin, but we couldn't figure out the major version number. We // already tried the library name without any changes, but let's do one final try for the // library with a .so suffix. final String darwinSoName = prefix + ".so"; if (resourceExists(darwinSoName)) { return darwinSoName; } } } else if (libFilename.endsWith(".so")) { // Libraries ending in ".so" are versioned like "libfoo.so.1", so try that. final String versionedSoName = libFilename + "." + versionName; if (versionName != null && resourceExists(versionedSoName)) { return versionedSoName; } } // Otherwise, we've got no idea. return libFilename; } /** * Returns the major version number of this TensorFlow Java API, or {@code null} if it cannot be * determined. */ private static String getMajorVersionNumber() { InputStream resourceStream = NativeLibrary.class.getClassLoader().getResourceAsStream("tensorflow-version-info"); if (resourceStream == null) { return null; } try { Properties props = new Properties(); props.load(resourceStream); String version = props.getProperty("version"); // expecting a string like 1.14.0, we want to get the first '1'. int dotIndex; if (version == null || (dotIndex = version.indexOf('.')) == -1) { return null; } String majorVersion = version.substring(0, dotIndex); try { Integer.parseInt(majorVersion); return majorVersion; } catch (NumberFormatException unused) { return null; } } catch (IOException e) { log("failed to load tensorflow version info."); return null; } } private static String extractResource( InputStream resource, String resourceName, String extractToDirectory) throws IOException { final File dst = new File(extractToDirectory, resourceName); dst.deleteOnExit(); final String dstPath = dst.toString(); log("extracting native library to: " + dstPath); final long nbytes = copy(resource, dst); log(String.format("copied %d bytes to %s", nbytes, dstPath)); return dstPath; } private static String os() { final String p = System.getProperty("os.name").toLowerCase(); if (p.contains("linux")) { return "linux"; } else if (p.contains("os x") || p.contains("darwin")) { return "darwin"; } else if (p.contains("windows")) { return "windows"; } else { return p.replaceAll("\\s", ""); } } private static String architecture() { final String arch = System.getProperty("os.arch").toLowerCase(); return (arch.equals("amd64")) ? "x86_64" : arch; } private static void log(String msg) { if (DEBUG) { System.err.println("org.tensorflow.NativeLibrary: " + msg); } } private static String makeResourceName(String baseName) { return "org/tensorflow/native/" + String.format("%s-%s/", os(), architecture()) + baseName; } private static long copy(InputStream src, File dstFile) throws IOException { FileOutputStream dst = new FileOutputStream(dstFile); try { byte[] buffer = new byte[1 << 20]; // 1MB long ret = 0; int n = 0; while ((n = src.read(buffer)) >= 0) { dst.write(buffer, 0, n); ret += n; } return ret; } finally { dst.close(); src.close(); } } // Shamelessly adapted from Guava to avoid using java.nio, for Android API // compatibility. private static File createTemporaryDirectory() { File baseDirectory = new File(System.getProperty("java.io.tmpdir")); String directoryName = "tensorflow_native_libraries-" + System.currentTimeMillis() + "-"; for (int attempt = 0; attempt < 1000; attempt++) { File temporaryDirectory = new File(baseDirectory, directoryName + attempt); if (temporaryDirectory.mkdir()) { return temporaryDirectory; } } throw new IllegalStateException( "Could not create a temporary directory (tried to make " + directoryName + "*) to extract TensorFlow native libraries."); } private NativeLibrary() {} }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/NativeLibrary.java
79
/** * In an attempt to bolster her sagging palm-reading business, Madam Phoenix has decided to offer * several numerological treats to her customers. She has been able to convince them that the frequency * of occurrence of the digits in the decimal representation of factorials bear witness to their futures. * Unlike palm-reading, however, she can’t just conjure up these frequencies, so she has employed you to * determine these values. * (Recall that the definition of n! (that is, n factorial) is just 1 × 2 × 3 × · · · × n. As she expects to use * either the day of the week, the day of the month, or the day of the year as the value of n, you must be * able to determine the number of occurrences of each decimal digit in numbers as large as 366 factorial * (366!), which has 781 digits. * Madam Phoenix will be forever (or longer) in your debt; she might even give you a trip if you do * your job well! * Input * The input data for the program is simply a list of integers for which the digit counts are desired. All * of these input values will be less than or equal to 366 and greater than 0, except for the last integer, * which will be zero. Don’t bother to process this zero value; just stop your program at that point. * Output * The output format isn’t too critical, but you should make your program produce results that look * similar to those shown below. * Sample Input * 3 * 8 * 100 * 0 * Sample Output * 3! -- * (0) 0 (1) 0 (2) 0 (3) 0 (4) 0 * (5) 0 (6) 1 (7) 0 (8) 0 (9) 0 * 8! -- * (0) 2 (1) 0 (2) 1 (3) 1 (4) 1 * (5) 0 (6) 0 (7) 0 (8) 0 (9) 0 * 100! -- * (0) 30 (1) 15 (2) 19 (3) 10 (4) 10 * (5) 14 (6) 19 (7) 7 (8) 14 (9) 20 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=260 import java.math.BigInteger; import java.util.Scanner; public class FactorialFrequenices { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); while (number != 0) { BigInteger product = BigInteger.ONE; for (int i = 2; i < number + 1; i++) { product = product.multiply(BigInteger.valueOf(i)); } int[] digitCounter = new int[10]; BigInteger productValue = product; while (!productValue.equals(BigInteger.ZERO)) { digitCounter[Integer.valueOf(productValue.mod(BigInteger.TEN) .toString())]++; productValue = productValue.divide(BigInteger.TEN); } formatOutput(number, digitCounter); number = input.nextInt(); } } private static void formatOutput(int number, int[] digits) { System.out.println(number + "! --"); for (int i = 0; i < 10; i++) { if (i != 0 || i != 9 || i != 4) System.out.printf(" "); System.out.printf("(%d)%5d", i, digits[i]); if (i == 4 || i == 9) System.out.printf("\n"); } } }
kdn251/interviews
uva/FactorialFrequenices.java
80
/** * In positional notation we know the position of a digit indicates the weight of that digit toward the * value of a number. For example, in the base 10 number 362 we know that 2 has the weight 100 * , 6 * has the weight 101 * , and 3 has the weight 102 * , yielding the value 3 × 102 + 6 × 101 + 2 × 100 * , or just * 300 + 60 + 2. The same mechanism is used for numbers expressed in other bases. While most people * assume the numbers they encounter everyday are expressed using base 10, we know that other bases * are possible. In particular, the number 362 in base 9 or base 14 represents a totally different value than * 362 in base 10. * For this problem your program will presented with a sequence of pairs of integers. Let’s call the * members of a pair X and Y . What your program is to do is determine the smallest base for X and the * smallest base for Y (likely different from that for X) so that X and Y represent the same value. * Consider, for example, the integers 12 and 5. Certainly these are not equal if base 10 is used for * each. But suppose 12 was a base 3 number and 5 was a base 6 number? 12 base 3 = 1 × 3 * 1 + 2 × 3 * 0 * , * or 5 base 10, and certainly 5 in any base is equal to 5 base 10. So 12 and 5 can be equal, if you select * the right bases for each of them! * Input * On each line of the input data there will be a pair of integers, X and Y , separated by one or more blanks; * leading and trailing blanks may also appear on each line, are are to be ignored. The bases associated * with X and Y will be between 1 and 36 (inclusive), and as noted above, need not be the same for X and * Y . In representing these numbers the digits 0 through 9 have their usual decimal interpretations. The * uppercase alphabetic characters A through Z represent digits with values 10 through 35, respectively. * Output * For each pair of integers in the input display a message similar to those shown in the examples shown * below. Of course if the two integers cannot be equal regardless of the assumed base for each, then print * an appropriate message; a suitable illustration is given in the examples. * Sample Input * 12 5 * 10 A * 12 34 * 123 456 * 1 2 * 10 2 * Sample Output * 12 (base 3) = 5 (base 6) * 10 (base 10) = A (base 11) * 12 (base 17) = 34 (base 5) * 123 is not equal to 456 in any base 2..36 * 1 is not equal to 2 in any base 2..36 * 10 (base 2) = 2 (base 3) */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=279 import java.math.BigInteger; import java.util.Scanner; public class WhatBaseIsThis { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String x = input.next(); String y = input.next(); boolean found = false; for (int i = 2; i < 37 && !found; i++) { BigInteger xConvertedToBase; try { xConvertedToBase = new BigInteger(x, i); } catch (Exception e) { continue; } for (int j = 2; j < 37; j++) { BigInteger yConvertedToBase; try { yConvertedToBase = new BigInteger(y, j); } catch (Exception e) { continue; } if (xConvertedToBase.equals(yConvertedToBase)) { System.out.println(x + " (base " + i + ") = " + y + " (base " + j + ")"); found = true; break; } } } if (!found) { System.out.println(x + " is not equal to " + y + " in any base 2..36"); } } } }
kdn251/interviews
uva/WhatBaseIsThis.java
81
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.op; import org.tensorflow.ExecutionEnvironment; import org.tensorflow.Operand; import org.tensorflow.OperationBuilder; import java.util.ArrayList; /** * Manages groups of related properties when creating Tensorflow Operations, such as a common name * prefix. * * <p>A {@code Scope} is a container for common properties applied to TensorFlow Ops. Normal user * code initializes a {@code Scope} and provides it to Operation building classes. For example: * * <pre>{@code * Scope scope = new Scope(graph); * Constant c = Constant.create(scope, 42); * }</pre> * * <p>An Operation building class acquires a Scope, and uses it to set properties on the underlying * Tensorflow ops. For example: * * <pre>{@code * // An operator class that adds a constant. * public class Constant { * public static Constant create(Scope scope, ...) { * scope.graph().opBuilder( * "Const", scope.makeOpName("Const")) * .setAttr(...) * .build() * ... * } * } * }</pre> * * <p><b>Scope hierarchy:</b> * * <p>A {@code Scope} provides various {@code with()} methods that create a new scope. The new scope * typically has one property changed while other properties are inherited from the parent scope. * * <p>An example using {@code Constant} implemented as before: * * <pre>{@code * Scope root = new Scope(graph); * * // The linear subscope will generate names like linear/... * Scope linear = Scope.withSubScope("linear"); * * // This op name will be "linear/W" * Constant.create(linear.withName("W"), ...); * * // This op will be "linear/Const", using the default * // name provided by Constant * Constant.create(linear, ...); * * // This op will be "linear/Const_1", using the default * // name provided by Constant and making it unique within * // this scope * Constant.create(linear, ...); * }</pre> * * <p>Scope objects are <b>not</b> thread-safe. */ public final class Scope { /** * Create a new top-level scope. * * @param env The execution environment used by the scope. */ public Scope(ExecutionEnvironment env) { this(env, new NameScope(), new ArrayList<Operand<?>>()); } /** Returns the execution environment used by this scope. */ public ExecutionEnvironment env() { return env; } /** * Returns a new scope where added operations will have the provided name prefix. * * <p>Ops created with this scope will have {@code name/childScopeName/} as the prefix. The actual * name will be unique in the returned scope. All other properties are inherited from the current * scope. * * <p>The child scope name must match the regular expression {@code [A-Za-z0-9.][A-Za-z0-9_.\-]*} * * @param childScopeName name for the new child scope * @return a new subscope * @throws IllegalArgumentException if the name is invalid */ public Scope withSubScope(String childScopeName) { return new Scope(env, nameScope.withSubScope(childScopeName), controlDependencies); } /** * Return a new scope that uses the provided name for an op. * * <p>Operations created within this scope will have a name of the form {@code * name/opName[_suffix]}. This lets you name a specific operator more meaningfully. * * <p>Names must match the regular expression {@code [A-Za-z0-9.][A-Za-z0-9_.\-]*} * * @param opName name for an operator in the returned scope * @return a new Scope that uses opName for operations. * @throws IllegalArgumentException if the name is invalid */ public Scope withName(String opName) { return new Scope(env, nameScope.withName(opName), controlDependencies); } /** * Create a unique name for an operator, using a provided default if necessary. * * <p>This is normally called only by operator building classes. * * <p>This method generates a unique name, appropriate for the name scope controlled by this * instance. Typical operator building code might look like * * <pre>{@code * scope.env().opBuilder("Const", scope.makeOpName("Const"))... * }</pre> * * <p><b>Note:</b> if you provide a composite operator building class (i.e, a class that creates a * set of related operations by calling other operator building code), the provided name will act * as a subscope to all underlying operators. * * @param defaultName name for the underlying operator. * @return unique name for the operator. * @throws IllegalArgumentException if the default name is invalid. */ public String makeOpName(String defaultName) { return nameScope.makeOpName(defaultName); } private Scope( ExecutionEnvironment env, NameScope nameScope, Iterable<Operand<?>> controlDependencies) { this.env = env; this.nameScope = nameScope; this.controlDependencies = controlDependencies; } /** * Returns a new scope where added operations will have the provided control dependencies. * * <p>Ops created with this scope will have a control edge from each of the provided controls. All * other properties are inherited from the current scope. * * @param controls control dependencies for ops created with the returned scope * @return a new scope with the provided control dependencies */ public Scope withControlDependencies(Iterable<Operand<?>> controls) { return new Scope(env, nameScope, controls); } /** * Adds each Operand in controlDependencies as a control input to the provided builder. * * @param builder OperationBuilder to add control inputs to */ public OperationBuilder applyControlDependencies(OperationBuilder builder) { for (Operand<?> control : controlDependencies) { builder = builder.addControlInput(control.asOutput().op()); } return builder; } private final ExecutionEnvironment env; private final Iterable<Operand<?>> controlDependencies; private final NameScope nameScope; }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/op/Scope.java
82
// Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. // Example: // For num = 5 you should return [0,1,1,2,1,2]. // Follow up: // It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? // Space complexity should be O(n). // Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. public class CountingBits { public int[] countBits(int num) { int[] bits = new int[num + 1]; bits[0] = 0; for(int i = 1; i <= num; i++) { bits[i] = bits[i >> 1] + (i & 1); } return bits; } }
kdn251/interviews
leetcode/dynamic-programming/CountingBits.java
83
// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. // Calling next() will return the next smallest number in the BST. // Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinarySearchTreeIterator { Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<TreeNode>(); while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty() ? false : true; } /** @return the next smallest number */ public int next() { TreeNode nextSmallest = stack.pop(); TreeNode addToStack = nextSmallest.right; while(addToStack != null) { stack.add(addToStack); addToStack = addToStack.left; } return nextSmallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
kdn251/interviews
company/facebook/BinarySearchTreeIterator.java
84
// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. // Calling next() will return the next smallest number in the BST. // Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinarySearchTreeIterator { Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<TreeNode>(); while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty() ? false : true; } /** @return the next smallest number */ public int next() { TreeNode nextSmallest = stack.pop(); TreeNode addToStack = nextSmallest.right; while(addToStack != null) { stack.add(addToStack); addToStack = addToStack.left; } return nextSmallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
kdn251/interviews
company/linkedin/BinarySearchTreeIterator.java
85
//Say you have an array for which the ith element is the price of a given stock on day i. //Design an algorithm to find the maximum profit. You may complete as many transactions as you //like (ie, buy one and sell one share of the stock multiple times). However, you may not engage //in multiple transactions at the same time (ie, you must sell the stock before you buy again). class BestTimeToBuyAndSellStockII { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) { return 0; } int profit = 0; for(int i = 0; i < prices.length - 1; i++) { if(prices[i] < prices[i + 1]) { profit += prices[i + 1] - prices[i]; } } return profit; } }
kdn251/interviews
leetcode/greedy/BestTimeToBuyAndSellStockII.java
86
package com.thealgorithms.others; import java.util.Arrays; import java.util.Objects; /** * The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod * 10" algorithm, named after its creator, IBM scientist Hans Peter Luhn, is a * simple checksum formula used to validate a variety of identification numbers. * * <p> * The algorithm is in the public domain and is in wide use today. It is * specified in ISO/IEC 7812-1. It is not intended to be a cryptographically * secure hash function; it was designed to protect against accidental errors, * not malicious attacks. Most credit cards and many government identification * numbers use the algorithm as a simple method of distinguishing valid numbers * from mistyped or otherwise incorrect numbers.</p> * * <p> * The Luhn algorithm will detect any single-digit error, as well as almost all * transpositions of adjacent digits. It will not, however, detect transposition * of the two-digit sequence 09 to 90 (or vice versa). It will detect most of * the possible twin errors (it will not detect 22 ↔ 55, 33 ↔ 66 or 44 ↔ * 77).</p> * * <p> * The check digit is computed as follows:</p> * <ol> * <li>Take the original number and starting from the rightmost digit moving * left, double the value of every second digit (including the rightmost * digit).</li> * <li>Replace the resulting value at each position with the sum of the digits * of this position's value or just subtract 9 from all numbers more or equal * then 10.</li> * <li>Sum up the resulting values from all positions (s).</li> * <li>The calculated check digit is equal to {@code 10 - s % 10}.</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Luhn_algorithm">Wiki</a> */ public final class Luhn { private Luhn() { } /** * Check input digits array by Luhn algorithm. Initial array doesn't change * while processing. * * @param digits array of digits from 0 to 9 * @return true if check was successful, false otherwise */ public static boolean luhnCheck(int[] digits) { int[] numbers = Arrays.copyOf(digits, digits.length); int sum = 0; for (int i = numbers.length - 1; i >= 0; i--) { if (i % 2 == 0) { int temp = numbers[i] * 2; if (temp > 9) { temp = temp - 9; } numbers[i] = temp; } sum += numbers[i]; } return sum % 10 == 0; } public static void main(String[] args) { System.out.println("Luhn algorithm usage examples:"); int[] validInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7}; int[] invalidInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4}; // typo in last // symbol checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nBusiness examples:"); String validCardNumber = "5265 9251 6151 1412"; String invalidCardNumber = "4929 3231 3088 1896"; String illegalCardNumber = "4F15 BC06 3A88 76D5"; businessExample(validCardNumber); businessExample(invalidCardNumber); businessExample(illegalCardNumber); } private static void checkAndPrint(int[] input) { String validationResult = Luhn.luhnCheck(input) ? "valid" : "not valid"; System.out.println("Input " + Arrays.toString(input) + " is " + validationResult); } /* ======================== Business usage example ======================== */ /** * Object representation of credit card. */ private record CreditCard(int[] digits) { private static final int DIGITS_COUNT = 16; /** * @param cardNumber string representation of credit card number - 16 * digits. Can have spaces for digits separation * @return credit card object * @throws IllegalArgumentException if input string is not 16 digits or * if Luhn check was failed */ public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); String trimmedCardNumber = cardNumber.replaceAll(" ", ""); if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) { throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number"); } int[] cardNumbers = toIntArray(trimmedCardNumber); boolean isValid = luhnCheck(cardNumbers); if (!isValid) { throw new IllegalArgumentException("Credit card number {" + cardNumber + "} - have a typo"); } return new CreditCard(cardNumbers); } /** * @return string representation separated by space every 4 digits. * Example: "5265 9251 6151 1412" */ public String number() { StringBuilder result = new StringBuilder(); for (int i = 0; i < DIGITS_COUNT; i++) { if (i % 4 == 0 && i != 0) { result.append(" "); } result.append(digits[i]); } return result.toString(); } @Override public String toString() { return String.format("%s {%s}", CreditCard.class.getSimpleName(), number()); } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } } private static void businessExample(String cardNumber) { try { System.out.println("Trying to create CreditCard object from valid card number: " + cardNumber); CreditCard creditCard = CreditCard.fromString(cardNumber); System.out.println("And business object is successfully created: " + creditCard + "\n"); } catch (IllegalArgumentException e) { System.out.println("And fail with exception message: " + e.getMessage() + "\n"); } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Luhn.java
87
package com.thealgorithms.maths; import java.util.Arrays; /** * Wikipedia: https://en.wikipedia.org/wiki/Median */ public final class Median { private Median() { } /** * Calculate average median * @param values sorted numbers to find median of * @return median of given {@code values} */ public static double median(int[] values) { Arrays.sort(values); int length = values.length; return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2]; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/Median.java
88
package com.thealgorithms.others; import java.util.Arrays; /** * BFPRT algorithm. */ public final class BFPRT { private BFPRT() { } public static int[] getMinKNumsByBFPRT(int[] arr, int k) { if (k < 1 || k > arr.length) { return null; } int minKth = getMinKthByBFPRT(arr, k); int[] res = new int[k]; int index = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < minKth) { res[index++] = arr[i]; } } for (; index != res.length; index++) { res[index] = minKth; } return res; } public static int getMinKthByBFPRT(int[] arr, int k) { int[] copyArr = copyArray(arr); return bfprt(copyArr, 0, copyArr.length - 1, k - 1); } public static int[] copyArray(int[] arr) { int[] copyArr = new int[arr.length]; for (int i = 0; i < arr.length; i++) { copyArr[i] = arr[i]; } return copyArr; } public static int bfprt(int[] arr, int begin, int end, int i) { if (begin == end) { return arr[begin]; } int pivot = medianOfMedians(arr, begin, end); int[] pivotRange = partition(arr, begin, end, pivot); if (i >= pivotRange[0] && i <= pivotRange[1]) { return arr[i]; } else if (i < pivotRange[0]) { return bfprt(arr, begin, pivotRange[0] - 1, i); } else { return bfprt(arr, pivotRange[1] + 1, end, i); } } /** * wikipedia: https://en.wikipedia.org/wiki/Median_of_medians . * * @param arr an array. * @param begin begin num. * @param end end num. * @return median of medians. */ public static int medianOfMedians(int[] arr, int begin, int end) { int num = end - begin + 1; int offset = num % 5 == 0 ? 0 : 1; int[] mArr = new int[num / 5 + offset]; for (int i = 0; i < mArr.length; i++) { mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); } return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); } public static void swap(int[] arr, int i, int j) { int swap = arr[i]; arr[i] = arr[j]; arr[j] = swap; } public static int[] partition(int[] arr, int begin, int end, int num) { int small = begin - 1; int cur = begin; int big = end + 1; while (cur != big) { if (arr[cur] < num) { swap(arr, ++small, cur++); } else if (arr[cur] > num) { swap(arr, --big, cur); } else { cur++; } } int[] pivotRange = new int[2]; pivotRange[0] = small + 1; pivotRange[1] = big - 1; return pivotRange; } public static int getMedian(int[] arr, int begin, int end) { insertionSort(arr, begin, end); int sum = begin + end; int mid = sum / 2 + (sum % 2); return arr[mid]; } public static void insertionSort(int[] arr, int begin, int end) { if (arr == null || arr.length < 2) { return; } for (int i = begin + 1; i != end + 1; i++) { for (int j = i; j != begin; j--) { if (arr[j - 1] > arr[j]) { swap(arr, j - 1, j); } else { break; } } } } public static void main(String[] args) { int[] arr = { 11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9, }; int[] minK = getMinKNumsByBFPRT(arr, 5); System.out.println(Arrays.toString(minK)); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/BFPRT.java
89
// Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island // by building roads, settlements and cities across its uncharted wilderness. // You are employed by a software company that just has decided to develop a computer version of // this game, and you are chosen to implement one of the game’s special rules: // When the game ends, the player who built the longest road gains two extra victory points. // The problem here is that the players usually build complex road networks and not just one linear // path. Therefore, determining the longest road is not trivial (although human players usually see it // immediately). // Compared to the original game, we will solve a simplified problem here: You are given a set of nodes // (cities) and a set of edges (road segments) of length 1 connecting the nodes. // The longest road is defined as the longest path within the network that doesn’t use an edge twice. // Nodes may be visited more than once, though. // Input // The input file will contain one or more test cases. // The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the // number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the // numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected. // Nodes have degrees of three or less. The network is not neccessarily connected. // Input will be terminated by two values of 0 for n and m. // Output // For each test case, print the length of the longest road on a single line. // Sample Input // 3 2 // 0 1 // 1 2 // 15 16 // 0 2 // 1 2 // 2 3 // 3 4 // 3 5 // 4 6 // 5 7 // 6 8 // 7 8 // 7 9 // 8 10 // 9 11 // 10 12 // 11 12 // 10 13 // 12 14 // 0 0 // Sample Output // 2 // 12 import java.io.*; /** * Created by kdn251 on 2/20/17. */ public class TheSettlersOfCatan { public static int[][] matrix = new int[30][30]; public static int answer; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate while current line is not equal to 0 0 while(!(line = br.readLine()).equals("0 0")) { //initialize number of nodes and edges int nodes = Integer.parseInt(line.split(" ")[0]); int edges = Integer.parseInt(line.split(" ")[1]); //iterate through all edges for(int i = 0; i < edges; i++) { //get edge between node x and node y String[] current = br.readLine().split(" "); int x = Integer.parseInt(current[0]); int y = Integer.parseInt(current[1]); //mark edge matrix[x][y] = 1; matrix[y][x] = 1; } //initialize answer to zero answer = 0; //dfs on every node for(int i = 0; i < nodes; i++) { dfs(i, 0, nodes); } //print answer System.out.println(answer); //reset graph matrix = new int[30][30]; } } public static void dfs(int nd, int l, int nodes) { //update answer if l is larger than current answer if(l > answer) { answer = l; } for(int i = 0; i < nodes; i++) { if(matrix[nd][i] > 0) { //ensure that edge is not counted twice (like marking as "visited") matrix[nd][i] = 0; matrix[i][nd] = 0; //continue traversing graph and add 1 to count dfs(i, l + 1, nodes); //set current edge again in case node further into graph can reach it matrix[nd][i] = 1; matrix[i][nd] = 1; } } } } //source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp
kdn251/interviews
uva/TheSettlersOfCatan.java
90
package com.thealgorithms.sorts; import static com.thealgorithms.sorts.SortUtils.less; /** * This is simplified TimSort algorithm implementation. The original one is more complicated. * <p> * For more details @see <a href="https://en.wikipedia.org/wiki/Timsort">TimSort Algorithm</a> */ class TimSort implements SortAlgorithm { private static final int SUB_ARRAY_SIZE = 32; private Comparable[] aux; @Override public <T extends Comparable<T>> T[] sort(T[] a) { int n = a.length; InsertionSort insertionSort = new InsertionSort(); for (int i = 0; i < n; i += SUB_ARRAY_SIZE) { insertionSort.sort(a, i, Math.min(i + SUB_ARRAY_SIZE, n)); } aux = new Comparable[n]; for (int sz = SUB_ARRAY_SIZE; sz < n; sz = sz + sz) { for (int lo = 0; lo < n - sz; lo += sz + sz) { merge(a, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, n - 1)); } } return a; } private <T extends Comparable<T>> void merge(T[] a, int lo, int mid, int hi) { int i = lo, j = mid + 1; System.arraycopy(a, lo, aux, lo, hi + 1 - lo); for (int k = lo; k <= hi; k++) { if (j > hi) { a[k] = (T) aux[i++]; } else if (i > mid) { a[k] = (T) aux[j++]; } else if (less(aux[j], aux[i])) { a[k] = (T) aux[j++]; } else { a[k] = (T) aux[i++]; } } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/TimSort.java
91
package com.thealgorithms.misc; import java.util.Scanner; /** * The array is divided into four sections: a[1..Lo-1] zeroes a[Lo..Mid-1] ones * a[Mid..Hi] unknown a[Hi+1..N] twos If array [mid] =0, then swap array [mid] * with array [low] and increment both pointers once. If array [mid] = 1, then * no swapping is required. Increment mid pointer once. If array [mid] = 2, then * we swap array [mid] with array [high] and decrement the high pointer once. * For more information on the Dutch national flag algorithm refer * https://en.wikipedia.org/wiki/Dutch_national_flag_problem */ public final class Sort012D { private Sort012D() { } public static void main(String[] args) { Scanner np = new Scanner(System.in); int n = np.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = np.nextInt(); } sort012(a); np.close(); } public static void sort012(int[] a) { int l = 0; int h = a.length - 1; int mid = 0; int temp; while (mid <= h) { switch (a[mid]) { case 0: { temp = a[l]; a[l] = a[mid]; a[mid] = temp; l++; mid++; break; } case 1: mid++; break; case 2: { temp = a[mid]; a[mid] = a[h]; a[h] = temp; h--; break; } } } System.out.println("the Sorted array is "); for (int i = 0; i < a.length; i++) { System.out.print(+a[i] + " "); } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/misc/Sort012D.java
92
package com.thealgorithms.others; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public final class Conway { private Conway() { } /* * This class will generate the conway sequence also known as the look and say sequence. * To generate a member of the sequence from the previous member, read off the digits of the *previous member, counting the number of digits in groups of the same digit. For example: 1 is *read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, one 1" *or 1211. 1211 is read off as "one 1, one 2, two 1s" or 111221. 111221 is read off as "three *1s, two 2s, one 1" or 312211. https://en.wikipedia.org/wiki/Look-and-say_sequence * */ private static final StringBuilder BUILDER = new StringBuilder(); protected static List<String> generateList(String originalString, int maxIteration) { List<String> numbers = new ArrayList<>(); for (int i = 0; i < maxIteration; i++) { originalString = generateNextElement(originalString); numbers.add(originalString); } return numbers; } public static String generateNextElement(String originalString) { BUILDER.setLength(0); String[] stp = originalString.split("(?<=(.))(?!\\1)"); Arrays.stream(stp).forEach(s -> BUILDER.append(s.length()).append(s.charAt(0))); return BUILDER.toString(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Conway.java
93
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { // To find gap between elements private int nextGap(int gap) { // Shrink gap by Shrink factor gap = (gap * 10) / 13; return Math.max(gap, 1); } /** * Function to sort arr[] using Comb * * @param arr - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int size = arr.length; // initialize gap int gap = size; // Initialize swapped as true to make sure that loop runs boolean swapped = true; // Keep running while gap is more than 1 and last iteration caused a swap while (gap != 1 || swapped) { // Find next gap gap = nextGap(gap); // Initialize swapped as false so that we can check if swap happened or not swapped = false; // Compare all elements with current gap for (int i = 0; i < size - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { // Swap arr[i] and arr[i+gap] SortUtils.swap(arr, i, i + gap); swapped = true; } } } return arr; } // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); Integer[] arr = { 8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0, }; ob.sort(arr); System.out.println("sorted array"); SortUtils.print(arr); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/CombSort.java
94
package com.thealgorithms.misc; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /* * MapReduce is a programming model for processing and generating large data sets with a parallel, distributed algorithm on a cluster. * It has two main steps: the Map step, where the data is divided into smaller chunks and processed in parallel, and the Reduce step, where the results from the Map step are combined to produce the final output. * Wikipedia link : https://en.wikipedia.org/wiki/MapReduce */ public final class MapReduce { private MapReduce() { } /* *Counting all the words frequency within a sentence. */ public static String mapreduce(String sentence) { List<String> wordList = Arrays.stream(sentence.split(" ")).toList(); // Map step Map<String, Long> wordCounts = wordList.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())); // Reduce step StringBuilder result = new StringBuilder(); wordCounts.forEach((word, count) -> result.append(word).append(": ").append(count).append(",")); // Removing the last ',' if it exists if (!result.isEmpty()) { result.setLength(result.length() - 1); } return result.toString(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/misc/MapReduce.java
95
package com.thealgorithms.sorts; import java.util.Random; /** * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SortAlgorithm */ public class BogoSort implements SortAlgorithm { private static final Random RANDOM = new Random(); private static <T extends Comparable<T>> boolean isSorted(T[] array) { for (int i = 0; i < array.length - 1; i++) { if (SortUtils.less(array[i + 1], array[i])) { return false; } } return true; } // Randomly shuffles the array private static <T> void nextPermutation(T[] array) { int length = array.length; for (int i = 0; i < array.length; i++) { int randomIndex = i + RANDOM.nextInt(length - i); SortUtils.swap(array, randomIndex, i); } } public <T extends Comparable<T>> T[] sort(T[] array) { while (!isSorted(array)) { nextPermutation(array); } return array; } // Driver Program public static void main(String[] args) { // Integer Input Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; BogoSort bogoSort = new BogoSort(); // print a sorted array SortUtils.print(bogoSort.sort(integers)); // String Input String[] strings = {"c", "a", "e", "b", "d"}; SortUtils.print(bogoSort.sort(strings)); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/BogoSort.java
96
// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorsOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } }
kdn251/interviews
company/facebook/LowestCommonAncestorOfABinaryTree.java
97
package com.thealgorithms.strings; import java.util.HashSet; /** * Wikipedia: https://en.wikipedia.org/wiki/Pangram */ public final class Pangram { private Pangram() { } /** * Test code */ public static void main(String[] args) { assert isPangram("The quick brown fox jumps over the lazy dog"); assert !isPangram("The quick brown fox jumps over the azy dog"); // L is missing assert !isPangram("+-1234 This string is not alphabetical"); assert !isPangram("\u0000/\\"); } /** * Checks if a String is considered a Pangram * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ // alternative approach using Java Collection Framework public static boolean isPangramUsingSet(String s) { HashSet<Character> alpha = new HashSet<>(); s = s.trim().toLowerCase(); for (int i = 0; i < s.length(); i++) if (s.charAt(i) != ' ') alpha.add(s.charAt(i)); return alpha.size() == 26; } /** * Checks if a String is considered a Pangram * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ public static boolean isPangram(String s) { boolean[] lettersExisting = new boolean[26]; for (char c : s.toCharArray()) { int letterIndex = c - (Character.isUpperCase(c) ? 'A' : 'a'); if (letterIndex >= 0 && letterIndex < lettersExisting.length) { lettersExisting[letterIndex] = true; } } for (boolean letterFlag : lettersExisting) { if (!letterFlag) { return false; } } return true; } /** * Checks if a String is Pangram or not by checking if each alhpabet is present or not * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ public static boolean isPangram2(String s) { if (s.length() < 26) { return false; } s = s.toLowerCase(); // Converting s to Lower-Case for (char i = 'a'; i <= 'z'; i++) { if (s.indexOf(i) == -1) { return false; // if any alphabet is not present, return false } } return true; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/strings/Pangram.java
98
package com.thealgorithms.sorts; /** * Implementation of gnome sort * * @author Podshivalov Nikita (https://github.com/nikitap492) * @since 2018-04-10 */ public class GnomeSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int i = 1; int j = 2; while (i < arr.length) { if (SortUtils.less(arr[i - 1], arr[i])) { i = j++; } else { SortUtils.swap(arr, i - 1, i); if (--i == 0) { i = j++; } } } return null; } public static void main(String[] args) { Integer[] integers = { 4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12, }; String[] strings = { "c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z", }; GnomeSort gnomeSort = new GnomeSort(); gnomeSort.sort(integers); gnomeSort.sort(strings); System.out.println("After sort : "); SortUtils.print(integers); SortUtils.print(strings); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/GnomeSort.java
99
package com.thealgorithms.others; import java.util.Objects; /** * The Verhoeff algorithm is a checksum formula for error detection developed by * the Dutch mathematician Jacobus Verhoeff and was first published in 1969. It * was the first decimal check digit algorithm which detects all single-digit * errors, and all transposition errors involving two adjacent digits. * * <p> * The strengths of the algorithm are that it detects all transliteration and * transposition errors, and additionally most twin, twin jump, jump * transposition and phonetic errors. The main weakness of the Verhoeff * algorithm is its complexity. The calculations required cannot easily be * expressed as a formula. For easy calculation three tables are required:</p> * <ol> * <li>multiplication table</li> * <li>inverse table</li> * <li>permutation table</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wiki. * Verhoeff algorithm</a> */ public final class Verhoeff { private Verhoeff() { } /** * Table {@code d}. Based on multiplication in the dihedral group D5 and is * simply the Cayley table of the group. Note that this group is not * commutative, that is, for some values of {@code j} and {@code k}, * {@code d(j,k) ≠ d(k, j)}. * * @see <a href="https://en.wikipedia.org/wiki/Dihedral_group">Wiki. * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ private static final byte[] MULTIPLICATIVE_INVERSE = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9, }; /** * The permutation table {@code p}. Applies a permutation to each digit * based on its position in the number. This is actually a single * permutation {@code (1 5 8 9 4 2 7 0)(3 6)} applied iteratively; i.e. * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** * Check input digits by Verhoeff algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); // The Verhoeff algorithm int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); // Add zero to end of input value var modifiedDigits = initialDigits + "0"; int[] numbers = toIntArray(modifiedDigits); int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } checksum = MULTIPLICATIVE_INVERSE[checksum]; return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Verhoeff algorithm usage examples:"); var validInput = "2363"; var invalidInput = "2364"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "236"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Verhoeff.java
100
package com.thealgorithms.maths; /* * Java program to find 'twin prime' of a prime number * Twin Prime: Twin prime of a number n is (n+2) * if and only if n & (n+2) are prime. * Wikipedia: https://en.wikipedia.org/wiki/Twin_prime * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class TwinPrime { private TwinPrime() { } /** * This method returns twin prime of the integer value passed as argument * * @param input_number Integer value of which twin prime is to be found * @return (number + 2) if number and (number + 2) are prime, -1 otherwise */ static int getTwinPrime(int inputNumber) { // if inputNumber and (inputNumber + 2) are both prime // then return (inputNumber + 2) as a result if (PrimeCheck.isPrime(inputNumber) && PrimeCheck.isPrime(inputNumber + 2)) { return inputNumber + 2; } // if any one from inputNumber and (inputNumber + 2) or if both of them are not prime // then return -1 as a result return -1; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/TwinPrime.java