file_id
int64 1
215k
| content
stringlengths 7
454k
| repo
stringlengths 6
113
| path
stringlengths 6
251
|
---|---|---|---|
214,099 | /**
* Packer version 3.0 (final)
* Copyright 2004-2007, Dean Edwards
* Web: {@link http://dean.edwards.name/}
*
* This software is licensed under the MIT license
* Web: {@link http://www.opensource.org/licenses/mit-license}
*
* Ported to Java by Pablo Santiago based on C# version by Jesse Hansen, <twindagger2k @ msn.com>
* Web: {@link http://jpacker.googlecode.com/}
* Email: <pablo.santiago @ gmail.com>
*/
package com.jpacker.evaluators;
import com.jpacker.JPackerPattern;
/**
* Abstract class for {@link Evaluator} objects. Its purpose is to provide the
* implementation of a getter and setter of a {@link JPackerPattern} object.
*
* @author Pablo Santiago <pablo.santiago @ gmail.com>
*/
public abstract class AbstractEvaluator implements Evaluator {
private JPackerPattern jpattern;
/**
* Gets the {@link JPackerPattern} object
*
* @return The {@link JPackerPattern} object
*/
@Override
public JPackerPattern getJPattern() {
return jpattern;
}
/**
* Sets the {@link JPackerPattern} object for this {@link Evaluator} object
*
* @param jpattern
* The {@link JPackerPattern} object to set
*/
@Override
public void setJPattern(JPackerPattern jpattern) {
this.jpattern = jpattern;
}
}
| jindrapetrik/jpexs-decompiler | libsrc/jpacker/src/com/jpacker/evaluators/AbstractEvaluator.java |
214,100 | /**
* Packer version 3.0 (final)
* Copyright 2004-2007, Dean Edwards
* Web: {@link http://dean.edwards.name/}
*
* This software is licensed under the MIT license
* Web: {@link http://www.opensource.org/licenses/mit-license}
*
* Ported to Java by Pablo Santiago based on C# version by Jesse Hansen, <twindagger2k @ msn.com>
* Web: {@link http://jpacker.googlecode.com/}
* Email: <pablo.santiago @ gmail.com>
*/
package com.jpacker;
import com.jpacker.exceptions.EmptyFileException;
import jargs.gnu.CmdLineParser;
import jargs.gnu.CmdLineParser.IllegalOptionValueException;
import jargs.gnu.CmdLineParser.Option;
import jargs.gnu.CmdLineParser.UnknownOptionException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
*
* @author Pablo Santiago <pablo.santiago @ gmail.com>
*/
public class JPacker {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
long startTime = System.currentTimeMillis();
CmdLineParser parser = new CmdLineParser();
Option baseOpt = parser.addIntegerOption('b', "base");
Option columnsOpt = parser.addIntegerOption('c', "column");
Option helpOpt = parser.addBooleanOption('h', "help");
Option minifyOpt = parser.addBooleanOption('m', "minify");
Option outputFilenameOpt = parser.addStringOption('o', "output");
Option quietOpt = parser.addBooleanOption('q', "quiet");
Option shrinkVariablesOpt = parser.addBooleanOption('s', "shrink-variables");
Writer out = null;
BufferedReader in = null;
try {
if (args.length == 0) {
throw new RuntimeException("No input file");
}
parser.parse(args);
Boolean help = (Boolean) parser.getOptionValue(helpOpt);
if (help != null && help.booleanValue()) {
printUsage();
System.exit(0);
}
boolean minify = parser.getOptionValue(minifyOpt) != null;
boolean shrinkVariables = parser.getOptionValue(shrinkVariablesOpt) != null;
boolean quiet = parser.getOptionValue(quietOpt) != null;
Integer base = (Integer) parser.getOptionValue(baseOpt);
Integer columns = (Integer) parser.getOptionValue(columnsOpt);
if (parser.getRemainingArgs().length == 0) {
throw new FileNotFoundException("No input file was provided");
}
String inputFilename = parser.getRemainingArgs()[0];
String outputFilename = (String) parser.getOptionValue(outputFilenameOpt);
JPackerExecuter executer;
if (base == null) {
executer = new JPackerExecuter(JPackerEncoding.NONE);
} else {
executer = new JPackerExecuter(getEncoding(baseOpt, base));
}
in = new BufferedReader(new FileReader(new File(inputFilename)));
String unpacked = buildStringFromTextFile(in);
if (unpacked.isEmpty()) {
throw new EmptyFileException("The file is empty");
}
String packed = executer.pack(unpacked, minify, shrinkVariables);
if (outputFilename == null) {
out = new OutputStreamWriter(System.out);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename));
}
if (columns != null) {
packed = wrapLines(packed, columns);
}
out.write(packed.replace("\n", System.getProperty("line.separator")));
out.close();
if (!quiet) {
long endTime = System.currentTimeMillis();
System.out.printf("Reduced to %.2f%% of its original size in %.4f seconds.\n",
((double) packed.length() / (double) unpacked.length()) * 100,
(double) (endTime - startTime) / 1000);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getLocalizedMessage());
System.exit(1);
} catch (IllegalOptionValueException e) {
System.out.println("Illegal option: " + e.getValue() + " - " + e.getOption());
System.exit(1);
} catch (UnknownOptionException e) {
printUsage();
System.exit(1);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
System.exit(1);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
}
}
}
}
private static void printUsage() {
System.out.println("\nUsage: java -jar jpacker-x.y.z.jar [options] [input file]\n\n"
+ "Options\n"
+ " -b, --base Encoding base. Options are: 10, 36, 52, 62 \n"
+ " and 95. Ignored if --minify option is set.\n"
+ " -c, --column <column> Insert a line break after the specified column \n"
+ " number.\n"
+ " -h, --help Displays this information.\n"
+ " -m, --minify Minify only, do not obfuscate.\n"
+ " --minify and --base values will be ignored.\n"
+ " -o <file>, --output <file> Place the output into <file>.\n"
+ " Defaults to stdout.\n"
+ " -q, --quiet Quiet mode, no message.\n"
+ " -s, --shrink-variables Shrink variables. Ignored if --minify option \n"
+ " is set.\n");
}
private static String wrapLines(String packedScript, Integer columns) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < packedScript.length(); i++) {
int end = ((i + columns) > (packedScript.length()) ? packedScript.length() : i + columns);
sb.append(packedScript.substring(i, end)).append(System.getProperty("line.separator"));
i = end + 1;
}
return sb.toString();
}
private static String buildStringFromTextFile(BufferedReader reader) throws FileNotFoundException, IOException {
StringBuilder sb = new StringBuilder();
String s;
while ((s = reader.readLine()) != null) {
sb.append(s).append(System.getProperty("line.separator"));
}
reader.close();
return sb.toString();
}
private static JPackerEncoding getEncoding(Option option, Integer base) throws IllegalOptionValueException {
switch (base) {
case 10:
return JPackerEncoding.NUMERIC;
case 36:
return JPackerEncoding.MID;
case 52:
return JPackerEncoding.BASIC;
case 62:
return JPackerEncoding.NORMAL;
case 95:
return JPackerEncoding.HIGH_ASCII;
default:
throw new IllegalOptionValueException(option, "Encoding base option not valid");
}
}
}
| jindrapetrik/jpexs-decompiler | libsrc/jpacker/src/com/jpacker/JPacker.java |
214,101 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.Annotations;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.spi.ScopeBinding;
import java.lang.annotation.Annotation;
import java.util.Objects;
/**
* Handles {@link Binder#bindScope} commands.
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
*/
class ScopeBindingProcessor extends AbstractProcessor {
ScopeBindingProcessor(Errors errors) {
super(errors);
}
@Override
public Boolean visit(ScopeBinding command) {
Scope scope = command.getScope();
Class<? extends Annotation> annotationType = command.getAnnotationType();
if (!Annotations.isScopeAnnotation(annotationType)) {
errors.withSource(annotationType).missingScopeAnnotation();
// Go ahead and bind anyway so we don't get collateral errors.
}
if (!Annotations.isRetainedAtRuntime(annotationType)) {
errors.withSource(annotationType)
.missingRuntimeRetention(command.getSource());
// Go ahead and bind anyway so we don't get collateral errors.
}
Scope existing = injector.state.getScope(Objects.requireNonNull(annotationType, "annotation type"));
if (existing != null) {
errors.duplicateScopes(existing, annotationType, scope);
} else {
injector.state.putAnnotation(annotationType, Objects.requireNonNull(scope, "scope"));
}
return true;
}
} | crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/ScopeBindingProcessor.java |
214,102 | /**
* Packer version 3.0 (final)
* Copyright 2004-2007, Dean Edwards
* Web: {@link http://dean.edwards.name/}
*
* This software is licensed under the MIT license
* Web: {@link http://www.opensource.org/licenses/mit-license}
*
* Ported to Java by Pablo Santiago based on C# version by Jesse Hansen, <twindagger2k @ msn.com>
* Web: {@link http://jpacker.googlecode.com/}
* Email: <pablo.santiago @ gmail.com>
*/
package com.jpacker;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.jpacker.evaluators.DeleteEvaluator;
import com.jpacker.evaluators.Evaluator;
import com.jpacker.evaluators.IntegerEvaluator;
import com.jpacker.evaluators.StringEvaluator;
import com.jpacker.strategies.DefaultReplacementStrategy;
import com.jpacker.strategies.ReplacementStrategy;
/**
* Parser class that matches RegGrp.js.
*
* This class parses the script using the expressions added via
* {@link #remove(String)}, {@link #ignore(String)},
* {@link #replace(String,String)} and {@link #replace(String,Evaluator)}
*
* @author Pablo Santiago <pablo.santiago @ gmail.com>
*/
public class JPackerParser {
private static Pattern GROUPS = Pattern.compile("\\(");
private static Pattern SUB_REPLACE = Pattern.compile("\\$(\\d+)");
private static Pattern INDEXED = Pattern.compile("^\\$\\d+$");
private static Pattern ESCAPE = Pattern.compile("\\\\.");
private static Pattern ESCAPE_BRACKETS = Pattern.compile("\\(\\?[:=!]|\\[[^\\]]+\\]");
private static Pattern DELETED = Pattern.compile("\\x01[^\\x01]*\\x01");
private static String IGNORE = "$0";
private List<JPackerPattern> jpatterns = new ArrayList<JPackerPattern>();
/**
* Add an expression to be removed
*
* @param expression
* Regular expression {@link String}
*/
public void remove(String expression) {
replace(expression, "");
}
/**
* Add an expression to be ignored
*
* @param expression
* Regular expression {@link String}
*/
public void ignore(String expression) {
replace(expression, IGNORE);
}
/**
* Add an expression to be replaced with the replacement string
*
* @param expression
* Regular expression {@link String}
* @param replacement
* Replacement {@link String}. Use $1, $2, etc. for groups
*/
public void replace(String expression, String replacement) {
if (replacement.isEmpty()) {
replace(expression, new DeleteEvaluator());
return;
}
Evaluator evaluator;
// does the pattern deal with sub-expressions? and a simple lookup (e.g. $2)
if (SUB_REPLACE.matcher(replacement).matches() && INDEXED.matcher(replacement).matches()) {
evaluator = new IntegerEvaluator(Integer.parseInt(replacement.substring(1)));
} else {
evaluator = new StringEvaluator(replacement);
}
JPackerPattern jpattern = new JPackerPattern(expression, evaluator);
// count the number of sub-expressions
jpattern.setLength(countSubExpressions(expression));
jpatterns.add(jpattern);
}
/**
* Add an expression to be replaced using an {@link Evaluator} object
*
* @param expression
* Regular expression String
* @param evaluator
* The {@link Evaluator} object
*/
public void replace(String expression, Evaluator evaluator) {
JPackerPattern jpattern = new JPackerPattern(expression, evaluator);
// count the number of sub-expressions
jpattern.setLength(countSubExpressions(expression));
jpatterns.add(jpattern);
}
// builds the patterns into a single regular expression
private Pattern buildPatterns() {
StringBuilder rtrn = new StringBuilder();
for (JPackerPattern jpattern : jpatterns) {
rtrn.append(jpattern).append("|");
}
rtrn.deleteCharAt(rtrn.length() - 1);
return Pattern.compile(rtrn.toString());
}
/**
* Executes the parser in order to parse the script with the expressions
* added via {@link #remove(String)}, {@link #ignore(String)},
* {@link #replace(String,String)} and {@link #replace(String,Evaluator)}
*
* @param input
* The script to be parsed
* @return The parsed script
*/
public String exec(String input) {
return exec(input, new DefaultReplacementStrategy());
}
/**
* Executes the parser in order to parse the script with the expressions
* added via {@link #remove(String)}, {@link #ignore(String)},
* {@link #replace(String,String)} and {@link #replace(String,Evaluator)}.
* Using a {@link ReplacementStrategy} object, a custom replacement
* algorithm can be used.
*
* @param input
* The script to be parsed
* @param strategy
* The {@link ReplacementStrategy} object for custom replacement
* @return The parsed script
*/
public String exec(String input, ReplacementStrategy strategy) {
Matcher matcher = buildPatterns().matcher(input);
StringBuffer sb = new StringBuffer(input.length());
while (matcher.find()) {
String rep = strategy.replace(jpatterns, matcher);
if (rep != null && !rep.isEmpty()) {
rep = Matcher.quoteReplacement(rep);
}
matcher.appendReplacement(sb, rep);
}
matcher.appendTail(sb);
return DELETED.matcher(sb).replaceAll("");
}
// count the number of sub-expressions
private int countSubExpressions(String expression) {
int cont = 0;
Matcher matcher = GROUPS.matcher(internalEscape(expression));
while (matcher.find()) {
cont++;
}
// - add 1 because each group is itself a sub-expression
return cont + 1;
}
private String internalEscape(String str) {
return ESCAPE_BRACKETS.matcher(ESCAPE.matcher(str).replaceAll("")).replaceAll("");
}
/**
* The patterns added to this {@link JPackerParser} object as a {@link List}
* of {@link JPackerPattern}
*
* @return The {@link List} of {@link JPackerPattern} objects
*/
public List<JPackerPattern> getJPatterns() {
return jpatterns;
}
}
| jindrapetrik/jpexs-decompiler | libsrc/jpacker/src/com/jpacker/JPackerParser.java |
214,103 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.inject.binder.AnnotatedElementBuilder;
/**
* Returns a binder whose configuration information is hidden from its environment by default. See
* {@link org.opensearch.common.inject.PrivateModule PrivateModule} for details.
*
* @author [email protected] (Jesse Wilson)
* @since 2.0
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public interface PrivateBinder extends Binder {
/**
* Makes the binding for {@code key} available to the enclosing environment
*/
void expose(Key<?> key);
/**
* Makes a binding for {@code type} available to the enclosing environment. Use {@link
* org.opensearch.common.inject.binder.AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a
* binding annotation.
*/
AnnotatedElementBuilder expose(Class<?> type);
/**
* Makes a binding for {@code type} available to the enclosing environment. Use {@link
* AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a
* binding annotation.
*/
AnnotatedElementBuilder expose(TypeLiteral<?> type);
@Override
PrivateBinder withSource(Object source);
@Override
PrivateBinder skipSources(Class... classesToSkip);
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/PrivateBinder.java |
214,104 | /*
* Copyright (C) 2009 Google 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 org.elasticsearch.common.inject;
/**
* Accessors for providers and members injectors. The returned values will not be functional until
* the injector has been created.
*
* @author [email protected] (Jesse Wilson)
*/
interface Lookups {
<T> Provider<T> getProvider(Key<T> key);
<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type);
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/Lookups.java |
214,105 | /*
* Copyright (C) 2006 Google 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 org.elasticsearch.common.inject;
import java.util.List;
/**
* Builds the graphs of objects that make up your application. The injector tracks the dependencies
* for each type and uses bindings to inject them. This is the core of Guice, although you rarely
* interact with it directly. This "behind-the-scenes" operation is what distinguishes dependency
* injection from its cousin, the service locator pattern.
* <p>
* Contains several default bindings:
* <ul>
* <li>This {@link Injector} instance itself
* <li>A {@code Provider<T>} for each binding of type {@code T}
* <li>The {@link java.util.logging.Logger} for the class being injected
* <li>The {@link Stage} in which the Injector was created
* </ul>
* <p>
* Injectors are created using the facade class {@link Guice}.
* <p>
* An injector can also {@link #injectMembers(Object) inject the dependencies} of
* already-constructed instances. This can be used to interoperate with objects created by other
* frameworks or services.
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
*/
public interface Injector {
/**
* Injects dependencies into the fields and methods of {@code instance}. Ignores the presence or
* absence of an injectable constructor.
* <p>
* Whenever Guice creates an instance, it performs this injection automatically (after first
* performing constructor injection), so if you're able to let Guice create all your objects for
* you, you'll never need to use this method.
*
* @param instance to inject members on
* @see Binder#getMembersInjector(Class) for a preferred alternative that supports checks before
* run time
*/
void injectMembers(Object instance);
/**
* Returns the members injector used to inject dependencies into methods and fields on instances
* of the given type {@code T}.
*
* @param typeLiteral type to get members injector for
* @see Binder#getMembersInjector(TypeLiteral) for an alternative that offers up front error
* detection
* @since 2.0
*/
<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral);
/**
* Returns the members injector used to inject dependencies into methods and fields on instances
* of the given type {@code T}. When feasible, use {@link Binder#getMembersInjector(TypeLiteral)}
* instead to get increased up front error detection.
*
* @param type type to get members injector for
* @see Binder#getMembersInjector(Class) for an alternative that offers up front error
* detection
* @since 2.0
*/
<T> MembersInjector<T> getMembersInjector(Class<T> type);
/**
* Returns all explicit bindings for {@code type}.
* <p>
* This method is part of the Guice SPI and is intended for use by tools and extensions.
*/
<T> List<Binding<T>> findBindingsByType(TypeLiteral<T> type);
/**
* Returns the provider used to obtain instances for the given injection key. When feasible, avoid
* using this method, in favor of having Guice inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @see Binder#getProvider(Key) for an alternative that offers up front error detection
*/
<T> Provider<T> getProvider(Key<T> key);
/**
* Returns the provider used to obtain instances for the given type. When feasible, avoid
* using this method, in favor of having Guice inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @see Binder#getProvider(Class) for an alternative that offers up front error detection
*/
<T> Provider<T> getProvider(Class<T> type);
/**
* Returns the appropriate instance for the given injection key; equivalent to {@code
* getProvider(key).get()}. When feasible, avoid using this method, in favor of having Guice
* inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @throws ProvisionException if there was a runtime failure while providing an instance.
*/
<T> T getInstance(Key<T> key);
/**
* Returns the appropriate instance for the given injection type; equivalent to {@code
* getProvider(type).get()}. When feasible, avoid using this method, in favor of having Guice
* inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @throws ProvisionException if there was a runtime failure while providing an instance.
*/
<T> T getInstance(Class<T> type);
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/Injector.java |
214,106 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.Annotations;
import org.elasticsearch.common.inject.internal.BindingImpl;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.internal.ErrorsException;
import org.elasticsearch.common.inject.internal.ExposedBindingImpl;
import org.elasticsearch.common.inject.internal.InstanceBindingImpl;
import org.elasticsearch.common.inject.internal.InternalFactory;
import org.elasticsearch.common.inject.internal.LinkedBindingImpl;
import org.elasticsearch.common.inject.internal.LinkedProviderBindingImpl;
import org.elasticsearch.common.inject.internal.ProviderInstanceBindingImpl;
import org.elasticsearch.common.inject.internal.ProviderMethod;
import org.elasticsearch.common.inject.internal.Scoping;
import org.elasticsearch.common.inject.internal.UntargettedBindingImpl;
import org.elasticsearch.common.inject.spi.BindingTargetVisitor;
import org.elasticsearch.common.inject.spi.ConstructorBinding;
import org.elasticsearch.common.inject.spi.ConvertedConstantBinding;
import org.elasticsearch.common.inject.spi.ExposedBinding;
import org.elasticsearch.common.inject.spi.InjectionPoint;
import org.elasticsearch.common.inject.spi.InstanceBinding;
import org.elasticsearch.common.inject.spi.LinkedKeyBinding;
import org.elasticsearch.common.inject.spi.PrivateElements;
import org.elasticsearch.common.inject.spi.ProviderBinding;
import org.elasticsearch.common.inject.spi.ProviderInstanceBinding;
import org.elasticsearch.common.inject.spi.ProviderKeyBinding;
import org.elasticsearch.common.inject.spi.UntargettedBinding;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Handles {@link Binder#bind} and {@link Binder#bindConstant} elements.
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
*/
class BindingProcessor extends AbstractProcessor {
private final List<CreationListener> creationListeners = new ArrayList<>();
private final Initializer initializer;
private final List<Runnable> uninitializedBindings = new ArrayList<>();
BindingProcessor(Errors errors, Initializer initializer) {
super(errors);
this.initializer = initializer;
}
@Override
public <T> Boolean visit(Binding<T> command) {
final Object source = command.getSource();
if (Void.class.equals(command.getKey().getRawType())) {
if (command instanceof ProviderInstanceBinding
&& ((ProviderInstanceBinding) command).getProviderInstance() instanceof ProviderMethod) {
errors.voidProviderMethod();
} else {
errors.missingConstantValues();
}
return true;
}
final Key<T> key = command.getKey();
Class<? super T> rawType = key.getTypeLiteral().getRawType();
if (rawType == Provider.class) {
errors.bindingToProvider();
return true;
}
validateKey(command.getSource(), command.getKey());
final Scoping scoping = Scopes.makeInjectable(
((BindingImpl<?>) command).getScoping(), injector, errors);
command.acceptTargetVisitor(new BindingTargetVisitor<T, Void>() {
@Override
public Void visit(InstanceBinding<? extends T> binding) {
Set<InjectionPoint> injectionPoints = binding.getInjectionPoints();
T instance = binding.getInstance();
Initializable<T> ref = initializer.requestInjection(
injector, instance, source, injectionPoints);
ConstantFactory<? extends T> factory = new ConstantFactory<>(ref);
InternalFactory<? extends T> scopedFactory = Scopes.scope(key, injector, factory, scoping);
putBinding(new InstanceBindingImpl<>(injector, key, source, scopedFactory, injectionPoints,
instance));
return null;
}
@Override
public Void visit(ProviderInstanceBinding<? extends T> binding) {
Provider<? extends T> provider = binding.getProviderInstance();
Set<InjectionPoint> injectionPoints = binding.getInjectionPoints();
Initializable<Provider<? extends T>> initializable = initializer
.<Provider<? extends T>>requestInjection(injector, provider, source, injectionPoints);
InternalFactory<T> factory = new InternalFactoryToProviderAdapter<>(initializable, source);
InternalFactory<? extends T> scopedFactory = Scopes.scope(key, injector, factory, scoping);
putBinding(new ProviderInstanceBindingImpl<>(injector, key, source, scopedFactory, scoping,
provider, injectionPoints));
return null;
}
@Override
public Void visit(ProviderKeyBinding<? extends T> binding) {
Key<? extends Provider<? extends T>> providerKey = binding.getProviderKey();
BoundProviderFactory<T> boundProviderFactory
= new BoundProviderFactory<>(injector, providerKey, source);
creationListeners.add(boundProviderFactory);
InternalFactory<? extends T> scopedFactory = Scopes.scope(
key, injector, (InternalFactory<? extends T>) boundProviderFactory, scoping);
putBinding(new LinkedProviderBindingImpl<>(
injector, key, source, scopedFactory, scoping, providerKey));
return null;
}
@Override
public Void visit(LinkedKeyBinding<? extends T> binding) {
Key<? extends T> linkedKey = binding.getLinkedKey();
if (key.equals(linkedKey)) {
errors.recursiveBinding();
}
FactoryProxy<T> factory = new FactoryProxy<>(injector, key, linkedKey, source);
creationListeners.add(factory);
InternalFactory<? extends T> scopedFactory = Scopes.scope(key, injector, factory, scoping);
putBinding(
new LinkedBindingImpl<>(injector, key, source, scopedFactory, scoping, linkedKey));
return null;
}
@Override
public Void visit(UntargettedBinding<? extends T> untargetted) {
// Error: Missing implementation.
// Example: bind(Date.class).annotatedWith(Red.class);
// We can't assume abstract types aren't injectable. They may have an
// @ImplementedBy annotation or something.
if (key.hasAnnotationType()) {
errors.missingImplementation(key);
putBinding(invalidBinding(injector, key, source));
return null;
}
// This cast is safe after the preceding check.
final BindingImpl<T> binding;
try {
binding = injector.createUnitializedBinding(key, scoping, source, errors);
putBinding(binding);
} catch (ErrorsException e) {
errors.merge(e.getErrors());
putBinding(invalidBinding(injector, key, source));
return null;
}
uninitializedBindings.add(new Runnable() {
@Override
public void run() {
try {
((InjectorImpl) binding.getInjector()).initializeBinding(
binding, errors.withSource(source));
} catch (ErrorsException e) {
errors.merge(e.getErrors());
}
}
});
return null;
}
@Override
public Void visit(ExposedBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
@Override
public Void visit(ConvertedConstantBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
@Override
public Void visit(ConstructorBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
@Override
public Void visit(ProviderBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
});
return true;
}
@Override
public Boolean visit(PrivateElements privateElements) {
for (Key<?> key : privateElements.getExposedKeys()) {
bindExposed(privateElements, key);
}
return false; // leave the private elements for the PrivateElementsProcessor to handle
}
private <T> void bindExposed(PrivateElements privateElements, Key<T> key) {
ExposedKeyFactory<T> exposedKeyFactory = new ExposedKeyFactory<>(key, privateElements);
creationListeners.add(exposedKeyFactory);
putBinding(new ExposedBindingImpl<>(
injector, privateElements.getExposedSource(key), key, exposedKeyFactory, privateElements));
}
private <T> void validateKey(Object source, Key<T> key) {
Annotations.checkForMisplacedScopeAnnotations(key.getRawType(), source, errors);
}
<T> UntargettedBindingImpl<T> invalidBinding(InjectorImpl injector, Key<T> key, Object source) {
return new UntargettedBindingImpl<>(injector, key, source);
}
public void initializeBindings() {
for (Runnable initializer : uninitializedBindings) {
initializer.run();
}
}
public void runCreationListeners() {
for (CreationListener creationListener : creationListeners) {
creationListener.notify(errors);
}
}
private void putBinding(BindingImpl<?> binding) {
Key<?> key = binding.getKey();
Class<?> rawType = key.getRawType();
if (FORBIDDEN_TYPES.contains(rawType)) {
errors.cannotBindToGuiceType(rawType.getSimpleName());
return;
}
Binding<?> original = injector.state.getExplicitBinding(key);
if (original != null && !isOkayDuplicate(original, binding)) {
errors.bindingAlreadySet(key, original.getSource());
return;
}
// prevent the parent from creating a JIT binding for this key
injector.state.parent().blacklist(key);
injector.state.putBinding(key, binding);
}
/**
* We tolerate duplicate bindings only if one exposes the other.
*
* @param original the binding in the parent injector (candidate for an exposing binding)
* @param binding the binding to check (candidate for the exposed binding)
*/
private boolean isOkayDuplicate(Binding<?> original, BindingImpl<?> binding) {
if (original instanceof ExposedBindingImpl) {
ExposedBindingImpl exposed = (ExposedBindingImpl) original;
InjectorImpl exposedFrom = (InjectorImpl) exposed.getPrivateElements().getInjector();
return (exposedFrom == binding.getInjector());
}
return false;
}
// It's unfortunate that we have to maintain a blacklist of specific
// classes, but we can't easily block the whole package because of
// all our unit tests.
private static final Set<Class<?>> FORBIDDEN_TYPES = Set.of(
AbstractModule.class,
Binder.class,
Binding.class,
Injector.class,
Key.class,
MembersInjector.class,
Module.class,
Provider.class,
Scope.class,
TypeLiteral.class);
// TODO(jessewilson): fix BuiltInModule, then add Stage
interface CreationListener {
void notify(Errors errors);
}
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/BindingProcessor.java |
214,107 | /*
* The MIT License
*
* Copyright 2014 Jesse Glick.
*
* 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 jenkins.model;
import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
import static javax.servlet.http.HttpServletResponse.SC_CREATED;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.Action;
import hudson.model.BuildAuthorizationToken;
import hudson.model.BuildableItem;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.listeners.ItemListener;
import hudson.model.queue.QueueTaskFuture;
import hudson.search.SearchIndexBuilder;
import hudson.triggers.Trigger;
import hudson.util.AlternativeUiTextProvider;
import hudson.views.BuildButtonColumn;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import jenkins.model.lazy.LazyBuildMixIn;
import jenkins.triggers.SCMTriggerItem;
import jenkins.triggers.TriggeredItem;
import jenkins.util.TimeDuration;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.accmod.restrictions.ProtectedExternally;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Allows a {@link Job} to make use of {@link ParametersDefinitionProperty} and be scheduled in various ways.
* Stateless so there is no need to keep an instance of it in a field.
* Besides implementing {@link ParameterizedJob}, you should
* <ul>
* <li>override {@link Job#makeSearchIndex} to call {@link #extendSearchIndex}
* <li>override {@link Job#performDelete} to call {@link ParameterizedJob#makeDisabled}
* <li>override {@link Job#getIconColor} to call {@link ParameterizedJob#isDisabled}
* <li>use {@code <p:config-disableBuild/>}
* <li>use {@code <p:makeDisabled/>}
* </ul>
* @since 1.556
*/
@SuppressWarnings("unchecked") // AbstractItem.getParent does not correctly override; scheduleBuild2 inherently untypable
public abstract class ParameterizedJobMixIn<JobT extends Job<JobT, RunT> & ParameterizedJobMixIn.ParameterizedJob<JobT, RunT> & Queue.Task, RunT extends Run<JobT, RunT> & Queue.Executable> {
protected abstract JobT asJob();
/** @see BuildableItem#scheduleBuild() */
@SuppressWarnings("deprecation")
public final boolean scheduleBuild() {
return scheduleBuild(asJob().getQuietPeriod(), new Cause.LegacyCodeCause());
}
/** @see BuildableItem#scheduleBuild(Cause) */
public final boolean scheduleBuild(Cause c) {
return scheduleBuild(asJob().getQuietPeriod(), c);
}
/** @see BuildableItem#scheduleBuild(int) */
@SuppressWarnings("deprecation")
public final boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new Cause.LegacyCodeCause());
}
/** @see BuildableItem#scheduleBuild(int, Cause) */
public final boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c != null ? List.of(new CauseAction(c)) : Collections.emptyList()) != null;
}
/**
* Standard implementation of {@link ParameterizedJob#scheduleBuild2}.
*/
public final @CheckForNull QueueTaskFuture<RunT> scheduleBuild2(int quietPeriod, Action... actions) {
Queue.Item i = scheduleBuild2(quietPeriod, Arrays.asList(actions));
return i != null ? (QueueTaskFuture) i.getFuture() : null;
}
/**
* Convenience method to schedule a build.
* Useful for {@link Trigger} implementations, for example.
* If you need to wait for the build to start (or finish), use {@link Queue.Item#getFuture}.
* @param job a job which might be schedulable
* @param quietPeriod seconds to wait before starting; use {@code -1} to use the job’s default settings
* @param actions various actions to associate with the scheduling, such as {@link ParametersAction} or {@link CauseAction}
* @return a newly created, or reused, queue item if the job could be scheduled;
* null if it was refused for some reason (e.g., some {@link Queue.QueueDecisionHandler} rejected it),
* or if {@code job} is not a {@link ParameterizedJob} or it is not {@link Job#isBuildable})
* @since 1.621
*/
public static @CheckForNull Queue.Item scheduleBuild2(final Job<?, ?> job, int quietPeriod, Action... actions) {
if (!(job instanceof ParameterizedJob)) {
return null;
}
return new ParameterizedJobMixIn() {
@Override protected Job asJob() {
return job;
}
}.scheduleBuild2(quietPeriod == -1 ? ((ParameterizedJob) job).getQuietPeriod() : quietPeriod, Arrays.asList(actions));
}
@CheckForNull Queue.Item scheduleBuild2(int quietPeriod, List<Action> actions) {
if (!asJob().isBuildable())
return null;
List<Action> queueActions = new ArrayList<>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
return Jenkins.get().getQueue().schedule2(asJob(), quietPeriod, queueActions).getItem();
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = asJob().getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if (paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if (defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Standard implementation of {@link ParameterizedJob#isParameterized}.
*/
public final boolean isParameterized() {
return asJob().getProperty(ParametersDefinitionProperty.class) != null;
}
/**
* Standard implementation of {@link ParameterizedJob#doBuild}.
*/
@SuppressWarnings("deprecation")
public final void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
if (delay == null) {
delay = new TimeDuration(TimeUnit.MILLISECONDS.convert(asJob().getQuietPeriod(), TimeUnit.SECONDS));
}
if (!asJob().isBuildable()) {
throw HttpResponses.error(SC_CONFLICT, new IOException(asJob().getFullName() + " is not buildable"));
}
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = asJob().getProperty(ParametersDefinitionProperty.class);
if (pp != null && !req.getMethod().equals("POST")) {
// show the parameter entry form.
req.getView(pp, "index.jelly").forward(req, rsp);
return;
}
BuildAuthorizationToken.checkPermission(asJob(), asJob().getAuthToken(), req, rsp);
if (pp != null) {
pp._doBuild(req, rsp, delay);
return;
}
Queue.Item item = Jenkins.get().getQueue().schedule2(asJob(), delay.getTimeInSeconds(), getBuildCause(asJob(), req)).getItem();
if (item != null) {
rsp.sendRedirect(SC_CREATED, req.getContextPath() + '/' + item.getUrl());
} else {
rsp.sendRedirect(".");
}
}
/**
* Standard implementation of {@link ParameterizedJob#doBuildWithParameters}.
*/
@SuppressWarnings("deprecation")
public final void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(asJob(), asJob().getAuthToken(), req, rsp);
ParametersDefinitionProperty pp = asJob().getProperty(ParametersDefinitionProperty.class);
if (!asJob().isBuildable()) {
throw HttpResponses.error(SC_CONFLICT, new IOException(asJob().getFullName() + " is not buildable!"));
}
if (pp != null) {
pp.buildWithParameters(req, rsp, delay);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Standard implementation of {@link ParameterizedJob#doCancelQueue}.
*/
@RequirePOST
public final void doCancelQueue(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
asJob().checkPermission(Item.CANCEL);
Jenkins.get().getQueue().cancel(asJob());
rsp.forwardToPreviousPage(req);
}
/**
* Use from a {@link Job#makeSearchIndex} override.
* @param sib the super value
* @return the value to return
*/
public final SearchIndexBuilder extendSearchIndex(SearchIndexBuilder sib) {
if (asJob().isBuildable() && asJob().hasPermission(Item.BUILD)) {
sib.add("build", "build");
}
return sib;
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
@Restricted(NoExternalUse.class)
public static CauseAction getBuildCause(ParameterizedJob job, StaplerRequest req) {
Cause cause;
@SuppressWarnings("deprecation")
BuildAuthorizationToken authToken = job.getAuthToken();
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new Cause.RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new Cause.UserIdCause();
}
return new CauseAction(cause);
}
/**
* Allows customization of the human-readable display name to be rendered in the <i>Build Now</i> link.
* @see #getBuildNowText
* @since 1.624
*/
public static final AlternativeUiTextProvider.Message<ParameterizedJob> BUILD_NOW_TEXT = new AlternativeUiTextProvider.Message<>();
public static final AlternativeUiTextProvider.Message<ParameterizedJob> BUILD_WITH_PARAMETERS_TEXT = new AlternativeUiTextProvider.Message<>();
/**
* Suggested implementation of {@link ParameterizedJob#getBuildNowText}.
*/
public final String getBuildNowText() {
return isParameterized() ? AlternativeUiTextProvider.get(BUILD_WITH_PARAMETERS_TEXT, asJob(),
AlternativeUiTextProvider.get(BUILD_NOW_TEXT, asJob(), Messages.ParameterizedJobMixIn_build_with_parameters()))
: AlternativeUiTextProvider.get(BUILD_NOW_TEXT, asJob(), Messages.ParameterizedJobMixIn_build_now());
}
/**
* Checks for the existence of a specific trigger on a job.
* @param <T> a trigger type
* @param job a job
* @param clazz the type of the trigger
* @return a configured trigger of the requested type, or null if there is none such, or {@code job} is not a {@link ParameterizedJob}
* @since 1.621
*/
public static @CheckForNull <T extends Trigger<?>> T getTrigger(Job<?, ?> job, Class<T> clazz) {
if (!(job instanceof ParameterizedJob)) {
return null;
}
for (Trigger<?> t : ((ParameterizedJob<?, ?>) job).getTriggers().values()) {
if (clazz.isInstance(t)) {
return clazz.cast(t);
}
}
return null;
}
/**
* Marker for job using this mixin, and default implementations of many methods.
*/
public interface ParameterizedJob<JobT extends Job<JobT, RunT> & ParameterizedJobMixIn.ParameterizedJob<JobT, RunT> & Queue.Task, RunT extends Run<JobT, RunT> & Queue.Executable> extends BuildableItem, TriggeredItem {
/**
* Used for CLI binding.
*/
@Restricted(DoNotUse.class)
@SuppressWarnings("rawtypes")
@CLIResolver
static ParameterizedJob resolveForCLI(@Argument(required = true, metaVar = "NAME", usage = "Job name") String name) throws CmdLineException {
ParameterizedJob item = Jenkins.get().getItemByFullName(name, ParameterizedJob.class);
if (item == null) {
ParameterizedJob project = Items.findNearest(ParameterizedJob.class, name, Jenkins.get());
throw new CmdLineException(null, project == null ?
hudson.model.Messages.AbstractItem_NoSuchJobExistsWithoutSuggestion(name) :
hudson.model.Messages.AbstractItem_NoSuchJobExists(name, project.getFullName()));
}
return item;
}
/**
* Creates a helper object.
* (Would have been done entirely as an interface with default methods had this been designed for Java 8.)
*/
default ParameterizedJobMixIn<JobT, RunT> getParameterizedJobMixIn() {
return new ParameterizedJobMixIn<JobT, RunT>() {
@SuppressWarnings("unchecked") // untypable
@Override protected JobT asJob() {
return (JobT) ParameterizedJob.this;
}
};
}
@SuppressWarnings("deprecation")
@CheckForNull BuildAuthorizationToken getAuthToken();
/**
* Quiet period for the job.
* @return by default, {@link Jenkins#getQuietPeriod}
*/
default int getQuietPeriod() {
return Jenkins.get().getQuietPeriod();
}
/**
* Text to display for a build button.
* Uses {@link #BUILD_NOW_TEXT}.
* @see ParameterizedJobMixIn#getBuildNowText
*/
default String getBuildNowText() {
return getParameterizedJobMixIn().getBuildNowText();
}
@Override
default boolean scheduleBuild(Cause c) {
return getParameterizedJobMixIn().scheduleBuild(c);
}
@Override
default boolean scheduleBuild(int quietPeriod, Cause c) {
return getParameterizedJobMixIn().scheduleBuild(quietPeriod, c);
}
/**
* Provides a standard implementation of {@link SCMTriggerItem#scheduleBuild2} to schedule a build with the ability to wait for its result.
* That job method is often used during functional tests ({@code JenkinsRule.assertBuildStatusSuccess}).
* @param quietPeriod seconds to wait before starting (normally 0)
* @param actions various actions to associate with the scheduling, such as {@link ParametersAction} or {@link CauseAction}
* @return a handle by which you may wait for the build to complete (or just start); or null if the build was not actually scheduled for some reason
*/
@CheckForNull
default QueueTaskFuture<RunT> scheduleBuild2(int quietPeriod, Action... actions) {
return getParameterizedJobMixIn().scheduleBuild2(quietPeriod, actions);
}
/**
* Schedules a new build command.
* @see ParameterizedJobMixIn#doBuild
*/
default void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
getParameterizedJobMixIn().doBuild(req, rsp, delay);
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
* @see ParameterizedJobMixIn#doBuildWithParameters
*/
default void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
getParameterizedJobMixIn().doBuildWithParameters(req, rsp, delay);
}
/**
* Cancels a scheduled build.
* @see ParameterizedJobMixIn#doCancelQueue
*/
@RequirePOST
default void doCancelQueue(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
getParameterizedJobMixIn().doCancelQueue(req, rsp);
}
/**
* Schedules a new SCM polling command.
*/
@SuppressWarnings("deprecation")
default void doPolling(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if (!(this instanceof SCMTriggerItem)) {
rsp.sendError(404);
return;
}
BuildAuthorizationToken.checkPermission((Job) this, getAuthToken(), req, rsp);
((SCMTriggerItem) this).schedulePolling();
rsp.sendRedirect(".");
}
/**
* For use from {@link BuildButtonColumn}.
* @see ParameterizedJobMixIn#isParameterized
*/
default boolean isParameterized() {
return getParameterizedJobMixIn().isParameterized();
}
default boolean isDisabled() {
return false;
}
@Restricted(ProtectedExternally.class)
default void setDisabled(boolean disabled) {
throw new UnsupportedOperationException("must be implemented if supportsMakeDisabled is overridden");
}
/**
* Specifies whether this project may be disabled by the user.
* @return true if the GUI should allow {@link #doDisable} and the like
*/
default boolean supportsMakeDisabled() {
return false;
}
/**
* Marks the build as disabled.
* The method will ignore the disable command if {@link #supportsMakeDisabled()}
* returns false. The enable command will be executed in any case.
* @param b true - disable, false - enable
*/
default void makeDisabled(boolean b) throws IOException {
if (isDisabled() == b) {
return; // noop
}
if (b && !supportsMakeDisabled()) {
return; // do nothing if the disabling is unsupported
}
setDisabled(b);
if (b) {
Jenkins.get().getQueue().cancel(this);
}
save();
ItemListener.fireOnUpdated(this);
}
@CLIMethod(name = "disable-job")
@RequirePOST
default HttpResponse doDisable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name = "enable-job")
@RequirePOST
default HttpResponse doEnable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
@Override
default RunT createExecutable() throws IOException {
if (isDisabled()) {
return null;
}
if (this instanceof LazyBuildMixIn.LazyLoadingJob) {
return (RunT) ((LazyBuildMixIn.LazyLoadingJob) this).getLazyBuildMixIn().newBuild();
}
return null;
}
default boolean isBuildable() {
return !isDisabled() && !((Job) this).isHoldOffBuildUntilSave();
}
}
}
| vsilverman/jenkins-1 | core/src/main/java/jenkins/model/ParameterizedJobMixIn.java |
214,108 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
import org.lwjgl.system.linux.*;
/**
* The {@code VK_KHR_wayland_surface} extension is an instance extension. It provides a mechanism to create a {@code VkSurfaceKHR} object (defined by the {@link KHRSurface VK_KHR_surface} extension) that refers to a Wayland {@code wl_surface}, as well as a query to determine support for rendering to a Wayland compositor.
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_KHR_wayland_surface}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Instance extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>7</dd>
* <dt><b>Revision</b></dt>
* <dd>6</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link KHRSurface VK_KHR_surface}</dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Jesse Hall <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_wayland_surface]%20@critsec%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_wayland_surface%20extension*">critsec</a></li>
* <li>Ian Elliott <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_wayland_surface]%20@ianelliottus%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_wayland_surface%20extension*">ianelliottus</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2015-11-28</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Patrick Doane, Blizzard</li>
* <li>Faith Ekstrand, Intel</li>
* <li>Ian Elliott, LunarG</li>
* <li>Courtney Goeltzenleuchter, LunarG</li>
* <li>Jesse Hall, Google</li>
* <li>James Jones, NVIDIA</li>
* <li>Antoine Labour, Google</li>
* <li>Jon Leech, Khronos</li>
* <li>David Mao, AMD</li>
* <li>Norbert Nopper, Freescale</li>
* <li>Alon Or-bach, Samsung</li>
* <li>Daniel Rakos, AMD</li>
* <li>Graham Sellers, AMD</li>
* <li>Ray Smith, ARM</li>
* <li>Jeff Vigil, Qualcomm</li>
* <li>Chia-I Wu, LunarG</li>
* </ul></dd>
* </dl>
*/
public class KHRWaylandSurface {
/** The extension specification version. */
public static final int VK_KHR_WAYLAND_SURFACE_SPEC_VERSION = 6;
/** The extension name. */
public static final String VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME = "VK_KHR_wayland_surface";
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR = 1000006000;
protected KHRWaylandSurface() {
throw new UnsupportedOperationException();
}
// --- [ vkCreateWaylandSurfaceKHR ] ---
/** Unsafe version of: {@link #vkCreateWaylandSurfaceKHR CreateWaylandSurfaceKHR} */
public static int nvkCreateWaylandSurfaceKHR(VkInstance instance, long pCreateInfo, long pAllocator, long pSurface) {
long __functionAddress = instance.getCapabilities().vkCreateWaylandSurfaceKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPPPPI(instance.address(), pCreateInfo, pAllocator, pSurface, __functionAddress);
}
/**
* Create a {@code VkSurfaceKHR} object for a Wayland window.
*
* <h5>C Specification</h5>
*
* <p>To create a {@code VkSurfaceKHR} object for a Wayland surface, call:</p>
*
* <pre><code>
* VkResult vkCreateWaylandSurfaceKHR(
* VkInstance instance,
* const VkWaylandSurfaceCreateInfoKHR* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkSurfaceKHR* pSurface);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code instance} <b>must</b> be a valid {@code VkInstance} handle</li>
* <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid {@link VkWaylandSurfaceCreateInfoKHR} structure</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>{@code pSurface} <b>must</b> be a valid pointer to a {@code VkSurfaceKHR} handle</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}, {@link VkWaylandSurfaceCreateInfoKHR}</p>
*
* @param instance the instance to associate the surface with.
* @param pCreateInfo a pointer to a {@link VkWaylandSurfaceCreateInfoKHR} structure containing parameters affecting the creation of the surface object.
* @param pAllocator the allocator used for host memory allocated for the surface object when there is no more specific allocator available (see <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a>).
* @param pSurface a pointer to a {@code VkSurfaceKHR} handle in which the created surface object is returned.
*/
@NativeType("VkResult")
public static int vkCreateWaylandSurfaceKHR(VkInstance instance, @NativeType("VkWaylandSurfaceCreateInfoKHR const *") VkWaylandSurfaceCreateInfoKHR pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSurfaceKHR *") LongBuffer pSurface) {
if (CHECKS) {
check(pSurface, 1);
}
return nvkCreateWaylandSurfaceKHR(instance, pCreateInfo.address(), memAddressSafe(pAllocator), memAddress(pSurface));
}
// --- [ vkGetPhysicalDeviceWaylandPresentationSupportKHR ] ---
/**
* Query physical device for presentation to Wayland.
*
* <h5>C Specification</h5>
*
* <p>To determine whether a queue family of a physical device supports presentation to a Wayland compositor, call:</p>
*
* <pre><code>
* VkBool32 vkGetPhysicalDeviceWaylandPresentationSupportKHR(
* VkPhysicalDevice physicalDevice,
* uint32_t queueFamilyIndex,
* struct wl_display* display);</code></pre>
*
* <h5>Description</h5>
*
* <p>This platform-specific function <b>can</b> be called prior to creating a surface.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code queueFamilyIndex} <b>must</b> be less than {@code pQueueFamilyPropertyCount} returned by {@code vkGetPhysicalDeviceQueueFamilyProperties} for the given {@code physicalDevice}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code display} <b>must</b> be a valid pointer to a {@code wl_display} value</li>
* </ul>
*
* @param physicalDevice the physical device.
* @param queueFamilyIndex the queue family index.
* @param display a pointer to the {@code wl_display} associated with a Wayland compositor.
*/
@NativeType("VkBool32")
public static boolean vkGetPhysicalDeviceWaylandPresentationSupportKHR(VkPhysicalDevice physicalDevice, @NativeType("uint32_t") int queueFamilyIndex, @NativeType("struct wl_display *") long display) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceWaylandPresentationSupportKHR;
if (CHECKS) {
check(__functionAddress);
check(display);
}
return callPPI(physicalDevice.address(), queueFamilyIndex, display, __functionAddress) != 0;
}
/** Array version of: {@link #vkCreateWaylandSurfaceKHR CreateWaylandSurfaceKHR} */
@NativeType("VkResult")
public static int vkCreateWaylandSurfaceKHR(VkInstance instance, @NativeType("VkWaylandSurfaceCreateInfoKHR const *") VkWaylandSurfaceCreateInfoKHR pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSurfaceKHR *") long[] pSurface) {
long __functionAddress = instance.getCapabilities().vkCreateWaylandSurfaceKHR;
if (CHECKS) {
check(__functionAddress);
check(pSurface, 1);
}
return callPPPPI(instance.address(), pCreateInfo.address(), memAddressSafe(pAllocator), pSurface, __functionAddress);
}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRWaylandSurface.java |
214,109 | /*
* The MIT License
*
* Copyright 2014 Jesse Glick.
*
* 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 jenkins.model.lazy;
import static java.util.logging.Level.FINER;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.AbstractItem;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.RunMap;
import hudson.model.listeners.ItemListener;
import hudson.model.queue.SubTask;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.RunIdMigrator;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
/**
* Makes it easier to use a lazy {@link RunMap} from a {@link Job} implementation.
* Provides method implementations for some abstract {@link Job} methods,
* as well as some methods which are not abstract but which you should override.
* <p>Should be kept in a {@code transient} field in the job.
* @since 1.556
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // BuildHistoryWidget, and AbstractItem.getParent
public abstract class LazyBuildMixIn<JobT extends Job<JobT, RunT> & Queue.Task & LazyBuildMixIn.LazyLoadingJob<JobT, RunT>, RunT extends Run<JobT, RunT> & LazyBuildMixIn.LazyLoadingRun<JobT, RunT>> {
private static final Logger LOGGER = Logger.getLogger(LazyBuildMixIn.class.getName());
// [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called
private @NonNull RunMap<RunT> builds = new RunMap<>(asJob());
/**
* Initializes this mixin.
* Call this from a constructor and {@link AbstractItem#onLoad} to make sure it is always initialized.
*/
protected LazyBuildMixIn() {}
protected abstract JobT asJob();
/**
* Gets the raw model.
* Normally should not be called as such.
* Note that the initial value is replaced during {@link #onCreatedFromScratch} or {@link #onLoad}.
*/
public final @NonNull RunMap<RunT> getRunMap() {
return builds;
}
/**
* Same as {@link #getRunMap} but suitable for {@link Job#_getRuns}.
*/
public final RunMap<RunT> _getRuns() {
assert builds.baseDirInitialized() : "neither onCreatedFromScratch nor onLoad called on " + asJob() + " yet";
return builds;
}
/**
* Something to be called from {@link Job#onCreatedFromScratch}.
*/
public final void onCreatedFromScratch() {
builds = createBuildRunMap();
}
/**
* Something to be called from {@link Job#onLoad}.
*/
@SuppressWarnings("unchecked")
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
RunMap<RunT> _builds = createBuildRunMap();
int max = _builds.maxNumberOnDisk();
int next = asJob().getNextBuildNumber();
if (next <= max) {
LOGGER.log(Level.WARNING, "JENKINS-27530: improper nextBuildNumber {0} detected in {1} with highest build number {2}; adjusting", new Object[] {next, asJob(), max});
asJob().updateNextBuildNumber(max + 1);
}
RunMap<RunT> currentBuilds = this.builds;
if (parent != null) {
// are we overwriting what currently exist?
// this is primarily when Jenkins is getting reloaded
Item current;
try {
current = parent.getItem(name);
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, "failed to look up " + name + " in " + parent, x);
current = null;
}
if (current != null && current.getClass() == asJob().getClass()) {
currentBuilds = (RunMap<RunT>) ((LazyLoadingJob) current).getLazyBuildMixIn().builds;
}
}
if (currentBuilds != null) {
// if we are reloading, keep all those that are still building intact
for (RunT r : currentBuilds.getLoadedBuilds().values()) {
if (r.isBuilding()) {
// Do not use RunMap.put(Run):
_builds.put(r.getNumber(), r);
LOGGER.log(Level.FINE, "keeping reloaded {0}", r);
}
}
}
this.builds = _builds;
}
private RunMap<RunT> createBuildRunMap() {
RunMap<RunT> r = new RunMap<>(asJob(), new RunMap.Constructor<RunT>() {
@Override
public RunT create(File dir) throws IOException {
return loadBuild(dir);
}
});
RunIdMigrator runIdMigrator = asJob().runIdMigrator;
assert runIdMigrator != null;
r.runIdMigrator = runIdMigrator;
return r;
}
/**
* Type token for the build type.
* The build class must have two constructors:
* one taking the project type ({@code P});
* and one taking {@code P}, then {@link File}.
*/
protected abstract Class<RunT> getBuildClass();
/**
* Loads an existing build record from disk.
* The default implementation just calls the ({@link Job}, {@link File}) constructor of {@link #getBuildClass},
* which will call {@link Run#Run(Job, File)}.
*/
public RunT loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(asJob().getClass(), File.class).newInstance(asJob(), dir);
} catch (InstantiationException | NoSuchMethodException | IllegalAccessException e) {
throw new LinkageError(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
}
}
/**
* Creates a new build of this project for immediate execution.
* Calls the ({@link Job}) constructor of {@link #getBuildClass}, which will call {@link Run#Run(Job)}.
* Suitable for {@link SubTask#createExecutable}.
*/
public final synchronized RunT newBuild() throws IOException {
try {
RunT lastBuild = getBuildClass().getConstructor(asJob().getClass()).newInstance(asJob());
var rootDir = lastBuild.getRootDir().toPath();
if (Files.isDirectory(rootDir)) {
LOGGER.warning(() -> "JENKINS-23152: " + rootDir + " already existed; will not overwrite with " + lastBuild + " but will create a fresh build #" + asJob().getNextBuildNumber());
return newBuild();
}
builds.put(lastBuild);
lastBuild.getPreviousBuild(); // JENKINS-20662: create connection to previous build
return lastBuild;
} catch (InvocationTargetException e) {
LOGGER.log(Level.WARNING, String.format("A new build could not be created in job %s", asJob().getFullName()), e);
throw handleInvocationTargetException(e);
} catch (ReflectiveOperationException e) {
throw new LinkageError("A new build could not be created in " + asJob().getFullName() + ": " + e, e);
} catch (IllegalStateException e) {
throw new IOException("A new build could not be created in " + asJob().getFullName() + ": " + e, e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Error) {
throw (Error) t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {
return (IOException) t;
}
throw new Error(t);
}
/**
* Suitable for {@link Job#removeRun}.
*/
public final void removeRun(RunT run) {
if (!builds.remove(run)) {
LOGGER.log(Level.WARNING, "{0} did not contain {1} to begin with", new Object[] {asJob(), run});
}
}
/**
* Suitable for {@link Job#getBuild}.
*/
public final RunT getBuild(String id) {
return builds.getById(id);
}
/**
* Suitable for {@link Job#getBuildByNumber}.
*/
public final RunT getBuildByNumber(int n) {
return builds.getByNumber(n);
}
/**
* Suitable for {@link Job#getFirstBuild}.
*/
public final RunT getFirstBuild() {
return builds.oldestBuild();
}
/**
* Suitable for {@link Job#getLastBuild}.
*/
public final @CheckForNull RunT getLastBuild() {
return builds.newestBuild();
}
/**
* Suitable for {@link Job#getNearestBuild}.
*/
public final RunT getNearestBuild(int n) {
return builds.search(n, AbstractLazyLoadRunMap.Direction.ASC);
}
/**
* Suitable for {@link Job#getNearestOldBuild}.
*/
public final RunT getNearestOldBuild(int n) {
return builds.search(n, AbstractLazyLoadRunMap.Direction.DESC);
}
/**
* Suitable for {@link Job#getEstimatedDurationCandidates}.
* @since 2.407
*/
public List<RunT> getEstimatedDurationCandidates() {
var loadedBuilds = builds.getLoadedBuilds().values(); // reverse chronological order
List<RunT> candidates = new ArrayList<>(3);
for (Result threshold : List.of(Result.UNSTABLE, Result.FAILURE)) {
for (RunT build : loadedBuilds) {
if (candidates.contains(build)) {
continue;
}
if (!build.isBuilding()) {
Result result = build.getResult();
if (result != null && result.isBetterOrEqualTo(threshold)) {
candidates.add(build);
if (candidates.size() == 3) {
LOGGER.fine(() -> "Candidates: " + candidates);
return candidates;
}
}
}
}
}
LOGGER.fine(() -> "Candidates: " + candidates);
return candidates;
}
/**
* Suitable for {@link Job#createHistoryWidget}.
*/
public final HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget(asJob(), builds, Job.HISTORY_ADAPTER);
}
/**
* Marker for a {@link Job} which uses this mixin.
*/
public interface LazyLoadingJob<JobT extends Job<JobT, RunT> & Queue.Task & LazyBuildMixIn.LazyLoadingJob<JobT, RunT>, RunT extends Run<JobT, RunT> & LazyLoadingRun<JobT, RunT>> {
LazyBuildMixIn<JobT, RunT> getLazyBuildMixIn();
// not offering default implementation for _getRuns(), removeRun(R), getBuild(String), getBuildByNumber(int), getFirstBuild(), getLastBuild(), getNearestBuild(int), getNearestOldBuild(int), or createHistoryWidget()
// since they are defined in Job
// (could allow implementations to call LazyLoadingJob.super.theMethod())
}
/**
* Marker for a {@link Run} which uses this mixin.
*/
public interface LazyLoadingRun<JobT extends Job<JobT, RunT> & Queue.Task & LazyBuildMixIn.LazyLoadingJob<JobT, RunT>, RunT extends Run<JobT, RunT> & LazyLoadingRun<JobT, RunT>> {
RunMixIn<JobT, RunT> getRunMixIn();
// not offering default implementations for createReference() or dropLinks() since they are protected
// (though could use @Restricted(ProtectedExternally.class))
// nor for getPreviousBuild() or getNextBuild() since they are defined in Run
// (though could allow implementations to call LazyLoadingRun.super.theMethod())
}
/**
* Accompanying helper for the run type.
* Stateful but should be held in a {@code final transient} field.
*/
public abstract static class RunMixIn<JobT extends Job<JobT, RunT> & Queue.Task & LazyBuildMixIn.LazyLoadingJob<JobT, RunT>, RunT extends Run<JobT, RunT> & LazyLoadingRun<JobT, RunT>> {
/**
* Pointers to form bi-directional link between adjacent runs using
* {@link LazyBuildMixIn}.
*
* <p>
* Some {@link Run}s do lazy-loading, so we don't use
* {@link #previousBuildR} and {@link #nextBuildR}, and instead use these
* fields and point to {@link #selfReference} (or {@link #none}) of
* adjacent builds.
*/
private volatile BuildReference<RunT> previousBuildR, nextBuildR;
/**
* Used in {@link #previousBuildR} and {@link #nextBuildR} to indicate
* that we know there is no next/previous build (as opposed to {@code null},
* which is used to indicate we haven't determined if there is a next/previous
* build.)
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private static final BuildReference NONE = new BuildReference("NONE", null);
@SuppressWarnings("unchecked")
private BuildReference<RunT> none() {
return NONE;
}
private BuildReference<RunT> selfReference;
protected RunMixIn() {}
protected abstract RunT asRun();
/**
* To implement {@link Run#createReference}.
*/
public final synchronized BuildReference<RunT> createReference() {
if (selfReference == null) {
selfReference = new BuildReference<>(asRun().getId(), asRun());
}
return selfReference;
}
/**
* To implement {@link Run#dropLinks}.
*/
public final void dropLinks() {
if (nextBuildR != null) {
RunT nb = nextBuildR.get();
if (nb != null) {
nb.getRunMixIn().previousBuildR = previousBuildR;
}
}
if (previousBuildR != null) {
RunT pb = previousBuildR.get();
if (pb != null) {
pb.getRunMixIn().nextBuildR = nextBuildR;
}
}
// make this build object unreachable by other Runs
createReference().clear();
}
/**
* To implement {@link Run#getPreviousBuild}.
*/
public final RunT getPreviousBuild() {
while (true) {
BuildReference<RunT> r = previousBuildR; // capture the value once
if (r == null) {
// having two neighbors pointing to each other is important to make RunMap.removeValue work
JobT _parent = Objects.requireNonNull(asRun().getParent(), "no parent for " + asRun().number);
RunT pb = _parent.getLazyBuildMixIn()._getRuns().search(asRun().number - 1, AbstractLazyLoadRunMap.Direction.DESC);
if (pb != null) {
pb.getRunMixIn().nextBuildR = createReference(); // establish bi-di link
this.previousBuildR = pb.getRunMixIn().createReference();
LOGGER.log(FINER, "Linked {0}<->{1} in getPreviousBuild()", new Object[]{this, pb});
return pb;
} else {
this.previousBuildR = none();
return null;
}
}
if (r == none()) {
return null;
}
RunT referent = r.get();
if (referent != null) {
return referent;
}
// the reference points to a GC-ed object, drop the reference and do it again
this.previousBuildR = null;
}
}
/**
* To implement {@link Run#getNextBuild}.
*/
public final RunT getNextBuild() {
while (true) {
BuildReference<RunT> r = nextBuildR; // capture the value once
if (r == null) {
// having two neighbors pointing to each other is important to make RunMap.removeValue work
RunT nb = asRun().getParent().getLazyBuildMixIn()._getRuns().search(asRun().number + 1, AbstractLazyLoadRunMap.Direction.ASC);
if (nb != null) {
nb.getRunMixIn().previousBuildR = createReference(); // establish bi-di link
this.nextBuildR = nb.getRunMixIn().createReference();
LOGGER.log(FINER, "Linked {0}<->{1} in getNextBuild()", new Object[]{this, nb});
return nb;
} else {
this.nextBuildR = none();
return null;
}
}
if (r == none()) {
return null;
}
RunT referent = r.get();
if (referent != null) {
return referent;
}
// the reference points to a GC-ed object, drop the reference and do it again
this.nextBuildR = null;
}
}
}
@Restricted(DoNotUse.class)
@Extension public static final class ItemListenerImpl extends ItemListener {
@Override public void onLocationChanged(Item item, String oldFullName, String newFullName) {
if (item instanceof LazyLoadingJob) {
RunMap<?> builds = ((LazyLoadingJob) item).getLazyBuildMixIn().builds;
builds.updateBaseDir(((Job) item).getBuildDir());
}
}
}
}
| Dohbedoh/jenkins | core/src/main/java/jenkins/model/lazy/LazyBuildMixIn.java |
214,110 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
import org.lwjgl.system.windows.*;
/**
* The {@code VK_KHR_win32_surface} extension is an instance extension. It provides a mechanism to create a {@code VkSurfaceKHR} object (defined by the {@link KHRSurface VK_KHR_surface} extension) that refers to a Win32 {@code HWND}, as well as a query to determine support for rendering to the windows desktop.
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_KHR_win32_surface}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Instance extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>10</dd>
* <dt><b>Revision</b></dt>
* <dd>6</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link KHRSurface VK_KHR_surface}</dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Jesse Hall <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_win32_surface]%20@critsec%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_win32_surface%20extension*">critsec</a></li>
* <li>Ian Elliott <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_win32_surface]%20@ianelliottus%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_win32_surface%20extension*">ianelliottus</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-04-24</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Patrick Doane, Blizzard</li>
* <li>Faith Ekstrand, Intel</li>
* <li>Ian Elliott, LunarG</li>
* <li>Courtney Goeltzenleuchter, LunarG</li>
* <li>Jesse Hall, Google</li>
* <li>James Jones, NVIDIA</li>
* <li>Antoine Labour, Google</li>
* <li>Jon Leech, Khronos</li>
* <li>David Mao, AMD</li>
* <li>Norbert Nopper, Freescale</li>
* <li>Alon Or-bach, Samsung</li>
* <li>Daniel Rakos, AMD</li>
* <li>Graham Sellers, AMD</li>
* <li>Ray Smith, ARM</li>
* <li>Jeff Vigil, Qualcomm</li>
* <li>Chia-I Wu, LunarG</li>
* </ul></dd>
* </dl>
*/
public class KHRWin32Surface {
/** The extension specification version. */
public static final int VK_KHR_WIN32_SURFACE_SPEC_VERSION = 6;
/** The extension name. */
public static final String VK_KHR_WIN32_SURFACE_EXTENSION_NAME = "VK_KHR_win32_surface";
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR = 1000009000;
protected KHRWin32Surface() {
throw new UnsupportedOperationException();
}
// --- [ vkCreateWin32SurfaceKHR ] ---
/** Unsafe version of: {@link #vkCreateWin32SurfaceKHR CreateWin32SurfaceKHR} */
public static int nvkCreateWin32SurfaceKHR(VkInstance instance, long pCreateInfo, long pAllocator, long pSurface) {
long __functionAddress = instance.getCapabilities().vkCreateWin32SurfaceKHR;
if (CHECKS) {
check(__functionAddress);
VkWin32SurfaceCreateInfoKHR.validate(pCreateInfo);
}
return callPPPPI(instance.address(), pCreateInfo, pAllocator, pSurface, __functionAddress);
}
/**
* Create a VkSurfaceKHR object for an Win32 native window.
*
* <h5>C Specification</h5>
*
* <p>To create a {@code VkSurfaceKHR} object for a Win32 window, call:</p>
*
* <pre><code>
* VkResult vkCreateWin32SurfaceKHR(
* VkInstance instance,
* const VkWin32SurfaceCreateInfoKHR* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkSurfaceKHR* pSurface);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code instance} <b>must</b> be a valid {@code VkInstance} handle</li>
* <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid {@link VkWin32SurfaceCreateInfoKHR} structure</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>{@code pSurface} <b>must</b> be a valid pointer to a {@code VkSurfaceKHR} handle</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <p>Some Vulkan functions <b>may</b> call the {@code SendMessage} system API when interacting with a {@code VkSurfaceKHR} through a {@code VkSwapchainKHR}. In a multithreaded environment, calling {@code SendMessage} from a thread that is not the thread associated with {@code pCreateInfo}{@code ::hwnd} will block until the application has processed the window message. Thus, applications <b>should</b> either call these Vulkan functions on the message pump thread, or make sure their message pump is actively running. Failing to do so <b>may</b> result in deadlocks.</p>
*
* <p>The functions subject to this requirement are:</p>
*
* <ul>
* <li>{@link KHRSwapchain#vkCreateSwapchainKHR CreateSwapchainKHR}</li>
* <li>{@link KHRSwapchain#vkDestroySwapchainKHR DestroySwapchainKHR}</li>
* <li>{@link KHRSwapchain#vkAcquireNextImageKHR AcquireNextImageKHR} and {@link KHRSwapchain#vkAcquireNextImage2KHR AcquireNextImage2KHR}</li>
* <li>{@link KHRSwapchain#vkQueuePresentKHR QueuePresentKHR}</li>
* <li>{@link EXTSwapchainMaintenance1#vkReleaseSwapchainImagesEXT ReleaseSwapchainImagesEXT}</li>
* <li>{@link EXTFullScreenExclusive#vkAcquireFullScreenExclusiveModeEXT AcquireFullScreenExclusiveModeEXT}</li>
* <li>{@link EXTFullScreenExclusive#vkReleaseFullScreenExclusiveModeEXT ReleaseFullScreenExclusiveModeEXT}</li>
* <li>{@link EXTHdrMetadata#vkSetHdrMetadataEXT SetHdrMetadataEXT}</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}, {@link VkWin32SurfaceCreateInfoKHR}</p>
*
* @param instance the instance to associate the surface with.
* @param pCreateInfo a pointer to a {@link VkWin32SurfaceCreateInfoKHR} structure containing parameters affecting the creation of the surface object.
* @param pAllocator the allocator used for host memory allocated for the surface object when there is no more specific allocator available (see <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a>).
* @param pSurface a pointer to a {@code VkSurfaceKHR} handle in which the created surface object is returned.
*/
@NativeType("VkResult")
public static int vkCreateWin32SurfaceKHR(VkInstance instance, @NativeType("VkWin32SurfaceCreateInfoKHR const *") VkWin32SurfaceCreateInfoKHR pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSurfaceKHR *") LongBuffer pSurface) {
if (CHECKS) {
check(pSurface, 1);
}
return nvkCreateWin32SurfaceKHR(instance, pCreateInfo.address(), memAddressSafe(pAllocator), memAddress(pSurface));
}
// --- [ vkGetPhysicalDeviceWin32PresentationSupportKHR ] ---
/**
* Query queue family support for presentation on a Win32 display.
*
* <h5>C Specification</h5>
*
* <p>To determine whether a queue family of a physical device supports presentation to the Microsoft Windows desktop, call:</p>
*
* <pre><code>
* VkBool32 vkGetPhysicalDeviceWin32PresentationSupportKHR(
* VkPhysicalDevice physicalDevice,
* uint32_t queueFamilyIndex);</code></pre>
*
* <h5>Description</h5>
*
* <p>This platform-specific function <b>can</b> be called prior to creating a surface.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code queueFamilyIndex} <b>must</b> be less than {@code pQueueFamilyPropertyCount} returned by {@code vkGetPhysicalDeviceQueueFamilyProperties} for the given {@code physicalDevice}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* </ul>
*
* @param physicalDevice the physical device.
* @param queueFamilyIndex the queue family index.
*/
@NativeType("VkBool32")
public static boolean vkGetPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice physicalDevice, @NativeType("uint32_t") int queueFamilyIndex) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceWin32PresentationSupportKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPI(physicalDevice.address(), queueFamilyIndex, __functionAddress) != 0;
}
/** Array version of: {@link #vkCreateWin32SurfaceKHR CreateWin32SurfaceKHR} */
@NativeType("VkResult")
public static int vkCreateWin32SurfaceKHR(VkInstance instance, @NativeType("VkWin32SurfaceCreateInfoKHR const *") VkWin32SurfaceCreateInfoKHR pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSurfaceKHR *") long[] pSurface) {
long __functionAddress = instance.getCapabilities().vkCreateWin32SurfaceKHR;
if (CHECKS) {
check(__functionAddress);
check(pSurface, 1);
VkWin32SurfaceCreateInfoKHR.validate(pCreateInfo.address());
}
return callPPPPI(instance.address(), pCreateInfo.address(), memAddressSafe(pAllocator), pSurface, __functionAddress);
}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRWin32Surface.java |
214,111 | /*
* Copyright (C) 2009 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.internal.ErrorsException;
import org.elasticsearch.common.inject.internal.FailableCache;
import org.elasticsearch.common.inject.spi.InjectionPoint;
/**
* Constructor injectors by type.
*
* @author [email protected] (Jesse Wilson)
*/
class ConstructorInjectorStore {
private final InjectorImpl injector;
private final FailableCache<TypeLiteral<?>, ConstructorInjector<?>> cache = new FailableCache<TypeLiteral<?>, ConstructorInjector<?>>() {
@Override
@SuppressWarnings("unchecked")
protected ConstructorInjector<?> create(TypeLiteral<?> type, Errors errors) throws ErrorsException {
return createConstructor(type, errors);
}
};
ConstructorInjectorStore(InjectorImpl injector) {
this.injector = injector;
}
/**
* Returns a new complete constructor injector with injection listeners registered.
*/
@SuppressWarnings("unchecked") // the ConstructorInjector type always agrees with the passed type
public <T> ConstructorInjector<T> get(TypeLiteral<T> key, Errors errors) throws ErrorsException {
return (ConstructorInjector<T>) cache.get(key, errors);
}
private <T> ConstructorInjector<T> createConstructor(TypeLiteral<T> type, Errors errors)
throws ErrorsException {
int numErrorsBefore = errors.size();
InjectionPoint injectionPoint;
try {
injectionPoint = InjectionPoint.forConstructorOf(type);
} catch (ConfigurationException e) {
errors.merge(e.getErrorMessages());
throw errors.toException();
}
SingleParameterInjector<?>[] constructorParameterInjectors
= injector.getParametersInjectors(injectionPoint.getDependencies(), errors);
MembersInjectorImpl<T> membersInjector = injector.membersInjectorStore.get(type, errors);
ConstructionProxyFactory<T> factory = new DefaultConstructionProxyFactory<>(injectionPoint);
errors.throwIfNewErrors(numErrorsBefore);
return new ConstructorInjector<>(membersInjector.getInjectionPoints(), factory.create(),
constructorParameterInjectors, membersInjector);
}
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/ConstructorInjectorStore.java |
214,112 | /*
* Copyright (C) 2001-2016 Food and Agriculture Organization of the
* United Nations (FAO-UN), United Nations World Food Programme (WFP)
* and United Nations Environment Programme (UNEP)
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
* Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
* Rome - Italy. email: [email protected]
*/
package org.fao.geonet.kernel;
/**
* Enumeration indicating if the datestamp should be updated.
*
* User: Jesse Date: 10/10/13 Time: 7:29 PM
*/
public enum UpdateDatestamp {
YES, NO
}
| pvgenuchten/core-geonetwork | core/src/main/java/org/fao/geonet/kernel/UpdateDatestamp.java |
214,113 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2006 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.inject.internal.Errors;
import org.opensearch.common.inject.spi.Message;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import static java.util.Collections.singleton;
import static java.util.Collections.unmodifiableSet;
import static org.opensearch.common.util.set.Sets.newHashSet;
/**
* Indicates that there was a runtime failure while providing an instance.
*
* @author [email protected] (Kevin Bourrillion)
* @author [email protected] (Jesse Wilson)
* @since 2.0
*
* @opensearch.internal
*/
public final class ProvisionException extends RuntimeException {
private final Set<Message> messages;
/**
* Creates a ConfigurationException containing {@code messages}.
*/
public ProvisionException(Iterable<Message> messages) {
this.messages = unmodifiableSet(newHashSet(messages));
if (this.messages.isEmpty()) {
throw new IllegalArgumentException();
}
initCause(Errors.getOnlyCause(this.messages));
}
public ProvisionException(String message, Throwable cause) {
super(cause);
this.messages = singleton(new Message(Collections.emptyList(), message, cause));
}
public ProvisionException(String message) {
this.messages = singleton(new Message(message));
}
/**
* Returns messages for the errors that caused this exception.
*/
public Collection<Message> getErrorMessages() {
return messages;
}
@Override
public String getMessage() {
return Errors.format("Guice provision errors", messages);
}
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/ProvisionException.java |
214,114 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2006 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.inject.internal.BindingImpl;
import org.opensearch.common.inject.internal.Errors;
import org.opensearch.common.inject.internal.ErrorsException;
import org.opensearch.common.inject.internal.InternalContext;
import org.opensearch.common.inject.internal.Stopwatch;
import org.opensearch.common.inject.spi.Dependency;
import java.util.List;
/**
* Builds a tree of injectors. This is a primary injector, plus child injectors needed for each
* {@link Binder#newPrivateBinder() private environment}. The primary injector is not necessarily a
* top-level injector.
* <p>
* Injector construction happens in two phases.
* <ol>
* <li>Static building. In this phase, we interpret commands, create bindings, and inspect
* dependencies. During this phase, we hold a lock to ensure consistency with parent injectors.
* No user code is executed in this phase.</li>
* <li>Dynamic injection. In this phase, we call user code. We inject members that requested
* injection. This may require user's objects be created and their providers be called. And we
* create eager singletons. In this phase, user code may have started other threads. This phase
* is not executed for injectors created using {@link Stage#TOOL the tool stage}</li>
* </ol>
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
*
* @opensearch.internal
*/
class InjectorBuilder {
private final Stopwatch stopwatch = new Stopwatch();
private final Errors errors = new Errors();
private Stage stage;
private final Initializer initializer = new Initializer();
private final BindingProcessor bindingProcesor;
private final InjectionRequestProcessor injectionRequestProcessor;
private final InjectorShell.Builder shellBuilder = new InjectorShell.Builder();
private List<InjectorShell> shells;
InjectorBuilder() {
injectionRequestProcessor = new InjectionRequestProcessor(errors, initializer);
bindingProcesor = new BindingProcessor(errors, initializer);
}
/**
* Sets the stage for the created injector. If the stage is {@link Stage#PRODUCTION}, this class
* will eagerly load singletons.
*/
InjectorBuilder stage(Stage stage) {
shellBuilder.stage(stage);
this.stage = stage;
return this;
}
InjectorBuilder addModules(Iterable<? extends Module> modules) {
shellBuilder.addModules(modules);
return this;
}
Injector build() {
if (shellBuilder == null) {
throw new AssertionError("Already built, builders are not reusable.");
}
// Synchronize while we're building up the bindings and other injector state. This ensures that
// the JIT bindings in the parent injector don't change while we're being built
synchronized (shellBuilder.lock()) {
shells = shellBuilder.build(initializer, bindingProcesor, stopwatch, errors);
stopwatch.resetAndLog("Injector construction");
initializeStatically();
}
injectDynamically();
return primaryInjector();
}
/**
* Initialize and validate everything.
*/
private void initializeStatically() {
bindingProcesor.initializeBindings();
stopwatch.resetAndLog("Binding initialization");
for (InjectorShell shell : shells) {
shell.getInjector().index();
}
stopwatch.resetAndLog("Binding indexing");
injectionRequestProcessor.process(shells);
stopwatch.resetAndLog("Collecting injection requests");
bindingProcesor.runCreationListeners();
stopwatch.resetAndLog("Binding validation");
injectionRequestProcessor.validate();
stopwatch.resetAndLog("Static validation");
initializer.validateOustandingInjections(errors);
stopwatch.resetAndLog("Instance member validation");
new LookupProcessor(errors).process(shells);
for (InjectorShell shell : shells) {
((DeferredLookups) shell.getInjector().lookups).initialize(errors);
}
stopwatch.resetAndLog("Provider verification");
for (InjectorShell shell : shells) {
if (!shell.getElements().isEmpty()) {
throw new AssertionError("Failed to execute " + shell.getElements());
}
}
errors.throwCreationExceptionIfErrorsExist();
}
/**
* Returns the injector being constructed. This is not necessarily the root injector.
*/
private Injector primaryInjector() {
return shells.get(0).getInjector();
}
/**
* Inject everything that can be injected. This method is intentionally not synchronized. If we
* locked while injecting members (ie. running user code), things would deadlock should the user
* code build a just-in-time binding from another thread.
*/
private void injectDynamically() {
injectionRequestProcessor.injectMembers();
stopwatch.resetAndLog("Static member injection");
initializer.injectAll(errors);
stopwatch.resetAndLog("Instance injection");
errors.throwCreationExceptionIfErrorsExist();
for (InjectorShell shell : shells) {
loadEagerSingletons(shell.getInjector(), stage, errors);
}
stopwatch.resetAndLog("Preloading singletons");
errors.throwCreationExceptionIfErrorsExist();
}
/**
* Loads eager singletons, or all singletons if we're in Stage.PRODUCTION. Bindings discovered
* while we're binding these singletons are not be eager.
*/
public void loadEagerSingletons(InjectorImpl injector, Stage stage, Errors errors) {
for (final Binding<?> binding : injector.state.getExplicitBindingsThisLevel().values()) {
loadEagerSingletons(injector, stage, errors, (BindingImpl<?>) binding);
}
for (final Binding<?> binding : injector.jitBindings.values()) {
loadEagerSingletons(injector, stage, errors, (BindingImpl<?>) binding);
}
}
private void loadEagerSingletons(InjectorImpl injector, Stage stage, final Errors errors, BindingImpl<?> binding) {
if (binding.getScoping().isEagerSingleton(stage)) {
try {
injector.callInContext(new ContextualCallable<Void>() {
Dependency<?> dependency = Dependency.get(binding.getKey());
@Override
public Void call(InternalContext context) {
context.setDependency(dependency);
Errors errorsForBinding = errors.withSource(dependency);
try {
binding.getInternalFactory().get(errorsForBinding, context, dependency);
} catch (ErrorsException e) {
errorsForBinding.merge(e.getErrors());
} finally {
context.setDependency(null);
}
return null;
}
});
} catch (ErrorsException e) {
throw new AssertionError();
}
}
}
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/InjectorBuilder.java |
214,115 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.inject.internal.BindingImpl;
import org.opensearch.common.inject.internal.Errors;
import org.opensearch.common.inject.internal.MatcherAndConverter;
import org.opensearch.common.inject.spi.TypeListenerBinding;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptySet;
/**
* The inheritable data within an injector. This class is intended to allow parent and local
* injector data to be accessed as a unit.
*
* @author [email protected] (Jesse Wilson)
*
* @opensearch.internal
*/
interface State {
State NONE = new State() {
@Override
public State parent() {
throw new UnsupportedOperationException();
}
@Override
public <T> BindingImpl<T> getExplicitBinding(Key<T> key) {
return null;
}
@Override
public Map<Key<?>, Binding<?>> getExplicitBindingsThisLevel() {
throw new UnsupportedOperationException();
}
@Override
public void putBinding(Key<?> key, BindingImpl<?> binding) {
throw new UnsupportedOperationException();
}
@Override
public Scope getScope(Class<? extends Annotation> scopingAnnotation) {
return null;
}
@Override
public void putAnnotation(Class<? extends Annotation> annotationType, Scope scope) {
throw new UnsupportedOperationException();
}
@Override
public void addConverter(MatcherAndConverter matcherAndConverter) {
throw new UnsupportedOperationException();
}
@Override
public MatcherAndConverter getConverter(String stringValue, TypeLiteral<?> type, Errors errors, Object source) {
throw new UnsupportedOperationException();
}
@Override
public Iterable<MatcherAndConverter> getConvertersThisLevel() {
return emptySet();
}
@Override
public void addTypeListener(TypeListenerBinding typeListenerBinding) {
throw new UnsupportedOperationException();
}
@Override
public List<TypeListenerBinding> getTypeListenerBindings() {
return Collections.emptyList();
}
@Override
public void denylist(Key<?> key) {}
@Override
public boolean isDenylisted(Key<?> key) {
return true;
}
@Override
public void clearDenylisted() {}
@Override
public void makeAllBindingsToEagerSingletons(Injector injector) {}
@Override
public Object lock() {
throw new UnsupportedOperationException();
}
};
State parent();
/**
* Gets a binding which was specified explicitly in a module, or null.
*/
<T> BindingImpl<T> getExplicitBinding(Key<T> key);
/**
* Returns the explicit bindings at this level only.
*/
Map<Key<?>, Binding<?>> getExplicitBindingsThisLevel();
void putBinding(Key<?> key, BindingImpl<?> binding);
/**
* Returns the matching scope, or null.
*/
Scope getScope(Class<? extends Annotation> scopingAnnotation);
void putAnnotation(Class<? extends Annotation> annotationType, Scope scope);
void addConverter(MatcherAndConverter matcherAndConverter);
/**
* Returns the matching converter for {@code type}, or null if none match.
*/
MatcherAndConverter getConverter(String stringValue, TypeLiteral<?> type, Errors errors, Object source);
/**
* Returns all converters at this level only.
*/
Iterable<MatcherAndConverter> getConvertersThisLevel();
void addTypeListener(TypeListenerBinding typeListenerBinding);
List<TypeListenerBinding> getTypeListenerBindings();
/**
* Forbids the corresponding injector from creating a binding to {@code key}. Child injectors
* denylist their bound keys on their parent injectors to prevent just-in-time bindings on the
* parent injector that would conflict.
*/
void denylist(Key<?> key);
/**
* Returns true if {@code key} is forbidden from being bound in this injector. This indicates that
* one of this injector's descendent's has bound the key.
*/
boolean isDenylisted(Key<?> key);
/**
* Returns the shared lock for all injector data. This is a low-granularity, high-contention lock
* to be used when reading mutable data (ie. just-in-time bindings, and binding denylists).
*/
Object lock();
// ES_GUICE: clean denylist keys
void clearDenylisted();
void makeAllBindingsToEagerSingletons(Injector injector);
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/State.java |
214,116 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject;
import java.lang.reflect.Constructor;
/**
* Abstraction for Java's reflection APIs. This interface exists to provide a single place where
* runtime reflection can be substituted for another mechanism such as CGLib or compile-time code
* generation.
*
* @author [email protected] (Jesse Wilson)
*/
class Reflection {
/**
* A placeholder. This enables us to continue processing and gather more
* errors but blows up if you actually try to use it.
*/
static class InvalidConstructor {
InvalidConstructor() {
throw new AssertionError();
}
}
@SuppressWarnings("unchecked")
static <T> Constructor<T> invalidConstructor() {
try {
return (Constructor<T>) InvalidConstructor.class.getConstructor();
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/Reflection.java |
214,117 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2009 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject.spi;
import org.opensearch.common.annotation.PublicApi;
/**
* Listens for injections into instances of type {@code I}. Useful for performing further
* injections, post-injection initialization, and more.
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
* @since 2.0
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public interface InjectionListener<I> {
/**
* Invoked by Guice after it injects the fields and methods of instance.
*
* @param injectee instance that Guice injected dependencies into
*/
void afterInjection(I injectee);
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/spi/InjectionListener.java |
214,119 | /**
* Packer version 3.0 (final)
* Copyright 2004-2007, Dean Edwards
* Web: {@link http://dean.edwards.name/}
*
* This software is licensed under the MIT license
* Web: {@link http://www.opensource.org/licenses/mit-license}
*
* Ported to Java by Pablo Santiago based on C# version by Jesse Hansen, <twindagger2k @ msn.com>
* Web: {@link http://jpacker.googlecode.com/}
* Email: <pablo.santiago @ gmail.com>
*/
package com.jpacker;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.jpacker.encoders.BasicEncoder;
import com.jpacker.encoders.Encoder;
import com.jpacker.strategies.DefaultReplacementStrategy;
import com.jpacker.strategies.ReplacementStrategy;
/**
* Packer class.
*
* Main jPacker class that packs the script.
*
* @author Pablo Santiago <pablo.santiago @ gmail.com>
*/
public class JPackerExecuter {
private JPackerEncoding encoding;
private static final String UNPACK = "eval(function(p,a,c,k,e,r){e=%5$s;if(!''.replace(/^/,String)){while(c--)r[%6$s]=k[c]"
+ "||%6$s;k=[function(e){return r[e]}];e=function(){return'\\\\w+'};c=1};while(c--)if(k[c])p=p."
+ "replace(new RegExp('\\\\b'+e(c)+'\\\\b','g'),k[c]);return p}('%1$s',%2$s,%3$s,'%4$s'.split('|'),0,{}))";
/**
* Constructor
*
* @param encoding
* The encoding level for this instance
*/
public JPackerExecuter(JPackerEncoding encoding) {
setEncoding(encoding);
}
/**
* Packs the script
*
* @param script
* The script to pack
* @param minifyOnly
* True if script should only be minified and not encoded and/or
* its variables shrunk, false otherwise.
* @param shrinkVariables
* True if variables should be shrunk, false otherwise. If
* minifyOnly is true, this option has no side effect.
* @return The packed script
*/
public String pack(String script, boolean minifyOnly, boolean shrinkVariables) {
script += "\n";
script = minify(script);
if (!minifyOnly) {
if (shrinkVariables) {
script = shrinkVariables(script);
}
if (encoding != JPackerEncoding.NONE) {
script = encode(script);
}
}
return script;
}
// zero encoding - just removal of whitespace and comments
private String minify(String script) {
JPackerParser parser = new JPackerParser();
ReplacementStrategy defaultStrat = new DefaultReplacementStrategy();
// protect data
parser = addDataRegEx(parser);
script = parser.exec(script, defaultStrat);
// remove white-space
parser = addWhiteSpaceRegEx(parser);
script = parser.exec(script, defaultStrat);
// clean
parser = addCleanUpRegEx(parser);
script = parser.exec(script, defaultStrat);
// done
return script;
}
private JPackerParser addDataRegEx(JPackerParser parser) {
final String COMMENT1 = "(\\/\\/|;;;)[^\\n]*";
final String COMMENT2 = "\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/";
final String REGEX = "\\/(\\\\[\\/\\\\]|[^*\\/])(\\\\.|[^\\/\\n\\\\])*\\/[gim]*";
// Packer.CONTINUE
parser.remove("\\\\\\r?\\n");
parser.ignore("'(\\\\.|[^'\\\\])*'");
parser.ignore("\"(\\\\.|[^\"\\\\])*\"");
parser.ignore("\\/\\*@|@\\*\\/|\\/\\/@[^\\n]*\\n");
parser.replace("(" + COMMENT1 + ")\\n\\s*(" + REGEX + ")?", "\n$3");
parser.replace("(" + COMMENT2 + ")\\s*(" + REGEX + ")?", " $3");
parser.replace("([\\[\\(\\^=,{}:;&|!*?])\\s*(" + REGEX + ")", "$1$2");
return parser;
}
private JPackerParser addCleanUpRegEx(JPackerParser parser) {
parser.replace("\\(\\s*;\\s*;\\s*\\)", "(;;)");
parser.ignore("throw[};]+[};]"); // safari 1.3 bug
parser.replace(";+\\s*([};])", "$1");
parser.remove(";;[^\\n\\r]+[\\n\\r]");
return parser;
}
private JPackerParser addWhiteSpaceRegEx(JPackerParser parser) {
parser.replace("(\\d)\\s+(\\.\\s*[a-z\\$_\\[\\(])", "$1 $2");
parser.replace("([+\\-])\\s+([+\\-])", "$1 $2");
parser.replace("(\\b|\\$)\\s+(\\b|\\$)", "$1 $2");
parser.replace("\\b\\s+\\$\\s+\\b", " $ ");
parser.replace("\\$\\s+\\b", "$ ");
parser.replace("\\b\\s+\\$", " $");
parser.replace("\\b\\s+\\b", " ");
parser.remove("\\s+");
return parser;
}
private String shrinkVariables(String script) {
final Pattern pattern = Pattern.compile("^[^'\"]\\/");
// identify blocks, particularly identify function blocks (which define
// scope)
Pattern blockPattern = Pattern.compile("(function\\s*[\\w$]*\\s*\\(\\s*([^\\)]*)\\s*\\)\\s*)?(\\{([^{}]*)\\})");
List<String> blocks = new ArrayList<String>(); // store program blocks
// (anything between
// braces {})
final List<String> data = new ArrayList<String>(); // encoded strings
// and regular
// expressions
JPackerParser parser = new JPackerParser();
parser = addDataRegEx(parser);
script = parser.exec(script, new ReplacementStrategy() {
@Override
public String replace(List<JPackerPattern> patterns, Matcher matcher) {
String replacement = "#" + data.size();
String string = matcher.group();
if (pattern.matcher(string).find()) {
replacement = string.charAt(0) + replacement;
string = string.substring(1);
}
data.add(string);
return replacement;
}
});
do {
// put the blocks back
Matcher blockMatcher = blockPattern.matcher(script);
StringBuffer sb = new StringBuffer();
while (blockMatcher.find()) {
blockMatcher.appendReplacement(sb, encodeBlock(blockMatcher, blocks));
}
blockMatcher.appendTail(sb);
script = sb.toString();
} while (blockPattern.matcher(script).find());
while (Pattern.compile("~(\\d+)~").matcher(script).find()) {
script = decodeBlock(script, blocks);
}
// put strings and regular expressions back
Matcher storeMatcher = Pattern.compile("#(\\d+)").matcher(script);
StringBuffer sb2 = new StringBuffer();
while (storeMatcher.find()) {
int num = Integer.parseInt(storeMatcher.group(1));
storeMatcher.appendReplacement(sb2, Matcher.quoteReplacement(data.get(num)));
}
storeMatcher.appendTail(sb2);
return sb2.toString();
}
private String encode(String script) {
JPackerWords words = new JPackerWords(script, encoding);
Pattern wordsPattern = Pattern.compile("\\w+");
Matcher wordsMatcher = wordsPattern.matcher(script);
StringBuffer sb = new StringBuffer();
while (wordsMatcher.find()) {
JPackerWord tempWord = new JPackerWord(wordsMatcher.group());
wordsMatcher.appendReplacement(sb, words.find(tempWord).getEncoded());
}
wordsMatcher.appendTail(sb);
int ascii = Math.min(Math.max(words.getWords().size(), 2), encoding.getEncodingBase());
String p = escape(sb.toString());
String a = String.valueOf(ascii);
String c = String.valueOf(words.getWords().size());
String k = words.toString();
String e = getEncode(ascii);
String r = ascii > 10 ? "e(c)" : "c";
return new Formatter().format(UNPACK, p, a, c, k, e, r).toString();
}
// encoder for program blocks
private String encodeBlock(Matcher matcher, List<String> blocks) {
String block = matcher.group();
String func = matcher.group(1);
String args = matcher.group(2);
if (func != null && !func.isEmpty()) { // the block is a function block
// decode the function block (THIS IS THE IMPORTANT BIT)
// We are retrieving all sub-blocks and will re-parse them in light
// of newly shrunk variables
while (Pattern.compile("~(\\d+)~").matcher(block).find()) {
block = decodeBlock(block, blocks);
}
// create the list of variable and argument names
Pattern varNamePattern = Pattern.compile("var\\s+[\\w$]+");
Matcher varNameMatcher = varNamePattern.matcher(block);
StringBuilder sb = new StringBuilder();
while (varNameMatcher.find()) {
sb.append(varNameMatcher.group()).append(",");
}
String vars = "";
if (!sb.toString().isEmpty()) {
vars = sb.deleteCharAt(sb.length() - 1).toString().replaceAll("var\\s+", "");
}
String[] ids = concat(args.split("\\s*,\\s*"), vars.split("\\s*,\\s*"));
Set<String> idList = new LinkedHashSet<String>();
for (String s : ids) {
if (!s.isEmpty()) {
idList.add(s);
}
}
// process each identifier
int count = 0;
String shortId;
for (String id : idList) {
id = id.trim();
if (id.length() > 1) { // > 1 char
id = Matcher.quoteReplacement(id);
// find the next free short name (check everything in the
// current scope)
Encoder e = new BasicEncoder();
do {
shortId = e.encode(count++);
} while (Pattern.compile("[^\\w$.]" + shortId + "[^\\w$:]").matcher(block).find());
// replace the long name with the short name
while (Pattern.compile("([^\\w$.])" + id + "([^\\w$:])").matcher(block).find()) {
block = block.replaceAll("([^\\w$.])" + id + "([^\\w$:])", "$1" + shortId + "$2");
}
block = block.replaceAll("([^{,\\w$.])" + id + ":", "$1" + shortId + ":");
}
}
}
String replacement = "~" + blocks.size() + "~";
blocks.add(block);
return replacement;
}
private String decodeBlock(String block, List<String> blocks) {
Matcher encoded = Pattern.compile("~(\\d+)~").matcher(block);
StringBuffer sbe = new StringBuffer();
while (encoded.find()) {
int num = Integer.parseInt(encoded.group(1));
encoded.appendReplacement(sbe, Matcher.quoteReplacement(blocks.get(num)));
}
encoded.appendTail(sbe);
return sbe.toString();
}
private String[] concat(String[] a, String[] b) {
String[] c = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
private String getEncode(int ascii) {
if (ascii > 96) {
return JPackerEncoding.HIGH_ASCII.getEncode();
} else if (ascii > 36) {
return JPackerEncoding.NORMAL.getEncode();
} else if (ascii > 10) {
return JPackerEncoding.MID.getEncode();
} else {
return JPackerEncoding.NUMERIC.getEncode();
}
}
private String escape(String input) {
// single quotes wrap the final string so escape them
// also escape new lines required by conditional comments
return input.replaceAll("([\\\\'])", "\\\\$1").replaceAll("[\\r\\n]+", "\\n");
}
/**
* Encoding level. Options are: {@link JPackerEncoding#NONE},
* {@link JPackerEncoding#NUMERIC}, {@link JPackerEncoding#MID},
* {@link JPackerEncoding#NORMAL} and {@link JPackerEncoding#HIGH_ASCII}.
*
* @return The current encoding level
*/
public JPackerEncoding getEncoding() {
return encoding;
}
/**
* Set the encoding level to use.
*
* @param encoding
*/
public final void setEncoding(JPackerEncoding encoding) {
this.encoding = encoding;
}
}
| jindrapetrik/jpexs-decompiler | libsrc/jpacker/src/com/jpacker/JPackerExecuter.java |
214,120 | /**
* Packer version 3.0 (final)
* Copyright 2004-2007, Dean Edwards
* Web: {@link http://dean.edwards.name/}
*
* This software is licensed under the MIT license
* Web: {@link http://www.opensource.org/licenses/mit-license}
*
* Ported to Java by Pablo Santiago based on C# version by Jesse Hansen, <twindagger2k @ msn.com>
* Web: {@link http://jpacker.googlecode.com/}
* Email: <pablo.santiago @ gmail.com>
*/
package com.jpacker.strategies;
import java.util.List;
import java.util.regex.Matcher;
import com.jpacker.JPackerPattern;
/**
* Default replacement strategy class.
*
* @author Pablo Santiago <pablo.santiago @ gmail.com>
*/
public class DefaultReplacementStrategy implements ReplacementStrategy {
/**
* Default replacement function. Called once for each match found
*
* @param jpatterns
* A List<JPackerPattern> that contains all
* {@link JPackerPattern} objects that wrap expressions to be
* evaluated
* @param matcher
* A {@link Matcher} object that corresponds to a match in the
* script
*/
@Override
public String replace(List<JPackerPattern> jpatterns, Matcher matcher) {
int i = 1;
// loop through the patterns
for (JPackerPattern jpattern : jpatterns) {
// do we have a result?
if (isMatch(matcher.group(i))) {
return jpattern.getEvaluator().evaluate(matcher, i);
} else { // skip over references to sub-expressions
i += jpattern.getLength();
}
}
return matcher.group(); // should never be hit, but you never know
}
// check that match is not an empty string
private boolean isMatch(String match) {
return match != null && !match.isEmpty();
}
}
| jindrapetrik/jpexs-decompiler | libsrc/jpacker/src/com/jpacker/strategies/DefaultReplacementStrategy.java |
214,121 | /*
* Copyright (C) 2018 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 okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public final class PreemptiveAuth {
private final OkHttpClient client;
public PreemptiveAuth() {
client = new OkHttpClient.Builder()
.addInterceptor(
new BasicAuthInterceptor("publicobject.com", "jesse", "password1"))
.build();
}
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/secrets/hellosecret.txt")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
public static void main(String... args) throws Exception {
new PreemptiveAuth().run();
}
static final class BasicAuthInterceptor implements Interceptor {
private final String credentials;
private final String host;
BasicAuthInterceptor(String host, String username, String password) {
this.credentials = Credentials.basic(username, password);
this.host = host;
}
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.url().host().equals(host)) {
request = request.newBuilder()
.header("Authorization", credentials)
.build();
}
return chain.proceed(request);
}
}
}
| DataDog/okhttp | samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java |
214,122 | /* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.wfs;
import java.util.List;
import org.geoserver.ExtendedCapabilitiesProvider;
import org.geoserver.platform.GeoServerExtensions;
import org.springframework.context.ApplicationContext;
/**
* Utility class uses to process GeoServer WFS extension points.
*
* @author Jesse Eichar
* @version $Id$
*/
public class WFSExtensions {
/** Looks up {@link ExtendedCapabilitiesProvider} extensions. */
public static List<WFSExtendedCapabilitiesProvider> findExtendedCapabilitiesProviders(
final ApplicationContext applicationContext) {
return GeoServerExtensions.extensions(
WFSExtendedCapabilitiesProvider.class, applicationContext);
}
}
| sweco-se/geoserver-planetfederal | src/wfs/src/main/java/org/geoserver/wfs/WFSExtensions.java |
214,123 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/**
* This extension allows the use of SPIR-V 1.4 shader modules. SPIR-V 1.4’s new features primarily make it an easier target for compilers from high-level languages, rather than exposing new hardware functionality.
*
* <p>SPIR-V 1.4 incorporates features that are also available separately as extensions. SPIR-V 1.4 shader modules do not need to enable those extensions with the {@code OpExtension} opcode, since they are integral parts of SPIR-V 1.4.</p>
*
* <p>SPIR-V 1.4 introduces new floating point execution mode capabilities, also available via {@code SPV_KHR_float_controls}. Implementations are not required to support all of these new capabilities; support can be queried using {@link VkPhysicalDeviceFloatControlsPropertiesKHR} from the {@link KHRShaderFloatControls VK_KHR_shader_float_controls} extension.</p>
*
* <h5>Promotion to Vulkan 1.2</h5>
*
* <p>All functionality in this extension is included in core Vulkan 1.2, with the KHR suffix omitted. The original type, enum and command names are still available as aliases of the core functionality.</p>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_KHR_spirv_1_4}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>237</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1">Version 1.1</a> and {@link KHRShaderFloatControls VK_KHR_shader_float_controls}</dd>
* <dt><b>Deprecation State</b></dt>
* <dd><ul>
* <li><em>Promoted</em> to <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.2-promotions">Vulkan 1.2</a></li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Jesse Hall <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_spirv_1_4]%20@critsec%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_spirv_1_4%20extension*">critsec</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2019-04-01</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Interactions and External Dependencies</b></dt>
* <dd><ul>
* <li>Requires SPIR-V 1.4.</li>
* </ul></dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Alexander Galazin, Arm</li>
* <li>David Neto, Google</li>
* <li>Jesse Hall, Google</li>
* <li>John Kessenich, Google</li>
* <li>Neil Henning, AMD</li>
* <li>Tom Olson, Arm</li>
* </ul></dd>
* </dl>
*/
public final class KHRSpirv14 {
/** The extension specification version. */
public static final int VK_KHR_SPIRV_1_4_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_KHR_SPIRV_1_4_EXTENSION_NAME = "VK_KHR_spirv_1_4";
private KHRSpirv14() {}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRSpirv14.java |
214,124 | /* (c) 2017 Open Source Geospatial Foundation - all rights reserved
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.wfs;
import java.util.Collections;
import java.util.List;
import org.geoserver.ExtendedCapabilitiesProvider;
import org.geoserver.wfs.request.GetCapabilitiesRequest;
import org.geotools.util.Version;
/**
* This interface is essentially an alias for the Generic ExtendedCapabilitiesProvider so that the
* Type Parameters do not need to be declared everywhere and so that when loading extensions there
* is a distinct class of beans to load
*
* @author Jesse Eichar, camptocamp
*/
public interface WFSExtendedCapabilitiesProvider
extends ExtendedCapabilitiesProvider<WFSInfo, GetCapabilitiesRequest> {
/**
* Returns the extra profiles this plugin is adding to the base specification for the given
* service version. Called only for version >= 2.0.
*
* @return A non null list of implemented profiles (eventually empty)
*/
default List<String> getProfiles(Version version) {
return Collections.emptyList();
}
/**
* Allows extension points to examine and eventually alter top level operation metadata
* constraints (the default implementation does nothing). Called only for version >= 2.0.
*/
default void updateRootOperationConstraints(Version version, List<DomainType> constraints) {
// does nothing
}
/**
* Allows extension points to examine and eventually alter single operation metadata. Called
* only for version >= 1.1.
*
* @param version The service version
* @param operations The operations
*/
default void updateOperationMetadata(Version version, List<OperationMetadata> operations) {
// does nothing
}
}
| sweco-se/geoserver-planetfederal | src/wfs/src/main/java/org/geoserver/wfs/WFSExtendedCapabilitiesProvider.java |
214,125 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject.spi;
import org.elasticsearch.common.inject.Binding;
import org.elasticsearch.common.inject.Key;
/**
* A binding to a linked key. The other key's binding is used to resolve injections.
*
* @author [email protected] (Jesse Wilson)
* @since 2.0
*/
public interface LinkedKeyBinding<T> extends Binding<T> {
/**
* Returns the linked key used to resolve injections.
*/
Key<? extends T> getLinkedKey();
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/spi/LinkedKeyBinding.java |
214,126 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/**
* This extension defines a special queue family, {@link #VK_QUEUE_FAMILY_FOREIGN_EXT QUEUE_FAMILY_FOREIGN_EXT}, which can be used to transfer ownership of resources backed by external memory to foreign, external queues. This is similar to {@link KHRExternalMemory#VK_QUEUE_FAMILY_EXTERNAL_KHR QUEUE_FAMILY_EXTERNAL_KHR}, defined in {@link KHRExternalMemory VK_KHR_external_memory}. The key differences between the two are:
*
* <ul>
* <li>The queues represented by {@link KHRExternalMemory#VK_QUEUE_FAMILY_EXTERNAL_KHR QUEUE_FAMILY_EXTERNAL_KHR} must share the same physical device and the same driver version as the current {@code VkInstance}. {@link #VK_QUEUE_FAMILY_FOREIGN_EXT QUEUE_FAMILY_FOREIGN_EXT} has no such restrictions. It can represent devices and drivers from other vendors, and can even represent non-Vulkan-capable devices.</li>
* <li>All resources backed by external memory support {@link KHRExternalMemory#VK_QUEUE_FAMILY_EXTERNAL_KHR QUEUE_FAMILY_EXTERNAL_KHR}. Support for {@link #VK_QUEUE_FAMILY_FOREIGN_EXT QUEUE_FAMILY_FOREIGN_EXT} is more restrictive.</li>
* <li>Applications should expect transitions to/from {@link #VK_QUEUE_FAMILY_FOREIGN_EXT QUEUE_FAMILY_FOREIGN_EXT} to be more expensive than transitions to/from {@link KHRExternalMemory#VK_QUEUE_FAMILY_EXTERNAL_KHR QUEUE_FAMILY_EXTERNAL_KHR}.</li>
* </ul>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_EXT_queue_family_foreign}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>127</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link KHRExternalMemory VK_KHR_external_memory} or <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1">Version 1.1</a></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Lina Versace <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_queue_family_foreign]%20@versalinyaa%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_queue_family_foreign%20extension*">versalinyaa</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-11-01</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Lina Versace, Google</li>
* <li>James Jones, NVIDIA</li>
* <li>Faith Ekstrand, Intel</li>
* <li>Jesse Hall, Google</li>
* <li>Daniel Rakos, AMD</li>
* <li>Ray Smith, ARM</li>
* </ul></dd>
* </dl>
*/
public final class EXTQueueFamilyForeign {
/** The extension specification version. */
public static final int VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = "VK_EXT_queue_family_foreign";
/** VK_QUEUE_FAMILY_FOREIGN_EXT */
public static final int VK_QUEUE_FAMILY_FOREIGN_EXT = (~2);
private EXTQueueFamilyForeign() {}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/EXTQueueFamilyForeign.java |
214,127 | /**
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Binder;
import com.google.inject.ConfigurationException;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.binder.ScopedBindingBuilder;
import com.google.inject.spi.Element;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.Message;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Set;
/**
* Bind a non-constant key.
*
* @author [email protected] (Jesse Wilson)
*/
public class BindingBuilder<T> extends AbstractBindingBuilder<T>
implements AnnotatedBindingBuilder<T> {
public BindingBuilder(Binder binder, List<Element> elements, Object source, Key<T> key) {
super(binder, elements, source, key);
}
public BindingBuilder<T> annotatedWith(Class<? extends Annotation> annotationType) {
annotatedWithInternal(annotationType);
return this;
}
public BindingBuilder<T> annotatedWith(Annotation annotation) {
annotatedWithInternal(annotation);
return this;
}
public BindingBuilder<T> to(Class<? extends T> implementation) {
return to(Key.get(implementation));
}
public BindingBuilder<T> to(TypeLiteral<? extends T> implementation) {
return to(Key.get(implementation));
}
public BindingBuilder<T> to(Key<? extends T> linkedKey) {
checkNotNull(linkedKey, "linkedKey");
checkNotTargetted();
BindingImpl<T> base = getBinding();
setBinding(new LinkedBindingImpl<T>(
base.getSource(), base.getKey(), base.getScoping(), linkedKey));
return this;
}
public void toInstance(T instance) {
checkNotTargetted();
// lookup the injection points, adding any errors to the binder's errors list
Set<InjectionPoint> injectionPoints;
if (instance != null) {
try {
injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass());
} catch (ConfigurationException e) {
copyErrorsToBinder(e);
injectionPoints = e.getPartialValue();
}
} else {
binder.addError(BINDING_TO_NULL);
injectionPoints = ImmutableSet.of();
}
BindingImpl<T> base = getBinding();
setBinding(new InstanceBindingImpl<T>(
base.getSource(), base.getKey(), Scoping.EAGER_SINGLETON, injectionPoints, instance));
}
public BindingBuilder<T> toProvider(Provider<? extends T> provider) {
return toProvider((javax.inject.Provider<T>) provider);
}
public BindingBuilder<T> toProvider(javax.inject.Provider<? extends T> provider) {
checkNotNull(provider, "provider");
checkNotTargetted();
// lookup the injection points, adding any errors to the binder's errors list
Set<InjectionPoint> injectionPoints;
try {
injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass());
} catch (ConfigurationException e) {
copyErrorsToBinder(e);
injectionPoints = e.getPartialValue();
}
BindingImpl<T> base = getBinding();
setBinding(new ProviderInstanceBindingImpl<T>(
base.getSource(), base.getKey(), base.getScoping(), injectionPoints, provider));
return this;
}
public BindingBuilder<T> toProvider(
Class<? extends javax.inject.Provider<? extends T>> providerType) {
return toProvider(Key.get(providerType));
}
public BindingBuilder<T> toProvider(
TypeLiteral<? extends javax.inject.Provider<? extends T>> providerType) {
return toProvider(Key.get(providerType));
}
public BindingBuilder<T> toProvider(
Key<? extends javax.inject.Provider<? extends T>> providerKey) {
checkNotNull(providerKey, "providerKey");
checkNotTargetted();
BindingImpl<T> base = getBinding();
setBinding(new LinkedProviderBindingImpl<T>(
base.getSource(), base.getKey(), base.getScoping(), providerKey));
return this;
}
public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor) {
return toConstructor(constructor, TypeLiteral.get(constructor.getDeclaringClass()));
}
public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor,
TypeLiteral<? extends S> type) {
checkNotNull(constructor, "constructor");
checkNotNull(type, "type");
checkNotTargetted();
BindingImpl<T> base = getBinding();
Set<InjectionPoint> injectionPoints;
try {
injectionPoints = InjectionPoint.forInstanceMethodsAndFields(type);
} catch (ConfigurationException e) {
copyErrorsToBinder(e);
injectionPoints = e.getPartialValue();
}
try {
InjectionPoint constructorPoint = InjectionPoint.forConstructor(constructor, type);
setBinding(new ConstructorBindingImpl<T>(base.getKey(), base.getSource(), base.getScoping(),
constructorPoint, injectionPoints));
} catch (ConfigurationException e) {
copyErrorsToBinder(e);
}
return this;
}
@Override public String toString() {
return "BindingBuilder<" + getBinding().getKey().getTypeLiteral() + ">";
}
private void copyErrorsToBinder(ConfigurationException e) {
for (Message message : e.getErrorMessages()) {
binder.addError(message);
}
}
}
| Andlab/roboguice | guice/core/src/com/google/inject/internal/BindingBuilder.java |
214,128 | /*
* 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.netbeans.modules.ant.freeform;
/**
* Freeform project type.
* @author Jesse Glick
*/
public final class FreeformProjectType {
public static final String TYPE = "org.netbeans.modules.ant.freeform";
public static final String NS_GENERAL_1 = "http://www.netbeans.org/ns/freeform-project/1"; // NOI18N
public static final String NS_GENERAL = org.netbeans.modules.ant.freeform.spi.support.Util.NAMESPACE;
public static final String NAME_SHARED = "general-data"; // NOI18N
static final String NS_GENERAL_PRIVATE = "http://www.netbeans.org/ns/freeform-project-private/1"; // NOI18N
}
| apache/netbeans | java/ant.freeform/src/org/netbeans/modules/ant/freeform/FreeformProjectType.java |
214,129 | /*
* Copyright (C) 2007 Google 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 org.elasticsearch.common.inject.assistedinject;
import org.elasticsearch.common.inject.ConfigurationException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.inject.TypeLiteral;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.spi.Dependency;
import org.elasticsearch.common.inject.spi.HasDependencies;
import org.elasticsearch.common.inject.spi.Message;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static java.util.Collections.singleton;
import static java.util.Collections.unmodifiableSet;
/**
* Provides a factory that combines the caller's arguments with injector-supplied values to
* construct objects.
* <h3>Defining a factory</h3>
* Create an interface whose methods return the constructed type, or any of its supertypes. The
* method's parameters are the arguments required to build the constructed type.
* <pre>public interface PaymentFactory {
* Payment create(Date startDate, Money amount);
* }</pre>
* You can name your factory methods whatever you like, such as <i>create</i>, <i>createPayment</i>
* or <i>newPayment</i>.
* <h3>Creating a type that accepts factory parameters</h3>
* {@code constructedType} is a concrete class with an {@literal @}{@link Inject}-annotated
* constructor. In addition to injector-supplied parameters, the constructor should have
* parameters that match each of the factory method's parameters. Each factory-supplied parameter
* requires an {@literal @}{@link Assisted} annotation. This serves to document that the parameter
* is not bound by your application's modules.
* <pre>public class RealPayment implements Payment {
* {@literal @}Inject
* public RealPayment(
* CreditService creditService,
* AuthService authService,
* <strong>{@literal @}Assisted Date startDate</strong>,
* <strong>{@literal @}Assisted Money amount</strong>) {
* ...
* }
* }</pre>
* Any parameter that permits a null value should also be annotated {@code @Nullable}.
* <h3>Configuring factories</h3>
* In your {@link org.elasticsearch.common.inject.Module module}, bind the factory interface to the returned
* factory:
* <pre>bind(PaymentFactory.class).toProvider(
* FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));</pre>
* As a side-effect of this binding, Guice will inject the factory to initialize it for use. The
* factory cannot be used until the injector has been initialized.
* <h3>Using the factory</h3>
* Inject your factory into your application classes. When you use the factory, your arguments
* will be combined with values from the injector to construct an instance.
* <pre>public class PaymentAction {
* {@literal @}Inject private PaymentFactory paymentFactory;
* public void doPayment(Money amount) {
* Payment payment = paymentFactory.create(new Date(), amount);
* payment.apply();
* }
* }</pre>
* <h3>Making parameter types distinct</h3>
* The types of the factory method's parameters must be distinct. To use multiple parameters of
* the same type, use a named {@literal @}{@link Assisted} annotation to disambiguate the
* parameters. The names must be applied to the factory method's parameters:
* <pre>public interface PaymentFactory {
* Payment create(
* <strong>{@literal @}Assisted("startDate")</strong> Date startDate,
* <strong>{@literal @}Assisted("dueDate")</strong> Date dueDate,
* Money amount);
* } </pre>
* ...and to the concrete type's constructor parameters:
* <pre>public class RealPayment implements Payment {
* {@literal @}Inject
* public RealPayment(
* CreditService creditService,
* AuthService authService,
* <strong>{@literal @}Assisted("startDate")</strong> Date startDate,
* <strong>{@literal @}Assisted("dueDate")</strong> Date dueDate,
* <strong>{@literal @}Assisted</strong> Money amount) {
* ...
* }
* }</pre>
* <h3>Values are created by Guice</h3>
* Returned factories use child injectors to create values. The values are eligible for method
* interception. In addition, {@literal @}{@literal Inject} members will be injected before they are
* returned.
* <h3>Backwards compatibility using {@literal @}AssistedInject</h3>
* Instead of the {@literal @}Inject annotation, you may annotate the constructed classes with
* {@literal @}{@link AssistedInject}. This triggers a limited backwards-compatibility mode.
* <p>Instead of matching factory method arguments to constructor parameters using their names, the
* <strong>parameters are matched by their order</strong>. The first factory method argument is
* used for the first {@literal @}Assisted constructor parameter, etc.. Annotation names have no
* effect.
* <p>Returned values are <strong>not created by Guice</strong>. These types are not eligible for
* method interception. They do receive post-construction member injection.
*
* @param <F> The factory interface
* @author [email protected] (Jerome Mourits)
* @author [email protected] (Jesse Wilson)
* @author [email protected] (Daniel Martin)
*/
public class FactoryProvider<F> implements Provider<F>, HasDependencies {
/*
* This class implements the old @AssistedInject implementation that manually matches constructors
* to factory methods.
*/
private Injector injector;
private final TypeLiteral<F> factoryType;
private final Map<Method, AssistedConstructor<?>> factoryMethodToConstructor;
private FactoryProvider(TypeLiteral<F> factoryType,
Map<Method, AssistedConstructor<?>> factoryMethodToConstructor) {
this.factoryType = factoryType;
this.factoryMethodToConstructor = factoryMethodToConstructor;
checkDeclaredExceptionsMatch();
}
private void checkDeclaredExceptionsMatch() {
for (Map.Entry<Method, AssistedConstructor<?>> entry : factoryMethodToConstructor.entrySet()) {
for (Class<?> constructorException : entry.getValue().getDeclaredExceptions()) {
if (!isConstructorExceptionCompatibleWithFactoryExeception(
constructorException, entry.getKey().getExceptionTypes())) {
throw newConfigurationException("Constructor %s declares an exception, but no compatible "
+ "exception is thrown by the factory method %s", entry.getValue(), entry.getKey());
}
}
}
}
private boolean isConstructorExceptionCompatibleWithFactoryExeception(
Class<?> constructorException, Class<?>[] factoryExceptions) {
for (Class<?> factoryException : factoryExceptions) {
if (factoryException.isAssignableFrom(constructorException)) {
return true;
}
}
return false;
}
@Override
public Set<Dependency<?>> getDependencies() {
Set<Dependency<?>> dependencies = new HashSet<>();
for (AssistedConstructor<?> constructor : factoryMethodToConstructor.values()) {
for (Parameter parameter : constructor.getAllParameters()) {
if (!parameter.isProvidedByFactory()) {
dependencies.add(Dependency.get(parameter.getPrimaryBindingKey()));
}
}
}
return unmodifiableSet(dependencies);
}
@Override
public F get() {
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] creationArgs) throws Throwable {
// pass methods from Object.class to the proxy
if (method.getDeclaringClass().equals(Object.class)) {
return method.invoke(this, creationArgs);
}
AssistedConstructor<?> constructor = factoryMethodToConstructor.get(method);
Object[] constructorArgs = gatherArgsForConstructor(constructor, creationArgs);
Object objectToReturn = constructor.newInstance(constructorArgs);
injector.injectMembers(objectToReturn);
return objectToReturn;
}
public Object[] gatherArgsForConstructor(
AssistedConstructor<?> constructor,
Object[] factoryArgs) {
int numParams = constructor.getAllParameters().size();
int argPosition = 0;
Object[] result = new Object[numParams];
for (int i = 0; i < numParams; i++) {
Parameter parameter = constructor.getAllParameters().get(i);
if (parameter.isProvidedByFactory()) {
result[i] = factoryArgs[argPosition];
argPosition++;
} else {
result[i] = parameter.getValue(injector);
}
}
return result;
}
};
@SuppressWarnings("unchecked") // we imprecisely treat the class literal of T as a Class<T>
Class<F> factoryRawType = (Class) factoryType.getRawType();
return factoryRawType.cast(Proxy.newProxyInstance(factoryRawType.getClassLoader(),
new Class[]{factoryRawType}, invocationHandler));
}
private static ConfigurationException newConfigurationException(String format, Object... args) {
return new ConfigurationException(singleton(new Message(Errors.format(format, args))));
}
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/assistedinject/FactoryProvider.java |
214,130 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject.spi;
import org.elasticsearch.common.inject.Binding;
/**
* A binding created from converting a bound instance to a new type. The source binding has the same
* binding annotation but a different type.
*
* @author [email protected] (Jesse Wilson)
* @since 2.0
*/
public interface ConvertedConstantBinding<T> extends Binding<T> {
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/spi/ConvertedConstantBinding.java |
214,131 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject.spi;
import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.inject.Binding;
import org.opensearch.common.inject.Key;
/**
* A binding to a linked key. The other key's binding is used to resolve injections.
*
* @author [email protected] (Jesse Wilson)
* @since 2.0
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public interface LinkedKeyBinding<T> extends Binding<T> {
/**
* Returns the linked key used to resolve injections.
*/
Key<? extends T> getLinkedKey();
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/spi/LinkedKeyBinding.java |
214,133 | /**
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import java.lang.annotation.Annotation;
/**
* Whether a member supports null values injected.
*
* <p>Support for {@code Nullable} annotations in Guice is loose.
* Any annotation type whose simplename is "Nullable" is sufficient to indicate
* support for null values injected.
*
* <p>This allows support for JSR-305's
* <a href="http://groups.google.com/group/jsr-305/web/proposed-annotations">
* javax.annotation.meta.Nullable</a> annotation and IntelliJ IDEA's
* <a href="http://www.jetbrains.com/idea/documentation/howto.html">
* org.jetbrains.annotations.Nullable</a>.
*
* @author [email protected] (Jesse Wilson)
*/
public class Nullability {
private Nullability() {}
public static boolean allowsNull(Annotation[] annotations) {
for(Annotation a : annotations) {
Class<? extends Annotation> type = a.annotationType();
if ("Nullable".equals(type.getSimpleName())) {
return true;
}
}
return false;
}
}
| Andlab/roboguice | guice/core/src/com/google/inject/internal/Nullability.java |
214,134 | /*
* Copyright (C) 2009 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.spi.Element;
import org.elasticsearch.common.inject.spi.MembersInjectorLookup;
import org.elasticsearch.common.inject.spi.ProviderLookup;
import java.util.ArrayList;
import java.util.List;
/**
* Returns providers and members injectors that haven't yet been initialized. As a part of injector
* creation it's necessary to {@link #initialize initialize} these lookups.
*
* @author [email protected] (Jesse Wilson)
*/
class DeferredLookups implements Lookups {
private final InjectorImpl injector;
private final List<Element> lookups = new ArrayList<>();
DeferredLookups(InjectorImpl injector) {
this.injector = injector;
}
/**
* Initialize the specified lookups, either immediately or when the injector is created.
*/
public void initialize(Errors errors) {
injector.lookups = injector;
new LookupProcessor(errors).process(injector, lookups);
}
@Override
public <T> Provider<T> getProvider(Key<T> key) {
ProviderLookup<T> lookup = new ProviderLookup<>(key, key);
lookups.add(lookup);
return lookup.getProvider();
}
@Override
public <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) {
MembersInjectorLookup<T> lookup = new MembersInjectorLookup<>(type, type);
lookups.add(lookup);
return lookup.getMembersInjector();
}
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/DeferredLookups.java |
214,135 | /*
* Licensed to The OpenNMS Group, Inc (TOG) under one or more
* contributor license agreements. See the LICENSE.md file
* distributed with this work for additional information
* regarding copyright ownership.
*
* TOG licenses this file to You under the GNU Affero General
* Public License Version 3 (the "License") or (at your option)
* any later version. You may not use this file except in
* compliance with the License. You may obtain a copy of the
* License at:
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.opennms.netmgt.dao.support;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang.CharEncoding;
import org.opennms.netmgt.collection.api.CollectionResource;
import org.opennms.netmgt.config.api.CollectdConfigFactory;
import org.opennms.netmgt.config.api.ResourceTypesDao;
import org.opennms.netmgt.config.collectd.Package;
import org.opennms.netmgt.dao.api.IpInterfaceDao;
import org.opennms.netmgt.dao.api.NodeDao;
import org.opennms.netmgt.dao.api.ResourceDao;
import org.opennms.netmgt.dao.api.ResourceStorageDao;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsResource;
import org.opennms.netmgt.model.OnmsResourceType;
import org.opennms.netmgt.model.ResourceId;
import org.opennms.netmgt.model.ResourceTypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import static org.opennms.netmgt.dao.support.NodeSnmpResourceType.PARENT_RESOURCE_TYPE_FOR_STORE_BY_FOREIGN_SOURCE;
/**
* Retrieves and enumerates elements from the resource tree.
*
* This class is responsible for maintaining the list of
* resource types and coordinating amongst these.
*
* All resource type specific logic should be contained in
* the resource type implementations rather than this class.
*
* @author <a href="mailto:[email protected]">Jesse White</a>
* @author <a href="mailto:[email protected]">Seth Leger </a>
* @author <a href="mailto:[email protected]">Lawrence Karnowski </a>
* @author <a href="mailto:[email protected]">DJ Gregor</a>
*/
public class DefaultResourceDao implements ResourceDao, InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(DefaultResourceDao.class);
private static final Pattern RESOURCE_ID_PATTERN = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
/**
* Largest depth at which we will find node related metrics:
* [0] will catch node-level resources
* [1] will catch interface-level resources
* [2] will catch generic index type resources
*/
public static final int MAXIMUM_NODE_METRIC_RESOURCE_DEPTH = 2;
private ResourceStorageDao m_resourceStorageDao;
private NodeDao m_nodeDao;
private IpInterfaceDao m_ipInterfaceDao;
private CollectdConfigFactory m_collectdConfig;
private ResourceTypesDao m_resourceTypesDao;
private Date m_lastUpdatedResourceTypesConfig;
private Map<String, OnmsResourceType> m_resourceTypes = Maps.newHashMap();
private NodeResourceType m_nodeResourceType;
/**
* <p>Constructor for DefaultResourceDao.</p>
*/
public DefaultResourceDao() {
}
public ResourceTypesDao getResourceTypesDao() {
return m_resourceTypesDao;
}
public void setResourceTypesDao(ResourceTypesDao resourceTypesDao) {
m_resourceTypesDao = Objects.requireNonNull(resourceTypesDao);
}
/**
* <p>getNodeDao</p>
*
* @return a {@link org.opennms.netmgt.dao.api.NodeDao} object.
*/
public NodeDao getNodeDao() {
return m_nodeDao;
}
/**
* <p>setNodeDao</p>
*
* @param nodeDao a {@link org.opennms.netmgt.dao.api.NodeDao} object.
*/
public void setNodeDao(NodeDao nodeDao) {
m_nodeDao = nodeDao;
}
/**
* <p>getCollectdConfig</p>
*
* @return a {@link org.opennms.netmgt.config.api.CollectdConfigFactory} object.
*/
public CollectdConfigFactory getCollectdConfig() {
return m_collectdConfig;
}
/**
* <p>setCollectdConfig</p>
*
* @param collectdConfig a {@link org.opennms.netmgt.config.api.CollectdConfigFactory} object.
*/
public void setCollectdConfig(CollectdConfigFactory collectdConfig) {
m_collectdConfig = collectdConfig;
}
public IpInterfaceDao getIpInterfaceDao() {
return m_ipInterfaceDao;
}
public void setIpInterfaceDao(IpInterfaceDao ipInterfaceDao) {
m_ipInterfaceDao = ipInterfaceDao;
}
public void setResourceStorageDao(ResourceStorageDao resourceStorageDao) {
m_resourceStorageDao = resourceStorageDao;
// The resource types depend on the resource resolver so
// we reinitialize these when it changes
if (m_resourceTypes.size() > 0) {
initResourceTypes();
}
}
public ResourceStorageDao getResourceStorageDao() {
return m_resourceStorageDao;
}
/**
* <p>afterPropertiesSet</p>
*/
@Override
public void afterPropertiesSet() {
if (m_collectdConfig == null) {
throw new IllegalStateException("collectdConfig property has not been set");
}
if (m_resourceTypesDao == null) {
throw new IllegalStateException("resourceTypesDao property has not been set");
}
if (m_nodeDao == null) {
throw new IllegalStateException("nodeDao property has not been set");
}
if (m_resourceStorageDao == null) {
throw new IllegalStateException("resourceStorageDao property has not been set");
}
initResourceTypes();
}
private void initResourceTypes() {
final Map<String, OnmsResourceType> resourceTypes = Maps.newLinkedHashMap();
OnmsResourceType resourceType;
ServiceResourceType serviceResourceType;
resourceType = new NodeSnmpResourceType(m_resourceStorageDao);
resourceTypes.put(resourceType.getName(), resourceType);
InterfaceSnmpResourceType intfResourceType = new InterfaceSnmpResourceType(m_resourceStorageDao);
resourceTypes.put(intfResourceType.getName(), intfResourceType);
resourceType = new InterfaceSnmpByIfIndexResourceType(intfResourceType);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = serviceResourceType = new ResponseTimeResourceType(m_resourceStorageDao, m_ipInterfaceDao);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = new PerspectiveResponseTimeResourceType(m_resourceStorageDao, serviceResourceType);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = serviceResourceType = new ServiceStatusResourceType(m_resourceStorageDao, m_ipInterfaceDao);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = new PerspectiveStatusResourceType(m_resourceStorageDao, serviceResourceType);
resourceTypes.put(resourceType.getName(), resourceType);
resourceTypes.putAll(GenericIndexResourceType.createTypes(m_resourceTypesDao.getResourceTypes(), m_resourceStorageDao));
m_nodeResourceType = new NodeResourceType(this, m_nodeDao);
resourceTypes.put(m_nodeResourceType.getName(), m_nodeResourceType);
// Add 'nodeSource' as an alias to for the 'node' resource type to preserve backwards compatibility
// See NMS-8404 for details
resourceTypes.put("nodeSource", m_nodeResourceType);
if (isDomainResourceTypeUsed()) {
LOG.debug("One or more packages are configured with storeByIfAlias=true. Enabling the domain resource type.");
resourceType = new DomainResourceType(this, m_resourceStorageDao);
resourceTypes.put(resourceType.getName(), resourceType);
} else {
LOG.debug("No packages are configured with storeByIfAlias=true. Excluding the domain resource type.");
}
m_resourceTypes = resourceTypes;
m_lastUpdatedResourceTypesConfig = m_resourceTypesDao.getLastUpdate();
}
/** {@inheritDoc} */
@Override
public Collection<OnmsResourceType> getResourceTypes() {
if (isResourceTypesConfigChanged()) {
LOG.debug("The resource type configuration has been changed, reloading resource types.");
initResourceTypes();
}
return m_resourceTypes.values();
}
/** {@inheritDoc} */
@Override
@Transactional(readOnly=true)
public List<OnmsResource> findTopLevelResources() {
// Retrieve all top-level resources by passing null as the parent
final List<OnmsResource> resources = m_resourceTypes.values().stream()
.distinct()
.map(type -> type.getResourcesForParent(null))
.flatMap(List::stream)
.filter(this::hasAnyChildResources)
.collect(Collectors.toList());
return resources;
}
/**
* Used to determine whether or not the given (parent) resource
* has any child resources.
*/
protected boolean hasAnyChildResources(OnmsResource resource) {
// The order of the resource types matter here since we want to
// check for the types are most likely occur first.
return getResourceTypes().stream()
.anyMatch(t -> t.isResourceTypeOnParent(resource));
}
/**
* Fetch a specific resource by string ID.
*
* @return Resource or null if resource cannot be found.
* @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
* @throws ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
*/
@Override
@Transactional(readOnly=true)
public OnmsResource getResourceById(final ResourceId id) {
if (id == null) {
return null;
}
try {
return getChildResource(id.parent != null ? this.getResourceById(id.parent) : null,
id.type,
id.name);
} catch (final Throwable e) {
LOG.warn("Could not get resource for resource ID \"{}\"", id, e);
return null;
}
}
/**
* Creates a resource for the given node using the most
* appropriate type.
*/
@Override
public OnmsResource getResourceForNode(OnmsNode node) {
Assert.notNull(node, "node argument must not be null");
return m_nodeResourceType.createResourceForNode(node);
}
@Override
public boolean deleteResourceById(final ResourceId resourceId) {
final OnmsResource resource = this.getResourceById(resourceId);
if (resource == null) {
return false;
}
return deleteResource(resource, true);
}
public boolean deleteResource(final OnmsResource resource, boolean recursive) {
boolean result = false;
if (recursive) {
for (final OnmsResource childResource : resource.getChildResources()) {
result = deleteResource(childResource, recursive) || result;
}
}
result = m_resourceStorageDao.delete(resource.getPath()) || result;
return result;
}
/**
* <p>getChildResource</p>
*
* @param parentResource a {@link org.opennms.netmgt.model.OnmsResource} object.
* @param resourceType a {@link java.lang.String} object.
* @param resource a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsResource} object.
*/
protected OnmsResource getChildResource(OnmsResource parentResource, String resourceType, String resource) {
final OnmsResourceType targetType = m_resourceTypes.get(resourceType);
if (targetType == null) {
throw new ObjectRetrievalFailureException(OnmsResource.class, resourceType + "/" + resource,
"Unsupported resource type: " + resourceType, null);
}
final OnmsResource childResource = targetType.getChildByName(parentResource, resource);
if (childResource != null) {
LOG.debug("getChildResource: returning resource {}", childResource);
return childResource;
}
throw new ObjectRetrievalFailureException(OnmsResource.class, resourceType + "/" + resource, "Could not find child resource '"
+ resource + "' with resource type '" + resourceType + "' on resource '" + resource + "'", null);
}
private boolean isResourceTypesConfigChanged() {
Date current = m_resourceTypesDao.getLastUpdate();
if (current.after(m_lastUpdatedResourceTypesConfig)) {
m_lastUpdatedResourceTypesConfig = current;
return true;
}
return false;
}
/**
* Encapsulate the deprecated decode method to fix it in one place.
*
* @param string
* string to be decoded
* @return decoded string
*/
public static String decode(String string) {
try {
return URLDecoder.decode(string, CharEncoding.UTF_8);
} catch (UnsupportedEncodingException e) {
// UTF-8 should *never* throw this
throw Throwables.propagate(e);
}
}
/**
* For performance reasons, we only enable the {@link DomainResourceType} if
* one or more packages use it. Here we iterator over all of defined packages,
* return true if a package uses the domain types, and false otherwise.
*/
private boolean isDomainResourceTypeUsed() {
for (Package pkg : m_collectdConfig.getPackages()) {
if ("true".equalsIgnoreCase(pkg.getStoreByIfAlias())) {
return true;
}
}
return false;
}
@Override
public ResourceId getResourceId(CollectionResource resource, long nodeId) {
if ( resource == null) {
return null;
}
String resourceType = resource.getResourceTypeName();
String resourceLabel = resource.getInterfaceLabel();
if (CollectionResource.RESOURCE_TYPE_NODE.equals(resourceType)) {
resourceType = NodeSnmpResourceType.NODE_RESOURCE_TYPE_NAME;
resourceLabel = "";
}
if (CollectionResource.RESOURCE_TYPE_IF.equals(resourceType)) {
resourceType = InterfaceSnmpResourceType.INTERFACE_RESOURCE_TYPE_NAME;
}
String parentResourceTypeName = CollectionResource.RESOURCE_TYPE_NODE;
String parentResourceName = String.valueOf(nodeId);
// When storeByForeignSource is enabled, need to account for parent resource.
if (resource.getParent() != null && resource.getParent().toString().startsWith(ResourceTypeUtils.FOREIGN_SOURCE_DIRECTORY)) {
// If separatorChar is backslash (like on Windows) use a double-escaped backslash in the regex
String[] parts = resource.getParent().toString().split(File.separatorChar == '\\' ? "\\\\" : File.separator);
if (parts.length == 3) {
parentResourceTypeName = PARENT_RESOURCE_TYPE_FOR_STORE_BY_FOREIGN_SOURCE;
parentResourceName = parts[1] + ":" + parts[2];
}
}
return ResourceId.get(parentResourceTypeName, parentResourceName).resolve(resourceType, resourceLabel);
}
}
| OpenNMS/opennms | opennms-dao/src/main/java/org/opennms/netmgt/dao/support/DefaultResourceDao.java |
214,137 | /*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import edu.umd.cs.findbugs.annotations.NonNull;
import io.jooby.internal.reflect.$Types;
/**
* Represents a generic type {@code T}. Java doesn't yet provide a way to represent generic types,
* so this class does. Forces clients to create a subclass of this class which enables retrieval the
* type information even at runtime.
*
* <p>For example, to create a type literal for {@code List<String>}, you can create an empty
* anonymous inner class:
*
* <p>{@code Reified<List<String>> list = new Reified<List<String>>() {};}
*
* <p>This syntax cannot be used to create type literals that have wildcard parameters, such as
* {@code Class<?>} or {@code List<? extends CharSequence>}.
*
* @param <T> Target type.
* @author Bob Lee
* @author Sven Mawson
* @author Jesse Wilson
*/
public class Reified<T> {
private final Class<? super T> rawType;
private final Type type;
private final int hashCode;
/**
* Constructs a new type literal. Derives represented class from type parameter.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
* anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
*/
@SuppressWarnings("unchecked")
public Reified() {
this.type = getSuperclassTypeParameter(getClass());
this.rawType = (Class<? super T>) $Types.getRawType(type);
this.hashCode = type.hashCode();
}
/**
* Unsafe. Constructs a type literal manually.
*
* @param type Generic type.
*/
@SuppressWarnings("unchecked")
private Reified(Type type) {
this.type = $Types.canonicalize(type);
this.rawType = (Class<? super T>) $Types.getRawType(this.type);
this.hashCode = this.type.hashCode();
}
/**
* Unsafe. Constructs a type literal manually.
*
* @param type Generic type.
*/
private Reified(Class type) {
this.type = type;
this.rawType = type;
this.hashCode = type.hashCode();
}
/**
* Returns the type from super class's type parameter in {@link $Types#canonicalize canonical
* form}.
*
* @param subclass Subclass.
* @return Type.
*/
private static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
/**
* Returns the raw (non-generic) type for this type.
*
* @return Returns the raw (non-generic) type for this type.
*/
public final @NonNull Class<? super T> getRawType() {
return rawType;
}
/**
* Gets underlying {@code Type} instance.
*
* @return Gets underlying {@code Type} instance.
*/
public final @NonNull Type getType() {
return type;
}
@Override
public final int hashCode() {
return this.hashCode;
}
@Override
public final boolean equals(Object o) {
return o instanceof Reified<?> && $Types.equals(type, ((Reified<?>) o).type);
}
@Override
public final String toString() {
return $Types.typeToString(type);
}
/**
* Gets type literal for the given {@code Type} instance.
*
* @param type Source type.
* @return Gets type literal for the given {@code Type} instance.
*/
public static @NonNull Reified<?> get(@NonNull Type type) {
return new Reified<>(type);
}
/**
* Get raw type (class) from given type.
*
* @param type Type.
* @return Raw type.
*/
public static @NonNull Class<?> rawType(@NonNull Type type) {
if (type instanceof Class) {
return (Class<?>) type;
}
return new Reified<>(type).rawType;
}
/**
* Gets type literal for the given {@code Class} instance.
*
* @param type Java type.
* @param <T> Generic type.
* @return Gets type literal for the given {@code Class} instance.
*/
public static @NonNull <T> Reified<T> get(@NonNull Class<T> type) {
return new Reified<>(type);
}
/**
* Creates a {@link List} type literal.
*
* @param type Item type.
* @param <T> Item type.
* @return A {@link List} type literal.
*/
public static @NonNull <T> Reified<List<T>> list(@NonNull Type type) {
return (Reified<List<T>>) getParameterized(List.class, type);
}
/**
* Creates a {@link Set} type literal.
*
* @param type Item type.
* @param <T> Item type.
* @return A {@link Set} type literal.
*/
public static @NonNull <T> Reified<Set<T>> set(@NonNull Type type) {
return (Reified<Set<T>>) getParameterized(Set.class, type);
}
/**
* Creates an {@link Optional} type literal.
*
* @param type Item type.
* @param <T> Item type.
* @return A {@link Optional} type literal.
*/
public static @NonNull <T> Reified<Optional<T>> optional(@NonNull Type type) {
return (Reified<Optional<T>>) getParameterized(Optional.class, type);
}
/**
* Creates an {@link Map} type literal.
*
* @param key Key type.
* @param value Value type.
* @param <K> Key type.
* @param <V> Key type.
* @return A {@link Map} type literal.
*/
public static @NonNull <K, V> Reified<Map<K, V>> map(@NonNull Type key, @NonNull Type value) {
return (Reified<Map<K, V>>) getParameterized(Map.class, key, value);
}
/**
* Creates a {@link CompletableFuture} type literal.
*
* @param type Item type.
* @param <T> Item type.
* @return A {@link CompletableFuture} type literal.
*/
public static @NonNull <T> Reified<CompletableFuture<T>> completableFuture(@NonNull Type type) {
return (Reified<CompletableFuture<T>>) getParameterized(CompletableFuture.class, type);
}
/**
* Gets type literal for the parameterized type represented by applying {@code typeArguments} to
* {@code rawType}.
*
* @param rawType Raw type.
* @param typeArguments Parameter types.
* @return Gets type literal for the parameterized type represented by applying {@code
* typeArguments} to {@code rawType}.
*/
public static @NonNull Reified<?> getParameterized(
@NonNull Type rawType, @NonNull Type... typeArguments) {
return new Reified<>($Types.newParameterizedTypeWithOwner(null, rawType, typeArguments));
}
}
| jooby-project/jooby | jooby/src/main/java/io/jooby/Reified.java |
214,138 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.inject.internal.Errors;
import org.opensearch.common.inject.spi.Element;
import org.opensearch.common.inject.spi.ElementVisitor;
import org.opensearch.common.inject.spi.InjectionRequest;
import org.opensearch.common.inject.spi.MembersInjectorLookup;
import org.opensearch.common.inject.spi.Message;
import org.opensearch.common.inject.spi.PrivateElements;
import org.opensearch.common.inject.spi.ProviderLookup;
import org.opensearch.common.inject.spi.ScopeBinding;
import org.opensearch.common.inject.spi.StaticInjectionRequest;
import org.opensearch.common.inject.spi.TypeConverterBinding;
import org.opensearch.common.inject.spi.TypeListenerBinding;
import java.util.Iterator;
import java.util.List;
/**
* Abstract base class for creating an injector from module elements.
* <p>
* Extending classes must return {@code true} from any overridden
* {@code visit*()} methods, in order for the element processor to remove the
* handled element.
*
* @author [email protected] (Jesse Wilson)
*
* @opensearch.internal
*/
abstract class AbstractProcessor implements ElementVisitor<Boolean> {
protected Errors errors;
protected InjectorImpl injector;
protected AbstractProcessor(Errors errors) {
this.errors = errors;
}
public void process(Iterable<InjectorShell> isolatedInjectorBuilders) {
for (InjectorShell injectorShell : isolatedInjectorBuilders) {
process(injectorShell.getInjector(), injectorShell.getElements());
}
}
public void process(InjectorImpl injector, List<Element> elements) {
Errors errorsAnyElement = this.errors;
this.injector = injector;
try {
for (Iterator<Element> i = elements.iterator(); i.hasNext();) {
Element element = i.next();
this.errors = errorsAnyElement.withSource(element.getSource());
Boolean allDone = element.acceptVisitor(this);
if (allDone) {
i.remove();
}
}
} finally {
this.errors = errorsAnyElement;
this.injector = null;
}
}
@Override
public Boolean visit(Message message) {
return false;
}
@Override
public Boolean visit(ScopeBinding scopeBinding) {
return false;
}
@Override
public Boolean visit(InjectionRequest<?> injectionRequest) {
return false;
}
@Override
public Boolean visit(StaticInjectionRequest staticInjectionRequest) {
return false;
}
@Override
public Boolean visit(TypeConverterBinding typeConverterBinding) {
return false;
}
@Override
public <T> Boolean visit(Binding<T> binding) {
return false;
}
@Override
public <T> Boolean visit(ProviderLookup<T> providerLookup) {
return false;
}
@Override
public Boolean visit(PrivateElements privateElements) {
return false;
}
@Override
public <T> Boolean visit(MembersInjectorLookup<T> lookup) {
return false;
}
@Override
public Boolean visit(TypeListenerBinding binding) {
return false;
}
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/AbstractProcessor.java |
214,140 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2009 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.inject.internal.Errors;
import org.opensearch.common.inject.spi.Element;
import org.opensearch.common.inject.spi.MembersInjectorLookup;
import org.opensearch.common.inject.spi.ProviderLookup;
import java.util.ArrayList;
import java.util.List;
/**
* Returns providers and members injectors that haven't yet been initialized. As a part of injector
* creation it's necessary to {@link #initialize initialize} these lookups.
*
* @author [email protected] (Jesse Wilson)
*
* @opensearch.internal
*/
class DeferredLookups implements Lookups {
private final InjectorImpl injector;
private final List<Element> lookups = new ArrayList<>();
DeferredLookups(InjectorImpl injector) {
this.injector = injector;
}
/**
* Initialize the specified lookups, either immediately or when the injector is created.
*/
public void initialize(Errors errors) {
injector.lookups = injector;
new LookupProcessor(errors).process(injector, lookups);
}
@Override
public <T> Provider<T> getProvider(Key<T> key) {
ProviderLookup<T> lookup = new ProviderLookup<>(key, key);
lookups.add(lookup);
return lookup.getProvider();
}
@Override
public <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) {
MembersInjectorLookup<T> lookup = new MembersInjectorLookup<>(type, type);
lookups.add(lookup);
return lookup.getMembersInjector();
}
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/DeferredLookups.java |
214,141 | package mage.cards.r;
import java.util.UUID;
import mage.abilities.effects.common.DestroyAllEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.ComparisonType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.PowerPredicate;
/**
*
* @author Jesse Whyte
*/
public final class RetributionOfTheMeek extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creatures with power 4 or greater");
static {
filter.add(new PowerPredicate(ComparisonType.MORE_THAN, 3));
}
public RetributionOfTheMeek (UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{2}{W}");
// Destroy all creatures with power 4 or greater. They can't be regenerated.
this.getSpellAbility().addEffect(new DestroyAllEffect(filter, true));
}
private RetributionOfTheMeek(final RetributionOfTheMeek card) {
super(card);
}
@Override
public RetributionOfTheMeek copy() {
return new RetributionOfTheMeek(this);
}
}
| RaelCappra/mage | Mage.Sets/src/mage/cards/r/RetributionOfTheMeek.java |
214,142 | /*
* The MIT License
*
* Copyright 2013 Jesse Glick.
*
* 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 jenkins.util;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.FilePath;
import hudson.Util;
import hudson.model.DirectoryBrowserSupport;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.VirtualChannel;
import hudson.util.DirScanner;
import hudson.util.FileVisitor;
import hudson.util.IOUtils;
import hudson.util.io.Archiver;
import hudson.util.io.ArchiverFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.OpenOption;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import jenkins.MasterToSlaveFileCallable;
import jenkins.model.ArtifactManager;
import jenkins.security.MasterToSlaveCallable;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.AbstractFileSet;
import org.apache.tools.ant.types.selectors.SelectorUtils;
import org.apache.tools.ant.types.selectors.TokenizedPath;
import org.apache.tools.ant.types.selectors.TokenizedPattern;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Abstraction over {@link File}, {@link FilePath}, or other items such as network resources or ZIP entries.
* Assumed to be read-only and makes very limited assumptions, just enough to display content and traverse directories.
*
* <p>
* To obtain a {@link VirtualFile} representation for an existing file, use {@link #forFile(File)} or {@link FilePath#toVirtualFile()}
*
* <h2>How are VirtualFile and FilePath different?</h2>
* <p>
* FilePath abstracts away {@link File}s on machines that are connected over {@link Channel}, whereas
* {@link VirtualFile} makes no assumption about where the actual files are, or whether there really exists
* {@link File}s somewhere. This makes VirtualFile more abstract.
*
* <h2>Opening files from other machines</h2>
*
* While {@link VirtualFile} is marked {@link Serializable},
* it is <em>not</em> safe in general to transfer over a Remoting channel.
* (For example, an implementation from {@link #forFilePath} could be sent on the <em>same</em> channel,
* but an implementation from {@link #forFile} will not.)
* Thus callers should assume that methods such as {@link #open} will work
* only on the node on which the object was created.
*
* <p>Since some implementations may in fact use external file storage,
* callers may request optional APIs to access those services more efficiently.
* Otherwise, for example, a plugin copying a file
* previously saved by {@link ArtifactManager} to an external storage service
* which tunneled a stream from {@link #open} using {@link RemoteInputStream}
* would wind up transferring the file from the service to the Jenkins master and then on to an agent.
* Similarly, if {@link DirectoryBrowserSupport} rendered a link to an in-Jenkins URL,
* a large file could be transferred from the service to the Jenkins master and then on to the browser.
* To avoid this overhead, callers may check whether an implementation supports {@link #toExternalURL}.
*
* @see DirectoryBrowserSupport
* @see FilePath
* @since 1.532
*/
public abstract class VirtualFile implements Comparable<VirtualFile>, Serializable {
/**
* Gets the base name, meaning just the last portion of the path name without any
* directories.
*
* For a “root directory” this may be the empty string.
* @return a simple name (no slashes)
*/
public abstract @NonNull String getName();
/**
* Gets a URI.
* Should at least uniquely identify this virtual file within its root, but not necessarily globally.
* <p>When {@link #toExternalURL} is implemented, that same value could be used here,
* unless some sort of authentication is also embedded.
* @return a URI (need not be absolute)
*/
public abstract @NonNull URI toURI();
/**
* Gets the parent file.
* Need only operate within the originally given root.
* @return the parent
*/
public abstract VirtualFile getParent();
/**
* Checks whether this file exists and is a directory.
* @return true if it is a directory, false if a file or nonexistent
* @throws IOException in case checking status failed
*/
public abstract boolean isDirectory() throws IOException;
/**
* Checks whether this file exists and is a plain file.
* @return true if it is a file, false if a directory or nonexistent
* @throws IOException in case checking status failed
*/
public abstract boolean isFile() throws IOException;
/**
* If this file is a symlink, returns the link target.
* <p>The default implementation always returns null.
* Some implementations may not support symlinks under any conditions.
* @return a target (typically a relative path in some format), or null if this is not a link
* @throws IOException if reading the link, or even determining whether this file is a link, failed
* @since 2.118
*/
public @CheckForNull String readLink() throws IOException {
return null;
}
/**
* Checks whether this file exists.
* The behavior is undefined for symlinks; if in doubt, check {@link #readLink} first.
* @return true if it is a plain file or directory, false if nonexistent
* @throws IOException in case checking status failed
*/
public abstract boolean exists() throws IOException;
/**
* Lists children of this directory. Only one level deep.
*
* @return a list of children (files and subdirectories); empty for a file or nonexistent directory
* @throws IOException if this directory exists but listing was not possible for some other reason
*/
public abstract @NonNull VirtualFile[] list() throws IOException;
/**
* Lists children of this directory. Only one level deep.
*
* This is intended to allow the caller to provide {@link java.nio.file.LinkOption#NOFOLLOW_LINKS} to ignore
* symlinks. However, this cannot be enforced. The base implementation here in VirtualFile ignores the openOptions.
* Some VirtualFile subclasses may not be able to provide
* an implementation in which NOFOLLOW_LINKS is used or makes sense. Implementations are free
* to ignore openOptions. Some subclasses of VirtualFile may not have a concept of symlinks.
* @param openOptions the options to apply when opening.
* @return a list of children (files and subdirectories); empty for a file or nonexistent directory
* @throws IOException if it could not be opened
*/
@Restricted(NoExternalUse.class)
public @NonNull VirtualFile[] list(OpenOption... openOptions) throws IOException {
return list();
}
@Restricted(NoExternalUse.class)
public boolean supportsQuickRecursiveListing() {
return false;
}
/**
* Determines when a VirtualFile has a recognized symlink.
* A recognized symlink can be the file itself or any containing directory between
* it and the optional root directory. If there is no provided root directory then
* only the file itself is considered.
*
* This base implementation ignores the existence of symlinks.
* @param openOptions the various open options to apply to the operation.
* @return True if the file is a symlink or is referenced within a containing symlink.
* directory before reaching the root directory.
* @throws IOException If there is a problem accessing the file.
*/
@Restricted(NoExternalUse.class)
public boolean hasSymlink(OpenOption... openOptions) throws IOException {
return false;
}
/**
* Lists only the children that are descendant of the root directory (not necessarily the current VirtualFile).
* Only one level deep.
*
* @return a list of descendant children (files and subdirectories); empty for a file or nonexistent directory
* @throws IOException if this directory exists but listing was not possible for some other reason
*/
@Restricted(NoExternalUse.class)
public @NonNull List<VirtualFile> listOnlyDescendants() throws IOException {
VirtualFile[] children = list();
List<VirtualFile> result = new ArrayList<>();
for (VirtualFile child : children) {
if (child.isDescendant("")) {
result.add(child);
}
}
return result;
}
/**
* @deprecated use {@link #list(String, String, boolean)} instead
*/
@Deprecated
public @NonNull String[] list(String glob) throws IOException {
return list(glob.replace('\\', '/'), null, true).toArray(MemoryReductionUtil.EMPTY_STRING_ARRAY);
}
/**
* Lists recursive files of this directory with pattern matching.
* <p>The default implementation calls {@link #list()} recursively inside {@link #run} and applies filtering to the result.
* Implementations may wish to override this more efficiently.
* @param includes comma-separated Ant-style globs as per {@link Util#createFileSet(File, String, String)} using {@code /} as a path separator;
* the empty string means <em>no matches</em> (use {@link SelectorUtils#DEEP_TREE_MATCH} if you want to match everything except some excludes)
* @param excludes optional excludes in similar format to {@code includes}
* @param useDefaultExcludes as per {@link AbstractFileSet#setDefaultexcludes}
* @return a list of {@code /}-separated relative names of children (files directly inside or in subdirectories)
* @throws IOException if this is not a directory, or listing was not possible for some other reason
* @since 2.118
*/
public @NonNull Collection<String> list(@NonNull String includes, @CheckForNull String excludes, boolean useDefaultExcludes) throws IOException {
return list(includes, excludes, useDefaultExcludes, new OpenOption[0]);
}
/**
* Lists recursive files of this directory with pattern matching.
*
* <p>The default implementation calls {@link #list()} recursively inside {@link #run} and applies filtering to the result.
* Implementations may wish to override this more efficiently.
* This method allows the user to specify that symlinks should not be followed by passing
* LinkOption.NOFOLLOW_LINKS as true. However, some implementations may not be able to reliably
* prevent link following. The base implementation here in VirtualFile ignores this parameter.
* @param includes comma-separated Ant-style globs as per {@link Util#createFileSet(File, String, String)} using {@code /} as a path separator;
* the empty string means <em>no matches</em> (use {@link SelectorUtils#DEEP_TREE_MATCH} if you want to match everything except some excludes)
* @param excludes optional excludes in similar format to {@code includes}
* @param useDefaultExcludes as per {@link AbstractFileSet#setDefaultexcludes}
* @param openOptions the options to apply when opening.
* @return a list of {@code /}-separated relative names of children (files directly inside or in subdirectories)
* @throws IOException if this is not a directory, or listing was not possible for some other reason
* @since 2.275 and 2.263.2
*/
@Restricted(NoExternalUse.class)
public @NonNull Collection<String> list(@NonNull String includes, @CheckForNull String excludes, boolean useDefaultExcludes,
OpenOption... openOptions) throws IOException {
Collection<String> r = run(new CollectFiles(this));
List<TokenizedPattern> includePatterns = patterns(includes);
List<TokenizedPattern> excludePatterns = patterns(excludes);
if (useDefaultExcludes) {
for (String patt : DirectoryScanner.getDefaultExcludes()) {
excludePatterns.add(new TokenizedPattern(patt.replace('/', File.separatorChar)));
}
}
return r.stream().filter(p -> {
TokenizedPath path = new TokenizedPath(p.replace('/', File.separatorChar));
return includePatterns.stream().anyMatch(patt -> patt.matchPath(path, true)) && excludePatterns.stream().noneMatch(patt -> patt.matchPath(path, true));
}).collect(Collectors.toSet());
}
@Restricted(NoExternalUse.class)
public boolean containsSymLinkChild(OpenOption... openOptions) throws IOException {
return false;
}
@Restricted(NoExternalUse.class)
public boolean containsTmpDirChild(OpenOption... openOptions) throws IOException {
for (VirtualFile child : list()) {
if (child.isDirectory() && FilePath.isTmpDir(child.getName(), openOptions)) {
return true;
}
}
return false;
}
private static final class CollectFiles extends MasterToSlaveCallable<Collection<String>, IOException> {
private static final long serialVersionUID = 1;
private final VirtualFile root;
CollectFiles(VirtualFile root) {
this.root = root;
}
@Override
public Collection<String> call() throws IOException {
List<String> r = new ArrayList<>();
collectFiles(root, r, "");
return r;
}
private static void collectFiles(VirtualFile d, Collection<String> names, String prefix) throws IOException {
for (VirtualFile child : d.list()) {
if (child.isFile()) {
names.add(prefix + child.getName());
} else if (child.isDirectory()) {
collectFiles(child, names, prefix + child.getName() + "/");
}
}
}
}
private List<TokenizedPattern> patterns(String patts) {
List<TokenizedPattern> r = new ArrayList<>();
if (patts != null) {
for (String patt : patts.split(",")) {
if (patt.endsWith("/")) {
patt += SelectorUtils.DEEP_TREE_MATCH;
}
r.add(new TokenizedPattern(patt.replace('/', File.separatorChar)));
}
}
return r;
}
/**
* Create a ZIP archive from the list of folders/files using the includes and excludes to filter them.
*
* <p>The default implementation calls other existing methods to list the folders/files, then retrieve them and zip them all.
*
* @param includes comma-separated Ant-style globs as per {@link Util#createFileSet(File, String, String)} using {@code /} as a path separator;
* the empty string means <em>no matches</em> (use {@link SelectorUtils#DEEP_TREE_MATCH} if you want to match everything except some excludes)
* @param excludes optional excludes in similar format to {@code includes}
* @param useDefaultExcludes as per {@link AbstractFileSet#setDefaultexcludes}
* @param prefix the partial path that will be added before each entry inside the archive.
* If non-empty, a trailing slash will be enforced.
* @param openOptions the options to apply when opening.
* @return the number of files inside the archive (not the folders)
* @throws IOException if this is not a directory, or listing was not possible for some other reason
* @since 2.275 and 2.263.2
*/
public int zip(OutputStream outputStream, String includes, String excludes, boolean useDefaultExcludes,
String prefix, OpenOption... openOptions) throws IOException {
String correctPrefix;
if (prefix == null || prefix.isBlank()) {
correctPrefix = "";
} else {
correctPrefix = Util.ensureEndsWith(prefix, "/");
}
Collection<String> files = list(includes, excludes, useDefaultExcludes, openOptions);
try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
zos.setEncoding(System.getProperty("file.encoding")); // TODO JENKINS-20663 make this overridable via query parameter
for (String relativePath : files) {
VirtualFile virtualFile = this.child(relativePath);
sendOneZipEntry(zos, virtualFile, relativePath, correctPrefix, openOptions);
}
}
return files.size();
}
private void sendOneZipEntry(ZipOutputStream zos, VirtualFile vf, String relativePath, String prefix, OpenOption... openOptions) throws IOException {
// In ZIP archives "All slashes MUST be forward slashes" (http://pkware.com/documents/casestudies/APPNOTE.TXT)
// TODO On Linux file names can contain backslashes which should not treated as file separators.
// Unfortunately, only the file separator char of the master is known (File.separatorChar)
// but not the file separator char of the (maybe remote) "dir".
String onlyForwardRelativePath = relativePath.replace('\\', '/');
String zipEntryName = prefix + onlyForwardRelativePath;
ZipEntry e = new ZipEntry(zipEntryName);
e.setTime(vf.lastModified());
zos.putNextEntry(e);
try (InputStream in = vf.open(openOptions)) {
// hudson.util.IOUtils is already present
org.apache.commons.io.IOUtils.copy(in, zos);
}
finally {
zos.closeEntry();
}
}
/**
* Obtains a child file.
* @param name a relative path, possibly including {@code /} (but not {@code ..})
* @return a representation of that child, whether it actually exists or not
*/
public abstract @NonNull VirtualFile child(@NonNull String name);
/**
* Gets the file length.
* @return a length, or 0 if inapplicable (e.g. a directory)
* @throws IOException if checking the length failed
*/
public abstract long length() throws IOException;
/**
* Gets the file timestamp.
* @return a length, or 0 if inapplicable
* @throws IOException if checking the timestamp failed
*/
public abstract long lastModified() throws IOException;
/**
* Gets the file’s Unix mode, if meaningful.
* If the file is symlink (see {@link #readLink}), the mode is that of the link target, not the link itself.
* @return for example, 0644 ~ {@code rw-r--r--}; -1 by default, meaning unknown or inapplicable
* @throws IOException if checking the mode failed
* @since 2.118
*/
public int mode() throws IOException {
return -1;
}
/**
* Checks whether this file can be read.
* @return true normally
* @throws IOException if checking status failed
*/
public abstract boolean canRead() throws IOException;
/**
* Opens an input stream on the file so its contents can be read.
* @return an open stream
* @throws IOException if it could not be opened
*/
public abstract InputStream open() throws IOException;
/**
* Opens an input stream on the file so its contents can be read.
*
* @param openOptions the options to apply when opening.
* @return an open stream
* @throws IOException if it could not be opened
*/
@Restricted(NoExternalUse.class)
public InputStream open(OpenOption... openOptions) throws IOException {
return open();
}
/**
* Does case-insensitive comparison.
* {@inheritDoc}
*/
@Override public final int compareTo(VirtualFile o) {
return getName().compareToIgnoreCase(o.getName());
}
/**
* Compares according to {@link #toURI}.
* {@inheritDoc}
*/
@Override public final boolean equals(Object obj) {
return obj instanceof VirtualFile && toURI().equals(((VirtualFile) obj).toURI());
}
/**
* Hashes according to {@link #toURI}.
* {@inheritDoc}
*/
@Override public final int hashCode() {
return toURI().hashCode();
}
/**
* Displays {@link #toURI}.
* {@inheritDoc}
*/
@Override public final String toString() {
return toURI().toString();
}
/**
* Does some calculations in batch.
* For a remote file, this can be much faster than doing the corresponding operations one by one as separate requests.
* The default implementation just calls the block directly.
* @param <V> a value type
* @param callable something to run all at once (only helpful if any mentioned files are on the same system)
* @return the callable result
* @throws IOException if remote communication failed
* @since 1.554
*/
public <V> V run(Callable<V, IOException> callable) throws IOException {
return callable.call();
}
/**
* Optionally obtains a URL which may be used to retrieve file contents from any process on any node.
* For example, given cloud storage this might produce a permalink to the file.
* <p>Only {@code http} and {@code https} protocols are permitted.
* It is recommended to use <a href="http://javadoc.jenkins.io/plugin/apache-httpcomponents-client-4-api/io/jenkins/plugins/httpclient/RobustHTTPClient.html#downloadFile-java.io.File-java.net.URL-hudson.model.TaskListener-">{@code RobustHTTPClient.downloadFile}</a> to work with these URLs.
* <p>This is only meaningful for {@link #isFile}:
* no ZIP etc. archiving protocol is defined to allow bulk access to directory trees.
* <p>Any necessary authentication must be encoded somehow into the URL itself;
* do not include any tokens or other authentication which might allow access to unrelated files
* (for example {@link ArtifactManager} builds from a different job).
* Authentication should be limited to download, not upload or any other modifications.
* <p>The URL might be valid for only a limited amount of time or even only a single use;
* this method should be called anew every time an external URL is required.
* @return an externally usable URL like {@code https://gist.githubusercontent.com/ACCT/GISTID/raw/COMMITHASH/FILE}, or null if there is no such support
* @since 2.118
* @see #toURI
*/
public @CheckForNull URL toExternalURL() throws IOException {
return null;
}
/**
* Determine if the implementation supports the {@link #isDescendant(String)} method
*
* TODO un-restrict it in a weekly after the patch
*/
@Restricted(NoExternalUse.class)
public boolean supportIsDescendant() {
return false;
}
/**
* Check if the relative path is really a descendant of this folder, following the symbolic links.
* Meant to be used in coordination with {@link #child(String)}.
*
* TODO un-restrict it in a weekly after the patch
*/
@Restricted(NoExternalUse.class)
public boolean isDescendant(String childRelativePath) throws IOException {
return false;
}
String joinWithForwardSlashes(Collection<String> relativePath) {
// instead of File.separator that is specific to the master, the / has the advantage to be supported
// by either Windows AND Linux for the Path.toRealPath() used in isDescendant
return String.join("/", relativePath) + "/";
}
/**
* Creates a virtual file wrapper for a local file.
* @param f a disk file (need not exist)
* @return a wrapper
*/
public static VirtualFile forFile(final File f) {
return new FileVF(f, f);
}
private static final class FileVF extends VirtualFile {
private final File f;
private final File root;
private boolean cacheDescendant = false;
FileVF(File f, File root) {
this.f = f;
this.root = root;
}
@Override public String getName() {
return f.getName();
}
@Override public URI toURI() {
return f.toURI();
}
@Override public VirtualFile getParent() {
return new FileVF(f.getParentFile(), root);
}
@Override public boolean isDirectory() throws IOException {
if (isIllegalSymlink()) {
return false;
}
return f.isDirectory();
}
@Override public boolean isFile() throws IOException {
if (isIllegalSymlink()) {
return false;
}
return f.isFile();
}
@Override public boolean exists() throws IOException {
if (isIllegalSymlink()) {
return false;
}
return f.exists();
}
@Override public String readLink() throws IOException {
if (isIllegalSymlink()) {
return null; // best to just ignore link -> ../whatever
}
return Util.resolveSymlink(f);
}
@Override public VirtualFile[] list() throws IOException {
if (isIllegalSymlink()) {
return new VirtualFile[0];
}
File[] kids = f.listFiles();
if (kids == null) {
return new VirtualFile[0];
}
VirtualFile[] vfs = new VirtualFile[kids.length];
for (int i = 0; i < kids.length; i++) {
vfs[i] = new FileVF(kids[i], root);
}
return vfs;
}
@NonNull
@Override
public VirtualFile[] list(OpenOption... openOptions) throws IOException {
String rootPath = determineRootPath();
File[] kids = f.listFiles();
List<VirtualFile> contents = new ArrayList<>(kids.length);
for (File child : kids) {
if (!FilePath.isSymlink(child, rootPath, openOptions) && !FilePath.isTmpDir(child, rootPath, openOptions)) {
contents.add(new FileVF(child, root));
}
}
return contents.toArray(new VirtualFile[0]);
}
@Override public boolean supportsQuickRecursiveListing() {
return true;
}
@Override public @NonNull List<VirtualFile> listOnlyDescendants() throws IOException {
if (isIllegalSymlink()) {
return Collections.emptyList();
}
File[] children = f.listFiles();
if (children == null) {
return Collections.emptyList();
}
List<VirtualFile> legalChildren = new ArrayList<>(children.length);
for (File child : children) {
if (isDescendant(child.getName())) {
FileVF legalChild = new FileVF(child, root);
legalChild.cacheDescendant = true;
legalChildren.add(legalChild);
}
}
return legalChildren;
}
@Override
public Collection<String> list(String includes, String excludes, boolean useDefaultExcludes) throws IOException {
if (isIllegalSymlink()) {
return Collections.emptySet();
}
return new Scanner(includes, excludes, useDefaultExcludes).invoke(f, null);
}
@Override
public Collection<String> list(String includes, String excludes, boolean useDefaultExcludes,
OpenOption... openOptions) throws IOException {
String rootPath = determineRootPath();
return new Scanner(includes, excludes, useDefaultExcludes, rootPath, openOptions).invoke(f, null);
}
@Override
public int zip(OutputStream outputStream, String includes, String excludes, boolean useDefaultExcludes,
String prefix, OpenOption... openOptions) throws IOException {
String rootPath = determineRootPath();
DirScanner.Glob globScanner = new DirScanner.Glob(includes, excludes, useDefaultExcludes, openOptions);
ArchiverFactory archiverFactory = prefix == null ? ArchiverFactory.ZIP : ArchiverFactory.createZipWithPrefix(prefix, openOptions);
try (Archiver archiver = archiverFactory.create(outputStream)) {
globScanner.scan(f, FilePath.ignoringTmpDirs(FilePath.ignoringSymlinks(archiver, rootPath, openOptions), rootPath, openOptions));
return archiver.countEntries();
}
}
@Override
public boolean hasSymlink(OpenOption... openOptions) throws IOException {
String rootPath = determineRootPath();
return FilePath.isSymlink(f, rootPath, openOptions);
}
@Override public VirtualFile child(String name) {
return new FileVF(new File(f, name), root);
}
@Override public long length() throws IOException {
if (isIllegalSymlink()) {
return 0;
}
return f.length();
}
@Override public int mode() throws IOException {
if (isIllegalSymlink()) {
return -1;
}
return IOUtils.mode(f);
}
@Override public long lastModified() throws IOException {
if (isIllegalSymlink()) {
return 0;
}
return f.lastModified();
}
@Override public boolean canRead() throws IOException {
if (isIllegalSymlink()) {
return false;
}
return f.canRead();
}
@Override public InputStream open() throws IOException {
if (isIllegalSymlink()) {
throw new FileNotFoundException(f.getPath());
}
try {
return Files.newInputStream(f.toPath());
} catch (InvalidPathException e) {
throw new IOException(e);
}
}
@Override
public InputStream open(OpenOption... openOptions) throws IOException {
String rootPath = determineRootPath();
InputStream inputStream = FilePath.newInputStreamDenyingSymlinkAsNeeded(f, rootPath, openOptions);
return inputStream;
}
@Override
public boolean containsSymLinkChild(OpenOption... openOptions) {
String rootPath = determineRootPath();
File[] kids = f.listFiles();
for (File child : kids) {
if (FilePath.isSymlink(child, rootPath, openOptions)) {
return true;
}
}
return false;
}
private String determineRootPath() {
return root == null ? null : root.getPath();
}
private boolean isIllegalSymlink() {
try {
String myPath = f.toPath().toRealPath().toString();
String rootPath = root.toPath().toRealPath().toString();
if (!myPath.equals(rootPath) && !myPath.startsWith(rootPath + File.separatorChar)) {
return true;
}
} catch (IOException x) {
Logger.getLogger(VirtualFile.class.getName()).log(Level.FINE, "could not determine symlink status of " + f, x);
} catch (InvalidPathException x2) {
// if this cannot be converted to a path, it cannot be an illegal symlink, as it cannot exist
// it's the case when we are calling it with *zip*
Logger.getLogger(VirtualFile.class.getName()).log(Level.FINE, "Could not convert " + f + " to path", x2);
}
return false;
}
/**
* TODO un-restrict it in a weekly after the patch
*/
@Override
@Restricted(NoExternalUse.class)
public boolean supportIsDescendant() {
return true;
}
/**
* TODO un-restrict it in a weekly after the patch
*/
@Override
@Restricted(NoExternalUse.class)
public boolean isDescendant(String potentialChildRelativePath) throws IOException {
if (potentialChildRelativePath.isEmpty() && cacheDescendant) {
return true;
}
if (new File(potentialChildRelativePath).isAbsolute()) {
throw new IllegalArgumentException("Only a relative path is supported, the given path is absolute: " + potentialChildRelativePath);
}
// shortcut for direct child to avoid the complexity of the whole computation
// as we know that a file that is a direct descendant of its parent can only be descendant of the root
// if the parent is descendant AND the file itself is not symbolic
File directChild = new File(f, potentialChildRelativePath);
if (directChild.getParentFile().equals(f)) {
// potential shortcut for "simple" / direct child
if (!Util.isSymlink(directChild)) {
return true;
}
}
FilePath root = new FilePath(this.root);
String relativePath = computeRelativePathToRoot();
try {
boolean isDescendant = root.isDescendant(relativePath + potentialChildRelativePath);
if (isDescendant && potentialChildRelativePath.isEmpty()) {
// in DirectoryBrowserSupport#zip, multiple calls to isDescendant are done for the same VirtualFile
cacheDescendant = true;
}
return isDescendant;
}
catch (InterruptedException e) {
return false;
}
}
/**
* To be kept in sync with {@link FilePathVF#computeRelativePathToRoot()}
*/
private String computeRelativePathToRoot() {
if (this.root.equals(this.f)) {
return "";
}
Deque<String> relativePath = new ArrayDeque<>();
File current = this.f;
while (current != null && !current.equals(this.root)) {
relativePath.addFirst(current.getName());
current = current.getParentFile();
}
return joinWithForwardSlashes(relativePath);
}
}
/**
* Creates a virtual file wrapper for a remotable file.
* @param f a local or remote file (need not exist)
* @return a wrapper
*/
public static VirtualFile forFilePath(final FilePath f) {
return new FilePathVF(f, f);
}
private static final class FilePathVF extends VirtualFile {
private final FilePath f;
private final FilePath root;
private boolean cacheDescendant = false;
FilePathVF(FilePath f, FilePath root) {
this.f = f;
this.root = root;
}
@Override public String getName() {
return f.getName();
}
@Override public URI toURI() {
try {
return f.toURI();
} catch (Exception x) {
return URI.create(f.getRemote());
}
}
@Override public VirtualFile getParent() {
return f.getParent().toVirtualFile();
}
@Override public boolean isDirectory() throws IOException {
try {
return f.isDirectory();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public boolean isFile() throws IOException {
// TODO should probably introduce a method for this purpose
return exists() && !isDirectory();
}
@Override public boolean exists() throws IOException {
try {
return f.exists();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public String readLink() throws IOException {
try {
return f.readLink();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public VirtualFile[] list() throws IOException {
try {
List<FilePath> kids = f.list();
return convertChildrenToVirtualFile(kids);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
private VirtualFile[] convertChildrenToVirtualFile(List<FilePath> kids) {
VirtualFile[] vfs = new VirtualFile[kids.size()];
for (int i = 0; i < vfs.length; i++) {
vfs[i] = new FilePathVF(kids.get(i), this.root);
}
return vfs;
}
@NonNull
@Override
public VirtualFile[] list(OpenOption... openOptions) throws IOException {
try {
List<FilePath> kids = f.list(root, openOptions);
return convertChildrenToVirtualFile(kids);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override
public boolean containsSymLinkChild(OpenOption... openOptions) throws IOException {
try {
return f.containsSymlink(root, openOptions);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override
public boolean hasSymlink(OpenOption... openOptions) throws IOException {
try {
return f.hasSymlink(root, openOptions);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public boolean supportsQuickRecursiveListing() {
return this.f.getChannel() == FilePath.localChannel;
}
@Override public @NonNull List<VirtualFile> listOnlyDescendants() throws IOException {
try {
if (!isDescendant("")) {
return Collections.emptyList();
}
List<FilePath> children = f.list();
List<VirtualFile> legalChildren = new ArrayList<>(children.size());
for (FilePath child : children) {
if (isDescendant(child.getName())) {
FilePathVF legalChild = new FilePathVF(child, this.root);
legalChild.cacheDescendant = true;
legalChildren.add(legalChild);
}
}
return legalChildren;
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public Collection<String> list(String includes, String excludes, boolean useDefaultExcludes) throws IOException {
try {
return f.act(new Scanner(includes, excludes, useDefaultExcludes));
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override
public Collection<String> list(String includes, String excludes, boolean useDefaultExcludes,
OpenOption... openOptions) throws IOException {
try {
String rootPath = root == null ? null : root.getRemote();
return f.act(new Scanner(includes, excludes, useDefaultExcludes, rootPath, openOptions));
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override
public int zip(OutputStream outputStream, String includes, String excludes, boolean useDefaultExcludes,
String prefix, OpenOption... openOptions) throws IOException {
try {
String rootPath = root == null ? null : root.getRemote();
DirScanner.Glob globScanner = new DirScanner.Glob(includes, excludes, useDefaultExcludes, openOptions);
return f.zip(outputStream, globScanner, rootPath, prefix, openOptions);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public VirtualFile child(String name) {
return new FilePathVF(f.child(name), this.root);
}
@Override public long length() throws IOException {
try {
return f.length();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public int mode() throws IOException {
try {
return f.mode();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public long lastModified() throws IOException {
try {
return f.lastModified();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public boolean canRead() throws IOException {
try {
return f.act(new Readable());
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public InputStream open() throws IOException {
try {
return f.read();
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public InputStream open(OpenOption... openOptions) throws IOException {
try {
return f.read(root, openOptions);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
@Override public <V> V run(Callable<V, IOException> callable) throws IOException {
try {
return f.act(callable);
} catch (InterruptedException x) {
throw new IOException(x);
}
}
/**
* TODO un-restrict it in a weekly after the patch
*/
@Override
@Restricted(NoExternalUse.class)
public boolean supportIsDescendant() {
return true;
}
/**
* TODO un-restrict it in a weekly after the patch
*/
@Override
@Restricted(NoExternalUse.class)
public boolean isDescendant(String potentialChildRelativePath) throws IOException {
if (potentialChildRelativePath.isEmpty() && cacheDescendant) {
return true;
}
if (new File(potentialChildRelativePath).isAbsolute()) {
throw new IllegalArgumentException("Only a relative path is supported, the given path is absolute: " + potentialChildRelativePath);
}
// shortcut for direct child to avoid the complexity of the whole computation
// as we know that a file that is a direct descendant of its parent can only be descendant of the root
// if the parent is descendant
FilePath directChild = this.f.child(potentialChildRelativePath);
if (Objects.equals(directChild.getParent(), this.f)) {
try {
boolean isDirectDescendant = this.f.isDescendant(potentialChildRelativePath);
if (isDirectDescendant) {
return true;
}
// not a return false because you can be a non-descendant of your parent but still
// inside the root directory
}
catch (InterruptedException e) {
return false;
}
}
String relativePath = computeRelativePathToRoot();
try {
return this.root.isDescendant(relativePath + potentialChildRelativePath);
}
catch (InterruptedException e) {
return false;
}
}
/**
* To be kept in sync with {@link FileVF#computeRelativePathToRoot()}
*/
private String computeRelativePathToRoot() {
if (this.root.equals(this.f)) {
return "";
}
Deque<String> relativePath = new ArrayDeque<>();
FilePath current = this.f;
while (current != null && !current.equals(this.root)) {
relativePath.addFirst(current.getName());
current = current.getParent();
}
return joinWithForwardSlashes(relativePath);
}
}
private static final class Scanner extends MasterToSlaveFileCallable<List<String>> {
private final String includes, excludes;
private final boolean useDefaultExcludes;
private final String verificationRoot;
private OpenOption[] openOptions;
Scanner(String includes, String excludes, boolean useDefaultExcludes, String verificationRoot, OpenOption... openOptions) {
this.includes = includes;
this.excludes = excludes;
this.useDefaultExcludes = useDefaultExcludes;
this.verificationRoot = verificationRoot;
this.openOptions = openOptions;
}
Scanner(String includes, String excludes, boolean useDefaultExcludes) {
this(includes, excludes, useDefaultExcludes, null, new OpenOption[0]);
}
@Override public List<String> invoke(File f, VirtualChannel channel) throws IOException {
if (includes.isEmpty()) { // see Glob class Javadoc, and list(String, String, boolean) note
return Collections.emptyList();
}
final List<String> paths = new ArrayList<>();
FileVisitor listing = new FileVisitor() {
@Override
public void visit(File f, String relativePath) {
paths.add(relativePath.replace('\\', '/'));
}
};
DirScanner.Glob globScanner = new DirScanner.Glob(includes, excludes, useDefaultExcludes, openOptions);
globScanner.scan(f, FilePath.ignoringTmpDirs(FilePath.ignoringSymlinks(listing, verificationRoot, openOptions), verificationRoot, openOptions));
return paths;
}
}
private static final class Readable extends MasterToSlaveFileCallable<Boolean> {
@Override public Boolean invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return f.canRead();
}
}
}
| Dohbedoh/jenkins | core/src/main/java/jenkins/util/VirtualFile.java |
214,143 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject.spi;
import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.inject.Binder;
/**
* A core component of a module or injector.
* <p>
* The elements of a module can be inspected, validated and rewritten. Use {@link
* Elements#getElements(org.opensearch.common.inject.Module[]) Elements.getElements()} to read the elements
* from a module, and {@link Elements#getModule(Iterable) Elements.getModule()} to rewrite them.
* This can be used for static analysis and generation of Guice modules.
*
* @author [email protected] (Jesse Wilson)
* @author [email protected] (Bob Lee)
* @since 2.0
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public interface Element {
/**
* Returns an arbitrary object containing information about the "place" where this element was
* configured. Used by Guice in the production of descriptive error messages.
* <p>
* Tools might specially handle types they know about; {@code StackTraceElement} is a good
* example. Tools should simply call {@code toString()} on the source object if the type is
* unfamiliar.
*/
Object getSource();
/**
* Accepts an element visitor. Invokes the visitor method specific to this element's type.
*
* @param visitor to call back on
*/
<T> T acceptVisitor(ElementVisitor<T> visitor);
/**
* Writes this module element to the given binder (optional operation).
*
* @param binder to apply configuration element to
* @throws UnsupportedOperationException if the {@code applyTo} method is not supported by this
* element.
*/
void applyTo(Binder binder);
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/spi/Element.java |
214,144 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* The {@code VK_KHR_swapchain} extension is the device-level companion to the {@link KHRSurface VK_KHR_surface} extension. It introduces {@code VkSwapchainKHR} objects, which provide the ability to present rendering results to a surface.
*
* <h5>Examples</h5>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The example code for the {@link KHRSurface VK_KHR_surface} and {@code VK_KHR_swapchain} extensions was removed from the appendix after revision 1.0.29. This WSI example code was ported to the cube demo that is shipped with the official Khronos SDK, and is being kept up-to-date in that location (see: <a href="https://github.com/KhronosGroup/Vulkan-Tools/blob/main/cube/cube.c">https://github.com/KhronosGroup/Vulkan-Tools/blob/main/cube/cube.c</a>).</p>
* </div>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_KHR_swapchain}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>2</dd>
* <dt><b>Revision</b></dt>
* <dd>70</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link KHRSurface VK_KHR_surface}</dd>
* <dt><b>API Interactions</b></dt>
* <dd><ul>
* <li>Interacts with VK_VERSION_1_1</li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>James Jones <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_swapchain]%20@cubanismo%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_swapchain%20extension*">cubanismo</a></li>
* <li>Ian Elliott <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_swapchain]%20@ianelliottus%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_swapchain%20extension*">ianelliottus</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-10-06</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Interactions and External Dependencies</b></dt>
* <dd><ul>
* <li>Interacts with Vulkan 1.1</li>
* </ul></dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Patrick Doane, Blizzard</li>
* <li>Ian Elliott, LunarG</li>
* <li>Jesse Hall, Google</li>
* <li>Mathias Heyer, NVIDIA</li>
* <li>James Jones, NVIDIA</li>
* <li>David Mao, AMD</li>
* <li>Norbert Nopper, Freescale</li>
* <li>Alon Or-bach, Samsung</li>
* <li>Daniel Rakos, AMD</li>
* <li>Graham Sellers, AMD</li>
* <li>Jeff Vigil, Qualcomm</li>
* <li>Chia-I Wu, LunarG</li>
* <li>Faith Ekstrand, Intel</li>
* <li>Matthaeus G. Chajdas, AMD</li>
* <li>Ray Smith, ARM</li>
* </ul></dd>
* </dl>
*/
public class KHRSwapchain {
/** The extension specification version. */
public static final int VK_KHR_SWAPCHAIN_SPEC_VERSION = 70;
/** The extension name. */
public static final String VK_KHR_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_swapchain";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PRESENT_INFO_KHR STRUCTURE_TYPE_PRESENT_INFO_KHR}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR = 1000001000,
VK_STRUCTURE_TYPE_PRESENT_INFO_KHR = 1000001001;
/** Extends {@code VkImageLayout}. */
public static final int VK_IMAGE_LAYOUT_PRESENT_SRC_KHR = 1000001002;
/**
* Extends {@code VkResult}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR}</li>
* <li>{@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR}</li>
* </ul>
*/
public static final int
VK_SUBOPTIMAL_KHR = 1000001003,
VK_ERROR_OUT_OF_DATE_KHR = -1000001004;
/** Extends {@code VkObjectType}. */
public static final int VK_OBJECT_TYPE_SWAPCHAIN_KHR = 1000001000;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR = 1000060007,
VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR = 1000060008,
VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR = 1000060009,
VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR = 1000060010,
VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR = 1000060011,
VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR = 1000060012;
/**
* Extends {@code VkSwapchainCreateFlagBitsKHR}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR}</li>
* <li>{@link #VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR SWAPCHAIN_CREATE_PROTECTED_BIT_KHR}</li>
* </ul>
*/
public static final int
VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = 0x1,
VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = 0x2;
/**
* VkDeviceGroupPresentModeFlagBitsKHR - Bitmask specifying supported device group present modes
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR} specifies that any physical device with a presentation engine <b>can</b> present its own swapchain images.</li>
* <li>{@link #VK_DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR} specifies that any physical device with a presentation engine <b>can</b> present swapchain images from any physical device in its {@code presentMask}.</li>
* <li>{@link #VK_DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR} specifies that any physical device with a presentation engine <b>can</b> present the sum of swapchain images from any physical devices in its {@code presentMask}.</li>
* <li>{@link #VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR} specifies that multiple physical devices with a presentation engine <b>can</b> each present their own swapchain images.</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkDeviceGroupPresentInfoKHR}</p>
*/
public static final int
VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR = 0x1,
VK_DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR = 0x2,
VK_DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR = 0x4,
VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR = 0x8;
protected KHRSwapchain() {
throw new UnsupportedOperationException();
}
// --- [ vkCreateSwapchainKHR ] ---
/** Unsafe version of: {@link #vkCreateSwapchainKHR CreateSwapchainKHR} */
public static int nvkCreateSwapchainKHR(VkDevice device, long pCreateInfo, long pAllocator, long pSwapchain) {
long __functionAddress = device.getCapabilities().vkCreateSwapchainKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPPPPI(device.address(), pCreateInfo, pAllocator, pSwapchain, __functionAddress);
}
/**
* Create a swapchain.
*
* <h5>C Specification</h5>
*
* <p>To create a swapchain, call:</p>
*
* <pre><code>
* VkResult vkCreateSwapchainKHR(
* VkDevice device,
* const VkSwapchainCreateInfoKHR* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkSwapchainKHR* pSwapchain);</code></pre>
*
* <h5>Description</h5>
*
* <p>As mentioned above, if {@code vkCreateSwapchainKHR} succeeds, it will return a handle to a swapchain containing an array of at least {@code pCreateInfo→minImageCount} presentable images.</p>
*
* <p>While acquired by the application, presentable images <b>can</b> be used in any way that equivalent non-presentable images <b>can</b> be used. A presentable image is equivalent to a non-presentable image created with the following {@link VkImageCreateInfo} parameters:</p>
*
* <table class="lwjgl">
* <thead><tr><th>{@link VkImageCreateInfo} Field</th><th>Value</th></tr></thead>
* <tbody>
* <tr><td>{@code flags}</td><td>{@link VK11#VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT} is set if {@link #VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR} is set {@link VK11#VK_IMAGE_CREATE_PROTECTED_BIT IMAGE_CREATE_PROTECTED_BIT} is set if {@link #VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR SWAPCHAIN_CREATE_PROTECTED_BIT_KHR} is set {@link VK10#VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT IMAGE_CREATE_MUTABLE_FORMAT_BIT} and {@link KHRMaintenance2#VK_IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR} are both set if {@link KHRSwapchainMutableFormat#VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR} is set all other bits are unset</td></tr>
* <tr><td>{@code imageType}</td><td>{@link VK10#VK_IMAGE_TYPE_2D IMAGE_TYPE_2D}</td></tr>
* <tr><td>{@code format}</td><td>{@code pCreateInfo→imageFormat}</td></tr>
* <tr><td>{@code extent}</td><td>{{@code pCreateInfo→imageExtent.width}, {@code pCreateInfo→imageExtent.height}, 1}</td></tr>
* <tr><td>{@code mipLevels}</td><td>1</td></tr>
* <tr><td>{@code arrayLayers}</td><td>{@code pCreateInfo→imageArrayLayers}</td></tr>
* <tr><td>{@code samples}</td><td>{@link VK10#VK_SAMPLE_COUNT_1_BIT SAMPLE_COUNT_1_BIT}</td></tr>
* <tr><td>{@code tiling}</td><td>{@link VK10#VK_IMAGE_TILING_OPTIMAL IMAGE_TILING_OPTIMAL}</td></tr>
* <tr><td>{@code usage}</td><td>{@code pCreateInfo→imageUsage}</td></tr>
* <tr><td>{@code sharingMode}</td><td>{@code pCreateInfo→imageSharingMode}</td></tr>
* <tr><td>{@code queueFamilyIndexCount}</td><td>{@code pCreateInfo→queueFamilyIndexCount}</td></tr>
* <tr><td>{@code pQueueFamilyIndices}</td><td>{@code pCreateInfo→pQueueFamilyIndices}</td></tr>
* <tr><td>{@code initialLayout}</td><td>{@link VK10#VK_IMAGE_LAYOUT_UNDEFINED IMAGE_LAYOUT_UNDEFINED}</td></tr>
* </tbody>
* </table>
*
* <p>The {@code pCreateInfo→surface} <b>must</b> not be destroyed until after the swapchain is destroyed.</p>
*
* <p>If {@code oldSwapchain} is {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, and the native window referred to by {@code pCreateInfo→surface} is already associated with a Vulkan swapchain, {@link KHRSurface#VK_ERROR_NATIVE_WINDOW_IN_USE_KHR ERROR_NATIVE_WINDOW_IN_USE_KHR} <b>must</b> be returned.</p>
*
* <p>If the native window referred to by {@code pCreateInfo→surface} is already associated with a non-Vulkan graphics API surface, {@link KHRSurface#VK_ERROR_NATIVE_WINDOW_IN_USE_KHR ERROR_NATIVE_WINDOW_IN_USE_KHR} <b>must</b> be returned.</p>
*
* <p>The native window referred to by {@code pCreateInfo→surface} <b>must</b> not become associated with a non-Vulkan graphics API surface before all associated Vulkan swapchains have been destroyed.</p>
*
* <p>{@code vkCreateSwapchainKHR} will return {@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST} if the logical device was lost. The {@code VkSwapchainKHR} is a child of the {@code device}, and <b>must</b> be destroyed before the {@code device}. However, {@code VkSurfaceKHR} is not a child of any {@code VkDevice} and is not affected by the lost device. After successfully recreating a {@code VkDevice}, the same {@code VkSurfaceKHR} <b>can</b> be used to create a new {@code VkSwapchainKHR}, provided the previous one was destroyed.</p>
*
* <p>If the {@code oldSwapchain} parameter of {@code pCreateInfo} is a valid swapchain, which has exclusive full-screen access, that access is released from {@code pCreateInfo→oldSwapchain}. If the command succeeds in this case, the newly created swapchain will automatically acquire exclusive full-screen access from {@code pCreateInfo→oldSwapchain}.</p>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>This implicit transfer is intended to avoid exiting and entering full-screen exclusive mode, which may otherwise cause unwanted visual updates to the display.</p>
* </div>
*
* <p>In some cases, swapchain creation <b>may</b> fail if exclusive full-screen mode is requested for application control, but for some implementation-specific reason exclusive full-screen access is unavailable for the particular combination of parameters provided. If this occurs, {@link VK10#VK_ERROR_INITIALIZATION_FAILED ERROR_INITIALIZATION_FAILED} will be returned.</p>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>In particular, it will fail if the {@code imageExtent} member of {@code pCreateInfo} does not match the extents of the monitor. Other reasons for failure may include the app not being set as high-dpi aware, or if the physical device and monitor are not compatible in this mode.</p>
* </div>
*
* <p>If the {@code pNext} chain of {@link VkSwapchainCreateInfoKHR} includes a {@link VkSwapchainPresentBarrierCreateInfoNV} structure, then that structure includes additional swapchain creation parameters specific to the present barrier. Swapchain creation <b>may</b> fail if the state of the current system restricts the usage of the present barrier feature {@link VkSurfaceCapabilitiesPresentBarrierNV}, or a swapchain itself does not satisfy all the required conditions. In this scenario {@link VK10#VK_ERROR_INITIALIZATION_FAILED ERROR_INITIALIZATION_FAILED} is returned.</p>
*
* <p>When the {@code VkSurfaceKHR} in {@link VkSwapchainCreateInfoKHR} is a display surface, then the {@code VkDisplayModeKHR} in display surface’s {@link VkDisplaySurfaceCreateInfoKHR} is associated with a particular {@code VkDisplayKHR}. Swapchain creation <b>may</b> fail if that {@code VkDisplayKHR} is not acquired by the application. In this scenario {@link VK10#VK_ERROR_INITIALIZATION_FAILED ERROR_INITIALIZATION_FAILED} is returned.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid {@link VkSwapchainCreateInfoKHR} structure</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>{@code pSwapchain} <b>must</b> be a valid pointer to a {@code VkSwapchainKHR} handle</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code pCreateInfo→surface} <b>must</b> be externally synchronized</li>
* <li>Host access to {@code pCreateInfo→oldSwapchain} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* <li>{@link KHRSurface#VK_ERROR_NATIVE_WINDOW_IN_USE_KHR ERROR_NATIVE_WINDOW_IN_USE_KHR}</li>
* <li>{@link VK10#VK_ERROR_INITIALIZATION_FAILED ERROR_INITIALIZATION_FAILED}</li>
* <li>{@link EXTImageCompressionControl#VK_ERROR_COMPRESSION_EXHAUSTED_EXT ERROR_COMPRESSION_EXHAUSTED_EXT}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}, {@link VkSwapchainCreateInfoKHR}</p>
*
* @param device the device to create the swapchain for.
* @param pCreateInfo a pointer to a {@link VkSwapchainCreateInfoKHR} structure specifying the parameters of the created swapchain.
* @param pAllocator the allocator used for host memory allocated for the swapchain object when there is no more specific allocator available (see <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a>).
* @param pSwapchain a pointer to a {@code VkSwapchainKHR} handle in which the created swapchain object will be returned.
*/
@NativeType("VkResult")
public static int vkCreateSwapchainKHR(VkDevice device, @NativeType("VkSwapchainCreateInfoKHR const *") VkSwapchainCreateInfoKHR pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSwapchainKHR *") LongBuffer pSwapchain) {
if (CHECKS) {
check(pSwapchain, 1);
}
return nvkCreateSwapchainKHR(device, pCreateInfo.address(), memAddressSafe(pAllocator), memAddress(pSwapchain));
}
// --- [ vkDestroySwapchainKHR ] ---
/** Unsafe version of: {@link #vkDestroySwapchainKHR DestroySwapchainKHR} */
public static void nvkDestroySwapchainKHR(VkDevice device, long swapchain, long pAllocator) {
long __functionAddress = device.getCapabilities().vkDestroySwapchainKHR;
if (CHECKS) {
check(__functionAddress);
}
callPJPV(device.address(), swapchain, pAllocator, __functionAddress);
}
/**
* Destroy a swapchain object.
*
* <h5>C Specification</h5>
*
* <p>To destroy a swapchain object call:</p>
*
* <pre><code>
* void vkDestroySwapchainKHR(
* VkDevice device,
* VkSwapchainKHR swapchain,
* const VkAllocationCallbacks* pAllocator);</code></pre>
*
* <h5>Description</h5>
*
* <p>The application <b>must</b> not destroy a swapchain until after completion of all outstanding operations on images that were acquired from the swapchain. {@code swapchain} and all associated {@code VkImage} handles are destroyed, and <b>must</b> not be acquired or used any more by the application. The memory of each {@code VkImage} will only be freed after that image is no longer used by the presentation engine. For example, if one image of the swapchain is being displayed in a window, the memory for that image <b>may</b> not be freed until the window is destroyed, or another swapchain is created for the window. Destroying the swapchain does not invalidate the parent {@code VkSurfaceKHR}, and a new swapchain <b>can</b> be created with it.</p>
*
* <p>When a swapchain associated with a display surface is destroyed, if the image most recently presented to the display surface is from the swapchain being destroyed, then either any display resources modified by presenting images from any swapchain associated with the display surface <b>must</b> be reverted by the implementation to their state prior to the first present performed on one of these swapchains, or such resources <b>must</b> be left in their current state.</p>
*
* <p>If {@code swapchain} has exclusive full-screen access, it is released before the swapchain is destroyed.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>All uses of presentable images acquired from {@code swapchain} <b>must</b> have completed execution</li>
* <li>If {@link VkAllocationCallbacks} were provided when {@code swapchain} was created, a compatible set of callbacks <b>must</b> be provided here</li>
* <li>If no {@link VkAllocationCallbacks} were provided when {@code swapchain} was created, {@code pAllocator} <b>must</b> be {@code NULL}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>If {@code swapchain} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code swapchain} <b>must</b> be a valid {@code VkSwapchainKHR} handle</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>If {@code swapchain} is a valid handle, it <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code swapchain} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}</p>
*
* @param device the {@code VkDevice} associated with {@code swapchain}.
* @param swapchain the swapchain to destroy.
* @param pAllocator the allocator used for host memory allocated for the swapchain object when there is no more specific allocator available (see <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a>).
*/
public static void vkDestroySwapchainKHR(VkDevice device, @NativeType("VkSwapchainKHR") long swapchain, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator) {
nvkDestroySwapchainKHR(device, swapchain, memAddressSafe(pAllocator));
}
// --- [ vkGetSwapchainImagesKHR ] ---
/**
* Unsafe version of: {@link #vkGetSwapchainImagesKHR GetSwapchainImagesKHR}
*
* @param pSwapchainImageCount a pointer to an integer related to the number of presentable images available or queried, as described below.
*/
public static int nvkGetSwapchainImagesKHR(VkDevice device, long swapchain, long pSwapchainImageCount, long pSwapchainImages) {
long __functionAddress = device.getCapabilities().vkGetSwapchainImagesKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPJPPI(device.address(), swapchain, pSwapchainImageCount, pSwapchainImages, __functionAddress);
}
/**
* Obtain the array of presentable images associated with a swapchain.
*
* <h5>C Specification</h5>
*
* <p>To obtain the array of presentable images associated with a swapchain, call:</p>
*
* <pre><code>
* VkResult vkGetSwapchainImagesKHR(
* VkDevice device,
* VkSwapchainKHR swapchain,
* uint32_t* pSwapchainImageCount,
* VkImage* pSwapchainImages);</code></pre>
*
* <h5>Description</h5>
*
* <p>If {@code pSwapchainImages} is {@code NULL}, then the number of presentable images for {@code swapchain} is returned in {@code pSwapchainImageCount}. Otherwise, {@code pSwapchainImageCount} <b>must</b> point to a variable set by the user to the number of elements in the {@code pSwapchainImages} array, and on return the variable is overwritten with the number of structures actually written to {@code pSwapchainImages}. If the value of {@code pSwapchainImageCount} is less than the number of presentable images for {@code swapchain}, at most {@code pSwapchainImageCount} structures will be written, and {@link VK10#VK_INCOMPLETE INCOMPLETE} will be returned instead of {@link VK10#VK_SUCCESS SUCCESS}, to indicate that not all the available presentable images were returned.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code swapchain} <b>must</b> be a valid {@code VkSwapchainKHR} handle</li>
* <li>{@code pSwapchainImageCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pSwapchainImageCount} is not 0, and {@code pSwapchainImages} is not {@code NULL}, {@code pSwapchainImages} <b>must</b> be a valid pointer to an array of {@code pSwapchainImageCount} {@code VkImage} handles</li>
* <li>{@code swapchain} <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link VK10#VK_INCOMPLETE INCOMPLETE}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* @param device the device associated with {@code swapchain}.
* @param swapchain the swapchain to query.
* @param pSwapchainImageCount a pointer to an integer related to the number of presentable images available or queried, as described below.
* @param pSwapchainImages either {@code NULL} or a pointer to an array of {@code VkImage} handles.
*/
@NativeType("VkResult")
public static int vkGetSwapchainImagesKHR(VkDevice device, @NativeType("VkSwapchainKHR") long swapchain, @NativeType("uint32_t *") IntBuffer pSwapchainImageCount, @Nullable @NativeType("VkImage *") LongBuffer pSwapchainImages) {
if (CHECKS) {
check(pSwapchainImageCount, 1);
checkSafe(pSwapchainImages, pSwapchainImageCount.get(pSwapchainImageCount.position()));
}
return nvkGetSwapchainImagesKHR(device, swapchain, memAddress(pSwapchainImageCount), memAddressSafe(pSwapchainImages));
}
// --- [ vkAcquireNextImageKHR ] ---
/** Unsafe version of: {@link #vkAcquireNextImageKHR AcquireNextImageKHR} */
public static int nvkAcquireNextImageKHR(VkDevice device, long swapchain, long timeout, long semaphore, long fence, long pImageIndex) {
long __functionAddress = device.getCapabilities().vkAcquireNextImageKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPJJJJPI(device.address(), swapchain, timeout, semaphore, fence, pImageIndex, __functionAddress);
}
/**
* Retrieve the index of the next available presentable image.
*
* <h5>C Specification</h5>
*
* <p>To acquire an available presentable image to use, and retrieve the index of that image, call:</p>
*
* <pre><code>
* VkResult vkAcquireNextImageKHR(
* VkDevice device,
* VkSwapchainKHR swapchain,
* uint64_t timeout,
* VkSemaphore semaphore,
* VkFence fence,
* uint32_t* pImageIndex);</code></pre>
*
* <h5>Description</h5>
*
* <p>If the {@code swapchain} has been created with the {@link EXTSwapchainMaintenance1#VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT} flag, the image whose index is returned in {@code pImageIndex} will be fully backed by memory before this call returns to the application, as if it is bound completely and contiguously to a single {@code VkDeviceMemory} object.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code swapchain} <b>must</b> not be in the retired state</li>
* <li>If {@code semaphore} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE} it <b>must</b> be unsignaled</li>
* <li>If {@code semaphore} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE} it <b>must</b> not have any uncompleted signal or wait operations pending</li>
* <li>If {@code fence} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE} it <b>must</b> be unsignaled and <b>must</b> not be associated with any other queue command that has not yet completed execution on that queue</li>
* <li>{@code semaphore} and {@code fence} <b>must</b> not both be equal to {@link VK10#VK_NULL_HANDLE NULL_HANDLE}</li>
* <li>If <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#swapchain-acquire-forward-progress">forward progress</a> cannot be guaranteed for the {@code surface} used to create the {@code swapchain} member of {@code pAcquireInfo}, the {@code timeout} member of {@code pAcquireInfo} <b>must</b> not be {@code UINT64_MAX}</li>
* <li>{@code semaphore} <b>must</b> have a {@code VkSemaphoreType} of {@link VK12#VK_SEMAPHORE_TYPE_BINARY SEMAPHORE_TYPE_BINARY}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code swapchain} <b>must</b> be a valid {@code VkSwapchainKHR} handle</li>
* <li>If {@code semaphore} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code semaphore} <b>must</b> be a valid {@code VkSemaphore} handle</li>
* <li>If {@code fence} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code fence} <b>must</b> be a valid {@code VkFence} handle</li>
* <li>{@code pImageIndex} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>{@code swapchain} <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* <li>If {@code semaphore} is a valid handle, it <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* <li>If {@code fence} is a valid handle, it <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code swapchain} <b>must</b> be externally synchronized</li>
* <li>Host access to {@code semaphore} <b>must</b> be externally synchronized</li>
* <li>Host access to {@code fence} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link VK10#VK_TIMEOUT TIMEOUT}</li>
* <li>{@link VK10#VK_NOT_READY NOT_READY}</li>
* <li>{@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST}</li>
* <li>{@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* <li>{@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT}</li>
* </ul></dd>
* </dl>
*
* @param device the device associated with {@code swapchain}.
* @param swapchain the non-retired swapchain from which an image is being acquired.
* @param timeout specifies how long the function waits, in nanoseconds, if no image is available.
* @param semaphore {@link VK10#VK_NULL_HANDLE NULL_HANDLE} or a semaphore to signal.
* @param fence {@link VK10#VK_NULL_HANDLE NULL_HANDLE} or a fence to signal.
* @param pImageIndex a pointer to a {@code uint32_t} in which the index of the next image to use (i.e. an index into the array of images returned by {@code vkGetSwapchainImagesKHR}) is returned.
*/
@NativeType("VkResult")
public static int vkAcquireNextImageKHR(VkDevice device, @NativeType("VkSwapchainKHR") long swapchain, @NativeType("uint64_t") long timeout, @NativeType("VkSemaphore") long semaphore, @NativeType("VkFence") long fence, @NativeType("uint32_t *") IntBuffer pImageIndex) {
if (CHECKS) {
check(pImageIndex, 1);
}
return nvkAcquireNextImageKHR(device, swapchain, timeout, semaphore, fence, memAddress(pImageIndex));
}
// --- [ vkQueuePresentKHR ] ---
/** Unsafe version of: {@link #vkQueuePresentKHR QueuePresentKHR} */
public static int nvkQueuePresentKHR(VkQueue queue, long pPresentInfo) {
long __functionAddress = queue.getCapabilities().vkQueuePresentKHR;
if (CHECKS) {
check(__functionAddress);
VkPresentInfoKHR.validate(pPresentInfo);
}
return callPPI(queue.address(), pPresentInfo, __functionAddress);
}
/**
* Queue an image for presentation.
*
* <h5>C Specification</h5>
*
* <p>After queueing all rendering commands and transitioning the image to the correct layout, to queue an image for presentation, call:</p>
*
* <pre><code>
* VkResult vkQueuePresentKHR(
* VkQueue queue,
* const VkPresentInfoKHR* pPresentInfo);</code></pre>
*
* <h5>Description</h5>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>There is no requirement for an application to present images in the same order that they were acquired - applications can arbitrarily present any image that is currently acquired.</p>
* </div>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The origin of the native orientation of the surface coordinate system is not specified in the Vulkan specification; it depends on the platform. For most platforms the origin is by default upper-left, meaning the pixel of the presented {@code VkImage} at coordinates <code>(0,0)</code> would appear at the upper left pixel of the platform surface (assuming {@link KHRSurface#VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR SURFACE_TRANSFORM_IDENTITY_BIT_KHR}, and the display standing the right way up).</p>
* </div>
*
* <p>The result codes {@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR} and {@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR} have the same meaning when returned by {@code vkQueuePresentKHR} as they do when returned by {@code vkAcquireNextImageKHR}. If any {@code swapchain} member of {@code pPresentInfo} was created with {@link EXTFullScreenExclusive#VK_FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT}, {@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT} will be returned if that swapchain does not have exclusive full-screen access, possibly for implementation-specific reasons outside of the application’s control. If multiple swapchains are presented, the result code is determined by applying the following rules in order:</p>
*
* <ul>
* <li>If the device is lost, {@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST} is returned.</li>
* <li>If any of the target surfaces are no longer available the error {@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR} is returned.</li>
* <li>If any of the presents would have a result of {@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR} if issued separately then {@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR} is returned.</li>
* <li>If any of the presents would have a result of {@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT} if issued separately then {@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT} is returned.</li>
* <li>If any of the presents would have a result of {@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR} if issued separately then {@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR} is returned.</li>
* <li>Otherwise {@link VK10#VK_SUCCESS SUCCESS} is returned.</li>
* </ul>
*
* <p>Any writes to memory backing the images referenced by the {@code pImageIndices} and {@code pSwapchains} members of {@code pPresentInfo}, that are available before {@link #vkQueuePresentKHR QueuePresentKHR} is executed, are automatically made visible to the read access performed by the presentation engine. This automatic visibility operation for an image happens-after the semaphore signal operation, and happens-before the presentation engine accesses the image.</p>
*
* <p>Presentation is a read-only operation that will not affect the content of the presentable images. Upon reacquiring the image and transitioning it away from the {@link #VK_IMAGE_LAYOUT_PRESENT_SRC_KHR IMAGE_LAYOUT_PRESENT_SRC_KHR} layout, the contents will be the same as they were prior to transitioning the image to the present source layout and presenting it. However, if a mechanism other than Vulkan is used to modify the platform window associated with the swapchain, the content of all presentable images in the swapchain becomes undefined.</p>
*
* <p>Calls to {@code vkQueuePresentKHR} <b>may</b> block, but <b>must</b> return in finite time. The processing of the presentation happens in issue order with other queue operations, but semaphores <b>must</b> be used to ensure that prior rendering and other commands in the specified queue complete before the presentation begins. The presentation command itself does not delay processing of subsequent commands on the queue. However, presentation requests sent to a particular queue are always performed in order. Exact presentation timing is controlled by the semantics of the presentation engine and native platform in use.</p>
*
* <p>If an image is presented to a swapchain created from a display surface, the mode of the associated display will be updated, if necessary, to match the mode specified when creating the display surface. The mode switch and presentation of the specified image will be performed as one atomic operation.</p>
*
* <p>Queueing an image for presentation defines a set of <em>queue operations</em>, including waiting on the semaphores and submitting a presentation request to the presentation engine. However, the scope of this set of queue operations does not include the actual processing of the image by the presentation engine.</p>
*
* <p>If {@code vkQueuePresentKHR} fails to enqueue the corresponding set of queue operations, it <b>may</b> return {@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY} or {@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}. If it does, the implementation <b>must</b> ensure that the state and contents of any resources or synchronization primitives referenced is unaffected by the call or its failure.</p>
*
* <p>If {@code vkQueuePresentKHR} fails in such a way that the implementation is unable to make that guarantee, the implementation <b>must</b> return {@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST}.</p>
*
* <p>However, if the presentation request is rejected by the presentation engine with an error {@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR}, {@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT}, or {@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}, the set of queue operations are still considered to be enqueued and thus any semaphore wait operation specified in {@link VkPresentInfoKHR} will execute when the corresponding queue operation is complete.</p>
*
* <p>{@code vkQueuePresentKHR} releases the acquisition of the images referenced by {@code imageIndices}. The queue family corresponding to the queue {@code vkQueuePresentKHR} is executed on <b>must</b> have ownership of the presented images as defined in <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#resources-sharing">Resource Sharing</a>. {@code vkQueuePresentKHR} does not alter the queue family ownership, but the presented images <b>must</b> not be used again before they have been reacquired using {@code vkAcquireNextImageKHR}.</p>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The application <b>can</b> continue to present any acquired images from a retired swapchain as long as the swapchain has not entered a state that causes {@link #vkQueuePresentKHR QueuePresentKHR} to return {@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR}.</p>
* </div>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>Each element of {@code pSwapchains} member of {@code pPresentInfo} <b>must</b> be a swapchain that is created for a surface for which presentation is supported from {@code queue} as determined using a call to {@code vkGetPhysicalDeviceSurfaceSupportKHR}</li>
* <li>If more than one member of {@code pSwapchains} was created from a display surface, all display surfaces referenced that refer to the same display <b>must</b> use the same display mode</li>
* <li>When a semaphore wait operation referring to a binary semaphore defined by the elements of the {@code pWaitSemaphores} member of {@code pPresentInfo} executes on {@code queue}, there <b>must</b> be no other queues waiting on the same semaphore</li>
* <li>All elements of the {@code pWaitSemaphores} member of {@code pPresentInfo} <b>must</b> be created with a {@code VkSemaphoreType} of {@link VK12#VK_SEMAPHORE_TYPE_BINARY SEMAPHORE_TYPE_BINARY}</li>
* <li>All elements of the {@code pWaitSemaphores} member of {@code pPresentInfo} <b>must</b> reference a semaphore signal operation that has been submitted for execution and any <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-semaphores-signaling">semaphore signal operations</a> on which it depends <b>must</b> have also been submitted for execution</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code queue} <b>must</b> be a valid {@code VkQueue} handle</li>
* <li>{@code pPresentInfo} <b>must</b> be a valid pointer to a valid {@link VkPresentInfoKHR} structure</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code queue} <b>must</b> be externally synchronized</li>
* <li>Host access to {@code pPresentInfo→pWaitSemaphores}[] <b>must</b> be externally synchronized</li>
* <li>Host access to {@code pPresentInfo→pSwapchains}[] <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>-</td><td>-</td><td>-</td><td>Any</td><td>-</td></tr></tbody>
* </table>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST}</li>
* <li>{@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* <li>{@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkPresentInfoKHR}</p>
*
* @param queue a queue that is capable of presentation to the target surface’s platform on the same device as the image’s swapchain.
* @param pPresentInfo a pointer to a {@link VkPresentInfoKHR} structure specifying parameters of the presentation.
*/
@NativeType("VkResult")
public static int vkQueuePresentKHR(VkQueue queue, @NativeType("VkPresentInfoKHR const *") VkPresentInfoKHR pPresentInfo) {
return nvkQueuePresentKHR(queue, pPresentInfo.address());
}
// --- [ vkGetDeviceGroupPresentCapabilitiesKHR ] ---
/** Unsafe version of: {@link #vkGetDeviceGroupPresentCapabilitiesKHR GetDeviceGroupPresentCapabilitiesKHR} */
public static int nvkGetDeviceGroupPresentCapabilitiesKHR(VkDevice device, long pDeviceGroupPresentCapabilities) {
long __functionAddress = device.getCapabilities().vkGetDeviceGroupPresentCapabilitiesKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPPI(device.address(), pDeviceGroupPresentCapabilities, __functionAddress);
}
/**
* Query present capabilities from other physical devices.
*
* <h5>C Specification</h5>
*
* <p>A logical device that represents multiple physical devices <b>may</b> support presenting from images on more than one physical device, or combining images from multiple physical devices.</p>
*
* <p>To query these capabilities, call:</p>
*
* <pre><code>
* VkResult vkGetDeviceGroupPresentCapabilitiesKHR(
* VkDevice device,
* VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pDeviceGroupPresentCapabilities} <b>must</b> be a valid pointer to a {@link VkDeviceGroupPresentCapabilitiesKHR} structure</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkDeviceGroupPresentCapabilitiesKHR}</p>
*
* @param device the logical device.
* @param pDeviceGroupPresentCapabilities a pointer to a {@link VkDeviceGroupPresentCapabilitiesKHR} structure in which the device’s capabilities are returned.
*/
@NativeType("VkResult")
public static int vkGetDeviceGroupPresentCapabilitiesKHR(VkDevice device, @NativeType("VkDeviceGroupPresentCapabilitiesKHR *") VkDeviceGroupPresentCapabilitiesKHR pDeviceGroupPresentCapabilities) {
return nvkGetDeviceGroupPresentCapabilitiesKHR(device, pDeviceGroupPresentCapabilities.address());
}
// --- [ vkGetDeviceGroupSurfacePresentModesKHR ] ---
/** Unsafe version of: {@link #vkGetDeviceGroupSurfacePresentModesKHR GetDeviceGroupSurfacePresentModesKHR} */
public static int nvkGetDeviceGroupSurfacePresentModesKHR(VkDevice device, long surface, long pModes) {
long __functionAddress = device.getCapabilities().vkGetDeviceGroupSurfacePresentModesKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPJPI(device.address(), surface, pModes, __functionAddress);
}
/**
* Query present capabilities for a surface.
*
* <h5>C Specification</h5>
*
* <p>Some surfaces <b>may</b> not be capable of using all the device group present modes.</p>
*
* <p>To query the supported device group present modes for a particular surface, call:</p>
*
* <pre><code>
* VkResult vkGetDeviceGroupSurfacePresentModesKHR(
* VkDevice device,
* VkSurfaceKHR surface,
* VkDeviceGroupPresentModeFlagsKHR* pModes);</code></pre>
*
* <h5>Description</h5>
*
* <p>The modes returned by this command are not invariant, and <b>may</b> change in response to the surface being moved, resized, or occluded. These modes <b>must</b> be a subset of the modes returned by {@link #vkGetDeviceGroupPresentCapabilitiesKHR GetDeviceGroupPresentCapabilitiesKHR}.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code surface} <b>must</b> be supported by all physical devices associated with {@code device}, as reported by {@link KHRSurface#vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR} or an equivalent platform-specific mechanism</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code surface} <b>must</b> be a valid {@code VkSurfaceKHR} handle</li>
* <li>{@code pModes} <b>must</b> be a valid pointer to a {@code VkDeviceGroupPresentModeFlagsKHR} value</li>
* <li>Both of {@code device}, and {@code surface} <b>must</b> have been created, allocated, or retrieved from the same {@code VkInstance}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code surface} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* </ul></dd>
* </dl>
*
* @param device the logical device.
* @param surface the surface.
* @param pModes a pointer to a {@code VkDeviceGroupPresentModeFlagsKHR} in which the supported device group present modes for the surface are returned.
*/
@NativeType("VkResult")
public static int vkGetDeviceGroupSurfacePresentModesKHR(VkDevice device, @NativeType("VkSurfaceKHR") long surface, @NativeType("VkDeviceGroupPresentModeFlagsKHR *") IntBuffer pModes) {
if (CHECKS) {
check(pModes, 1);
}
return nvkGetDeviceGroupSurfacePresentModesKHR(device, surface, memAddress(pModes));
}
// --- [ vkGetPhysicalDevicePresentRectanglesKHR ] ---
/**
* Unsafe version of: {@link #vkGetPhysicalDevicePresentRectanglesKHR GetPhysicalDevicePresentRectanglesKHR}
*
* @param pRectCount a pointer to an integer related to the number of rectangles available or queried, as described below.
*/
public static int nvkGetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice physicalDevice, long surface, long pRectCount, long pRects) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDevicePresentRectanglesKHR;
if (CHECKS) {
check(__functionAddress);
}
return callPJPPI(physicalDevice.address(), surface, pRectCount, pRects, __functionAddress);
}
/**
* Query present rectangles for a surface on a physical device.
*
* <h5>C Specification</h5>
*
* <p>When using {@link #VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR}, the application <b>may</b> need to know which regions of the surface are used when presenting locally on each physical device. Presentation of swapchain images to this surface need only have valid contents in the regions returned by this command.</p>
*
* <p>To query a set of rectangles used in presentation on the physical device, call:</p>
*
* <pre><code>
* VkResult vkGetPhysicalDevicePresentRectanglesKHR(
* VkPhysicalDevice physicalDevice,
* VkSurfaceKHR surface,
* uint32_t* pRectCount,
* VkRect2D* pRects);</code></pre>
*
* <h5>Description</h5>
*
* <p>If {@code pRects} is {@code NULL}, then the number of rectangles used when presenting the given {@code surface} is returned in {@code pRectCount}. Otherwise, {@code pRectCount} <b>must</b> point to a variable set by the user to the number of elements in the {@code pRects} array, and on return the variable is overwritten with the number of structures actually written to {@code pRects}. If the value of {@code pRectCount} is less than the number of rectangles, at most {@code pRectCount} structures will be written, and {@link VK10#VK_INCOMPLETE INCOMPLETE} will be returned instead of {@link VK10#VK_SUCCESS SUCCESS}, to indicate that not all the available rectangles were returned.</p>
*
* <p>The values returned by this command are not invariant, and <b>may</b> change in response to the surface being moved, resized, or occluded.</p>
*
* <p>The rectangles returned by this command <b>must</b> not overlap.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code surface} <b>must</b> be a valid {@code VkSurfaceKHR} handle</li>
* <li>{@code surface} <b>must</b> be supported by {@code physicalDevice}, as reported by {@link KHRSurface#vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR} or an equivalent platform-specific mechanism</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code surface} <b>must</b> be a valid {@code VkSurfaceKHR} handle</li>
* <li>{@code pRectCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pRectCount} is not 0, and {@code pRects} is not {@code NULL}, {@code pRects} <b>must</b> be a valid pointer to an array of {@code pRectCount} {@link VkRect2D} structures</li>
* <li>Both of {@code physicalDevice}, and {@code surface} <b>must</b> have been created, allocated, or retrieved from the same {@code VkInstance}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code surface} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link VK10#VK_INCOMPLETE INCOMPLETE}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkRect2D}</p>
*
* @param physicalDevice the physical device.
* @param surface the surface.
* @param pRectCount a pointer to an integer related to the number of rectangles available or queried, as described below.
* @param pRects either {@code NULL} or a pointer to an array of {@link VkRect2D} structures.
*/
@NativeType("VkResult")
public static int vkGetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice physicalDevice, @NativeType("VkSurfaceKHR") long surface, @NativeType("uint32_t *") IntBuffer pRectCount, @Nullable @NativeType("VkRect2D *") VkRect2D.Buffer pRects) {
if (CHECKS) {
check(pRectCount, 1);
checkSafe(pRects, pRectCount.get(pRectCount.position()));
}
return nvkGetPhysicalDevicePresentRectanglesKHR(physicalDevice, surface, memAddress(pRectCount), memAddressSafe(pRects));
}
// --- [ vkAcquireNextImage2KHR ] ---
/** Unsafe version of: {@link #vkAcquireNextImage2KHR AcquireNextImage2KHR} */
public static int nvkAcquireNextImage2KHR(VkDevice device, long pAcquireInfo, long pImageIndex) {
long __functionAddress = device.getCapabilities().vkAcquireNextImage2KHR;
if (CHECKS) {
check(__functionAddress);
}
return callPPPI(device.address(), pAcquireInfo, pImageIndex, __functionAddress);
}
/**
* Retrieve the index of the next available presentable image.
*
* <h5>C Specification</h5>
*
* <p>To acquire an available presentable image to use, and retrieve the index of that image, call:</p>
*
* <pre><code>
* VkResult vkAcquireNextImage2KHR(
* VkDevice device,
* const VkAcquireNextImageInfoKHR* pAcquireInfo,
* uint32_t* pImageIndex);</code></pre>
*
* <h5>Description</h5>
*
* <p>If the {@code swapchain} has been created with the {@link EXTSwapchainMaintenance1#VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT} flag, the image whose index is returned in {@code pImageIndex} will be fully backed by memory before this call returns to the application.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>If <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#swapchain-acquire-forward-progress">forward progress</a> cannot be guaranteed for the {@code surface} used to create {@code swapchain}, the {@code timeout} member of {@code pAcquireInfo} <b>must</b> not be {@code UINT64_MAX}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pAcquireInfo} <b>must</b> be a valid pointer to a valid {@link VkAcquireNextImageInfoKHR} structure</li>
* <li>{@code pImageIndex} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link VK10#VK_TIMEOUT TIMEOUT}</li>
* <li>{@link VK10#VK_NOT_READY NOT_READY}</li>
* <li>{@link #VK_SUBOPTIMAL_KHR SUBOPTIMAL_KHR}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_DEVICE_LOST ERROR_DEVICE_LOST}</li>
* <li>{@link #VK_ERROR_OUT_OF_DATE_KHR ERROR_OUT_OF_DATE_KHR}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* <li>{@link EXTFullScreenExclusive#VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkAcquireNextImageInfoKHR}</p>
*
* @param device the device associated with {@code swapchain}.
* @param pAcquireInfo a pointer to a {@link VkAcquireNextImageInfoKHR} structure containing parameters of the acquire.
* @param pImageIndex a pointer to a {@code uint32_t} that is set to the index of the next image to use.
*/
@NativeType("VkResult")
public static int vkAcquireNextImage2KHR(VkDevice device, @NativeType("VkAcquireNextImageInfoKHR const *") VkAcquireNextImageInfoKHR pAcquireInfo, @NativeType("uint32_t *") IntBuffer pImageIndex) {
if (CHECKS) {
check(pImageIndex, 1);
}
return nvkAcquireNextImage2KHR(device, pAcquireInfo.address(), memAddress(pImageIndex));
}
/** Array version of: {@link #vkCreateSwapchainKHR CreateSwapchainKHR} */
@NativeType("VkResult")
public static int vkCreateSwapchainKHR(VkDevice device, @NativeType("VkSwapchainCreateInfoKHR const *") VkSwapchainCreateInfoKHR pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSwapchainKHR *") long[] pSwapchain) {
long __functionAddress = device.getCapabilities().vkCreateSwapchainKHR;
if (CHECKS) {
check(__functionAddress);
check(pSwapchain, 1);
}
return callPPPPI(device.address(), pCreateInfo.address(), memAddressSafe(pAllocator), pSwapchain, __functionAddress);
}
/** Array version of: {@link #vkGetSwapchainImagesKHR GetSwapchainImagesKHR} */
@NativeType("VkResult")
public static int vkGetSwapchainImagesKHR(VkDevice device, @NativeType("VkSwapchainKHR") long swapchain, @NativeType("uint32_t *") int[] pSwapchainImageCount, @Nullable @NativeType("VkImage *") long[] pSwapchainImages) {
long __functionAddress = device.getCapabilities().vkGetSwapchainImagesKHR;
if (CHECKS) {
check(__functionAddress);
check(pSwapchainImageCount, 1);
checkSafe(pSwapchainImages, pSwapchainImageCount[0]);
}
return callPJPPI(device.address(), swapchain, pSwapchainImageCount, pSwapchainImages, __functionAddress);
}
/** Array version of: {@link #vkAcquireNextImageKHR AcquireNextImageKHR} */
@NativeType("VkResult")
public static int vkAcquireNextImageKHR(VkDevice device, @NativeType("VkSwapchainKHR") long swapchain, @NativeType("uint64_t") long timeout, @NativeType("VkSemaphore") long semaphore, @NativeType("VkFence") long fence, @NativeType("uint32_t *") int[] pImageIndex) {
long __functionAddress = device.getCapabilities().vkAcquireNextImageKHR;
if (CHECKS) {
check(__functionAddress);
check(pImageIndex, 1);
}
return callPJJJJPI(device.address(), swapchain, timeout, semaphore, fence, pImageIndex, __functionAddress);
}
/** Array version of: {@link #vkGetDeviceGroupSurfacePresentModesKHR GetDeviceGroupSurfacePresentModesKHR} */
@NativeType("VkResult")
public static int vkGetDeviceGroupSurfacePresentModesKHR(VkDevice device, @NativeType("VkSurfaceKHR") long surface, @NativeType("VkDeviceGroupPresentModeFlagsKHR *") int[] pModes) {
long __functionAddress = device.getCapabilities().vkGetDeviceGroupSurfacePresentModesKHR;
if (CHECKS) {
check(__functionAddress);
check(pModes, 1);
}
return callPJPI(device.address(), surface, pModes, __functionAddress);
}
/** Array version of: {@link #vkGetPhysicalDevicePresentRectanglesKHR GetPhysicalDevicePresentRectanglesKHR} */
@NativeType("VkResult")
public static int vkGetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice physicalDevice, @NativeType("VkSurfaceKHR") long surface, @NativeType("uint32_t *") int[] pRectCount, @Nullable @NativeType("VkRect2D *") VkRect2D.Buffer pRects) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDevicePresentRectanglesKHR;
if (CHECKS) {
check(__functionAddress);
check(pRectCount, 1);
checkSafe(pRects, pRectCount[0]);
}
return callPJPPI(physicalDevice.address(), surface, pRectCount, memAddressSafe(pRects), __functionAddress);
}
/** Array version of: {@link #vkAcquireNextImage2KHR AcquireNextImage2KHR} */
@NativeType("VkResult")
public static int vkAcquireNextImage2KHR(VkDevice device, @NativeType("VkAcquireNextImageInfoKHR const *") VkAcquireNextImageInfoKHR pAcquireInfo, @NativeType("uint32_t *") int[] pImageIndex) {
long __functionAddress = device.getCapabilities().vkAcquireNextImage2KHR;
if (CHECKS) {
check(__functionAddress);
check(pImageIndex, 1);
}
return callPPPI(device.address(), pAcquireInfo.address(), pImageIndex, __functionAddress);
}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRSwapchain.java |
214,145 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.BindingImpl;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.internal.MatcherAndConverter;
import org.elasticsearch.common.inject.spi.TypeListenerBinding;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptySet;
/**
* The inheritable data within an injector. This class is intended to allow parent and local
* injector data to be accessed as a unit.
*
* @author [email protected] (Jesse Wilson)
*/
interface State {
State NONE = new State() {
@Override
public State parent() {
throw new UnsupportedOperationException();
}
@Override
public <T> BindingImpl<T> getExplicitBinding(Key<T> key) {
return null;
}
@Override
public Map<Key<?>, Binding<?>> getExplicitBindingsThisLevel() {
throw new UnsupportedOperationException();
}
@Override
public void putBinding(Key<?> key, BindingImpl<?> binding) {
throw new UnsupportedOperationException();
}
@Override
public Scope getScope(Class<? extends Annotation> scopingAnnotation) {
return null;
}
@Override
public void putAnnotation(Class<? extends Annotation> annotationType, Scope scope) {
throw new UnsupportedOperationException();
}
@Override
public void addConverter(MatcherAndConverter matcherAndConverter) {
throw new UnsupportedOperationException();
}
@Override
public MatcherAndConverter getConverter(String stringValue, TypeLiteral<?> type, Errors errors,
Object source) {
throw new UnsupportedOperationException();
}
@Override
public Iterable<MatcherAndConverter> getConvertersThisLevel() {
return emptySet();
}
@Override
public void addTypeListener(TypeListenerBinding typeListenerBinding) {
throw new UnsupportedOperationException();
}
@Override
public List<TypeListenerBinding> getTypeListenerBindings() {
return Collections.emptyList();
}
@Override
public void blacklist(Key<?> key) {
}
@Override
public boolean isBlacklisted(Key<?> key) {
return true;
}
@Override
public void clearBlacklisted() {
}
@Override
public void makeAllBindingsToEagerSingletons(Injector injector) {
}
@Override
public Object lock() {
throw new UnsupportedOperationException();
}
};
State parent();
/**
* Gets a binding which was specified explicitly in a module, or null.
*/
<T> BindingImpl<T> getExplicitBinding(Key<T> key);
/**
* Returns the explicit bindings at this level only.
*/
Map<Key<?>, Binding<?>> getExplicitBindingsThisLevel();
void putBinding(Key<?> key, BindingImpl<?> binding);
/**
* Returns the matching scope, or null.
*/
Scope getScope(Class<? extends Annotation> scopingAnnotation);
void putAnnotation(Class<? extends Annotation> annotationType, Scope scope);
void addConverter(MatcherAndConverter matcherAndConverter);
/**
* Returns the matching converter for {@code type}, or null if none match.
*/
MatcherAndConverter getConverter(
String stringValue, TypeLiteral<?> type, Errors errors, Object source);
/**
* Returns all converters at this level only.
*/
Iterable<MatcherAndConverter> getConvertersThisLevel();
void addTypeListener(TypeListenerBinding typeListenerBinding);
List<TypeListenerBinding> getTypeListenerBindings();
/**
* Forbids the corresponding injector from creating a binding to {@code key}. Child injectors
* blacklist their bound keys on their parent injectors to prevent just-in-time bindings on the
* parent injector that would conflict.
*/
void blacklist(Key<?> key);
/**
* Returns true if {@code key} is forbidden from being bound in this injector. This indicates that
* one of this injector's descendent's has bound the key.
*/
boolean isBlacklisted(Key<?> key);
/**
* Returns the shared lock for all injector data. This is a low-granularity, high-contention lock
* to be used when reading mutable data (ie. just-in-time bindings, and binding blacklists).
*/
Object lock();
// ES_GUICE: clean blacklist keys
void clearBlacklisted();
void makeAllBindingsToEagerSingletons(Injector injector);
}
| crate/crate | libs/guice/src/main/java/org/elasticsearch/common/inject/State.java |
214,149 | /*
* Copyright (C) 2008 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.internal.ErrorsException;
/**
* Holds a reference that requires initialization to be performed before it can be used.
*
* @author [email protected] (Jesse Wilson)
*/
interface Initializable<T> {
/**
* Ensures the reference is initialized, then returns it.
*/
T get(Errors errors) throws ErrorsException;
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/Initializable.java |
214,150 | /*
* 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.netbeans.spi.project.support.ant;
import java.util.EventObject;
/**
* Event object corresponding to a change made in an Ant project's metadata.
* The event source is an {@link AntProjectHelper}.
* @see AntProjectListener
* @author Jesse Glick
*/
public final class AntProjectEvent extends EventObject {
private final String path;
private final boolean expected;
AntProjectEvent(AntProjectHelper helper, String path, boolean expected) {
super(helper);
this.path = path;
this.expected = expected;
}
/**
* Get the associated Ant project helper object.
* @return the project helper which fired the event
*/
public AntProjectHelper getHelper() {
return (AntProjectHelper)getSource();
}
/**
* Get the path to the modified (or created or deleted) file.
* Paths typically used are:
* <ol>
* <li>{@link AntProjectHelper#PROJECT_PROPERTIES_PATH}
* <li>{@link AntProjectHelper#PRIVATE_PROPERTIES_PATH}
* <li>{@link AntProjectHelper#PROJECT_XML_PATH}
* <li>{@link AntProjectHelper#PRIVATE_XML_PATH}
* </ol>
* However for properties files, other paths may exist if the project
* uses them for some purpose.
* @return a project-relative path
*/
public String getPath() {
return path;
}
/**
* Check whether the change was produced by calling methods on
* {@link AntProjectHelper} or whether it represents a change
* detected on disk.
* @return true if the change was triggered by in-memory modification methods,
* false if occurred on disk in the metadata files and is being loaded
*/
public boolean isExpected() {
return expected;
}
}
| apache/netbeans | ide/project.ant/src/org/netbeans/spi/project/support/ant/AntProjectEvent.java |
214,153 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* This extension provides new queries for memory requirements of images and buffers that can be easily extended by other extensions, without introducing any further entry points. The Vulkan 1.0 {@link VkMemoryRequirements} and {@link VkSparseImageMemoryRequirements} structures do not include {@code sType} and {@code pNext} members. This extension wraps them in new structures with these members, so an application can query a chain of memory requirements structures by constructing the chain and letting the implementation fill them in. A new command is added for each {@code vkGet*MemoryRequrements} command in core Vulkan 1.0.
*
* <h5>Promotion to Vulkan 1.1</h5>
*
* <p>All functionality in this extension is included in core Vulkan 1.1, with the KHR suffix omitted. The original type, enum and command names are still available as aliases of the core functionality.</p>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_KHR_get_memory_requirements2}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>147</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Deprecation State</b></dt>
* <dd><ul>
* <li><em>Promoted</em> to <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1-promotions">Vulkan 1.1</a></li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Faith Ekstrand <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_get_memory_requirements2]%20@gfxstrand%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_get_memory_requirements2%20extension*">gfxstrand</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-09-05</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Faith Ekstrand, Intel</li>
* <li>Jeff Bolz, NVIDIA</li>
* <li>Jesse Hall, Google</li>
* </ul></dd>
* </dl>
*/
public class KHRGetMemoryRequirements2 {
/** The extension specification version. */
public static final int VK_KHR_GET_MEMORY_REQUIREMENTS_2_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME = "VK_KHR_get_memory_requirements2";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR = 1000146000,
VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR = 1000146001,
VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR = 1000146002,
VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR = 1000146003,
VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR = 1000146004;
protected KHRGetMemoryRequirements2() {
throw new UnsupportedOperationException();
}
// --- [ vkGetImageMemoryRequirements2KHR ] ---
/** Unsafe version of: {@link #vkGetImageMemoryRequirements2KHR GetImageMemoryRequirements2KHR} */
public static void nvkGetImageMemoryRequirements2KHR(VkDevice device, long pInfo, long pMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetImageMemoryRequirements2KHR;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(device.address(), pInfo, pMemoryRequirements, __functionAddress);
}
/**
* See {@link VK11#vkGetImageMemoryRequirements2 GetImageMemoryRequirements2}.
*
* @param device the logical device that owns the image.
* @param pInfo a pointer to a {@link VkImageMemoryRequirementsInfo2} structure containing parameters required for the memory requirements query.
* @param pMemoryRequirements a pointer to a {@link VkMemoryRequirements2} structure in which the memory requirements of the image object are returned.
*/
public static void vkGetImageMemoryRequirements2KHR(VkDevice device, @NativeType("VkImageMemoryRequirementsInfo2 const *") VkImageMemoryRequirementsInfo2 pInfo, @NativeType("VkMemoryRequirements2 *") VkMemoryRequirements2 pMemoryRequirements) {
nvkGetImageMemoryRequirements2KHR(device, pInfo.address(), pMemoryRequirements.address());
}
// --- [ vkGetBufferMemoryRequirements2KHR ] ---
/** Unsafe version of: {@link #vkGetBufferMemoryRequirements2KHR GetBufferMemoryRequirements2KHR} */
public static void nvkGetBufferMemoryRequirements2KHR(VkDevice device, long pInfo, long pMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetBufferMemoryRequirements2KHR;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(device.address(), pInfo, pMemoryRequirements, __functionAddress);
}
/**
* See {@link VK11#vkGetBufferMemoryRequirements2 GetBufferMemoryRequirements2}.
*
* @param device the logical device that owns the buffer.
* @param pInfo a pointer to a {@link VkBufferMemoryRequirementsInfo2} structure containing parameters required for the memory requirements query.
* @param pMemoryRequirements a pointer to a {@link VkMemoryRequirements2} structure in which the memory requirements of the buffer object are returned.
*/
public static void vkGetBufferMemoryRequirements2KHR(VkDevice device, @NativeType("VkBufferMemoryRequirementsInfo2 const *") VkBufferMemoryRequirementsInfo2 pInfo, @NativeType("VkMemoryRequirements2 *") VkMemoryRequirements2 pMemoryRequirements) {
nvkGetBufferMemoryRequirements2KHR(device, pInfo.address(), pMemoryRequirements.address());
}
// --- [ vkGetImageSparseMemoryRequirements2KHR ] ---
/**
* Unsafe version of: {@link #vkGetImageSparseMemoryRequirements2KHR GetImageSparseMemoryRequirements2KHR}
*
* @param pSparseMemoryRequirementCount a pointer to an integer related to the number of sparse memory requirements available or queried, as described below.
*/
public static void nvkGetImageSparseMemoryRequirements2KHR(VkDevice device, long pInfo, long pSparseMemoryRequirementCount, long pSparseMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetImageSparseMemoryRequirements2KHR;
if (CHECKS) {
check(__functionAddress);
}
callPPPPV(device.address(), pInfo, pSparseMemoryRequirementCount, pSparseMemoryRequirements, __functionAddress);
}
/**
* See {@link VK11#vkGetImageSparseMemoryRequirements2 GetImageSparseMemoryRequirements2}.
*
* @param device the logical device that owns the image.
* @param pInfo a pointer to a {@link VkImageSparseMemoryRequirementsInfo2} structure containing parameters required for the memory requirements query.
* @param pSparseMemoryRequirementCount a pointer to an integer related to the number of sparse memory requirements available or queried, as described below.
* @param pSparseMemoryRequirements either {@code NULL} or a pointer to an array of {@link VkSparseImageMemoryRequirements2} structures.
*/
public static void vkGetImageSparseMemoryRequirements2KHR(VkDevice device, @NativeType("VkImageSparseMemoryRequirementsInfo2 const *") VkImageSparseMemoryRequirementsInfo2 pInfo, @NativeType("uint32_t *") IntBuffer pSparseMemoryRequirementCount, @Nullable @NativeType("VkSparseImageMemoryRequirements2 *") VkSparseImageMemoryRequirements2.Buffer pSparseMemoryRequirements) {
if (CHECKS) {
check(pSparseMemoryRequirementCount, 1);
checkSafe(pSparseMemoryRequirements, pSparseMemoryRequirementCount.get(pSparseMemoryRequirementCount.position()));
}
nvkGetImageSparseMemoryRequirements2KHR(device, pInfo.address(), memAddress(pSparseMemoryRequirementCount), memAddressSafe(pSparseMemoryRequirements));
}
/** Array version of: {@link #vkGetImageSparseMemoryRequirements2KHR GetImageSparseMemoryRequirements2KHR} */
public static void vkGetImageSparseMemoryRequirements2KHR(VkDevice device, @NativeType("VkImageSparseMemoryRequirementsInfo2 const *") VkImageSparseMemoryRequirementsInfo2 pInfo, @NativeType("uint32_t *") int[] pSparseMemoryRequirementCount, @Nullable @NativeType("VkSparseImageMemoryRequirements2 *") VkSparseImageMemoryRequirements2.Buffer pSparseMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetImageSparseMemoryRequirements2KHR;
if (CHECKS) {
check(__functionAddress);
check(pSparseMemoryRequirementCount, 1);
checkSafe(pSparseMemoryRequirements, pSparseMemoryRequirementCount[0]);
}
callPPPPV(device.address(), pInfo.address(), pSparseMemoryRequirementCount, memAddressSafe(pSparseMemoryRequirements), __functionAddress);
}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRGetMemoryRequirements2.java |
214,154 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2011, Open Source Geospatial Foundation (OSGeo)
* (C) 2003-2005, Open Geospatial Consortium Inc.
*
* All Rights Reserved. http://www.opengis.org/legal/
*/
package org.geotools.api.util;
import java.util.Locale;
import java.util.Map;
/**
* Factory for {@linkplain GenericName generic names} and {@linkplain InternationalString
* international strings}.
*
* <p>
*
* <blockquote>
*
* <font size=-1><b>Implementation note:</b> despite the "create" name, implementations may return
* cached instances. </font>
*
* </blockquote>
*
* @author Jesse Crossley (SYS Technologies)
* @author Martin Desruisseaux (Geomatys)
* @since GeoAPI 2.0
*/
public interface NameFactory {
/**
* Creates an international string from a set of strings in different locales.
*
* @param strings String value for each locale key.
* @return The international string.
*/
InternationalString createInternationalString(Map<Locale, String> strings);
/**
* Creates a namespace having the given name and separators.
*
* <p>
*
* <blockquote>
*
* <font size=-1><b>Implementation note:</b> despite the "create" name, implementations may
* return existing instances. </font>
*
* </blockquote>
*
* @param name The name of the namespace to be returned. This argument can be created using
* <code>{@linkplain #createGenericName createGenericName}(null, parsedNames)</code>.
* @param headSeparator The separator to insert between the namespace and the {@linkplain
* GenericName#head head}. For HTTP namespace, it is {@code "://"}. For URN namespace, it is
* typically {@code ":"}.
* @param separator The separator to insert between {@linkplain GenericName#getParsedNames
* parsed names} in that namespace. For HTTP namespace, it is {@code "."}. For URN
* namespace, it is typically {@code ":"}.
* @return A namespace having the given name and separators.
* @since GeoAPI 2.2
*/
NameSpace createNameSpace(GenericName name, String headSeparator, String separator);
/**
* Creates a local name from the given character sequence. The character sequence can be either
* a {@link String} or an {@link InternationalString} instance. In the later case,
* implementations can use an arbitrary {@linkplain Locale locale} (typically {@link
* Locale#ENGLISH ENGLISH}, but not necessarly) for the unlocalized string to be returned by
* {@link LocalName#toString}.
*
* @param scope The {@linkplain GenericName#scope scope} of the local name to be created, or
* {@code null} for a global namespace.
* @param name The local name as a string or an international string.
* @return The local name for the given character sequence.
* @since GeoAPI 2.2
*/
LocalName createLocalName(NameSpace scope, CharSequence name);
/**
* Creates a local or scoped name from an array of parsed names. The array elements can be
* either {@link String} or {@link InternationalString} instances. In the later case,
* implementations can use an arbitrary {@linkplain Locale locale} (typically {@link
* Locale#ENGLISH ENGLISH}, but not necessarly) for the unlocalized string to be returned by
* {@link GenericName#toString}.
*
* <p>If the length of the {@code parsedNames} array is 1, then this method returns an instance
* of {@link LocalName}. If the length is 2 or more, then this method returns an instance of
* {@link ScopedName}.
*
* @param scope The {@linkplain GenericName#scope scope} of the generic name to be created, or
* {@code null} for a global namespace.
* @param parsedNames The local names as an array of strings or international strings. This
* array must contains at least one element.
* @return The generic name for the given parsed names.
* @since GeoAPI 2.2
*/
GenericName createGenericName(NameSpace scope, CharSequence... parsedNames);
/**
* Constructs a generic name from a qualified name. This method splits the given name around a
* separator inferred from the given scope, or an implementation-dependant default separator if
* the given scope is null.
*
* <p>For example if the {@code scope} argument is the namespace {@code "urn:ogc:def"} with
* {@code ":"} as the separator, and if the {@code name} argument is the string {@code
* "crs:epsg:4326"}, then the result is a {@linkplain ScopedName scoped name} having a
* {@linkplain GenericName#depth depth} of 3, which is the length of the list of {@linkplain
* GenericName#getParsedNames parsed names} ({@code "crs"}, {@code "epsg"}, {@code "4326"}).
*
* @param scope The {@linkplain AbstractName#scope scope} of the generic name to be created, or
* {@code null} for a global namespace.
* @param name The qualified name, as a sequence of names separated by a scope-dependant
* separator.
* @return A name parsed from the given string.
* @since GeoAPI 2.2
*/
GenericName parseGenericName(NameSpace scope, CharSequence name);
}
| geotools/geotools | modules/library/api/src/main/java/org/geotools/api/util/NameFactory.java |
214,155 | /*
* Copyright (C) 2007 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.binder.AnnotatedBindingBuilder;
import org.elasticsearch.common.inject.binder.AnnotatedConstantBindingBuilder;
import org.elasticsearch.common.inject.binder.LinkedBindingBuilder;
import org.elasticsearch.common.inject.matcher.Matcher;
import org.elasticsearch.common.inject.spi.Message;
import org.elasticsearch.common.inject.spi.TypeConverter;
import org.elasticsearch.common.inject.spi.TypeListener;
import java.lang.annotation.Annotation;
/**
* Collects configuration information (primarily <i>bindings</i>) which will be
* used to create an {@link Injector}. Guice provides this object to your
* application's {@link Module} implementors so they may each contribute
* their own bindings and other registrations.
* <h3>The Guice Binding EDSL</h3>
* <p>
* Guice uses an <i>embedded domain-specific language</i>, or EDSL, to help you
* create bindings simply and readably. This approach is great for overall
* usability, but it does come with a small cost: <b>it is difficult to
* learn how to use the Binding EDSL by reading
* method-level javadocs</b>. Instead, you should consult the series of
* examples below. To save space, these examples omit the opening
* {@code binder}, just as you will if your module extends
* {@link AbstractModule}.
* <pre>
* bind(ServiceImpl.class);</pre>
*
* This statement does essentially nothing; it "binds the {@code ServiceImpl}
* class to itself" and does not change Guice's default behavior. You may still
* want to use this if you prefer your {@link Module} class to serve as an
* explicit <i>manifest</i> for the services it provides. Also, in rare cases,
* Guice may be unable to validate a binding at injector creation time unless it
* is given explicitly.
*
* <pre>
* bind(Service.class).to(ServiceImpl.class);</pre>
*
* Specifies that a request for a {@code Service} instance with no binding
* annotations should be treated as if it were a request for a
* {@code ServiceImpl} instance. This <i>overrides</i> the function of any
* {@link ImplementedBy @ImplementedBy} or {@link ProvidedBy @ProvidedBy}
* annotations found on {@code Service}, since Guice will have already
* "moved on" to {@code ServiceImpl} before it reaches the point when it starts
* looking for these annotations.
*
* <pre>
* bind(Service.class).toProvider(ServiceProvider.class);</pre>
*
* In this example, {@code ServiceProvider} must extend or implement
* {@code Provider<Service>}. This binding specifies that Guice should resolve
* an unannotated injection request for {@code Service} by first resolving an
* instance of {@code ServiceProvider} in the regular way, then calling
* {@link Provider#get get()} on the resulting Provider instance to obtain the
* {@code Service} instance.
*
* <p>The {@link Provider} you use here does not have to be a "factory"; that
* is, a provider which always <i>creates</i> each instance it provides.
* However, this is generally a good practice to follow. You can then use
* Guice's concept of {@link Scope scopes} to guide when creation should happen
* -- "letting Guice work for you".
*
* <pre>
* bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);</pre>
*
* Like the previous example, but only applies to injection requests that use
* the binding annotation {@code @Red}. If your module also includes bindings
* for particular <i>values</i> of the {@code @Red} annotation (see below),
* then this binding will serve as a "catch-all" for any values of {@code @Red}
* that have no exact match in the bindings.
*
* <pre>
* bind(ServiceImpl.class).in(Singleton.class);
* // or, alternatively
* bind(ServiceImpl.class).in(Scopes.SINGLETON);</pre>
*
* Either of these statements places the {@code ServiceImpl} class into
* singleton scope. Guice will create only one instance of {@code ServiceImpl}
* and will reuse it for all injection requests of this type. Note that it is
* still possible to bind another instance of {@code ServiceImpl} if the second
* binding is qualified by an annotation as in the previous example. Guice is
* not overly concerned with <i>preventing</i> you from creating multiple
* instances of your "singletons", only with <i>enabling</i> your application to
* share only one instance if that's all you tell Guice you need.
*
* <p><b>Note:</b> a scope specified in this way <i>overrides</i> any scope that
* was specified with an annotation on the {@code ServiceImpl} class.
*
* <p>Besides {@link Singleton}/{@link Scopes#SINGLETON}, there are
* servlet-specific scopes available in
* {@code com.google.inject.servlet.ServletScopes}, and your Modules can
* contribute their own custom scopes for use here as well.
*
* <pre>
* bind(new TypeLiteral<PaymentService<CreditCard>>() {})
* .to(CreditCardPaymentService.class);</pre>
*
* This admittedly odd construct is the way to bind a parameterized type. It
* tells Guice how to honor an injection request for an element of type
* {@code PaymentService<CreditCard>}. The class
* {@code CreditCardPaymentService} must implement the
* {@code PaymentService<CreditCard>} interface. Guice cannot currently bind or
* inject a generic type, such as {@code Set<E>}; all type parameters must be
* fully specified.
*
* <pre>
* bind(Service.class).toInstance(new ServiceImpl());
* // or, alternatively
* bind(Service.class).toInstance(SomeLegacyRegistry.getService());</pre>
*
* In this example, your module itself, <i>not Guice</i>, takes responsibility
* for obtaining a {@code ServiceImpl} instance, then asks Guice to always use
* this single instance to fulfill all {@code Service} injection requests. When
* the {@link Injector} is created, it will automatically perform field
* and method injection for this instance, but any injectable constructor on
* {@code ServiceImpl} is simply ignored. Note that using this approach results
* in "eager loading" behavior that you can't control.
*
* <pre>
* bindConstant().annotatedWith(ServerHost.class).to(args[0]);</pre>
*
* Sets up a constant binding. Constant injections must always be annotated.
* When a constant binding's value is a string, it is eligible for conversion to
* all primitive types, to {@link Enum#valueOf all enums}, and to
* {@link Class#forName class literals}. Conversions for other types can be
* configured using {@link #convertToTypes(Matcher, TypeConverter)
* convertToTypes()}.
*
* <pre>
* {@literal @}Color("red") Color red; // A member variable (field)
* . . .
* red = MyModule.class.getDeclaredField("red").getAnnotation(Color.class);
* bind(Service.class).annotatedWith(red).to(RedService.class);</pre>
*
* If your binding annotation has parameters you can apply different bindings to
* different specific values of your annotation. Getting your hands on the
* right instance of the annotation is a bit of a pain -- one approach, shown
* above, is to apply a prototype annotation to a field in your module class, so
* that you can read this annotation instance and give it to Guice.
*
* <pre>
* bind(Service.class)
* .annotatedWith(Names.named("blue"))
* .to(BlueService.class);</pre>
*
* Differentiating by names is a common enough use case that we provided a
* standard annotation, {@link org.elasticsearch.common.inject.name.Named @Named}. Because of
* Guice's library support, binding by name is quite easier than in the
* arbitrary binding annotation case we just saw. However, remember that these
* names will live in a single flat namespace with all the other names used in
* your application.
*
* <p>The above list of examples is far from exhaustive. If you can think of
* how the concepts of one example might coexist with the concepts from another,
* you can most likely weave the two together. If the two concepts make no
* sense with each other, you most likely won't be able to do it. In a few
* cases Guice will let something bogus slip by, and will then inform you of
* the problems at runtime, as soon as you try to create your Injector.
*
* <p>The other methods of Binder such as {@link #bindScope},
* {@link #install}, {@link #requestStaticInjection},
* {@link #addError} and {@link #currentStage} are not part of the Binding EDSL;
* you can learn how to use these in the usual way, from the method
* documentation.
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
* @author [email protected] (Kevin Bourrillion)
*/
public interface Binder {
/**
* Binds a scope to an annotation.
*/
void bindScope(Class<? extends Annotation> annotationType, Scope scope);
/**
* See the EDSL examples at {@link Binder}.
*/
<T> LinkedBindingBuilder<T> bind(Key<T> key);
/**
* See the EDSL examples at {@link Binder}.
*/
<T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral);
/**
* See the EDSL examples at {@link Binder}.
*/
<T> AnnotatedBindingBuilder<T> bind(Class<T> type);
/**
* See the EDSL examples at {@link Binder}.
*/
AnnotatedConstantBindingBuilder bindConstant();
/**
* Upon successful creation, the {@link Injector} will inject instance fields
* and methods of the given object.
*
* @param type of instance
* @param instance for which members will be injected
* @since 2.0
*/
<T> void requestInjection(TypeLiteral<T> type, T instance);
/**
* Upon successful creation, the {@link Injector} will inject instance fields
* and methods of the given object.
*
* @param instance for which members will be injected
* @since 2.0
*/
void requestInjection(Object instance);
/**
* Upon successful creation, the {@link Injector} will inject static fields
* and methods in the given classes.
*
* @param types for which static members will be injected
*/
void requestStaticInjection(Class<?>... types);
/**
* Uses the given module to configure more bindings.
*/
void install(Module module);
/**
* Gets the current stage.
*/
Stage currentStage();
/**
* Records an error message which will be presented to the user at a later
* time. Unlike throwing an exception, this enable us to continue
* configuring the Injector and discover more errors. Uses {@link
* String#format(String, Object[])} to insert the arguments into the
* message.
*/
void addError(String message, Object... arguments);
/**
* Records an exception, the full details of which will be logged, and the
* message of which will be presented to the user at a later
* time. If your Module calls something that you worry may fail, you should
* catch the exception and pass it into this.
*/
void addError(Throwable t);
/**
* Records an error message to be presented to the user at a later time.
*
* @since 2.0
*/
void addError(Message message);
/**
* Returns the provider used to obtain instances for the given injection key.
* The returned will not be valid until the {@link Injector} has been
* created. The provider will throw an {@code IllegalStateException} if you
* try to use it beforehand.
*
* @since 2.0
*/
<T> Provider<T> getProvider(Key<T> key);
/**
* Returns the provider used to obtain instances for the given injection type.
* The returned provider will not be valid until the {@link Injector} has been
* created. The provider will throw an {@code IllegalStateException} if you
* try to use it beforehand.
*
* @since 2.0
*/
<T> Provider<T> getProvider(Class<T> type);
/**
* Returns the members injector used to inject dependencies into methods and fields on instances
* of the given type {@code T}. The returned members injector will not be valid until the main
* {@link Injector} has been created. The members injector will throw an {@code
* IllegalStateException} if you try to use it beforehand.
*
* @param typeLiteral type to get members injector for
* @since 2.0
*/
<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral);
/**
* Returns the members injector used to inject dependencies into methods and fields on instances
* of the given type {@code T}. The returned members injector will not be valid until the main
* {@link Injector} has been created. The members injector will throw an {@code
* IllegalStateException} if you try to use it beforehand.
*
* @param type type to get members injector for
* @since 2.0
*/
<T> MembersInjector<T> getMembersInjector(Class<T> type);
/**
* Binds a type converter. The injector will use the given converter to
* convert string constants to matching types as needed.
*
* @param typeMatcher matches types the converter can handle
* @param converter converts values
* @since 2.0
*/
void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeConverter converter);
/**
* Registers a listener for injectable types. Guice will notify the listener when it encounters
* injectable types matched by the given type matcher.
*
* @param typeMatcher that matches injectable types the listener should be notified of
* @param listener for injectable types matched by typeMatcher
* @since 2.0
*/
void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeListener listener);
/**
* Returns a binder that uses {@code source} as the reference location for
* configuration errors. This is typically a {@link StackTraceElement}
* for {@code .java} source but it could any binding source, such as the
* path to a {@code .properties} file.
*
* @param source any object representing the source location and has a
* concise {@link Object#toString() toString()} value
* @return a binder that shares its configuration with this binder
* @since 2.0
*/
Binder withSource(Object source);
/**
* Returns a binder that skips {@code classesToSkip} when identify the
* calling code. The caller's {@link StackTraceElement} is used to locate
* the source of configuration errors.
*
* @param classesToSkip library classes that create bindings on behalf of
* their clients.
* @return a binder that shares its configuration with this binder.
* @since 2.0
*/
Binder skipSources(Class... classesToSkip);
/**
* Creates a new private child environment for bindings and other configuration. The returned
* binder can be used to add and configuration information in this environment. See {@link
* PrivateModule} for details.
*
* @return a binder that inherits configuration from this binder. Only exposed configuration on
* the returned binder will be visible to this binder.
* @since 2.0
*/
PrivateBinder newPrivateBinder();
}
| logrhythm/dx-elasticsearch | server/src/main/java/org/elasticsearch/common/inject/Binder.java |
214,157 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* This extension adds some more dynamic state to support applications that need to reduce the number of pipeline state objects they compile and bind.
*
* <h5>Promotion to Vulkan 1.3</h5>
*
* <p>This extension has been partially promoted. All dynamic state enumerants and entry points in this extension are included in core Vulkan 1.3, with the EXT suffix omitted. The feature structure is not promoted. Extension interfaces that were promoted remain available as aliases of the core functionality.</p>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_EXT_extended_dynamic_state}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>268</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} or <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1">Version 1.1</a></dd>
* <dt><b>Deprecation State</b></dt>
* <dd><ul>
* <li><em>Promoted</em> to <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.3-promotions">Vulkan 1.3</a></li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Piers Daniell <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_extended_dynamic_state]%20@pdaniell-nv%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_extended_dynamic_state%20extension*">pdaniell-nv</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2019-12-09</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Dan Ginsburg, Valve Corporation</li>
* <li>Graeme Leese, Broadcom</li>
* <li>Hans-Kristian Arntzen, Valve Corporation</li>
* <li>Jan-Harald Fredriksen, Arm Limited</li>
* <li>Faith Ekstrand, Intel</li>
* <li>Jeff Bolz, NVIDIA</li>
* <li>Jesse Hall, Google</li>
* <li>Philip Rebohle, Valve Corporation</li>
* <li>Stuart Smith, Imagination Technologies</li>
* <li>Tobias Hector, AMD</li>
* </ul></dd>
* </dl>
*/
public class EXTExtendedDynamicState {
/** The extension specification version. */
public static final int VK_EXT_EXTENDED_DYNAMIC_STATE_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME = "VK_EXT_extended_dynamic_state";
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT = 1000267000;
/**
* Extends {@code VkDynamicState}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_DYNAMIC_STATE_CULL_MODE_EXT DYNAMIC_STATE_CULL_MODE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_FRONT_FACE_EXT DYNAMIC_STATE_FRONT_FACE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT}</li>
* <li>{@link #VK_DYNAMIC_STATE_STENCIL_OP_EXT DYNAMIC_STATE_STENCIL_OP_EXT}</li>
* </ul>
*/
public static final int
VK_DYNAMIC_STATE_CULL_MODE_EXT = 1000267000,
VK_DYNAMIC_STATE_FRONT_FACE_EXT = 1000267001,
VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT = 1000267002,
VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT = 1000267003,
VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT = 1000267004,
VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT = 1000267005,
VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT = 1000267006,
VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT = 1000267007,
VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT = 1000267008,
VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT = 1000267009,
VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT = 1000267010,
VK_DYNAMIC_STATE_STENCIL_OP_EXT = 1000267011;
protected EXTExtendedDynamicState() {
throw new UnsupportedOperationException();
}
// --- [ vkCmdSetCullModeEXT ] ---
/**
* See {@link VK13#vkCmdSetCullMode CmdSetCullMode}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param cullMode specifies the cull mode property to use for drawing.
*/
public static void vkCmdSetCullModeEXT(VkCommandBuffer commandBuffer, @NativeType("VkCullModeFlags") int cullMode) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetCullModeEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), cullMode, __functionAddress);
}
// --- [ vkCmdSetFrontFaceEXT ] ---
/**
* See {@link VK13#vkCmdSetFrontFace CmdSetFrontFace}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param frontFace a {@code VkFrontFace} value specifying the front-facing triangle orientation to be used for culling.
*/
public static void vkCmdSetFrontFaceEXT(VkCommandBuffer commandBuffer, @NativeType("VkFrontFace") int frontFace) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetFrontFaceEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), frontFace, __functionAddress);
}
// --- [ vkCmdSetPrimitiveTopologyEXT ] ---
/**
* See {@link VK13#vkCmdSetPrimitiveTopology CmdSetPrimitiveTopology}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param primitiveTopology specifies the primitive topology to use for drawing.
*/
public static void vkCmdSetPrimitiveTopologyEXT(VkCommandBuffer commandBuffer, @NativeType("VkPrimitiveTopology") int primitiveTopology) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetPrimitiveTopologyEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), primitiveTopology, __functionAddress);
}
// --- [ vkCmdSetViewportWithCountEXT ] ---
/**
* Unsafe version of: {@link #vkCmdSetViewportWithCountEXT CmdSetViewportWithCountEXT}
*
* @param viewportCount specifies the viewport count.
*/
public static void nvkCmdSetViewportWithCountEXT(VkCommandBuffer commandBuffer, int viewportCount, long pViewports) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetViewportWithCountEXT;
if (CHECKS) {
check(__functionAddress);
}
callPPV(commandBuffer.address(), viewportCount, pViewports, __functionAddress);
}
/**
* See {@link VK13#vkCmdSetViewportWithCount CmdSetViewportWithCount}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param pViewports specifies the viewports to use for drawing.
*/
public static void vkCmdSetViewportWithCountEXT(VkCommandBuffer commandBuffer, @NativeType("VkViewport const *") VkViewport.Buffer pViewports) {
nvkCmdSetViewportWithCountEXT(commandBuffer, pViewports.remaining(), pViewports.address());
}
// --- [ vkCmdSetScissorWithCountEXT ] ---
/**
* Unsafe version of: {@link #vkCmdSetScissorWithCountEXT CmdSetScissorWithCountEXT}
*
* @param scissorCount specifies the scissor count.
*/
public static void nvkCmdSetScissorWithCountEXT(VkCommandBuffer commandBuffer, int scissorCount, long pScissors) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetScissorWithCountEXT;
if (CHECKS) {
check(__functionAddress);
}
callPPV(commandBuffer.address(), scissorCount, pScissors, __functionAddress);
}
/**
* See {@link VK13#vkCmdSetScissorWithCount CmdSetScissorWithCount}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param pScissors specifies the scissors to use for drawing.
*/
public static void vkCmdSetScissorWithCountEXT(VkCommandBuffer commandBuffer, @NativeType("VkRect2D const *") VkRect2D.Buffer pScissors) {
nvkCmdSetScissorWithCountEXT(commandBuffer, pScissors.remaining(), pScissors.address());
}
// --- [ vkCmdBindVertexBuffers2EXT ] ---
/**
* Unsafe version of: {@link #vkCmdBindVertexBuffers2EXT CmdBindVertexBuffers2EXT}
*
* @param bindingCount the number of vertex input bindings whose state is updated by the command.
*/
public static void nvkCmdBindVertexBuffers2EXT(VkCommandBuffer commandBuffer, int firstBinding, int bindingCount, long pBuffers, long pOffsets, long pSizes, long pStrides) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdBindVertexBuffers2EXT;
if (CHECKS) {
check(__functionAddress);
}
callPPPPPV(commandBuffer.address(), firstBinding, bindingCount, pBuffers, pOffsets, pSizes, pStrides, __functionAddress);
}
/**
* See {@link VK13#vkCmdBindVertexBuffers2 CmdBindVertexBuffers2}.
*
* @param commandBuffer the command buffer into which the command is recorded.
* @param firstBinding the index of the first vertex input binding whose state is updated by the command.
* @param pBuffers a pointer to an array of buffer handles.
* @param pOffsets a pointer to an array of buffer offsets.
* @param pSizes {@code NULL} or a pointer to an array of the size in bytes of vertex data bound from {@code pBuffers}.
* @param pStrides {@code NULL} or a pointer to an array of buffer strides.
*/
public static void vkCmdBindVertexBuffers2EXT(VkCommandBuffer commandBuffer, @NativeType("uint32_t") int firstBinding, @NativeType("VkBuffer const *") LongBuffer pBuffers, @NativeType("VkDeviceSize const *") LongBuffer pOffsets, @Nullable @NativeType("VkDeviceSize const *") LongBuffer pSizes, @Nullable @NativeType("VkDeviceSize const *") LongBuffer pStrides) {
if (CHECKS) {
check(pOffsets, pBuffers.remaining());
checkSafe(pSizes, pBuffers.remaining());
checkSafe(pStrides, pBuffers.remaining());
}
nvkCmdBindVertexBuffers2EXT(commandBuffer, firstBinding, pBuffers.remaining(), memAddress(pBuffers), memAddress(pOffsets), memAddressSafe(pSizes), memAddressSafe(pStrides));
}
// --- [ vkCmdSetDepthTestEnableEXT ] ---
/**
* See {@link VK13#vkCmdSetDepthTestEnable CmdSetDepthTestEnable}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param depthTestEnable specifies if the depth test is enabled.
*/
public static void vkCmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, @NativeType("VkBool32") boolean depthTestEnable) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetDepthTestEnableEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), depthTestEnable ? 1 : 0, __functionAddress);
}
// --- [ vkCmdSetDepthWriteEnableEXT ] ---
/**
* See {@link VK13#vkCmdSetDepthWriteEnable CmdSetDepthWriteEnable}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param depthWriteEnable specifies if depth writes are enabled.
*/
public static void vkCmdSetDepthWriteEnableEXT(VkCommandBuffer commandBuffer, @NativeType("VkBool32") boolean depthWriteEnable) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetDepthWriteEnableEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), depthWriteEnable ? 1 : 0, __functionAddress);
}
// --- [ vkCmdSetDepthCompareOpEXT ] ---
/**
* See {@link VK13#vkCmdSetDepthCompareOp CmdSetDepthCompareOp}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param depthCompareOp a {@code VkCompareOp} value specifying the comparison operator used for the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fragops-depth-comparison">Depth Comparison</a> step of the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fragops-depth">depth test</a>.
*/
public static void vkCmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, @NativeType("VkCompareOp") int depthCompareOp) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetDepthCompareOpEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), depthCompareOp, __functionAddress);
}
// --- [ vkCmdSetDepthBoundsTestEnableEXT ] ---
/**
* See {@link VK13#vkCmdSetDepthBoundsTestEnable CmdSetDepthBoundsTestEnable}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param depthBoundsTestEnable specifies if the depth bounds test is enabled.
*/
public static void vkCmdSetDepthBoundsTestEnableEXT(VkCommandBuffer commandBuffer, @NativeType("VkBool32") boolean depthBoundsTestEnable) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetDepthBoundsTestEnableEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), depthBoundsTestEnable ? 1 : 0, __functionAddress);
}
// --- [ vkCmdSetStencilTestEnableEXT ] ---
/**
* See {@link VK13#vkCmdSetStencilTestEnable CmdSetStencilTestEnable}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param stencilTestEnable specifies if the stencil test is enabled.
*/
public static void vkCmdSetStencilTestEnableEXT(VkCommandBuffer commandBuffer, @NativeType("VkBool32") boolean stencilTestEnable) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetStencilTestEnableEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), stencilTestEnable ? 1 : 0, __functionAddress);
}
// --- [ vkCmdSetStencilOpEXT ] ---
/**
* See {@link VK13#vkCmdSetStencilOp CmdSetStencilOp}.
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param faceMask a bitmask of {@code VkStencilFaceFlagBits} specifying the set of stencil state for which to update the stencil operation.
* @param failOp a {@code VkStencilOp} value specifying the action performed on samples that fail the stencil test.
* @param passOp a {@code VkStencilOp} value specifying the action performed on samples that pass both the depth and stencil tests.
* @param depthFailOp a {@code VkStencilOp} value specifying the action performed on samples that pass the stencil test and fail the depth test.
* @param compareOp a {@code VkCompareOp} value specifying the comparison operator used in the stencil test.
*/
public static void vkCmdSetStencilOpEXT(VkCommandBuffer commandBuffer, @NativeType("VkStencilFaceFlags") int faceMask, @NativeType("VkStencilOp") int failOp, @NativeType("VkStencilOp") int passOp, @NativeType("VkStencilOp") int depthFailOp, @NativeType("VkCompareOp") int compareOp) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetStencilOpEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), faceMask, failOp, passOp, depthFailOp, compareOp, __functionAddress);
}
/** Array version of: {@link #vkCmdBindVertexBuffers2EXT CmdBindVertexBuffers2EXT} */
public static void vkCmdBindVertexBuffers2EXT(VkCommandBuffer commandBuffer, @NativeType("uint32_t") int firstBinding, @NativeType("VkBuffer const *") long[] pBuffers, @NativeType("VkDeviceSize const *") long[] pOffsets, @Nullable @NativeType("VkDeviceSize const *") long[] pSizes, @Nullable @NativeType("VkDeviceSize const *") long[] pStrides) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdBindVertexBuffers2EXT;
if (CHECKS) {
check(__functionAddress);
check(pOffsets, pBuffers.length);
checkSafe(pSizes, pBuffers.length);
checkSafe(pStrides, pBuffers.length);
}
callPPPPPV(commandBuffer.address(), firstBinding, pBuffers.length, pBuffers, pOffsets, pSizes, pStrides, __functionAddress);
}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/EXTExtendedDynamicState.java |
214,158 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject.spi;
import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.inject.Binding;
import org.opensearch.common.inject.Key;
import org.opensearch.common.inject.Provider;
/**
* A binding to a provider key. To resolve injections, the provider key is first resolved, then that
* provider's {@code get} method is invoked.
*
* @author [email protected] (Jesse Wilson)
* @since 2.0
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public interface ProviderKeyBinding<T> extends Binding<T> {
/**
* Returns the key used to resolve the provider's binding.
*/
Key<? extends Provider<? extends T>> getProviderKey();
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/spi/ProviderKeyBinding.java |
214,159 | /*
* 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.netbeans.core.startup;
// LIMITED INTERACTIONS with APIs and UI--may use ModuleInstall,
// and FileSystems API, and localized messages (but not notification),
// in addition to what is permitted for central classes (utility APIs
// and ModuleInfo-related things). Should be possible to use without
// the rest of core.
/** Representation of the history of the module.
* @author Jesse Glick
*/
// XXX no longer useful, could probably delete, and deprecate Module.history
public final class ModuleHistory {
private final String jar;
private String info;
/** Create a module history with essential information.
* You also need to specify a relative or absolute JAR name.
*/
public ModuleHistory(String jar) {
assert jar != null;
this.jar = jar;
}
ModuleHistory(String jar, String info) {
this(jar);
this.info = info;
}
/**
* The name of the JAR relative to the installation, or
* an absolute path.
*/
String getJar() {
return jar;
}
@Override public String toString() {
return info != null ? info : jar;
}
}
| apache/netbeans | platform/core.startup/src/org/netbeans/core/startup/ModuleHistory.java |
214,160 | /*
* 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.util.concurrent;
import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
/**
* Base class for services that can implement {@link #startUp}, {@link #run} and {@link #shutDown}
* methods. This class uses a single thread to execute the service; consider {@link AbstractService}
* if you would like to manage any threading manually.
*
* @author Jesse Wilson
* @since 1.0
*/
@GwtIncompatible
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractExecutionThreadService implements Service {
private static final LazyLogger logger = new LazyLogger(AbstractExecutionThreadService.class);
/* use AbstractService for state management */
private final Service delegate =
new AbstractService() {
@Override
protected final void doStart() {
Executor executor = MoreExecutors.renamingDecorator(executor(), () -> serviceName());
executor.execute(
() -> {
try {
startUp();
notifyStarted();
// If stopAsync() is called while starting we may be in the STOPPING state in
// which case we should skip right down to shutdown.
if (isRunning()) {
try {
AbstractExecutionThreadService.this.run();
} catch (Throwable t) {
restoreInterruptIfIsInterruptedException(t);
try {
shutDown();
} catch (Exception ignored) {
restoreInterruptIfIsInterruptedException(ignored);
// TODO(lukes): if guava ever moves to java7, this would be a good
// candidate for a suppressed exception, or maybe we could generalize
// Closer.Suppressor
logger
.get()
.log(
Level.WARNING,
"Error while attempting to shut down the service after failure.",
ignored);
}
notifyFailed(t);
return;
}
}
shutDown();
notifyStopped();
} catch (Throwable t) {
restoreInterruptIfIsInterruptedException(t);
notifyFailed(t);
}
});
}
@Override
protected void doStop() {
triggerShutdown();
}
@Override
public String toString() {
return AbstractExecutionThreadService.this.toString();
}
};
/** Constructor for use by subclasses. */
protected AbstractExecutionThreadService() {}
/**
* Start the service. This method is invoked on the execution thread.
*
* <p>By default this method does nothing.
*/
protected void startUp() throws Exception {}
/**
* Run the service. This method is invoked on the execution thread. Implementations must respond
* to stop requests. You could poll for lifecycle changes in a work loop:
*
* <pre>
* public void run() {
* while ({@link #isRunning()}) {
* // perform a unit of work
* }
* }
* </pre>
*
* <p>...or you could respond to stop requests by implementing {@link #triggerShutdown()}, which
* should cause {@link #run()} to return.
*/
protected abstract void run() throws Exception;
/**
* Stop the service. This method is invoked on the execution thread.
*
* <p>By default this method does nothing.
*/
// TODO: consider supporting a TearDownTestCase-like API
protected void shutDown() throws Exception {}
/**
* Invoked to request the service to stop.
*
* <p>By default this method does nothing.
*
* <p>Currently, this method is invoked while holding a lock. If an implementation of this method
* blocks, it can prevent this service from changing state. If you need to performing a blocking
* operation in order to trigger shutdown, consider instead registering a listener and
* implementing {@code stopping}. Note, however, that {@code stopping} does not run at exactly the
* same times as {@code triggerShutdown}.
*/
protected void triggerShutdown() {}
/**
* Returns the {@link Executor} that will be used to run this service. Subclasses may override
* this method to use a custom {@link Executor}, which may configure its worker thread with a
* specific name, thread group or priority. The returned executor's {@link
* Executor#execute(Runnable) execute()} method is called when this service is started, and should
* return promptly.
*
* <p>The default implementation returns a new {@link Executor} that sets the name of its threads
* to the string returned by {@link #serviceName}
*/
protected Executor executor() {
return command -> MoreExecutors.newThread(serviceName(), command).start();
}
@Override
public String toString() {
return serviceName() + " [" + state() + "]";
}
@Override
public final boolean isRunning() {
return delegate.isRunning();
}
@Override
public final State state() {
return delegate.state();
}
/** @since 13.0 */
@Override
public final void addListener(Listener listener, Executor executor) {
delegate.addListener(listener, executor);
}
/** @since 14.0 */
@Override
public final Throwable failureCause() {
return delegate.failureCause();
}
/** @since 15.0 */
@CanIgnoreReturnValue
@Override
public final Service startAsync() {
delegate.startAsync();
return this;
}
/** @since 15.0 */
@CanIgnoreReturnValue
@Override
public final Service stopAsync() {
delegate.stopAsync();
return this;
}
/** @since 15.0 */
@Override
public final void awaitRunning() {
delegate.awaitRunning();
}
/** @since 15.0 */
@Override
public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException {
delegate.awaitRunning(timeout, unit);
}
/** @since 15.0 */
@Override
public final void awaitTerminated() {
delegate.awaitTerminated();
}
/** @since 15.0 */
@Override
public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
delegate.awaitTerminated(timeout, unit);
}
/**
* Returns the name of this service. {@link AbstractExecutionThreadService} may include the name
* in debugging output.
*
* <p>Subclasses may override this method.
*
* @since 14.0 (present in 10.0 as getServiceName)
*/
protected String serviceName() {
return getClass().getSimpleName();
}
}
| google/guava | android/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java |
214,161 | /*
* Copyright (C) 2008 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.collect;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.ImmutableMapEntry.createEntryArray;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableMapEntry;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMap} with two or more entries.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Gregory Kick
*/
@GwtCompatible(serializable = true, emulated = true)
final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// entries in insertion order
private final transient Entry<K, V>[] entries;
// array of linked lists of entries
private final transient ImmutableMapEntry<K, V>[] table;
// 'and' with an int to get a table index
private final transient int mask;
static <K, V> RegularImmutableMap<K, V> fromEntries(Entry<K, V>... entries) {
return fromEntryArray(entries.length, entries);
}
/**
* Creates a RegularImmutableMap from the first n entries in entryArray. This implementation
* may replace the entries in entryArray with its own entry objects (though they will have the
* same key/value contents), and may take ownership of entryArray.
*/
static <K, V> RegularImmutableMap<K, V> fromEntryArray(int n, Entry<K, V>[] entryArray) {
checkPositionIndex(n, entryArray.length);
Entry<K, V>[] entries;
if (n == entryArray.length) {
entries = entryArray;
} else {
entries = createEntryArray(n);
}
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
ImmutableMapEntry<K, V>[] table = createEntryArray(tableSize);
int mask = tableSize - 1;
for (int entryIndex = 0; entryIndex < n; entryIndex++) {
Entry<K, V> entry = entryArray[entryIndex];
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int tableIndex = Hashing.smear(key.hashCode()) & mask;
@Nullable ImmutableMapEntry<K, V> existing = table[tableIndex];
// prepend, not append, so the entries can be immutable
ImmutableMapEntry<K, V> newEntry;
if (existing == null) {
boolean reusable =
entry instanceof ImmutableMapEntry
&& ((ImmutableMapEntry<K, V>) entry).isReusable();
newEntry = reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value);
} else {
newEntry = new NonTerminalImmutableMapEntry<K, V>(key, value, existing);
}
table[tableIndex] = newEntry;
entries[entryIndex] = newEntry;
checkNoConflictInKeyBucket(key, newEntry, existing);
}
return new RegularImmutableMap<K, V>(entries, table, mask);
}
private RegularImmutableMap(Entry<K, V>[] entries, ImmutableMapEntry<K, V>[] table, int mask) {
this.entries = entries;
this.table = table;
this.mask = mask;
}
static void checkNoConflictInKeyBucket(Object key, Entry<?, ?> entry, @Nullable ImmutableMapEntry<?, ?> keyBucketHead) {
for (; keyBucketHead != null; keyBucketHead = keyBucketHead.getNextInKeyBucket()) {
checkNoConflict(!key.equals(keyBucketHead.getKey()), "key", entry, keyBucketHead);
}
}
/**
* Closed addressing tends to perform well even with high load factors.
* Being conservative here ensures that the table is still likely to be
* relatively sparse (hence it misses fast) while saving space.
*/
private static final double MAX_LOAD_FACTOR = 1.2;
@Override
public V get(@Nullable Object key) {
return get(key, table, mask);
}
@Nullable
static <V> V get(@Nullable Object key, ImmutableMapEntry<?, V>[] keyTable, int mask) {
if (key == null) {
return null;
}
int index = Hashing.smear(key.hashCode()) & mask;
for (ImmutableMapEntry<?, V> entry = keyTable[index]; entry != null; entry = entry.getNextInKeyBucket()) {
Object candidateKey = entry.getKey();
/*
* Assume that equals uses the == optimization when appropriate, and that
* it would check hash codes as an optimization when appropriate. If we
* did these things, it would just make things worse for the most
* performance-conscious users.
*/
if (key.equals(candidateKey)) {
return entry.getValue();
}
}
return null;
}
@Override
public int size() {
return entries.length;
}
@Override
boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet.RegularEntrySet<K, V>(this, entries);
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
} | antlr/codebuff | output/java_guava/1.4.18/RegularImmutableMap.java |
214,163 | /*
* Copyright (C) 2009 Google 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 org.elasticsearch.common.inject;
import org.elasticsearch.common.inject.internal.Errors;
import org.elasticsearch.common.inject.internal.ErrorsException;
import org.elasticsearch.common.inject.internal.FailableCache;
import org.elasticsearch.common.inject.spi.InjectionPoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Members injectors by type.
*
* @author [email protected] (Jesse Wilson)
*/
class MembersInjectorStore {
private final InjectorImpl injector;
private final FailableCache<TypeLiteral<?>, MembersInjectorImpl<?>> cache = new FailableCache<>() {
@Override
protected MembersInjectorImpl<?> create(TypeLiteral<?> type, Errors errors) throws ErrorsException {
return createWithListeners(type, errors);
}
};
MembersInjectorStore(InjectorImpl injector) {
this.injector = injector;
}
/**
* Returns a new complete members injector with injection listeners registered.
*/
@SuppressWarnings("unchecked") // the MembersInjector type always agrees with the passed type
public <T> MembersInjectorImpl<T> get(TypeLiteral<T> key, Errors errors) throws ErrorsException {
return (MembersInjectorImpl<T>) cache.get(key, errors);
}
/**
* Creates a new members injector and attaches both injection listeners and method aspects.
*/
private <T> MembersInjectorImpl<T> createWithListeners(TypeLiteral<T> type, Errors errors) throws ErrorsException {
int numErrorsBefore = errors.size();
Set<InjectionPoint> injectionPoints;
try {
injectionPoints = InjectionPoint.forInstanceMethods(type);
} catch (ConfigurationException e) {
errors.merge(e.getErrorMessages());
injectionPoints = e.getPartialValue();
}
List<SingleMethodInjector> injectors = getInjectors(injectionPoints, errors);
errors.throwIfNewErrors(numErrorsBefore);
return new MembersInjectorImpl<>(injector, type, injectors);
}
/**
* Returns the injectors for the specified injection points.
*/
List<SingleMethodInjector> getInjectors(Set<InjectionPoint> injectionPoints, Errors errors) {
List<SingleMethodInjector> injectors = new ArrayList<>();
for (InjectionPoint injectionPoint : injectionPoints) {
try {
Errors errorsForMember = injectionPoint.isOptional() ? new Errors(injectionPoint) : errors.withSource(injectionPoint);
SingleMethodInjector injector = new SingleMethodInjector(this.injector, injectionPoint, errorsForMember);
injectors.add(injector);
} catch (ErrorsException ignoredForNow) {
// ignored for now
}
}
return Collections.unmodifiableList(injectors);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/MembersInjectorStore.java |
214,164 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2008 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject.util;
import org.opensearch.common.inject.AbstractModule;
import org.opensearch.common.inject.Binder;
import org.opensearch.common.inject.Binding;
import org.opensearch.common.inject.Key;
import org.opensearch.common.inject.Module;
import org.opensearch.common.inject.PrivateBinder;
import org.opensearch.common.inject.Scope;
import org.opensearch.common.inject.spi.DefaultBindingScopingVisitor;
import org.opensearch.common.inject.spi.DefaultElementVisitor;
import org.opensearch.common.inject.spi.Element;
import org.opensearch.common.inject.spi.Elements;
import org.opensearch.common.inject.spi.PrivateElements;
import org.opensearch.common.inject.spi.ScopeBinding;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Collections.unmodifiableSet;
import static org.opensearch.common.util.set.Sets.newHashSet;
/**
* Static utility methods for creating and working with instances of {@link Module}.
*
* @author [email protected] (Jesse Wilson)
* @since 2.0
*
* @opensearch.internal
*/
public final class Modules {
private Modules() {}
public static final Module EMPTY_MODULE = new Module() {
@Override
public void configure(Binder binder) {}
};
/**
* Returns a builder that creates a module that overlays override modules over the given
* modules. If a key is bound in both sets of modules, only the binding from the override modules
* is kept. This can be used to replace the bindings of a production module with test bindings:
* <pre>
* Module functionalTestModule
* = Modules.override(new ProductionModule()).with(new TestModule());
* </pre>
* <p>
* Prefer to write smaller modules that can be reused and tested without overrides.
*
* @param modules the modules whose bindings are open to be overridden
*/
public static OverriddenModuleBuilder override(Module... modules) {
return new RealOverriddenModuleBuilder(Arrays.asList(modules));
}
/**
* Returns a builder that creates a module that overlays override modules over the given
* modules. If a key is bound in both sets of modules, only the binding from the override modules
* is kept. This can be used to replace the bindings of a production module with test bindings:
* <pre>
* Module functionalTestModule
* = Modules.override(getProductionModules()).with(getTestModules());
* </pre>
* <p>
* Prefer to write smaller modules that can be reused and tested without overrides.
*
* @param modules the modules whose bindings are open to be overridden
*/
public static OverriddenModuleBuilder override(Iterable<? extends Module> modules) {
return new RealOverriddenModuleBuilder(modules);
}
/**
* Returns a new module that installs all of {@code modules}.
*/
public static Module combine(Module... modules) {
return combine(Arrays.asList(modules));
}
/**
* Returns a new module that installs all of {@code modules}.
*/
public static Module combine(Iterable<? extends Module> modules) {
final Set<? extends Module> modulesSet = newHashSet(modules);
return new Module() {
@Override
public void configure(Binder binder) {
binder = binder.skipSources(getClass());
for (Module module : modulesSet) {
binder.install(module);
}
}
};
}
/**
* See the EDSL example at {@link Modules#override(Module[]) override()}.
*
* @opensearch.internal
*/
public interface OverriddenModuleBuilder {
/**
* See the EDSL example at {@link Modules#override(Module[]) override()}.
*/
Module with(Module... overrides);
/**
* See the EDSL example at {@link Modules#override(Module[]) override()}.
*/
Module with(Iterable<? extends Module> overrides);
}
private static final class RealOverriddenModuleBuilder implements OverriddenModuleBuilder {
private final Set<Module> baseModules;
private RealOverriddenModuleBuilder(Iterable<? extends Module> baseModules) {
HashSet<? extends Module> modules = newHashSet(baseModules);
this.baseModules = unmodifiableSet(modules);
}
@Override
public Module with(Module... overrides) {
return with(Arrays.asList(overrides));
}
@Override
public Module with(final Iterable<? extends Module> overrides) {
return new AbstractModule() {
@Override
public void configure() {
final List<Element> elements = Elements.getElements(baseModules);
final List<Element> overrideElements = Elements.getElements(overrides);
final Set<Key> overriddenKeys = new HashSet<>();
final Set<Class<? extends Annotation>> overridesScopeAnnotations = new HashSet<>();
// execute the overrides module, keeping track of which keys and scopes are bound
new ModuleWriter(binder()) {
@Override
public <T> Void visit(Binding<T> binding) {
overriddenKeys.add(binding.getKey());
return super.visit(binding);
}
@Override
public Void visit(ScopeBinding scopeBinding) {
overridesScopeAnnotations.add(scopeBinding.getAnnotationType());
return super.visit(scopeBinding);
}
@Override
public Void visit(PrivateElements privateElements) {
overriddenKeys.addAll(privateElements.getExposedKeys());
return super.visit(privateElements);
}
}.writeAll(overrideElements);
// execute the original module, skipping all scopes and overridden keys. We only skip each
// overridden binding once so things still blow up if the module binds the same thing
// multiple times.
final Map<Scope, Object> scopeInstancesInUse = new HashMap<>();
final List<ScopeBinding> scopeBindings = new ArrayList<>();
new ModuleWriter(binder()) {
@Override
public <T> Void visit(Binding<T> binding) {
if (!overriddenKeys.remove(binding.getKey())) {
super.visit(binding);
// Record when a scope instance is used in a binding
Scope scope = getScopeInstanceOrNull(binding);
if (scope != null) {
scopeInstancesInUse.put(scope, binding.getSource());
}
}
return null;
}
@Override
public Void visit(PrivateElements privateElements) {
PrivateBinder privateBinder = binder.withSource(privateElements.getSource()).newPrivateBinder();
Set<Key<?>> skippedExposes = new HashSet<>();
for (Key<?> key : privateElements.getExposedKeys()) {
if (overriddenKeys.remove(key)) {
skippedExposes.add(key);
} else {
privateBinder.withSource(privateElements.getExposedSource(key)).expose(key);
}
}
// we're not skipping deep exposes, but that should be okay. If we ever need to, we
// have to search through this set of elements for PrivateElements, recursively
for (Element element : privateElements.getElements()) {
if (element instanceof Binding && skippedExposes.contains(((Binding) element).getKey())) {
continue;
}
element.applyTo(privateBinder);
}
return null;
}
@Override
public Void visit(ScopeBinding scopeBinding) {
scopeBindings.add(scopeBinding);
return null;
}
}.writeAll(elements);
// execute the scope bindings, skipping scopes that have been overridden. Any scope that
// is overridden and in active use will prompt an error
new ModuleWriter(binder()) {
@Override
public Void visit(ScopeBinding scopeBinding) {
if (!overridesScopeAnnotations.remove(scopeBinding.getAnnotationType())) {
super.visit(scopeBinding);
} else {
Object source = scopeInstancesInUse.get(scopeBinding.getScope());
if (source != null) {
binder().withSource(source)
.addError(
"The scope for @%s is bound directly and cannot be overridden.",
scopeBinding.getAnnotationType().getSimpleName()
);
}
}
return null;
}
}.writeAll(scopeBindings);
// TODO: bind the overridden keys using multibinder
}
private Scope getScopeInstanceOrNull(Binding<?> binding) {
return binding.acceptScopingVisitor(new DefaultBindingScopingVisitor<Scope>() {
@Override
public Scope visitScope(Scope scope) {
return scope;
}
});
}
};
}
}
/**
* A module writer
*
* @opensearch.internal
*/
private static class ModuleWriter extends DefaultElementVisitor<Void> {
protected final Binder binder;
ModuleWriter(Binder binder) {
this.binder = binder;
}
@Override
protected Void visitOther(Element element) {
element.applyTo(binder);
return null;
}
void writeAll(Iterable<? extends Element> elements) {
for (Element element : elements) {
element.acceptVisitor(this);
}
}
}
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/util/Modules.java |
214,165 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2006 Google 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject;
import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.inject.internal.MoreTypes;
import org.opensearch.common.inject.util.Types;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static org.opensearch.common.inject.internal.MoreTypes.canonicalize;
/**
* Represents a generic type {@code T}. Java doesn't yet provide a way to
* represent generic types, so this class does. Forces clients to create a
* subclass of this class which enables retrieval the type information even at
* runtime.
* <p>
* For example, to create a type literal for {@code List<String>}, you can
* create an empty anonymous inner class:
* <p>
* {@code TypeLiteral<List<String>> list = new TypeLiteral<List<String>>() {};}
* <p>
* This syntax cannot be used to create type literals that have wildcard
* parameters, such as {@code Class<?>} or {@code List<? extends CharSequence>}.
* Such type literals must be constructed programmatically, either by {@link
* Method#getGenericReturnType extracting types from members} or by using the
* {@link Types} factory class.
* <p>
* Along with modeling generic types, this class can resolve type parameters.
* For example, to figure out what type {@code keySet()} returns on a {@code
* Map<Integer, String>}, use this code:{@code
* <p>
* TypeLiteral<Map<Integer, String>> mapType
* = new TypeLiteral<Map<Integer, String>>() {};
* TypeLiteral<?> keySetType
* = mapType.getReturnType(Map.class.getMethod("keySet"));
* System.out.println(keySetType); // prints "Set<Integer>"}
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public class TypeLiteral<T> {
final Class<? super T> rawType;
final Type type;
final int hashCode;
/**
* Constructs a new type literal. Derives represented class from type
* parameter.
* <p>
* Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute it
* at runtime despite erasure.
*/
@SuppressWarnings("unchecked")
protected TypeLiteral() {
this.type = getSuperclassTypeParameter(getClass());
this.rawType = (Class<? super T>) MoreTypes.getRawType(type);
this.hashCode = MoreTypes.hashCode(type);
}
/**
* Unsafe. Constructs a type literal manually.
*/
@SuppressWarnings("unchecked")
TypeLiteral(Type type) {
this.type = canonicalize(Objects.requireNonNull(type, "type"));
this.rawType = (Class<? super T>) MoreTypes.getRawType(this.type);
this.hashCode = MoreTypes.hashCode(this.type);
}
/**
* Returns the type from super class's type parameter in {@link MoreTypes#canonicalize(Type)
* canonical form}.
*/
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return canonicalize(parameterized.getActualTypeArguments()[0]);
}
/**
* Gets type literal from super class's type parameter.
*/
static TypeLiteral<?> fromSuperclassTypeParameter(Class<?> subclass) {
return new TypeLiteral<Object>(getSuperclassTypeParameter(subclass));
}
/**
* Returns the raw (non-generic) type for this type.
*
* @since 2.0
*/
public final Class<? super T> getRawType() {
return rawType;
}
/**
* Gets underlying {@code Type} instance.
*/
public final Type getType() {
return type;
}
/**
* Gets the type of this type's provider.
*/
@SuppressWarnings("unchecked")
final TypeLiteral<Provider<T>> providerType() {
// This cast is safe and wouldn't generate a warning if Type had a type
// parameter.
return (TypeLiteral<Provider<T>>) get(Types.providerOf(getType()));
}
@Override
public final int hashCode() {
return this.hashCode;
}
@Override
public final boolean equals(Object o) {
return o instanceof TypeLiteral<?> && MoreTypes.equals(type, ((TypeLiteral) o).type);
}
@Override
public final String toString() {
return MoreTypes.toString(type);
}
/**
* Gets type literal for the given {@code Type} instance.
*/
public static TypeLiteral<?> get(Type type) {
return new TypeLiteral<Object>(type);
}
/**
* Gets type literal for the given {@code Class} instance.
*/
public static <T> TypeLiteral<T> get(Class<T> type) {
return new TypeLiteral<>(type);
}
/**
* Returns an immutable list of the resolved types.
*/
private List<TypeLiteral<?>> resolveAll(Type[] types) {
TypeLiteral<?>[] result = new TypeLiteral<?>[types.length];
for (int t = 0; t < types.length; t++) {
result[t] = resolve(types[t]);
}
return Arrays.asList(result);
}
/**
* Resolves known type parameters in {@code toResolve} and returns the result.
*/
TypeLiteral<?> resolve(Type toResolve) {
return TypeLiteral.get(resolveType(toResolve));
}
Type resolveType(Type toResolve) {
// this implementation is made a little more complicated in an attempt to avoid object-creation
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable original = (TypeVariable) toResolve;
toResolve = MoreTypes.resolveTypeVariable(type, rawType, original);
if (toResolve == original) {
return toResolve;
}
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolveType(componentType);
return componentType == newComponentType ? original : Types.arrayOf(newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolveType(ownerType);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolveType(args[t]);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed ? Types.newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args) : original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolveType(originalLowerBound[0]);
if (lowerBound != originalLowerBound[0]) {
return Types.supertypeOf(lowerBound);
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolveType(originalUpperBound[0]);
if (upperBound != originalUpperBound[0]) {
return Types.subtypeOf(upperBound);
}
}
return original;
} else {
return toResolve;
}
}
}
/**
* Returns the generic form of {@code supertype}. For example, if this is {@code
* ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
* Iterable.class}.
*
* @param supertype a superclass of, or interface implemented by, this.
* @since 2.0
*
* @opensearch.internal
*/
public TypeLiteral<?> getSupertype(Class<?> supertype) {
if (!supertype.isAssignableFrom(rawType)) {
throw new IllegalArgumentException(supertype + " is not a supertype of " + type);
}
return resolve(MoreTypes.getGenericSupertype(type, rawType, supertype));
}
/**
* Returns the resolved generic type of {@code field}.
*
* @param field a field defined by this or any superclass.
* @since 2.0
*/
public TypeLiteral<?> getFieldType(Field field) {
if (!field.getDeclaringClass().isAssignableFrom(rawType)) {
throw new IllegalArgumentException(field + " is not defined by a supertype of " + type);
}
return resolve(field.getGenericType());
}
/**
* Returns the resolved generic parameter types of {@code methodOrConstructor}.
*
* @param methodOrConstructor a method or constructor defined by this or any supertype.
* @since 2.0
*/
public List<TypeLiteral<?>> getParameterTypes(Member methodOrConstructor) {
Type[] genericParameterTypes;
if (methodOrConstructor instanceof Method) {
Method method = (Method) methodOrConstructor;
if (!method.getDeclaringClass().isAssignableFrom(rawType)) {
throw new IllegalArgumentException(method + " is not defined by a supertype of " + type);
}
genericParameterTypes = method.getGenericParameterTypes();
} else if (methodOrConstructor instanceof Constructor) {
Constructor constructor = (Constructor) methodOrConstructor;
if (!constructor.getDeclaringClass().isAssignableFrom(rawType)) {
throw new IllegalArgumentException(constructor + " does not construct a supertype of " + type);
}
genericParameterTypes = constructor.getGenericParameterTypes();
} else {
throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
}
return resolveAll(genericParameterTypes);
}
/**
* Returns the resolved generic exception types thrown by {@code constructor}.
*
* @param methodOrConstructor a method or constructor defined by this or any supertype.
* @since 2.0
*/
public List<TypeLiteral<?>> getExceptionTypes(Member methodOrConstructor) {
Type[] genericExceptionTypes;
if (methodOrConstructor instanceof Method) {
Method method = (Method) methodOrConstructor;
if (!method.getDeclaringClass().isAssignableFrom(rawType)) {
throw new IllegalArgumentException(method + " is not defined by a supertype of " + type);
}
genericExceptionTypes = method.getGenericExceptionTypes();
} else if (methodOrConstructor instanceof Constructor) {
Constructor<?> constructor = (Constructor<?>) methodOrConstructor;
if (!constructor.getDeclaringClass().isAssignableFrom(rawType)) {
throw new IllegalArgumentException(constructor + " does not construct a supertype of " + type);
}
genericExceptionTypes = constructor.getGenericExceptionTypes();
} else {
throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
}
return resolveAll(genericExceptionTypes);
}
/**
* Returns the resolved generic return type of {@code method}.
*
* @param method a method defined by this or any supertype.
* @since 2.0
*/
public TypeLiteral<?> getReturnType(Method method) {
if (!method.getDeclaringClass().isAssignableFrom(rawType)) {
throw new IllegalArgumentException(method + " is not defined by a supertype of " + type);
}
return resolve(method.getGenericReturnType());
}
}
| opensearch-project/OpenSearch | server/src/main/java/org/opensearch/common/inject/TypeLiteral.java |
214,166 | package Media;
import java.util.ArrayList;
public class Seizoen {
public ArrayList<Aflevering> afleveringen;
public String beschrijving;
public Poster poster;
public Seizoen(ArrayList<Aflevering> afleveringen, String beschrijving, Poster poster) {
this.afleveringen = afleveringen;
this.beschrijving = beschrijving;
this.poster = poster;
}
} | jeffrey0402/NetNix | src/Media/Seizoen.java |
214,168 | package be.kdg.seizoenen;
/**
* @author Kristiaan Behiels
* @version 1.0 21/10/13
*/
public abstract class Seizoen {
public abstract String getBegin();
}
| gvdhaege/KdG | Java Programming/Deel 2/W1 - Overerving/Oefeningen/Oplossingen/Seizoenen/src/be/kdg/seizoenen/Seizoen.java |
214,170 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.07.21 at 10:52:28 AM CEST
//
package nl.vpro.domain.npo.projectm.metadata.v2_1;
import java.math.BigInteger;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}srid"/>
* <element ref="{}titel"/>
* <element name="seizoen" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element ref="{}lexico_titel" minOccurs="0"/>
* <element ref="{}icon" minOccurs="0"/>
* <element ref="{}start_jaar" minOccurs="0"/>
* <element ref="{}orti" minOccurs="0"/>
* <element ref="{}inh1" minOccurs="0"/>
* <element ref="{}mail" minOccurs="0"/>
* <element ref="{}webs" minOccurs="0"/>
* <element ref="{}twitteraccount" minOccurs="0"/>
* <element ref="{}twitterhashtag" minOccurs="0"/>
* <element ref="{}genre" minOccurs="0"/>
* <element ref="{}subgenre" minOccurs="0"/>
* <element ref="{}omroepen" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"srid",
"titel",
"seizoen",
"lexicoTitel",
"icon",
"startJaar",
"orti",
"inh1",
"mail",
"webs",
"twitteraccount",
"twitterhashtag",
"genre",
"subgenre",
"omroepen"
})
@XmlRootElement(name = "serie")
public class Serie {
@XmlElement(required = true)
protected String srid;
@XmlElement(required = true)
protected String titel;
protected Integer seizoen;
@XmlElement(name = "lexico_titel")
protected String lexicoTitel;
protected String icon;
@XmlElement(name = "start_jaar")
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger startJaar;
protected String orti;
protected String inh1;
protected String mail;
protected String webs;
protected String twitteraccount;
protected String twitterhashtag;
protected String genre;
protected String subgenre;
protected Omroepen omroepen;
/**
* Gets the value of the srid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrid() {
return srid;
}
/**
* Sets the value of the srid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrid(String value) {
this.srid = value;
}
/**
* Gets the value of the titel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitel() {
return titel;
}
/**
* Sets the value of the titel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitel(String value) {
this.titel = value;
}
/**
* Gets the value of the seizoen property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getSeizoen() {
return seizoen;
}
/**
* Sets the value of the seizoen property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setSeizoen(Integer value) {
this.seizoen = value;
}
/**
* Gets the value of the lexicoTitel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLexicoTitel() {
return lexicoTitel;
}
/**
* Sets the value of the lexicoTitel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLexicoTitel(String value) {
this.lexicoTitel = value;
}
/**
* Gets the value of the icon property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIcon() {
return icon;
}
/**
* Sets the value of the icon property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIcon(String value) {
this.icon = value;
}
/**
* Gets the value of the startJaar property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getStartJaar() {
return startJaar;
}
/**
* Sets the value of the startJaar property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setStartJaar(BigInteger value) {
this.startJaar = value;
}
/**
* Gets the value of the orti property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrti() {
return orti;
}
/**
* Sets the value of the orti property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrti(String value) {
this.orti = value;
}
/**
* Gets the value of the inh1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInh1() {
return inh1;
}
/**
* Sets the value of the inh1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInh1(String value) {
this.inh1 = value;
}
/**
* Gets the value of the mail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMail() {
return mail;
}
/**
* Sets the value of the mail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMail(String value) {
this.mail = value;
}
/**
* Gets the value of the webs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWebs() {
return webs;
}
/**
* Sets the value of the webs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWebs(String value) {
this.webs = value;
}
/**
* Gets the value of the twitteraccount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitteraccount() {
return twitteraccount;
}
/**
* Sets the value of the twitteraccount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitteraccount(String value) {
this.twitteraccount = value;
}
/**
* Gets the value of the twitterhashtag property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitterhashtag() {
return twitterhashtag;
}
/**
* Sets the value of the twitterhashtag property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitterhashtag(String value) {
this.twitterhashtag = value;
}
/**
* Gets the value of the genre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGenre() {
return genre;
}
/**
* Sets the value of the genre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGenre(String value) {
this.genre = value;
}
/**
* Gets the value of the subgenre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubgenre() {
return subgenre;
}
/**
* Sets the value of the subgenre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubgenre(String value) {
this.subgenre = value;
}
/**
* Gets the value of the omroepen property.
*
* @return
* possible object is
* {@link Omroepen }
*
*/
public Omroepen getOmroepen() {
return omroepen;
}
/**
* Sets the value of the omroepen property.
*
* @param value
* allowed object is
* {@link Omroepen }
*
*/
public void setOmroepen(Omroepen value) {
this.omroepen = value;
}
}
| npo-poms/poms-shared | media-projectm/src/main/java/nl/vpro/domain/npo/projectm/metadata/v2_1/Serie.java |
214,174 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.07.21 at 10:52:28 AM CEST
//
package nl.vpro.domain.npo.projectm.metadata.v2_1;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}srid"/>
* <element ref="{}titel"/>
* <element name="seizoen" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element ref="{}lexico_titel" minOccurs="0"/>
* <element ref="{}icon" minOccurs="0"/>
* <element ref="{}start_jaar" minOccurs="0"/>
* <element ref="{}orti" minOccurs="0"/>
* <element ref="{}inh1" minOccurs="0"/>
* <element ref="{}mail" minOccurs="0"/>
* <element ref="{}webs" minOccurs="0"/>
* <element ref="{}twitteraccount" minOccurs="0"/>
* <element ref="{}twitterhashtag" minOccurs="0"/>
* <element ref="{}genre" minOccurs="0"/>
* <element ref="{}subgenre" minOccurs="0"/>
* <element ref="{}omroepen" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"srid",
"titel",
"seizoen",
"lexicoTitel",
"icon",
"startJaar",
"orti",
"inh1",
"mail",
"webs",
"twitteraccount",
"twitterhashtag",
"genre",
"subgenre",
"omroepen"
})
@XmlRootElement(name = "serie")
public class Serie {
@XmlElement(required = true)
protected String srid;
@XmlElement(required = true)
protected String titel;
protected Integer seizoen;
@XmlElement(name = "lexico_titel")
protected String lexicoTitel;
protected String icon;
@XmlElement(name = "start_jaar")
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger startJaar;
protected String orti;
protected String inh1;
protected String mail;
protected String webs;
protected String twitteraccount;
protected String twitterhashtag;
protected String genre;
protected String subgenre;
protected Omroepen omroepen;
/**
* Gets the value of the srid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrid() {
return srid;
}
/**
* Sets the value of the srid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrid(String value) {
this.srid = value;
}
/**
* Gets the value of the titel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitel() {
return titel;
}
/**
* Sets the value of the titel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitel(String value) {
this.titel = value;
}
/**
* Gets the value of the seizoen property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getSeizoen() {
return seizoen;
}
/**
* Sets the value of the seizoen property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setSeizoen(Integer value) {
this.seizoen = value;
}
/**
* Gets the value of the lexicoTitel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLexicoTitel() {
return lexicoTitel;
}
/**
* Sets the value of the lexicoTitel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLexicoTitel(String value) {
this.lexicoTitel = value;
}
/**
* Gets the value of the icon property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIcon() {
return icon;
}
/**
* Sets the value of the icon property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIcon(String value) {
this.icon = value;
}
/**
* Gets the value of the startJaar property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getStartJaar() {
return startJaar;
}
/**
* Sets the value of the startJaar property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setStartJaar(BigInteger value) {
this.startJaar = value;
}
/**
* Gets the value of the orti property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrti() {
return orti;
}
/**
* Sets the value of the orti property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrti(String value) {
this.orti = value;
}
/**
* Gets the value of the inh1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInh1() {
return inh1;
}
/**
* Sets the value of the inh1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInh1(String value) {
this.inh1 = value;
}
/**
* Gets the value of the mail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMail() {
return mail;
}
/**
* Sets the value of the mail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMail(String value) {
this.mail = value;
}
/**
* Gets the value of the webs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWebs() {
return webs;
}
/**
* Sets the value of the webs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWebs(String value) {
this.webs = value;
}
/**
* Gets the value of the twitteraccount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitteraccount() {
return twitteraccount;
}
/**
* Sets the value of the twitteraccount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitteraccount(String value) {
this.twitteraccount = value;
}
/**
* Gets the value of the twitterhashtag property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitterhashtag() {
return twitterhashtag;
}
/**
* Sets the value of the twitterhashtag property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitterhashtag(String value) {
this.twitterhashtag = value;
}
/**
* Gets the value of the genre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGenre() {
return genre;
}
/**
* Sets the value of the genre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGenre(String value) {
this.genre = value;
}
/**
* Gets the value of the subgenre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubgenre() {
return subgenre;
}
/**
* Sets the value of the subgenre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubgenre(String value) {
this.subgenre = value;
}
/**
* Gets the value of the omroepen property.
*
* @return
* possible object is
* {@link Omroepen }
*
*/
public Omroepen getOmroepen() {
return omroepen;
}
/**
* Sets the value of the omroepen property.
*
* @param value
* allowed object is
* {@link Omroepen }
*
*/
public void setOmroepen(Omroepen value) {
this.omroepen = value;
}
}
| mihxil/poms-shared | media-projectm/src/main/java/nl/vpro/domain/npo/projectm/metadata/v2_1/Serie.java |
214,177 | 404: Not Found | SammieLeung/VideoNameParser | src/main/java/com/firefly/videonameparser/VideoNameParserV2.java |
214,183 | package be.kdg.seizoenen;
/**
* @author Kristiaan Behiels
* @version 1.0 21/10/13
*/
public class Lente extends Seizoen {
private int jaar = 2014;
private String begin = "20 maart";
public Lente() {
}
public Lente(int jaar, String begin) {
this.jaar = jaar;
this.begin = begin;
}
@Override
public String getBegin() {
return "In " + jaar + " begint de lente op " + begin;
}
}
| gvdhaege/KdG | Java Programming/Deel 2/W1 - Overerving/Oefeningen/Oplossingen/Seizoenen/src/be/kdg/seizoenen/Lente.java |
214,184 | /*
* Copyright (C) 2010 All rights reserved
* VPRO The Netherlands
*/
package nl.vpro.domain.media;
import lombok.SneakyThrows;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* This class provides a combined view on all program and group types and their
* configuration options. Both program and groups have a type property, but there
* is now way to add this property to their abstract super class while providing two
* implementations of a generic super type.
*/
@XmlEnum
@XmlType(name = "mediaTypeEnum")
public enum MediaType {
/**
* The abstract type denoting every possible media type
*/
MEDIA(MediaObject.class) {
@Override
public String toString() {
return "Alle media";
}
@Override
public SubMediaType getSubType() {
return null;
}
@Override
public List<SubMediaType> getSubTypes () {
return
Stream.concat(
Stream.concat(
Arrays.stream(ProgramType.values()),
Arrays.stream(GroupType.values())
),
Arrays.stream(SegmentType.values())
).collect(Collectors.toList());
}
},
/**
* The abstract type denoting every type of a {@link Program}
*/
PROGRAM(Program.class) {
@Override
public String toString() {
return "Programma";
}
@Override
public ProgramType getSubType() {
return null;
}
@Override
public List<SubMediaType> getSubTypes() {
return Arrays.asList(ProgramType.values());
}
@Override
public boolean hasSegments() {
return true;
}
},
BROADCAST(Program.class) {
@Override
public String toString() {
return "Uitzending";
}
@Override
public ProgramType getSubType() {
return ProgramType.BROADCAST;
}
@Override
public boolean hasSegments() {
return true;
}
},
CLIP(Program.class) {
@Override
public String toString() {
return "Clip";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.CLIP;
}
},
STRAND(Program.class) {
@Override
public String toString() {
return "Koepelprogramma";
}
@Override
public ProgramType getSubType() {
return ProgramType.STRAND;
}
},
TRAILER(Program.class) {
@Override
public String toString() {
return "Trailer";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.TRAILER;
}
},
MOVIE(Program.class) {
@Override
public String toString() {
return "Film";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.MOVIE;
}
},
/**
* The abstract type denoting every type of a {@link Group}
*/
GROUP(Group.class) {
@Override
public String toString() {
return "Groep";
}
@Override
public GroupType getSubType() {
return null;
}
@Override
public List<SubMediaType> getSubTypes() {
return Arrays.asList(GroupType.values());
}
},
SERIES(Group.class) {
@Override
public String toString() {
return "Serie";
}
@Override
public GroupType getSubType() {
return GroupType.SERIES;
}
@Override
public boolean hasOrdering() {
return true;
}
},
SEASON(Group.class) {
@Override
public String toString() {
return "Seizoen";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.SEASON;
}
},
UMBRELLA(Group.class) {
@Override
public String toString() {
return "Paraplu";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.UMBRELLA;
}
},
// MSE-1453
@Deprecated
ARCHIVE(Group.class) {
@Override
public String toString() {
return "Archief";
}
@Override
public GroupType getSubType() {
return GroupType.ARCHIVE;
}
},
COLLECTION(Group.class) {
@Override
public String toString() {
return "Collectie";
}
@Override
public GroupType getSubType() {
return GroupType.COLLECTION;
}
},
PLAYLIST(Group.class) {
@Override
public String toString() {
return "Speellijst";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.PLAYLIST;
}
},
ALBUM(Group.class) {
@Override
public String toString() {
return "Album";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.ALBUM;
}
},
SEGMENT(Segment.class) {
@Override
public String toString() {
return "Segment";
}
@Override
public SegmentType getSubType() {
return SegmentType.SEGMENT;
}
},
/*
COLLECTION {
@Override
public String toString() {
return "Collectie";
}
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
COMPILATION {
@Override
public String toString() {
return "Compilatie";
}
@Override
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
CONCEPT {
@Override
public String toString() {
return "Concept";
}
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
SHOW {
@Override
public String toString() {
return "Show";
}
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
*/
TRACK(Program.class) {
@Override
public String toString() {
return "Track";
}
@Override
public MediaType[] allowedEpisodeOfTypes() {
return new MediaType[]{MediaType.ALBUM};
}
@Override
public boolean hasSegments() {
return false;
}
@Override
public ProgramType getSubType() {
return ProgramType.TRACK;
}
},
VISUALRADIO(Program.class) {
@Override
public String toString() {
return "Visual radio";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.VISUALRADIO;
}
},
VISUALRADIOSEGMENT(Segment.class) {
@Override
public String toString () {
return "Visual radio segment";
}
@Override
public SegmentType getSubType () {
return SegmentType.VISUALRADIOSEGMENT;
}
},
/**
* The abstract type denoting every type of a {@link Segment}
*/
SEGMENTTYPE(Segment.class) {
@Override
public String toString() {
return "Segments";
}
@Override
public SegmentType getSubType() {
return null;
}
@Override
public List<SubMediaType> getSubTypes() {
return Arrays.asList(SegmentType.values());
}
},
/**
* @since 2.1
*/
RECORDING(Program.class) {
@Override
public String toString() {
return "Opname";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.RECORDING;
}
},
PROMO(Program.class) {
@Override
public String toString() {
return "Promo";
}
@Override
public boolean hasSegments() {
return false;
}
@Override
public ProgramType getSubType() {
return ProgramType.PROMO;
}
};
final Class<? extends MediaObject> clazz;
final Constructor<?> constructor;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Optional<Method> setType;
MediaType(Class<? extends MediaObject> clazz) {
this.clazz = clazz;
if (Modifier.isAbstract(this.clazz.getModifiers())) {
this.constructor = null;
} else {
try {
this.constructor = clazz.getConstructor();
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
}
}
protected void setType(MediaObject o) throws InvocationTargetException, IllegalAccessException {
if (this.setType == null){
Method st;
if (this.getSubType() != null) {
try {
st = clazz.getMethod("setType", this.getSubType().getClass());
} catch (NoSuchMethodException nsme) {
st = null;
}
} else {
st = null;
}
this.setType = Optional.ofNullable(st);
}
if (this.setType.isPresent()) {
this.setType.get().invoke(o, getSubType());
}
}
public final MediaObject getMediaInstance() {
try {
if (constructor == null) {
throw new RuntimeException("Not possible to make instances of " + this);
}
MediaObject o = (MediaObject) constructor.newInstance();
setType(o);
return o;
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new RuntimeException("For " + this + " ", e);
}
}
public final String getMediaClass() {
return getMediaObjectClass().getSimpleName();
}
public final Class<? extends MediaObject> getMediaObjectClass() {
return clazz;
}
public boolean hasSegments() {
return false;
}
/**
* @since 5.11
*/
public boolean canHaveScheduleEvents() {
return getSubType() != null && getSubType().canHaveScheduleEvents();
}
public final boolean hasEpisodeOf() {
return getSubType() != null && getSubType().hasEpisodeOf();
}
public MediaType[] preferredEpisodeOfTypes() {
if(!hasEpisodeOf()) {
return new MediaType[]{};
}
return new MediaType[]{MediaType.SERIES, MediaType.SEASON};
}
public MediaType[] allowedEpisodeOfTypes() {
if(!hasEpisodeOf()) {
return new MediaType[0];
}
return new MediaType[]{MediaType.SERIES, MediaType.SEASON};
}
public final boolean canContainEpisodes() {
return getSubType() != null && getSubType().canContainEpisodes();
}
public MediaType[] preferredEpisodeTypes() {
if(!canContainEpisodes()) {
return new MediaType[0];
}
return new MediaType[]{MediaType.BROADCAST};
}
public MediaType[] allowedEpisodeTypes() {
if(!canContainEpisodes()) {
return new MediaType[0];
}
return new MediaType[]{MediaType.BROADCAST};
}
public boolean hasMemberOf() {
return true;
}
public MediaType[] preferredMemberOfTypes() {
if(!hasMemberOf()) {
return new MediaType[]{};
}
return new MediaType[]{MediaType.MEDIA};
}
public MediaType[] allowedMemberOfTypes() {
return preferredMemberOfTypes();
}
public boolean hasMembers() {
return true;
}
public MediaType[] preferredMemberTypes() {
if(!hasMembers()) {
return new MediaType[]{};
}
return new MediaType[]{MediaType.MEDIA};
}
public MediaType[] allowedMemberTypes() {
return preferredMemberTypes();
}
public boolean hasOrdering() {
return false;
}
public abstract SubMediaType getSubType();
public List<SubMediaType> getSubTypes() {
return getSubType() != null ? Collections.singletonList(getSubType()) : null;
}
public static MediaType of(String type) {
return type == null ? null : valueOf(type.toUpperCase());
}
@Nonnull
public static MediaType getMediaType(MediaObject media) {
SubMediaType type = media.getType();
if (type != null) {
return type.getMediaType();
}
if (media instanceof Program) {
return MediaType.PROGRAM;
}
if (media instanceof Group) {
return MediaType.GROUP;
}
if (media instanceof Segment) {
return MediaType.SEGMENT;
}
return MediaType.MEDIA;
}
@SneakyThrows
public MediaObject createInstance() {
Class<? extends MediaObject> clazz = getMediaObjectClass();
if (Program.class.isAssignableFrom(clazz)) {
Program o = (Program) clazz.newInstance();
o.setType((ProgramType) getSubType());
return o;
}
if (Group.class.isAssignableFrom(clazz)) {
Group o = (Group) clazz.newInstance();
o.setType((GroupType) getSubType());
return o;
}
if (Segment.class.isAssignableFrom(clazz)) {
Segment o = (Segment) clazz.newInstance();
o.setType((SegmentType) getSubType());
return o;
}
throw new IllegalStateException(clazz + " of " + this + " is not a program, group or segment");
}
/**
* Returns all 'leaf' mediaTypes. That are all non abstract instances, that actually have a certain {@link #getSubType()}.
* @since 5.8
*/
public static MediaType[] leafValues() {
return Arrays.stream(values()).filter(f -> f.getSubType() != null).toArray(MediaType[]::new);
}
/**
* @since 5.8
*/
public static MediaType[] leafValues(Class<? extends MediaObject> clazz) {
return Arrays.stream(values()).filter(f -> f.getSubType() != null).filter(t -> clazz.isAssignableFrom(t.getMediaObjectClass())).toArray(MediaType[]::new);
}
/**
* @since 2.1
*/
public static Class<?>[] getClasses(Collection<MediaType> types) {
if(types == null) {
return new Class<?>[]{Program.class, Group.class, Segment.class};
} else {
Set<Class<?>> c = new HashSet<>();
for(MediaType type : types) {
c.add(type.getMediaObjectClass());
}
return c.toArray(new Class<?>[0]);
}
}
/**
* @since 2.1
*/
public static Collection<MediaType> valuesOf(String types) {
List<MediaType> result = new ArrayList<>();
for(String s : types.split(",")) {
result.add(valueOf(s.trim()));
}
return result;
}
}
| mihxil/poms-shared | media-domain/src/main/java/nl/vpro/domain/media/MediaType.java |
214,185 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.07.21 at 10:40:57 AM CEST
//
package nl.vpro.domain.npo.projectm.metadata.v3_2;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="srid" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element ref="{}titel"/>
* <element ref="{}lexico_titel" minOccurs="0"/>
* <element ref="{}bron" minOccurs="0"/>
* <element ref="{}orti" minOccurs="0"/>
* <element name="start_jaar" type="{http://www.w3.org/2001/XMLSchema}gYear" minOccurs="0"/>
* <element name="seizoen" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{}lcod" minOccurs="0"/>
* <element ref="{}icon" minOccurs="0"/>
* <element ref="{}inhl" minOccurs="0"/>
* <element ref="{}genre" minOccurs="0"/>
* <element ref="{}subgenre" minOccurs="0"/>
* <element ref="{}psrt" minOccurs="0"/>
* <element ref="{}mail" minOccurs="0"/>
* <element ref="{}webs" minOccurs="0"/>
* <element ref="{}twitteraccount" minOccurs="0"/>
* <element ref="{}twitterhashtag" minOccurs="0"/>
* <element ref="{}omroepen" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"srid",
"titel",
"lexicoTitel",
"bron",
"orti",
"startJaar",
"seizoen",
"lcod",
"icon",
"inhl",
"genre",
"subgenre",
"psrt",
"mail",
"webs",
"twitteraccount",
"twitterhashtag",
"omroepen"
})
@XmlRootElement(name = "serie")
public class Serie {
@XmlElement(required = true)
protected String srid;
@XmlElement(required = true)
protected String titel;
@XmlElement(name = "lexico_titel")
protected String lexicoTitel;
protected String bron;
protected String orti;
@XmlElement(name = "start_jaar")
@XmlSchemaType(name = "gYear")
protected XMLGregorianCalendar startJaar;
protected String seizoen;
protected String lcod;
@XmlSchemaType(name = "anyURI")
protected String icon;
protected String inhl;
protected String genre;
protected String subgenre;
protected String psrt;
protected String mail;
@XmlSchemaType(name = "anyURI")
protected String webs;
protected String twitteraccount;
protected String twitterhashtag;
protected Omroepen omroepen;
/**
* Gets the value of the srid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrid() {
return srid;
}
/**
* Sets the value of the srid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrid(String value) {
this.srid = value;
}
/**
* Gets the value of the titel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitel() {
return titel;
}
/**
* Sets the value of the titel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitel(String value) {
this.titel = value;
}
/**
* Gets the value of the lexicoTitel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLexicoTitel() {
return lexicoTitel;
}
/**
* Sets the value of the lexicoTitel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLexicoTitel(String value) {
this.lexicoTitel = value;
}
/**
* Gets the value of the bron property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBron() {
return bron;
}
/**
* Sets the value of the bron property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBron(String value) {
this.bron = value;
}
/**
* Gets the value of the orti property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrti() {
return orti;
}
/**
* Sets the value of the orti property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrti(String value) {
this.orti = value;
}
/**
* Gets the value of the startJaar property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartJaar() {
return startJaar;
}
/**
* Sets the value of the startJaar property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartJaar(XMLGregorianCalendar value) {
this.startJaar = value;
}
/**
* Gets the value of the seizoen property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSeizoen() {
return seizoen;
}
/**
* Sets the value of the seizoen property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSeizoen(String value) {
this.seizoen = value;
}
/**
* Gets the value of the lcod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLcod() {
return lcod;
}
/**
* Sets the value of the lcod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLcod(String value) {
this.lcod = value;
}
/**
* Gets the value of the icon property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIcon() {
return icon;
}
/**
* Sets the value of the icon property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIcon(String value) {
this.icon = value;
}
/**
* Gets the value of the inhl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInhl() {
return inhl;
}
/**
* Sets the value of the inhl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInhl(String value) {
this.inhl = value;
}
/**
* Gets the value of the genre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGenre() {
return genre;
}
/**
* Sets the value of the genre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGenre(String value) {
this.genre = value;
}
/**
* Gets the value of the subgenre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubgenre() {
return subgenre;
}
/**
* Sets the value of the subgenre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubgenre(String value) {
this.subgenre = value;
}
/**
* Gets the value of the psrt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPsrt() {
return psrt;
}
/**
* Sets the value of the psrt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPsrt(String value) {
this.psrt = value;
}
/**
* Gets the value of the mail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMail() {
return mail;
}
/**
* Sets the value of the mail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMail(String value) {
this.mail = value;
}
/**
* Gets the value of the webs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWebs() {
return webs;
}
/**
* Sets the value of the webs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWebs(String value) {
this.webs = value;
}
/**
* Gets the value of the twitteraccount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitteraccount() {
return twitteraccount;
}
/**
* Sets the value of the twitteraccount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitteraccount(String value) {
this.twitteraccount = value;
}
/**
* Gets the value of the twitterhashtag property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitterhashtag() {
return twitterhashtag;
}
/**
* Sets the value of the twitterhashtag property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitterhashtag(String value) {
this.twitterhashtag = value;
}
/**
* Gets the value of the omroepen property.
*
* @return
* possible object is
* {@link Omroepen }
*
*/
public Omroepen getOmroepen() {
return omroepen;
}
/**
* Sets the value of the omroepen property.
*
* @param value
* allowed object is
* {@link Omroepen }
*
*/
public void setOmroepen(Omroepen value) {
this.omroepen = value;
}
}
| npo-poms/poms-shared | media-projectm/src/main/java/nl/vpro/domain/npo/projectm/metadata/v3_2/Serie.java |
214,188 | package FactoryMethod;
import Media.*;
import java.util.ArrayList;
public class MediaFactory {
public AbstractMedia createMedia(String type,String naam, Poster poster, ArrayList<Seizoen> seizoenen, String beschrijving,Ondertiteling ondertiteling, int duratie, Categorie categorie) {
if ("Film".equalsIgnoreCase(type)) {
return new Film(naam, poster, ondertiteling, duratie, beschrijving, categorie);
} else if ("Serie".equalsIgnoreCase(type)) {
return new Serie(naam, poster, seizoenen, beschrijving);
} else {
throw new IllegalArgumentException("Invalid media type");
}
}
} | jeffrey0402/NetNix | src/FactoryMethod/MediaFactory.java |
214,189 | package weekopdracht_racing.Gameplay;
import java.util.InputMismatchException;
import weekopdracht_racing.*;
import weekopdracht_racing.Team.TeamFactory;
import weekopdracht_racing.Teamlid.*;
public class Main {
public static void main(String[] args) {
InputHandler inputhandler = new InputHandler();
Menu menu = new Menu();
inputhandler.spelInstructie();
System.out.print(menu.toonStartMenu());
inputhandler.checkMenuKeuze(menu);
Seizoen seizoen = new Seizoen();
//System.out.println(seizoen.toonAlleTeams());
//System.out.println(seizoen.toonAlleCoureurs());
System.out.println();
}
} | SweerenK/Weekopdracht_Racing | Gameplay/Main.java |
214,190 | package com.firefly.videonameparser.bean;
import android.text.TextUtils;
import com.firefly.videonameparser.utils.StringUtils;
import java.util.ArrayList;
public class Episodes {
public int season = -1;
public int episode = -1;
public int toEpisode = -1;
private ArrayList<String> mMatchList =new ArrayList<>();
private static final int SEASON_MAX_RANGE = 100;
private static final int EPISODE_MAX_RANGE = 100;
private static final String[] SEASON_MARKERS = {"s"};
private static final String[] SEASON_EP_MARKERS = {"x"};
private static final String[] DISC_MARKERS = {"d"};
private static final String[] EPISODE_MARKERS = {"xe", "ex", "ep", "e"};
private static final String[] RANGE_SEPARATORS = {"_", "-", "~", "to", "a"};
private static final String[] DISCRETE_SEPARATORS = {"+", "&", "and", "et"};
private static final String[] SEASON_WORDS = {
"season",
"saison",
"seizoen",
"serie",
"seasons",
"saisons",
"series",
"tem",
"temp",
"temporada",
"temporadas",
"stagione"
};
private static final String[] EPISODE_WORDS = {
"episode",
"episodes",
"eps",
"ep",
"episodio",
"episodios",
"capitulo",
"capitulos"
};
// ? +2x5
// ? +2X5
// ? +02x05
// ? +2X05
// ? +02x5
// ? S02E05
// ? s02e05
// ? s02e5
// ? s2e05
// ? s02ep05
// ? s2EP5
// ? -s03e05
// ? -s02e06
// ? -3x05
// ? -2x06
// : season: 2
// episode: 5
//
// ? "+0102"
// ? "+102"
// : season: 1
// episode: 2
//
// ? "0102 S03E04"
// ? "S03E04 102"
// : season: 3
// episode: 4
public Episodes(int season, int episode) {
super();
this.season = season;
this.episode = episode;
}
public static Episodes parser(String input) {
if (TextUtils.isEmpty(input)) return null;
input=input.trim();
Episodes episodes = new Episodes(-1, -1);
String regex = build_or_pattern(SEASON_MARKERS, SEASON_WORDS) + "(\\d+)?" +
build_or_pattern(EPISODE_MARKERS, EPISODE_WORDS, DISC_MARKERS) + "(\\d+)";
String[] dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 3&&dotStampMatch[1]!=null&&dotStampMatch[2]!=null) {
episodes.mMatchList.add(dotStampMatch[0]);
episodes.season = Integer.parseInt(dotStampMatch[1]);
episodes.episode = Integer.parseInt(dotStampMatch[2]);
}
if(episodes.season==-1){
regex = "^" + build_or_pattern(SEASON_MARKERS, SEASON_WORDS) + "(\\d+)$";
dotStampMatch = StringUtils.matcher(regex, input);
if (dotStampMatch != null) {
if (dotStampMatch.length == 2&&dotStampMatch[1]!=null) {
episodes.season = Integer.parseInt(dotStampMatch[1]);
}
}
}
if (episodes.episode == -1 && !input.contains("x265") &&!input.contains("x264")) {
regex = "^" + build_or_pattern(EPISODE_MARKERS, EPISODE_WORDS, DISC_MARKERS) + "(\\d+)";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null) {
if (dotStampMatch.length == 2&&dotStampMatch[1]!=null) {
episodes.mMatchList.add(dotStampMatch[0]);
episodes.episode = Integer.parseInt(dotStampMatch[1]);
}
if (dotStampMatch.length == 4) {
episodes.mMatchList.add(dotStampMatch[0]);
episodes.episode = Integer.parseInt(dotStampMatch[1]);
episodes.toEpisode = Integer.parseInt(dotStampMatch[3]);
}
}
}
regex = "\\D(\\d{1,3})@?" +
build_or_pattern(SEASON_EP_MARKERS) +
"@?(\\d{1,3})\\D";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 3&&dotStampMatch[1]!=null&&dotStampMatch[2]!=null) {
episodes.mMatchList.add(dotStampMatch[0]);
episodes.season = Integer.parseInt(dotStampMatch[1]);
episodes.episode = Integer.parseInt(dotStampMatch[2]);
}
regex = build_or_pattern(EPISODE_MARKERS, EPISODE_WORDS, DISC_MARKERS) + "(\\d+)" + build_or_pattern(RANGE_SEPARATORS) + "(\\d+)";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 3) {
episodes.mMatchList.add(dotStampMatch[0]);
episodes.episode = Integer.parseInt(dotStampMatch[1]);
episodes.toEpisode = Integer.parseInt(dotStampMatch[2]);
}
regex = "[全共]([0-9]{1,4}|[一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾百千佰仟]{1,})[集话話章]";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 2) {
episodes.mMatchList.add(dotStampMatch[0]);
String numStr = dotStampMatch[1];
if (StringUtils.checkChina(numStr)) {
episodes.episode = 1;
episodes.toEpisode = (int) StringUtils.ch2Num(numStr);
} else {
episodes.episode = 1;
episodes.toEpisode = Integer.parseInt(dotStampMatch[1]);
}
}
regex = "第([0-9]{1,4}|[一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾百千佰仟]{1,})[集话話章]";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 2) {
episodes.mMatchList.add(dotStampMatch[0]);
String numStr = dotStampMatch[1];
if (StringUtils.checkChina(numStr)) {
episodes.episode = (int) StringUtils.ch2Num(numStr);
} else {
episodes.episode = Integer.parseInt(dotStampMatch[1]);
}
}
regex = "第([0-9]{1,4}|[一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾百千佰仟]{1,})[部季]";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 2) {
episodes.mMatchList.add(dotStampMatch[0]);
String numStr = dotStampMatch[1];
if (StringUtils.checkChina(numStr)) {
episodes.season = (int) StringUtils.ch2Num(numStr);
} else {
episodes.season = Integer.parseInt(dotStampMatch[1]);
}
}
if (episodes.episode == 0) {
regex = "^\\d{2,}$";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 1) {
episodes.mMatchList.add(dotStampMatch[0]);
episodes.episode = Integer.parseInt(dotStampMatch[0]);
}
}
regex="[上中下]$";
dotStampMatch = StringUtils.matcher(regex, input);
StringUtils.debug(dotStampMatch);
if (dotStampMatch != null && dotStampMatch.length == 1) {
episodes.mMatchList.add(dotStampMatch[0]);
}
if (episodes.episode != -1 && episodes.season == -1)
episodes.season = 1;
return episodes;
}
// def build_or_pattern(patterns, name=None, escape=False):
// or_pattern = []
// for pattern in patterns:
// if not or_pattern:
// or_pattern.append('(?')
// if name:
// or_pattern.append('P<' + name + '>')
// else:
// or_pattern.append(':')
// else:
// or_pattern.append('|')
// or_pattern.append('(?:%s)' % re.escape(pattern) if escape else pattern)
// or_pattern.append(')')
// return ''.join(or_pattern)
private static String build_or_pattern(String[]... patterns) {
StringBuilder result = new StringBuilder();
for (String[] strings : patterns) {
for (String string : strings) {
if (result.length() == 0) {
result.append("(?");
result.append(":");
} else {
result.append("|");
}
result.append(StringUtils.escapeExprSpecialWord(string));
// result.append(string);
//result.append(String.format("(?:%s)",string));
}
}
result.append(")");
if (result.length() == 0) return null;
return result.toString();
}
public boolean saneEpisodes(){
if(episode!=-1||season!=-1||toEpisode!=-1)
return true;
return false;
}
public boolean isMatch(){
return mMatchList.size()>0;
}
public ArrayList<String> getMatchList() {
return mMatchList;
}
@Override
public String toString() {
return "Episodes{" +
"season=" + season +
", episode=" + episode +
", toEpisode=" + toEpisode +
'}';
}
}
| SammieLeung/VideoNameParser | src/main/java/com/firefly/videonameparser/bean/Episodes.java |
214,194 | package Media;
import java.util.ArrayList;
public class Serie extends AbstractMedia{
public String naam;
public Poster poster;
public ArrayList<Seizoen> seizoenen;
public String beschrijving;
public Serie(String naam, Poster poster, ArrayList<Seizoen> seizoenen, String beschrijving) {
super(naam, poster, null, 0, beschrijving, null);
this.naam = naam;
this.poster = poster;
this.seizoenen = seizoenen;
this.beschrijving = beschrijving;
}
@Override
public void Play() {
System.out.println("Playing: " + naam);
}
} | jeffrey0402/NetNix | src/Media/Serie.java |
214,196 | package com.firefly.videonameparser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.firefly.videonameparser.bean.AudioCodec;
import com.firefly.videonameparser.bean.Country;
import com.firefly.videonameparser.bean.Episode;
import com.firefly.videonameparser.bean.FileSize;
import com.firefly.videonameparser.bean.OtherItem;
import com.firefly.videonameparser.bean.Resolution;
import com.firefly.videonameparser.bean.SubTitle;
import com.firefly.videonameparser.bean.VideoCodec;
import com.firefly.videonameparser.bean.Year;
import com.firefly.videonameparser.utils.StringUtils;
//import com.google.common.collect.Collections2;
//import com.google.common.collect.Lists;
import android.text.TextUtils;
public class VideoNameParser {
private static final String TAG = "VideoNameParser";
/*
* 视频名称解析依据
* * http://wiki.xbmc.org/index.php?title=Adding_videos_to_the_library/Naming_files/TV_shows
* * http://wiki.xbmc.org/index.php?title=Advancedsettings.xml#.3Ctvshowmatching.3E
*/
private final static int maxSegments = 3;
private final static String[] movieKeywords = {
"2160p",
"1080p",
"720p",
"480p",
"blurayrip",
"brrip",
"divx",
"dvdrip",
"hdrip",
"hdtv",
"tvrip",
"xvid",
"camrip",
"hd",
"4k",
"2k",
"bd"
};
private static final String[] SEASON_WORDS = {
"s",
"season",
"saison",
"seizoen",
"serie",
"seasons",
"saisons",
"series",
"tem",
"temp",
"temporada",
"temporadas",
"stagione"
};
private static final String[] EPISODE_WORDS = {
"e",
"episode",
"episodes",
"eps",
"ep",
"episodio",
"episodios",
"capitulo",
"capitulos"
};
private final static String SEGMENTS_SPLIT = "\\.| |-|;|_";
private final static String MATCH_FILES = "/.mp4$|.mkv$|.avi$/";
private final static int minYear = 1900, maxYear = 2060;
private final static String[] excluded = {};
private String simplifyName(String name) {
if (name == null || name.length() == 0) return "";
String[] arrays = name.toLowerCase()
.trim()
.replace("/\\([^\\(]+\\)$/", "") // remove brackets at end
.replace("/&/g", "and")
.replace("/[^0-9a-z ]+/g", " ") // remove special chars
.split(" ");
return join("", arrays);
//.split(" ").filter(function(r){return r}).join(" ")
}
MovieNameInfo mInfo;
public MovieNameInfo parseVideoName(String filePath) {
if (StringUtils.checkChina(filePath)) {
filePath = StringUtils.ChineseToEnglish(filePath);
}
mInfo = new MovieNameInfo();
String[] segments = slice(reverse(filePath
.replace("\\", "/") // Support Windows slashes, lol
.split("/")), 0, maxSegments);
String[] firstNameSplit = segments[0].split("\\.| |_");//file name
mInfo.setExtension(firstNameSplit != null ? firstNameSplit[firstNameSplit.length - 1] : "");
String firstName = segments[0].replaceAll("\\.| |_", "");
for (String seg : segments) {
parserYear(seg);
parserAired(seg);
parserEpisode(seg);
}
/*
* This stamp must be tested before splitting (by dot)
* a pattern of the kind [4.02]
* This pattern should be arround characters which are not digits and not letters
* */
if (!(mInfo.saneSeason() && mInfo.saneEpisode()) && mInfo.getYear() == 0) {
String[] dotStampMatch = matcher("[^\\da-zA-Z](\\d\\d?)\\.(\\d\\d?)[^\\da-zA-Z]", segments[0]);
if (dotStampMatch != null && dotStampMatch.length >= 3) {
//Log.v(TAG, "dotStampMatch:"+dotStampMatch[0]);
mInfo.setSeason(Integer.parseInt(dotStampMatch[1]));
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(Integer.parseInt(dotStampMatch[2]));
mInfo.setEpisode(tmp);
}
}
/*
* A stamp of the style "804", meaning season 8, episode 4
* */
if (!(mInfo.saneSeason() && mInfo.saneEpisode())) {
String stamp = null;
/* search from the end */
for (String x : reverse(firstNameSplit)) {
if (x.matches("\\d\\d\\d\\d?(e|E)"))// This is a weird case, but I've seen it: dexter.801e.720p.x264-kyr.mkv
{
x = x.substring(0, x.length() - 1);
} else if (x.matches("(s|S)\\d\\d\\d\\d?"))// This is a weird case, but I've seen it: dexter.s801.720p.x264-kyr.mkv
{
x = x.substring(1);
}
//Log.v(TAG, "x:"+x);
/* 4-digit only allowed if this has not been identified as a year */
if (!TextUtils.isEmpty(x) && TextUtils.isDigitsOnly(x) && (x.length() == 3 || (mInfo.getYear() == 0 && x.length() == 4))) {
/* Notice how always the first match is choosen ; the second might be a part of the episode name (e.g. "Southpark - 102 - weight gain 4000");
* that presumes episode number/stamp comes before the name, which is where most human beings would put it */
stamp = x;
break;
}
}
//Log.v(TAG, "stamp:"+stamp);
/* Since this one is risky, do it only if we haven't matched a year (most likely not a movie)
* or if year is BEFORE stamp, like: show.2014.801.mkv */
if (!TextUtils.isEmpty(stamp) && TextUtils.isDigitsOnly(stamp) && (mInfo.getYear() == 0
|| (mInfo.getYear() != 0 && (firstName.indexOf(stamp) < firstName.indexOf(mInfo.getYear()))))) {
String episode = stamp.substring(stamp.length() - 2);
String season = stamp.substring(0, stamp.length() - 2);
//Log.v(TAG, "season:"+season+",episode:"+episode);
mInfo.setSeason(Integer.parseInt(season));
mInfo.setEpisode(Integer.parseInt(episode));
}
}
/*
* "season 1", "season.1", "season1"
* */
if (!mInfo.saneSeason()) {
//Log.v(TAG,"segments:"+segments.length);
String segments_str = join("/", segments);
String[] seasonMatch = matcher("season(\\.| )?(\\d{1,2})", segments_str);
if (seasonMatch != null && seasonMatch.length > 0) {
String season = join("", matcher("\\d", seasonMatch[0]));
mInfo.setSeason(Integer.parseInt(season));
//Log.v(TAG,"season:"+season);
}
String[] seasonEpMatch = matcher("Season (\\d{1,2}) - (\\d{1,2})", segments_str);
if (seasonEpMatch != null && seasonEpMatch.length > 0) {
String season = seasonEpMatch[1];
String episode = seasonEpMatch[2];
mInfo.setSeason(Integer.parseInt(season));
mInfo.setEpisode(Integer.parseInt(episode));
//Log.v(TAG,"season:"+season+",episode:"+episode);
}
}
/*
* "episode 13", "episode.13", "episode13", "ep13", etc.
* */
if (!mInfo.saneEpisode()) {
/* TODO: consider the case when a hyphen is used for multiple episodes ; e.g. e1-3*/
String segments_str = join("/", segments);
String[] episodeMatch = matcher("ep(isode)?(\\.| )?(\\d+)", segments_str);
if (episodeMatch != null && episodeMatch.length > 0) {
String episode = join("", matcher("\\d", episodeMatch[0]));
mInfo.setEpisode(Integer.parseInt(episode));
//Log.v(TAG,"episode:"+episode);
}
}
/*
* Which part (for mapsList which are split into .cd1. and .cd2., etc.. files)
* TODO: WARNING: this assumes it's in the filename segment
*
* */
String[] diskNumberMatch = matcher("[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck]|d)[ _.-]*(\\d{1,2})[^\\d]*", segments[0]);/* weird regexp? */
if (diskNumberMatch != null && diskNumberMatch.length > 0) {
int diskNumber = Integer.parseInt(diskNumberMatch[1]);
mInfo.setDiskNumber(diskNumber);
//Log.v(TAG,"diskNumber:"+diskNumber);
}
/*
* The name of the series / movie
* TODO
* */
boolean isSample = false;
for (String seg : segments) {
//Log.v(TAG, "seg1:"+seg);
/* Remove extension */
if (seg.lastIndexOf(".") > -1) {
seg = seg.substring(0, seg.lastIndexOf("."));//remove "."
}
String[] sourcePrefix = matcher("\\[(.*?)\\]", seg);
/* seg:[HYSUB]ONE PUNCH MAN[10][GB_MP4][1280X720].mp4
sourcePrefix[0]:[HYSUB]
sourcePrefix[1]:HYSUB
sourcePrefix[2]:[10]
sourcePrefix[3]:10
sourcePrefix[4]:[GB_MP4]
sourcePrefix[5]:GB_MP4
sourcePrefix[6]:[1280X720]
sourcePrefix[7]:1280X720
*/
ArrayList<String> removeWords = new ArrayList<String>();
if (sourcePrefix != null && sourcePrefix.length > 0) {
for (int i = 0; i < (sourcePrefix.length) / 2; i++) {
String key = sourcePrefix[i * 2];
String value = sourcePrefix[i * 2 + 1];
//Log.v("sjfq", "key:"+key);
if (StringUtils.hasHttpUrl(value)) {
//Log.v("sjfq", "hasHttpUrl removeWords:"+key);
removeWords.add(key);
continue;
}
Country country = Country.parser(value);
if (country != null) {
//Log.v("sjfq", "setCountry removeWords:"+key);
mInfo.setCountry(country.code);
removeWords.add(key);
continue;
}
int year = Year.parser(value);
if (year > 0) {
//Log.v("sjfq", "Year removeWords:"+key);
mInfo.setYear(year);
removeWords.add(key);
continue;
}
Episode episode = Episode.parser(value);
if (episode != null) {
//Log.v("sjfq", "Episode removeWords:"+key);
mInfo.setEpisode(episode.episode);
mInfo.setSeason(episode.season);
removeWords.add(key);
continue;
}
Resolution resolution = Resolution.parser(value);
if (resolution != null) {
//Log.v("sjfq", "resolution removeWords:"+key);
mInfo.pushTag(resolution.tag);
removeWords.add(key);
continue;
}
VideoCodec videoCodec = VideoCodec.parser(value);
if (videoCodec != null) {
mInfo.setVideoCodec(videoCodec.codec);
removeWords.add(key);
continue;
}
AudioCodec audioCodec = AudioCodec.parser(value);
if (audioCodec != null) {
mInfo.setAudioCodec(audioCodec.codec);
removeWords.add(key);
continue;
}
FileSize fileSize = FileSize.parser(value);
if (fileSize != null) {
mInfo.setFileSize(fileSize.size);
removeWords.add(key);
continue;
}
if (SubTitle.parser(value)) {
//Log.v("sjfq", "SubTitle removeWords:"+key);
removeWords.add(key);
continue;
}
OtherItem otherItem = OtherItem.parser(value);
if (otherItem != null) {
mInfo.pushTag(otherItem.tag);
removeWords.add(key);
continue;
}
}
}
//排除
// 阳光电影www.ygdy8.com.
// 阳光电影www.ygdy8.com
// 阳光电影_www.ygdy8.com
// 阳光电影-www.ygdy8.com
// 阳光电影.www.ygdy8.com
// 阳光电影|www.ygdy8.com
if (!TextUtils.isEmpty(seg)) {
String regex = "^[\u4e00-\u9fa5]+[-_\\|\\.]?(([a-z0-9]+\\.)+(com|net|cn)\\.|www\\.([a-z0-9]+\\.){2,6})";
// String regex = "^[\u4e00-\u9fa5]+[-_\\|\\.]?"
// + "(((https|http|ftp|rtsp|mms)?://)"
// + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
// + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
// + "|" // 允许IP和DOMAIN(域名)
// + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
// + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
// + "[a-z]{2,6})" // first level domain- .com or .museum
// + "(:[0-9]{1,4})?" // 端口- :80
// + "((/?)|" // a slash isn't required if there is no file name
// + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?))\\.?";
String[] httpPreTests = matcher(regex, seg);
if (httpPreTests.length > 0) {
removeWords.add(httpPreTests[0]);
}
}
seg = StringUtils.removeAll(seg, removeWords).trim();
//Log.v("sjfq","seg:"+seg);
sourcePrefix = matcher("\\[.*?\\]", seg);
if (sourcePrefix != null && sourcePrefix.length > 1)// Keep only first title from this filepart, as other ones are most likely release group.
{
seg = seg.replace(sourcePrefix[sourcePrefix.length - 1], "");
}
//Log.v("sjfq","seg2:"+seg);
/*
* WARNING: we must change how this works in order to handle cases like
* "the office[1.01]" as well as "the office [1.01]"; if we split those at '[' or ']', we will get the name "the office 1 10"
* For now, here's a hack to fix this
*/
int squareBracket = seg.indexOf("[");
if (squareBracket > -1) {
if (squareBracket == 0) {
if (seg.indexOf("]") == seg.length() - 1) { //[导火新闻线]
seg = seg.replaceAll("[\\[\\]]", " ").trim();
} else {//
if (seg.indexOf("]") > -1)
seg = seg.substring(seg.indexOf("]") + 1);
}
}
// else{
// seg = seg.replaceAll("[\\[\\]]", " ").trim();
// }
// else{ //the office [1.01]
// seg = seg.substring(0, squareBracket);
// }
seg = seg.replaceAll("[\\[\\]]", " ").trim();
}
//Log.v(TAG, "seg3:"+seg);
//FooBar --> Foo Bar
seg = seg.replaceAll("[A-Z]", " $0").trim();
//String[] segSplit = seg.split("\\.| |-|;|_");
String[] segSplit = seg.split(SEGMENTS_SPLIT);
isSample = seg.matches("^sample") || seg.matches("^etrg");
/* No need to go further; */
if (!TextUtils.isEmpty(mInfo.name))
break;
ArrayList<String> nameParts = new ArrayList<String>();
int lastIndex = -1;
for (int i = 0; i < segSplit.length; i++) {
String word = segSplit[i];
//Log.v(TAG, "word:"+word);
lastIndex = i;
/* words with basic punctuation and two-digit numbers; or numbers in the first position */
String[] x = {"ep", "episode", "season"};
if (!(isChinese(word) || word.matches("^[a-zA-Z,?!'&]*$") || (!isNaN(word) && word.length() <= 2) || (!isNaN(word) && i == 0))
// || contain(excluded,word.toLowerCase())
|| ((indexOf(x, word.toLowerCase()) > -1) && !isNaN(segSplit[i + 1])) || indexOf(movieKeywords, word.toLowerCase()) > -1) // TODO: more than that, match for stamp too
break;
nameParts.add(word);
}
//Log.v(TAG, "nameParts.size():"+nameParts.size());
if (nameParts.size() == 0)
nameParts.add(seg);
// if (nameParts.size() == 1 && !isNaN(nameParts.get(0))) break; /* Only a number: unacceptable */
ArrayList<String> parts = new ArrayList<String>();
for (String part : nameParts) {
//Log.v(TAG, "part:"+part);
if (part != null && part.length() > 0) {
parts.add(part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase());
}
}
String name = join(" ", parts.toArray(new String[0]));
mInfo.autoSetName(name);
}
isSample = isSample || (segments.length > 1 && !TextUtils.isEmpty(segments[1]) && segments[1].toLowerCase().equals("sample")); /* The directory where the file resides */
boolean canBeMovie = mInfo.getYear() != 0
|| mInfo.getDiskNumber() != 0
|| checkMovieKeywords(join("/", segments));
if (mInfo.hasName()) {
if (mInfo.hasAired()) {
mInfo.setType(MovieNameInfo.TYPE_SERIES);
}
if (mInfo.saneSeason() && mInfo.saneEpisode()) {
mInfo.setType(MovieNameInfo.TYPE_SERIES);
} else if (canBeMovie) {
mInfo.setType(MovieNameInfo.TYPE_MOVIE);
} else if (mInfo.getType() != null && mInfo.getType().equals(MovieNameInfo.TYPE_MOVIE) && mInfo.saneSeason())// Must be deprioritized compared to mapsList
{
mInfo.setType(MovieNameInfo.TYPE_EXTRAS);
} else {
mInfo.setType(MovieNameInfo.TYPE_OTHER);
}
} else {
mInfo.setType(MovieNameInfo.TYPE_OTHER);
}
if (filePath.matches("(.*)1080(p|P)(.*)")) {
mInfo.pushTag("hd");
mInfo.pushTag("1080p");
} else if (filePath.matches("(.*)720(p|P)(.*)")) {
mInfo.pushTag("720p");
} else if (filePath.matches("(.*)480[p|P](.*)")) {
mInfo.pushTag("480p");
}
if (isSample) mInfo.pushTag("sample");
return mInfo;
}
/*
* Test for a year in the name
* */
private final static String MATCH_YEAR_REGEX = "[^\\d](19[0-9][0-9]|20[0-9][0-9])[^\\d]";//匹配4位数字,范围为1900-2099
private void parserYear(String seg) {
String[] numbers = matcher(MATCH_YEAR_REGEX, seg);
if (numbers != null && numbers.length > 1) {
//Log.v(TAG, "year:"+numbers[1]);
mInfo.setYear(Integer.parseInt(numbers[1]));
}
}
/*
* Test for "aired" stamp; if aired stamp is there, we have a series
*/
private final static String MATCH_AIRED_REGEX = "(19[0-9][0-9]|20[0-1][0-9])(\\.|-| )(\\d\\d)(\\.|-| )(\\d\\d)";//匹配4位数字,范围为1900-2099
void parserAired(String seg) {
String[] aired = matcher(MATCH_AIRED_REGEX, Pattern.CASE_INSENSITIVE, seg);
if (aired != null && aired.length > 0) {
//Log.v(TAG, "aired:"+aired[0]);
// String year = aired[1];
// String month = aired[3];
// String day = aired[5];
mInfo.setAired(aired[0]);
}
}
/*
* A typical pattern - "s05e12", "S01E01", etc. ; can be only "E01"
* Those are matched only in the file name
*
* TODO: this stamp may be in another segment (e.g. directory name)
*
* season,episode,
* */
private void parserEpisode(String seg) {
String[] splits = seg.split("\\.| |_");
for (String split : splits) {
//Log.v(TAG, "split:"+split);
String season_regex = "^" + build_or_pattern(SEASON_WORDS) + "(\\d{1,2})";//"S(\\d{1,2})"
String[] seasonMatch = matcher(season_regex, Pattern.CASE_INSENSITIVE, split);
if (seasonMatch != null && seasonMatch.length > 1) {
mInfo.setSeason(Integer.parseInt(seasonMatch[1]));
}
String episode_regex = build_or_pattern(EPISODE_WORDS) + "(\\d{1,2})(?:-(\\d{1,2}))?";//"E(\\d{1,2})"
String[] episodeMatch = matcher(episode_regex, Pattern.CASE_INSENSITIVE, split);
if (episodeMatch != null && episodeMatch.length > 1) {
ArrayList<Integer> episode = new ArrayList<Integer>();
if (episodeMatch[0].contains("-")) {
if (episodeMatch.length == 3) {
for (int i = Integer.parseInt(episodeMatch[1]); i <= Integer.parseInt(episodeMatch[2]); i++) {
episode.add(i);
}
}
} else {
for (int i = 1; i < episodeMatch.length; i++) {
if (episodeMatch[i] != null)
episode.add(Integer.parseInt(episodeMatch[i]));
}
}
mInfo.setEpisode(episode);
}
String[] xStampMatch = matcher("(\\d\\d?)x(\\d\\d?)", Pattern.CASE_INSENSITIVE, split);
}
String[] fullMatch = matcher("^([a-zA-Z0-9,-?!'& ]*) S(\\d{1,2})E(\\d{2})", seg.replace("\\.| |;|_", " "));
//if (TextUtils.isEmpty(mInfo.getName()) && meta.season && meta.episode && fullMatch && fullMatch[1]) meta.name = fullMatch[1];
}
private String[] matcher(String regex, String input) {
return matcher(regex, Pattern.CASE_INSENSITIVE, input);
}
private String[] matcher(String regex, int flag, String input) {
Pattern pattern = Pattern.compile(regex, flag);
Matcher matcher = pattern.matcher(input);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
//Log.v(TAG, "matcher.groupCount():"+matcher.groupCount());
for (int i = 0; i <= matcher.groupCount(); i++) {
list.add(matcher.group(i));
//Log.v(TAG, "matcher.group("+i+"):"+matcher.group(i));
}
//Log.v(TAG, "list:"+list.size());
// list.add(matcher.group());
// //Log.v(TAG, "matcher.group():"+matcher.group());
}
return list.toArray(new String[0]);
}
private static String[] reverse(String[] Array) {
String[] new_array = new String[Array.length];
for (int i = 0; i < Array.length; i++) {
// 反转后数组的第一个元素等于源数组的最后一个元素:
new_array[i] = Array[Array.length - i - 1];
}
return new_array;
}
private static String[] slice(String[] Array, int start, int end) {
if (end >= Array.length - 1) end = Array.length - 1;
if (start < 0) start = 0;
int length = end - start + 1;
String[] new_array = new String[length];
for (int i = 0; i < length; i++) {
// 反转后数组的第一个元素等于源数组的最后一个元素:
new_array[i] = Array[i]; //????
}
return new_array;
}
public static String join(String join, String[] strAry) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < strAry.length; i++) {
if (i == (strAry.length - 1)) {
sb.append(strAry[i]);
} else {
sb.append(strAry[i]).append(join);
}
}
return new String(sb);
}
public static boolean isNaN(String num) {
if (!TextUtils.isEmpty(num) && TextUtils.isDigitsOnly(num)) {
return false;
}
return true;
}
public static boolean isChinese(String word) {
if (word == null)
return false;
for (char c : word.toCharArray()) {
if (c >= 0x4E00 && c <= 0x9FA5) // 根据字节码判断
return true;// 有一个中文字符就返回
}
return false;
}
public static boolean isOnlyChinese(String word) {
if (word == null)
return false;
for (char c : word.toCharArray()) {
if (c >= 0x4E00 && c <= 0x9FA5) // 根据字节码判断
continue;
else
return false;
}
return true;
}
public static boolean contain(String[] array, String str) {
if (array == null || array.length == 0) return false;
List<String> list = Arrays.asList(array);
return list.contains(str);
}
public static int indexOf(String[] array, String str) {
if (array == null || array.length == 0) return -1;
List<String> list = Arrays.asList(array);
return list.indexOf(str);
}
public static boolean checkMovieKeywords(String str) {
if (str == null || str.length() == 0) return false;
for (String keyWord : movieKeywords) {
if (str.toLowerCase().indexOf(keyWord) > -1) {
return true;
}
}
return false;
}
private static String build_or_pattern(String[]... patterns) {
StringBuilder result = new StringBuilder();
for (String[] strings : patterns) {
for (String string : strings) {
if (result.length() == 0) {
result.append("(?");
result.append(":");
} else {
result.append("|");
}
result.append(StringUtils.escapeExprSpecialWord(string));
// result.append(string);
//result.append(String.format("(?:%s)",string));
}
}
result.append(")");
if (result.length() == 0) return null;
return result.toString();
}
}
| SammieLeung/VideoNameParser | src/main/java/com/firefly/videonameparser/VideoNameParser.java |
214,198 | import be.kdg.seizoenen.*;
import java.util.Random;
/**
* @author Kristiaan Behiels
* @version 1.0 21/10/13
*/
public class TestSeizoenen {
public static void main(String[] args) {
Seizoen[] seizoenen = {
new Lente(), new Zomer(), new Herfst(), new Winter()
};
for (Seizoen seizoen : seizoenen) {
System.out.println(seizoen.getBegin());
}
System.out.println();
System.out.println("Random:");
Random random = new Random();
for (Seizoen seizoen : seizoenen) {
int index = random.nextInt(4);
System.out.println(seizoenen[index].getBegin());
}
}
}
/*
In 2014 begint de lente op 20 maart
In 2014 begint de zomer op 21 juni
In 2014 begint de herfst op 23 september
In 2014 begint de winter op 21 december
Random:
In 2014 begint de lente op 20 maart
In 2014 begint de herfst op 23 september
In 2014 begint de herfst op 23 september
In 2014 begint de winter op 21 december
*/ | gvdhaege/KdG | Java Programming/Deel 2/W1 - Overerving/Oefeningen/Oplossingen/Seizoenen/src/TestSeizoenen.java |
214,199 | package be.kdg.seizoenen;
/**
* @author Kristiaan Behiels
* @version 1.0 21/10/13
*/
public class Winter extends Seizoen {
private int jaar = 2014;
private String begin = "21 december";
public Winter() {
}
public Winter(int jaar, String begin) {
this.jaar = jaar;
this.begin = begin;
}
@Override
public String getBegin() {
return "In " + jaar + " begint de winter op " + begin;
}
}
| gvdhaege/KdG | Java Programming/Deel 2/W1 - Overerving/Oefeningen/Oplossingen/Seizoenen/src/be/kdg/seizoenen/Winter.java |
214,200 | package be.kdg;
import be.kdg.seizoenen.*;
import java.util.Random;
/**
* @author Kristiaan Behiels
* @version 1.0 21/10/13
*/
public class TestSeizoenen {
public static void main(String[] args) {
Seizoen[] seizoenen = {
new Lente(), new Zomer(), new Herfst(), new Winter()
};
for (Seizoen seizoen : seizoenen) {
System.out.println(seizoen.getBegin());
}
System.out.println();
System.out.println("Random:");
Random random = new Random();
for (Seizoen seizoen : seizoenen) {
int index = random.nextInt(4);
System.out.println(seizoenen[index].getBegin());
}
}
}
/*
In 2014 begint de lente op 20 maart
In 2014 begint de zomer op 21 juni
In 2014 begint de herfst op 23 september
In 2014 begint de winter op 21 december
Random:
In 2014 begint de lente op 20 maart
In 2014 begint de herfst op 23 september
In 2014 begint de herfst op 23 september
In 2014 begint de winter op 21 december
*/ | gvdhaege/KdG | Java Programming/Deel 2/W1 - Overerving/Oefeningen/Oplossingen/Seizoenen/src/be/kdg/TestSeizoenen.java |
214,201 | package be.kdg.seizoenen;
/**
* @author Kristiaan Behiels
* @version 1.0 21/10/13
*/
public class Herfst extends Seizoen {
private int jaar = 2014;
private String begin = "23 september";
public Herfst() {
}
public Herfst(int jaar, String begin) {
this.jaar = jaar;
this.begin = begin;
}
@Override
public String getBegin() {
return "In " + jaar + " begint de herfst op " + begin;
}
}
| gvdhaege/KdG | Java Programming/Deel 2/W1 - Overerving/Oefeningen/Oplossingen/Seizoenen/src/be/kdg/seizoenen/Herfst.java |
214,208 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.07.21 at 10:40:57 AM CEST
//
package nl.vpro.domain.npo.projectm.metadata.v3_2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="srid" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element ref="{}titel"/>
* <element ref="{}lexico_titel" minOccurs="0"/>
* <element ref="{}bron" minOccurs="0"/>
* <element ref="{}orti" minOccurs="0"/>
* <element name="start_jaar" type="{http://www.w3.org/2001/XMLSchema}gYear" minOccurs="0"/>
* <element name="seizoen" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{}lcod" minOccurs="0"/>
* <element ref="{}icon" minOccurs="0"/>
* <element ref="{}inhl" minOccurs="0"/>
* <element ref="{}genre" minOccurs="0"/>
* <element ref="{}subgenre" minOccurs="0"/>
* <element ref="{}psrt" minOccurs="0"/>
* <element ref="{}mail" minOccurs="0"/>
* <element ref="{}webs" minOccurs="0"/>
* <element ref="{}twitteraccount" minOccurs="0"/>
* <element ref="{}twitterhashtag" minOccurs="0"/>
* <element ref="{}omroepen" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"srid",
"titel",
"lexicoTitel",
"bron",
"orti",
"startJaar",
"seizoen",
"lcod",
"icon",
"inhl",
"genre",
"subgenre",
"psrt",
"mail",
"webs",
"twitteraccount",
"twitterhashtag",
"omroepen"
})
@XmlRootElement(name = "serie")
public class Serie {
@XmlElement(required = true)
protected String srid;
@XmlElement(required = true)
protected String titel;
@XmlElement(name = "lexico_titel")
protected String lexicoTitel;
protected String bron;
protected String orti;
@XmlElement(name = "start_jaar")
@XmlSchemaType(name = "gYear")
protected XMLGregorianCalendar startJaar;
protected String seizoen;
protected String lcod;
@XmlSchemaType(name = "anyURI")
protected String icon;
protected String inhl;
protected String genre;
protected String subgenre;
protected String psrt;
protected String mail;
@XmlSchemaType(name = "anyURI")
protected String webs;
protected String twitteraccount;
protected String twitterhashtag;
protected Omroepen omroepen;
/**
* Gets the value of the srid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrid() {
return srid;
}
/**
* Sets the value of the srid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrid(String value) {
this.srid = value;
}
/**
* Gets the value of the titel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitel() {
return titel;
}
/**
* Sets the value of the titel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitel(String value) {
this.titel = value;
}
/**
* Gets the value of the lexicoTitel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLexicoTitel() {
return lexicoTitel;
}
/**
* Sets the value of the lexicoTitel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLexicoTitel(String value) {
this.lexicoTitel = value;
}
/**
* Gets the value of the bron property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBron() {
return bron;
}
/**
* Sets the value of the bron property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBron(String value) {
this.bron = value;
}
/**
* Gets the value of the orti property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrti() {
return orti;
}
/**
* Sets the value of the orti property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrti(String value) {
this.orti = value;
}
/**
* Gets the value of the startJaar property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartJaar() {
return startJaar;
}
/**
* Sets the value of the startJaar property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartJaar(XMLGregorianCalendar value) {
this.startJaar = value;
}
/**
* Gets the value of the seizoen property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSeizoen() {
return seizoen;
}
/**
* Sets the value of the seizoen property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSeizoen(String value) {
this.seizoen = value;
}
/**
* Gets the value of the lcod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLcod() {
return lcod;
}
/**
* Sets the value of the lcod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLcod(String value) {
this.lcod = value;
}
/**
* Gets the value of the icon property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIcon() {
return icon;
}
/**
* Sets the value of the icon property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIcon(String value) {
this.icon = value;
}
/**
* Gets the value of the inhl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInhl() {
return inhl;
}
/**
* Sets the value of the inhl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInhl(String value) {
this.inhl = value;
}
/**
* Gets the value of the genre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGenre() {
return genre;
}
/**
* Sets the value of the genre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGenre(String value) {
this.genre = value;
}
/**
* Gets the value of the subgenre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubgenre() {
return subgenre;
}
/**
* Sets the value of the subgenre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubgenre(String value) {
this.subgenre = value;
}
/**
* Gets the value of the psrt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPsrt() {
return psrt;
}
/**
* Sets the value of the psrt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPsrt(String value) {
this.psrt = value;
}
/**
* Gets the value of the mail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMail() {
return mail;
}
/**
* Sets the value of the mail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMail(String value) {
this.mail = value;
}
/**
* Gets the value of the webs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWebs() {
return webs;
}
/**
* Sets the value of the webs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWebs(String value) {
this.webs = value;
}
/**
* Gets the value of the twitteraccount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitteraccount() {
return twitteraccount;
}
/**
* Sets the value of the twitteraccount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitteraccount(String value) {
this.twitteraccount = value;
}
/**
* Gets the value of the twitterhashtag property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwitterhashtag() {
return twitterhashtag;
}
/**
* Sets the value of the twitterhashtag property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwitterhashtag(String value) {
this.twitterhashtag = value;
}
/**
* Gets the value of the omroepen property.
*
* @return
* possible object is
* {@link Omroepen }
*
*/
public Omroepen getOmroepen() {
return omroepen;
}
/**
* Sets the value of the omroepen property.
*
* @param value
* allowed object is
* {@link Omroepen }
*
*/
public void setOmroepen(Omroepen value) {
this.omroepen = value;
}
}
| mihxil/poms-shared | media-projectm/src/main/java/nl/vpro/domain/npo/projectm/metadata/v3_2/Serie.java |
214,209 | /*
* Copyright (C) 2010 Licensed under the Apache License, Version 2.0
* VPRO The Netherlands
*/
package nl.vpro.domain.media;
import java.lang.reflect.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlType;
import org.checkerframework.checker.nullness.qual.NonNull;
import nl.vpro.i18n.Displayable;
/**
* This class provides a combined view on all program and group types and their
* configuration options. Both program and groups have a type property, but there
* is now way to add this property to their abstract super class while providing two
* implementations of a generic super type.
*/
@XmlEnum
@XmlType(name = "mediaTypeEnum")
public enum MediaType implements Displayable {
/**
* The abstract type denoting every possible media type
*/
MEDIA(MediaObject.class) {
@Override
public String getDisplayName() {
return "Alle media";
}
@Override
public SubMediaType getSubType() {
return null;
}
@Override
public String getUrnPrefix() {
return null;
}
@Override
public List<SubMediaType> getSubTypes () {
return
Stream.concat(
Stream.concat(
Arrays.stream(ProgramType.values()),
Arrays.stream(GroupType.values())
),
Arrays.stream(SegmentType.values())
).collect(Collectors.toList());
}
},
/**
* The abstract type denoting every type of a {@link Program}
*/
PROGRAM(Program.class) {
@Override
public String getDisplayName() {
return "Programma";
}
@Override
public ProgramType getSubType() {
return null;
}
@Override
public String getUrnPrefix() {
return ProgramType.URN_PREFIX;
}
@Override
public List<SubMediaType> getSubTypes() {
return Arrays.asList(ProgramType.values());
}
@Override
public boolean hasSegments() {
return true;
}
},
BROADCAST(Program.class) {
@Override
public String getDisplayName() {
return "Uitzending";
}
@Override
public ProgramType getSubType() {
return ProgramType.BROADCAST;
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public boolean requiresGenre() {
return true;
}
},
CLIP(Program.class) {
@Override
public String getDisplayName() {
return "Clip";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.CLIP;
}
@Override
public boolean requiresGenre() {
return true;
}
},
STRAND(Program.class) {
@Override
public String getDisplayName() {
return "Koepelprogramma";
}
@Override
public ProgramType getSubType() {
return ProgramType.STRAND;
}
},
TRAILER(Program.class) {
@Override
public String getDisplayName() {
return "Trailer";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.TRAILER;
}
@Override
public boolean requiresGenre() {
return true;
}
},
MOVIE(Program.class) {
@Override
public String getDisplayName() {
return "Film";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.MOVIE;
}
},
/**
* The abstract type denoting every type of a {@link Group}
*/
GROUP(Group.class) {
@Override
public String getDisplayName() {
return "Groep";
}
@Override
public GroupType getSubType() {
return null;
}
@Override
public String getUrnPrefix() {
return GroupType.URN_PREFIX;
}
@Override
public List<SubMediaType> getSubTypes() {
return Arrays.asList(GroupType.values());
}
},
SERIES(Group.class) {
@Override
public String getDisplayName() {
return "Serie";
}
@Override
public GroupType getSubType() {
return GroupType.SERIES;
}
@Override
public boolean hasOrdering() {
return true;
}
},
SEASON(Group.class) {
@Override
public String getDisplayName() {
return "Seizoen";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.SEASON;
}
},
UMBRELLA(Group.class) {
@Override
public String getDisplayName() {
return "Paraplu";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.UMBRELLA;
}
},
// MSE-1453
@Deprecated
ARCHIVE(Group.class) {
@Override
public String getDisplayName() {
return "Archief";
}
@Override
public GroupType getSubType() {
return GroupType.ARCHIVE;
}
},
COLLECTION(Group.class) {
@Override
public String getDisplayName() {
return "Collectie";
}
@Override
public GroupType getSubType() {
return GroupType.COLLECTION;
}
},
PLAYLIST(Group.class) {
@Override
public String getDisplayName() {
return "Speellijst";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.PLAYLIST;
}
},
ALBUM(Group.class) {
@Override
public String getDisplayName() {
return "Album";
}
@Override
public boolean hasOrdering() {
return true;
}
@Override
public GroupType getSubType() {
return GroupType.ALBUM;
}
},
SEGMENT(Segment.class) {
@Override
public String getDisplayName() {
return "Segment";
}
@Override
public SegmentType getSubType() {
return SegmentType.SEGMENT;
}
},
/*
COLLECTION {
@Override
public String getDisplayName() {
return "Collectie";
}
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
COMPILATION {
@Override
public String getDisplayName() {
return "Compilatie";
}
@Override
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
CONCEPT {
@Override
public String getDisplayName() {
return "Concept";
}
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
SHOW {
@Override
public String getDisplayName() {
return "Show";
}
public String getMediaClass() {
return Group.class.getSimpleName();
}
},
*/
TRACK(Program.class) {
@Override
public String getDisplayName() {
return "Track";
}
@Override
public MediaType[] allowedEpisodeOfTypes() {
return new MediaType[]{MediaType.ALBUM};
}
@Override
public ProgramType getSubType() {
return ProgramType.TRACK;
}
},
VISUALRADIO(Program.class) {
@Override
public String getDisplayName() {
return "Visual radio";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.VISUALRADIO;
}
},
VISUALRADIOSEGMENT(Segment.class) {
@Override
public String getDisplayName() {
return "Visual radio segment";
}
@Override
public SegmentType getSubType() {
return SegmentType.VISUALRADIOSEGMENT;
}
},
/**
* The abstract type denoting every type of a {@link Segment}
*/
SEGMENTTYPE(Segment.class) {
@Override
public String getDisplayName() {
return "Segments";
}
@Override
public SegmentType getSubType() {
return null;
}
@Override
public String getUrnPrefix() {
return SegmentType.URN_PREFIX;
}
@Override
public List<SubMediaType> getSubTypes() {
return Arrays.asList(SegmentType.values());
}
},
/**
* @since 2.1
*/
RECORDING(Program.class) {
@Override
public String getDisplayName() {
return "Opname";
}
@Override
public boolean hasSegments() {
return true;
}
@Override
public ProgramType getSubType() {
return ProgramType.RECORDING;
}
},
PROMO(Program.class) {
@Override
public String getDisplayName() {
return "Promo";
}
@Override
public ProgramType getSubType() {
return ProgramType.PROMO;
}
};
/**
*
*/
public static final Set<MediaType> VISUALS = Set.of(VISUALRADIO, VISUALRADIOSEGMENT);
@Override
public String toString() {
return getDisplayName();
}
final Class<? extends MediaObject> clazz;
final Constructor<?> constructor;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Optional<Method> setType;
MediaType(Class<? extends MediaObject> clazz) {
this.clazz = clazz;
if (Modifier.isAbstract(this.clazz.getModifiers())) {
this.constructor = null;
} else {
try {
this.constructor = clazz.getDeclaredConstructor();
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
}
}
protected void setType(MediaObject o) throws InvocationTargetException, IllegalAccessException {
if (this.setType == null){
Method st;
if (this.getSubType() != null) {
try {
st = clazz.getMethod("setType", this.getSubType().getClass());
} catch (NoSuchMethodException nsme) {
st = null;
}
} else {
st = null;
}
this.setType = Optional.ofNullable(st);
}
if (this.setType.isPresent()) {
this.setType.get().invoke(o, getSubType());
}
}
/**
* @see #defaultAVType()
* @see #setType(MediaObject)
*/
public final MediaObject getMediaInstance() {
try {
if (constructor == null) {
throw new IllegalStateException("Not possible to make instances of " + this);
}
MediaObject o = (MediaObject) constructor.newInstance();
setType(o);
o.setAVType(defaultAVType());
return o;
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new RuntimeException("For " + this + " ", e);
}
}
public final String getMediaClass() {
return getMediaObjectClass().getSimpleName();
}
public final Class<? extends MediaObject> getMediaObjectClass() {
return clazz;
}
public boolean hasSegments() {
return false;
}
/**
* @since 7.8
*/
public boolean canBeCreatedByNormalUsers() {
return ! isAbstract() && getSubType().canBeCreatedByNormalUsers();
}
/**
* @since 5.11
*/
public boolean canHaveScheduleEvents() {
return ! isAbstract() && getSubType().canHaveScheduleEvents();
}
public final boolean hasEpisodeOf() {
return ! isAbstract() && getSubType().hasEpisodeOf();
}
public MediaType[] preferredEpisodeOfTypes() {
if(!hasEpisodeOf()) {
return new MediaType[]{};
}
return new MediaType[]{MediaType.SERIES, MediaType.SEASON};
}
public MediaType[] allowedEpisodeOfTypes() {
if(!hasEpisodeOf()) {
return new MediaType[0];
}
return new MediaType[]{MediaType.SERIES, MediaType.SEASON};
}
public final boolean canContainEpisodes() {
return getSubType() != null && getSubType().canContainEpisodes();
}
public MediaType[] preferredEpisodeTypes() {
if(!canContainEpisodes()) {
return new MediaType[0];
}
return new MediaType[]{MediaType.BROADCAST};
}
public MediaType[] allowedEpisodeTypes() {
if(!canContainEpisodes()) {
return new MediaType[0];
}
return new MediaType[]{MediaType.BROADCAST};
}
public boolean hasMemberOf() {
return true;
}
public MediaType[] preferredMemberOfTypes() {
if(!hasMemberOf()) {
return new MediaType[]{};
}
return new MediaType[]{MediaType.MEDIA};
}
public MediaType[] allowedMemberOfTypes() {
return preferredMemberOfTypes();
}
public boolean hasMembers() {
return true;
}
public MediaType[] preferredMemberTypes() {
if(!hasMembers()) {
return new MediaType[]{};
}
return new MediaType[]{MediaType.MEDIA};
}
public MediaType[] allowedMemberTypes() {
return preferredMemberTypes();
}
public boolean hasOrdering() {
return false;
}
public abstract SubMediaType getSubType();
public List<SubMediaType> getSubTypes() {
return getSubType() != null ? Collections.singletonList(getSubType()) : null;
}
public static MediaType of(String type) {
return type == null ? null : valueOf(type.toUpperCase());
}
@NonNull
public static MediaType getMediaType(MediaObject media) {
SubMediaType type = media.getType();
if (type != null) {
return type.getMediaType();
}
if (media instanceof Program) {
return MediaType.PROGRAM;
}
if (media instanceof Group) {
return MediaType.GROUP;
}
if (media instanceof Segment) {
return MediaType.SEGMENT;
}
return MediaType.MEDIA;
}
/**
* @deprecated
*/
@Deprecated
public MediaObject createInstance() {
return getMediaInstance();
}
/**
* @since 7.6
*/
public String getUrnPrefix() {
return getSubType().getUrnPrefix();
}
/**
* @since 7.8
*/
public boolean isAbstract() {
return getSubType() == null;
}
public boolean requiresGenre() {
return false;
}
/**
* @since 7.8
*/
public AVType defaultAVType() {
if (AVType.MIXED.test(clazz)) {
return AVType.MIXED;
}
if (AVType.VIDEO.test(clazz)) {
return AVType.VIDEO;
}
return AVType.AUDIO;
}
/**
* Returns all 'leaf' mediaTypes. That are all non-{@link #isAbstract()abstract} instances, that actually have a certain {@link #getSubType()}.
* @since 5.8
*/
public static MediaType[] leafValues() {
return Arrays.stream(values())
.filter(f -> ! f.isAbstract())
.toArray(MediaType[]::new);
}
/**
* @since 5.8
*/
public static MediaType[] leafValues(Class<? extends MediaObject> clazz) {
return Arrays.stream(values()).filter(f -> f.getSubType() != null).filter(t -> clazz.isAssignableFrom(t.getMediaObjectClass())).toArray(MediaType[]::new);
}
/**
* @since 2.1
*/
@NonNull
public static Set<Class<? extends MediaObject>> getClasses(Collection<MediaType> types) {
if(types == null) {
return Set.of(Program.class, Group.class, Segment.class);
} else {
Set<Class<? extends MediaObject>> c = new HashSet<>();
for(MediaType type : types) {
c.add(type.getMediaObjectClass());
}
return Collections.unmodifiableSet(c);
}
}
/**
* @since 2.1
*/
public static Collection<MediaType> valuesOf(String types) {
List<MediaType> result = new ArrayList<>();
for(String s : types.split(",")) {
result.add(valueOf(s.trim()));
}
return result;
}
}
| npo-poms/poms-shared | media-domain/src/main/java/nl/vpro/domain/media/MediaType.java |
214,216 | package net.querz.mcaselector.cli;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CLIJFX {
public static void launch() throws ExecutionException, InterruptedException {
CompletableFuture<Void> started = new CompletableFuture<>();
javafx.application.Platform.startup(() -> started.complete(null));
started.get();
}
public static boolean hasJavaFX() {
try {
Class.forName("javafx.scene.paint.Color");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
| Querz/mcaselector | src/main/java/net/querz/mcaselector/cli/CLIJFX.java |
214,217 | package com.lijf.bigdata;
import com.lijf.bigdata.common.combine.CombineFile;
import com.lijf.bigdata.common.combine.dto.FileCombineDto;
import com.lijf.bigdata.common.combine.factory.FileCombineFactory;
import org.apache.spark.sql.SparkSession;
import java.io.IOException;
/**
* @author lijf
* @date 2019/8/21 16:03
* @desc
*/
public class Main {
public static void main(String[] args) throws IOException {
SparkSession spark = getSparkSession();
FileCombineDto fileCombineDto = new FileCombineDto();
//最终的合并文件数
fileCombineDto.setPartNum(8);
// 要合并的目录
fileCombineDto.setFileDir("/apps/hive/warehouse/mlg.db/tb_browser_user_action_20190823/dt=2019-08-21");
// 文件格式
fileCombineDto.setType("text");
CombineFile combine = FileCombineFactory.getCombine(fileCombineDto);
combine.combine(fileCombineDto, spark);
}
private static SparkSession getSparkSession() {
return SparkSession
.builder()
.master("local[2]")
.appName(Main.class.getSimpleName())
.enableHiveSupport()
.getOrCreate();
}
}
| lijufeng2016/bigdata-tools | src/main/java/com/lijf/bigdata/Main.java |
214,218 | /*
ZZKeyBindings0.java
*
* Copyright (c) 1999, Ted Nelson and Tuomas Lukka
*
* You may use and distribute under the terms of either the GNU Lesser
* General Public License, either version 2 of the license or,
* at your choice, any later version. Alternatively, you may use and
* distribute under the terms of the XPL.
*
* See the LICENSE.lgpl and LICENSE.xpl files for the specific terms of
* the licenses.
*
* This software 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 README
* file for more details.
*
*/
/*
* Written by Tuomas Lukka
*/
package org.gzigzag;
import java.awt.event.*;
/** A very simple keybindings class which is hardcoded for the cursor keys.
* Does nothing else. OBSOLETE.
*/
/*
public class ZZKeyBindings0 implements ZZKeyBindings {
public static final String rcsid = "$Id: ZZKeyBindings0.java,v 1.7 2000/09/19 10:31:58 ajk Exp $";
ZZCell current;
public void perform(KeyEvent k, ZZView v) {
// XXX Hardcoded - should update automatically from the structure..
switch(k.getKeyCode()) {
case k.VK_UP: v.move(0,-1); break;
case k.VK_DOWN: v.move(0,1); break;
case k.VK_LEFT: v.move(-1,0); break;
case k.VK_RIGHT: v.move(1,0); break;
}
}
}
*/
class LIJFSELFJLISEFJLSEFSF { }
| deepstupid/gzigzag | gzigzag/Java/ZZKeyBindings0.java |
214,219 | package saros.intellij.filesystem;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Path;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import saros.filesystem.IFile;
import saros.filesystem.IResource;
import saros.intellij.runtime.FilesystemRunner;
/** Intellij implementation of the Saros file interface. */
public class IntellijFile extends AbstractIntellijResource implements IFile {
private static final Logger log = Logger.getLogger(IntellijFile.class);
public IntellijFile(@NotNull IntellijReferencePoint referencePoint, @NotNull Path relativePath) {
super(referencePoint, relativePath);
}
@Override
public boolean exists() {
if (!referencePoint.exists()) {
return false;
}
VirtualFile virtualFile = getVirtualFile();
return existsInternal(virtualFile);
}
/**
* Returns whether the given virtual file is not <code>null</code>, exists, and is a file.
*
* @param virtualFile the virtual file to check
* @return whether the given virtual file is not <code>null</code>, exists, and is a file
*/
private static boolean existsInternal(@Nullable VirtualFile virtualFile) {
return virtualFile != null && virtualFile.exists() && !virtualFile.isDirectory();
}
@Override
public void delete() throws IOException {
FilesystemRunner.runWriteAction(
(ThrowableComputable<Void, IOException>)
() -> {
deleteInternal();
return null;
},
ModalityState.defaultModalityState());
}
/**
* Deletes the file in the filesystem.
*
* @throws IOException if the resource is a directory or the deletion failed
* @see VirtualFile#delete(Object)
*/
private void deleteInternal() throws IOException {
VirtualFile virtualFile = getVirtualFile();
if (virtualFile == null || !virtualFile.exists()) {
log.debug("Ignoring file deletion request for " + this + " as it does not exist.");
return;
}
if (virtualFile.isDirectory()) {
throw new IOException("Failed to delete " + this + " as it is not a file");
}
virtualFile.delete(this);
}
@Override
@Nullable
public String getCharset() throws IOException {
VirtualFile virtualFile = getVirtualFile();
if (!existsInternal(virtualFile)) {
throw new FileNotFoundException(
"Could not obtain charset for " + this + " as it does not exist or is not valid");
}
return virtualFile.getCharset().name();
}
@Override
public void setCharset(@Nullable String charset) throws IOException {
if (charset == null) {
return;
}
VirtualFile virtualFile = getVirtualFile();
if (!existsInternal(virtualFile)) {
throw new FileNotFoundException(
"Could not set charset for " + this + " as it does not exist or is not valid");
}
virtualFile.setCharset(Charset.forName(charset));
}
@Override
@NotNull
public InputStream getContents() throws IOException {
VirtualFile virtualFile = getVirtualFile();
if (!existsInternal(virtualFile)) {
throw new FileNotFoundException(
"Could not obtain contents for " + this + " as it does not exist or is not valid");
}
return virtualFile.getInputStream();
}
@Override
public void setContents(@Nullable InputStream input) throws IOException {
FilesystemRunner.runWriteAction(
(ThrowableComputable<Void, IOException>)
() -> {
setContentsInternal(input);
return null;
},
ModalityState.defaultModalityState());
}
/**
* Sets the content of the file.
*
* @param input an input stream to write into the file
* @throws IOException if the file does not exist or could not be written to
* @see IOUtils#copy(InputStream, OutputStream)
*/
private void setContentsInternal(@Nullable InputStream input) throws IOException {
VirtualFile virtualFile = getVirtualFile();
if (!existsInternal(virtualFile)) {
throw new FileNotFoundException(
"Could not set contents of " + this + " as it does not exist or is not valid.");
}
try (InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input;
OutputStream out = virtualFile.getOutputStream(this)) {
IOUtils.copy(in, out);
}
}
@Override
public void create(@Nullable InputStream input) throws IOException {
FilesystemRunner.runWriteAction(
(ThrowableComputable<Void, IOException>)
() -> {
createInternal(input);
return null;
},
ModalityState.defaultModalityState());
}
/**
* Creates this file in the local filesystem with the given content.
*
* @param input an input stream to write into the file
* @throws FileAlreadyExistsException if a resource with the same name already exists
* @throws FileNotFoundException if the parent directory of this file does not exist
*/
private void createInternal(@Nullable InputStream input) throws IOException {
IResource parent = getParent();
VirtualFile parentFile = referencePoint.findVirtualFile(parent.getReferencePointRelativePath());
if (parentFile == null || !parentFile.exists()) {
throw new FileNotFoundException(
"Could not create "
+ this
+ " as its parent folder "
+ parent
+ " does not exist or is not valid");
}
VirtualFile virtualFile = parentFile.findChild(getName());
if (virtualFile != null && virtualFile.exists()) {
throw new FileAlreadyExistsException(
"Could not create "
+ this
+ " as a resource with the same name already exists: "
+ virtualFile);
}
parentFile.createChildData(this, getName());
if (input != null) {
setContents(input);
}
}
@Override
public long getSize() throws IOException {
VirtualFile virtualFile = getVirtualFile();
if (!existsInternal(virtualFile)) {
throw new FileNotFoundException(
"Could not obtain the size for " + this + " as it does not exist or is not valid");
}
return virtualFile.getLength();
}
}
| saros-project/saros | intellij/src/saros/intellij/filesystem/IntellijFile.java |
214,221 | /*
* Copyright 2020 FormDev Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.formdev.flatlaf.testing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.beans.*;
import java.net.URL;
import javax.swing.*;
import com.formdev.flatlaf.FlatLaf;
import com.formdev.flatlaf.util.MultiResolutionImageSupport;
import com.formdev.flatlaf.util.SystemInfo;
import com.formdev.flatlaf.util.UIScale;
import net.miginfocom.swing.*;
/**
* @author Karl Tauber
*/
public class FlatDisabledIconsTest
extends FlatTestPanel
{
public static void main( String[] args ) {
SwingUtilities.invokeLater( () -> {
FlatTestFrame frame = FlatTestFrame.create( args, "FlatDisabledIconsTest" );
frame.showFrame( FlatDisabledIconsTest::new );
} );
}
FlatDisabledIconsTest() {
initComponents();
RGBImageFilter plasticLafFilter = new PlasticRGBGrayFilter();
RGBImageFilter intellijTextFilter = new IntelliJGrayFilter( 20, 0, 100 );
RGBImageFilter netbeansFilter = new NetBeansDisabledButtonFilter();
for( Component c : enabledToolBar.getComponents() ) {
AbstractButton b = (AbstractButton) c;
Icon icon = b.getIcon();
JToggleButton cb = new JToggleButton( icon );
cb.setEnabled( false );
currentLafToolBar.add( cb );
basicLafToolBar.add( new FilterButton( null, icon ) );
metalLafToolBar.add( new FilterButton( null, icon ) );
plasticToolBar.add( new FilterButton( plasticLafFilter, icon ) );
intellijTextToolBar.add( new FilterButton( intellijTextFilter, icon ) );
intellijLightToolBar.add( new FilterButton( null, icon ) );
intellijDarkToolBar.add( new FilterButton( null, icon ) );
netbeansToolBar.add( new FilterButton( netbeansFilter, icon ) );
}
Icon zipIcon = zipButton.getIcon();
JToggleButton cb = new JToggleButton( zipIcon );
cb.setEnabled( false );
zipToolBar.add( cb );
zipToolBar.add( new FilterButton( null, zipIcon ) );
zipToolBar.add( new FilterButton( null, zipIcon ) );
zipToolBar.add( new FilterButton( plasticLafFilter, zipIcon ) );
zipToolBar.add( new FilterButton( intellijTextFilter, zipIcon ) );
zipToolBar.add( new FilterButton( null, zipIcon ) );
zipToolBar.add( new FilterButton( null, zipIcon ) );
zipToolBar.add( new FilterButton( netbeansFilter, zipIcon ) );
basicLafReset();
metalLafReset();
intelliJTextFilterController.defaultBrightness = 20;
intelliJTextFilterController.defaultContrast = 0;
intelliJTextFilterController.reset();
// values from intellijlaf.properties
intelliJLightFilterController.defaultBrightness = 33;
intelliJLightFilterController.defaultContrast = -35;
intelliJLightFilterController.reset();
// values from darcula.properties
intelliJDarkFilterController.defaultBrightness = -70;
intelliJDarkFilterController.defaultContrast = -70;
intelliJDarkFilterController.reset();
toolBars = new JToolBar[] {
enabledToolBar,
currentLafToolBar,
basicLafToolBar,
metalLafToolBar,
plasticToolBar,
intellijTextToolBar,
intellijLightToolBar,
intellijDarkToolBar,
netbeansToolBar
};
}
private void selectedChanged() {
boolean armed = selectedCheckBox.isSelected();
for( Component c : getComponents() ) {
if( c instanceof JToolBar ) {
for( Component c2 : ((JToolBar)c).getComponents() ) {
if( c2 instanceof JToggleButton )
((JToggleButton)c2).getModel().setSelected( armed );
}
}
}
}
private final JToolBar[] toolBars;
private Icon[] oldIcons;
private static final String[] COLOR_NAMES = {
"Actions.Red",
"Actions.Yellow",
"Actions.Green",
"Actions.Blue",
"Actions.Grey",
"Actions.GreyInline",
"Objects.Grey",
"Objects.Blue",
"Objects.Green",
"Objects.Yellow",
"Objects.YellowDark",
"Objects.Purple",
"Objects.Pink",
"Objects.Red",
"Objects.RedStatus",
"Objects.GreenAndroid",
"Objects.BlackText",
"", // black
};
private void paletteIconsChanged() {
if( paletteIconsCheckBox.isSelected() ) {
oldIcons = new Icon[COLOR_NAMES.length];
for( int i = 0; i < COLOR_NAMES.length; i++ )
oldIcons[i] = ((JToggleButton)enabledToolBar.getComponent( i )).getIcon();
for( int i = 0; i < COLOR_NAMES.length; i++ ) {
ColorIcon icon = new ColorIcon( UIManager.getColor( COLOR_NAMES[i] ) );
for( JToolBar toolBar : toolBars )
((JToggleButton)toolBar.getComponent( i )).setIcon( icon );
}
} else if( oldIcons != null ){
for( int i = 0; i < COLOR_NAMES.length; i++ ) {
for( JToolBar toolBar : toolBars )
((JToggleButton)toolBar.getComponent( i )).setIcon( oldIcons[i] );
}
}
}
private void basicLafChanged() {
boolean brighter = basicLafBrighterCheckBox.isSelected();
int percent = basicLafPercentSlider.getValue();
basicLafPercentValue.setText( String.valueOf( percent ) );
RGBImageFilter filter = new GrayFilter( brighter, percent );
updateFilter( basicLafToolBar, 2, filter );
}
private void basicLafReset() {
basicLafBrighterCheckBox.setSelected( true );
basicLafPercentSlider.setValue( 50 );
basicLafChanged();
}
private void metalLafChanged() {
int min = metalLafMinSlider.getValue();
int max = metalLafMaxSlider.getValue();
metalLafMinValue.setText( String.valueOf( min ) );
metalLafMaxValue.setText( String.valueOf( max ) );
RGBImageFilter filter = new MetalDisabledButtonImageFilter( min, max );
updateFilter( metalLafToolBar, 3, filter );
}
private void metalLafReset() {
metalLafMinSlider.setValue( 180 );
metalLafMaxSlider.setValue( 215 );
metalLafChanged();
}
private void intelliJTextFilterChanged(PropertyChangeEvent e) {
updateFilter( intellijTextToolBar, 5, (RGBImageFilter) e.getNewValue() );
}
private void intelliJLightFilterChanged(PropertyChangeEvent e) {
updateFilter( intellijLightToolBar, 6, (RGBImageFilter) e.getNewValue() );
}
private void intelliJDarkFilterChanged(PropertyChangeEvent e) {
updateFilter( intellijDarkToolBar, 7, (RGBImageFilter) e.getNewValue() );
}
private void updateFilter( JToolBar toolBar, int zipIndex, RGBImageFilter filter ) {
for( Component c : toolBar.getComponents() )
((FilterButton)c).setFilter( filter );
((FilterButton)zipToolBar.getComponent( zipIndex )).setFilter( filter );
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
JLabel enabledLabel = new JLabel();
enabledToolBar = new JToolBar();
JToggleButton button1 = new JToggleButton();
JToggleButton button2 = new JToggleButton();
JToggleButton button3 = new JToggleButton();
JToggleButton button4 = new JToggleButton();
JToggleButton button5 = new JToggleButton();
JToggleButton button6 = new JToggleButton();
JToggleButton button7 = new JToggleButton();
JToggleButton button8 = new JToggleButton();
JToggleButton button9 = new JToggleButton();
JToggleButton button10 = new JToggleButton();
JToggleButton button11 = new JToggleButton();
JToggleButton button12 = new JToggleButton();
JToggleButton button13 = new JToggleButton();
JToggleButton button14 = new JToggleButton();
JToggleButton button15 = new JToggleButton();
JToggleButton button16 = new JToggleButton();
JToggleButton button17 = new JToggleButton();
JToggleButton button18 = new JToggleButton();
JLabel currentLabel = new JLabel();
currentLafToolBar = new JToolBar();
JLabel basicLafLabel = new JLabel();
basicLafToolBar = new JToolBar();
JPanel panel2 = new JPanel();
basicLafBrighterCheckBox = new JCheckBox();
JLabel basicLafPercentLabel = new JLabel();
basicLafPercentSlider = new JSlider();
basicLafPercentValue = new JLabel();
JButton basicLafResetButton = new JButton();
JLabel metalLafLabel = new JLabel();
metalLafToolBar = new JToolBar();
JPanel panel4 = new JPanel();
JLabel metalLafMinLabel = new JLabel();
metalLafMinSlider = new JSlider();
metalLafMinValue = new JLabel();
JButton metalLafResetButton = new JButton();
JLabel metalLafMaxLabel = new JLabel();
metalLafMaxSlider = new JSlider();
metalLafMaxValue = new JLabel();
JLabel plasticLabel = new JLabel();
plasticToolBar = new JToolBar();
JLabel intellijTextLabel = new JLabel();
intellijTextToolBar = new JToolBar();
intelliJTextFilterController = new FlatDisabledIconsTest.IntelliJFilterController();
JLabel intellijLightLabel = new JLabel();
intellijLightToolBar = new JToolBar();
intelliJLightFilterController = new FlatDisabledIconsTest.IntelliJFilterController();
JLabel intellijDarkLabel = new JLabel();
intellijDarkToolBar = new JToolBar();
intelliJDarkFilterController = new FlatDisabledIconsTest.IntelliJFilterController();
JLabel netbeansLabel = new JLabel();
netbeansToolBar = new JToolBar();
zipToolBar = new JToolBar();
zipButton = new JToggleButton();
selectedCheckBox = new JCheckBox();
paletteIconsCheckBox = new JCheckBox();
//======== this ========
setLayout(new MigLayout(
"ltr,insets dialog,hidemode 3",
// columns
"[fill]" +
"[fill]" +
"[left]" +
"[fill]",
// rows
"[]" +
"[]" +
"[center]" +
"[center]" +
"[center]" +
"[center]" +
"[center]" +
"[center]" +
"[center]para" +
"[center]" +
"[]"));
//---- enabledLabel ----
enabledLabel.setText("enabled");
add(enabledLabel, "cell 0 0");
//======== enabledToolBar ========
{
//---- button1 ----
button1.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/netbeans-cut24.gif")));
enabledToolBar.add(button1);
//---- button2 ----
button2.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/netbeans-copy24.gif")));
enabledToolBar.add(button2);
//---- button3 ----
button3.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/netbeans-paste24.gif")));
enabledToolBar.add(button3);
//---- button4 ----
button4.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/netbeans-undo24.gif")));
enabledToolBar.add(button4);
//---- button5 ----
button5.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/netbeans-redo24.gif")));
enabledToolBar.add(button5);
//---- button6 ----
button6.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/netbeans-find24.gif")));
enabledToolBar.add(button6);
enabledToolBar.add(button7);
enabledToolBar.add(button8);
enabledToolBar.add(button9);
enabledToolBar.add(button10);
enabledToolBar.add(button11);
enabledToolBar.add(button12);
enabledToolBar.add(button13);
enabledToolBar.add(button14);
enabledToolBar.add(button15);
enabledToolBar.add(button16);
enabledToolBar.add(button17);
enabledToolBar.add(button18);
}
add(enabledToolBar, "cell 1 0");
//---- currentLabel ----
currentLabel.setText("current LaF");
add(currentLabel, "cell 0 1");
add(currentLafToolBar, "cell 1 1");
//---- basicLafLabel ----
basicLafLabel.setText("Basic LaF");
add(basicLafLabel, "cell 0 2");
add(basicLafToolBar, "cell 1 2");
//======== panel2 ========
{
panel2.setLayout(new MigLayout(
"insets 0,hidemode 3,gap 0 0",
// columns
"[60,fill]" +
"[fill]" +
"[25,right]rel" +
"[fill]",
// rows
"[center]" +
"[center]"));
//---- basicLafBrighterCheckBox ----
basicLafBrighterCheckBox.setText("brighter");
basicLafBrighterCheckBox.addActionListener(e -> basicLafChanged());
panel2.add(basicLafBrighterCheckBox, "cell 0 0 2 1,alignx left,growx 0");
//---- basicLafPercentLabel ----
basicLafPercentLabel.setText("Percent");
panel2.add(basicLafPercentLabel, "cell 0 1");
//---- basicLafPercentSlider ----
basicLafPercentSlider.setToolTipText("Percent");
basicLafPercentSlider.setValue(0);
basicLafPercentSlider.addChangeListener(e -> basicLafChanged());
panel2.add(basicLafPercentSlider, "cell 1 1");
//---- basicLafPercentValue ----
basicLafPercentValue.setText("000");
panel2.add(basicLafPercentValue, "cell 2 1");
//---- basicLafResetButton ----
basicLafResetButton.setText("Reset");
basicLafResetButton.addActionListener(e -> basicLafReset());
panel2.add(basicLafResetButton, "cell 3 0 1 2");
}
add(panel2, "cell 2 2");
//---- metalLafLabel ----
metalLafLabel.setText("Metal LaF");
add(metalLafLabel, "cell 0 3");
add(metalLafToolBar, "cell 1 3");
//======== panel4 ========
{
panel4.setLayout(new MigLayout(
"insets 0,hidemode 3,gap 0 0",
// columns
"[60,fill]" +
"[fill]" +
"[25,right]rel" +
"[fill]",
// rows
"[center]" +
"[center]"));
//---- metalLafMinLabel ----
metalLafMinLabel.setText("Min");
panel4.add(metalLafMinLabel, "cell 0 0");
//---- metalLafMinSlider ----
metalLafMinSlider.setMaximum(255);
metalLafMinSlider.addChangeListener(e -> metalLafChanged());
panel4.add(metalLafMinSlider, "cell 1 0");
//---- metalLafMinValue ----
metalLafMinValue.setText("000");
panel4.add(metalLafMinValue, "cell 2 0");
//---- metalLafResetButton ----
metalLafResetButton.setText("Reset");
metalLafResetButton.addActionListener(e -> metalLafReset());
panel4.add(metalLafResetButton, "cell 3 0 1 2");
//---- metalLafMaxLabel ----
metalLafMaxLabel.setText("Max");
panel4.add(metalLafMaxLabel, "cell 0 1");
//---- metalLafMaxSlider ----
metalLafMaxSlider.setMaximum(255);
metalLafMaxSlider.addChangeListener(e -> metalLafChanged());
panel4.add(metalLafMaxSlider, "cell 1 1");
//---- metalLafMaxValue ----
metalLafMaxValue.setText("000");
panel4.add(metalLafMaxValue, "cell 2 1");
}
add(panel4, "cell 2 3");
//---- plasticLabel ----
plasticLabel.setText("Plastic LaF");
add(plasticLabel, "cell 0 4");
add(plasticToolBar, "cell 1 4");
//---- intellijTextLabel ----
intellijTextLabel.setText("IntelliJ text");
add(intellijTextLabel, "cell 0 5");
add(intellijTextToolBar, "cell 1 5");
//---- intelliJTextFilterController ----
intelliJTextFilterController.addPropertyChangeListener("filter", e -> intelliJTextFilterChanged(e));
add(intelliJTextFilterController, "cell 2 5");
//---- intellijLightLabel ----
intellijLightLabel.setText("IntelliJ light");
add(intellijLightLabel, "cell 0 6");
add(intellijLightToolBar, "cell 1 6");
//---- intelliJLightFilterController ----
intelliJLightFilterController.addPropertyChangeListener("filter", e -> intelliJLightFilterChanged(e));
add(intelliJLightFilterController, "cell 2 6");
//---- intellijDarkLabel ----
intellijDarkLabel.setText("IntelliJ dark");
add(intellijDarkLabel, "cell 0 7");
add(intellijDarkToolBar, "cell 1 7");
//---- intelliJDarkFilterController ----
intelliJDarkFilterController.addPropertyChangeListener("filter", e -> intelliJDarkFilterChanged(e));
add(intelliJDarkFilterController, "cell 2 7");
//---- netbeansLabel ----
netbeansLabel.setText("NetBeans");
add(netbeansLabel, "cell 0 8");
add(netbeansToolBar, "cell 1 8");
//======== zipToolBar ========
{
//---- zipButton ----
zipButton.setIcon(new ImageIcon(getClass().getResource("/com/formdev/flatlaf/testing/disabled_icons_test/zip128.png")));
zipToolBar.add(zipButton);
}
add(zipToolBar, "cell 1 9 3 1");
//---- selectedCheckBox ----
selectedCheckBox.setText("selected");
selectedCheckBox.addActionListener(e -> selectedChanged());
add(selectedCheckBox, "cell 0 10");
//---- paletteIconsCheckBox ----
paletteIconsCheckBox.setText("palette icons");
paletteIconsCheckBox.addActionListener(e -> paletteIconsChanged());
add(paletteIconsCheckBox, "cell 1 10,alignx left,growx 0");
// JFormDesigner - End of component initialization //GEN-END:initComponents
button7.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-menu-cut.png",
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-menu-cut_dark.png" ) );
button8.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-menu-paste.png",
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-menu-paste_dark.png" ) );
button9.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-show.png",
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-show_dark.png" ) );
button10.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-showReadAccess.png",
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-showReadAccess_dark.png" ) );
button11.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-showWriteAccess.png",
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-showWriteAccess_dark.png" ) );
button12.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-search.png",
"/com/formdev/flatlaf/testing/disabled_icons_test/intellij-search_dark.png" ) );
button13.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]",
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]" ) );
button14.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]",
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]" ) );
button15.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]",
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]" ) );
button16.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]",
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]" ) );
button17.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]",
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]" ) );
button18.setIcon( new LightOrDarkIcon(
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]",
"/com/formdev/flatlaf/testing/disabled_icons_test/[email protected]" ) );
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JToolBar enabledToolBar;
private JToolBar currentLafToolBar;
private JToolBar basicLafToolBar;
private JCheckBox basicLafBrighterCheckBox;
private JSlider basicLafPercentSlider;
private JLabel basicLafPercentValue;
private JToolBar metalLafToolBar;
private JSlider metalLafMinSlider;
private JLabel metalLafMinValue;
private JSlider metalLafMaxSlider;
private JLabel metalLafMaxValue;
private JToolBar plasticToolBar;
private JToolBar intellijTextToolBar;
private FlatDisabledIconsTest.IntelliJFilterController intelliJTextFilterController;
private JToolBar intellijLightToolBar;
private FlatDisabledIconsTest.IntelliJFilterController intelliJLightFilterController;
private JToolBar intellijDarkToolBar;
private FlatDisabledIconsTest.IntelliJFilterController intelliJDarkFilterController;
private JToolBar netbeansToolBar;
private JToolBar zipToolBar;
private JToggleButton zipButton;
private JCheckBox selectedCheckBox;
private JCheckBox paletteIconsCheckBox;
// JFormDesigner - End of variables declaration //GEN-END:variables
//---- class LightOrDarkIcon ----------------------------------------------
private static class LightOrDarkIcon
extends ImageIcon
{
private final ImageIcon lightIcon;
private final ImageIcon darkIcon;
LightOrDarkIcon( String lightIconName, String darkIconName ) {
this.lightIcon = loadIcon( lightIconName );
this.darkIcon = loadIcon( darkIconName );
}
private static ImageIcon loadIcon( String iconName ) {
ImageIcon icon = new ImageIcon( LightOrDarkIcon.class.getResource( iconName ) );
if( SystemInfo.isMacOS || !MultiResolutionImageSupport.isAvailable() || !iconName.endsWith( ".png" ) )
return icon;
String iconName2x = iconName.replace( ".png", "@2x.png" );
URL url2x = LightOrDarkIcon.class.getResource( iconName2x );
if( url2x == null )
return icon;
ImageIcon icon2x = new ImageIcon( url2x );
return new ImageIcon( MultiResolutionImageSupport.create( 0, icon.getImage(), icon2x.getImage() ) );
}
private ImageIcon getCurrentIcon() {
return FlatLaf.isLafDark() ? darkIcon : lightIcon;
}
@Override
public int getIconWidth() {
return getCurrentIcon().getIconWidth();
}
@Override
public int getIconHeight() {
return getCurrentIcon().getIconHeight();
}
@Override
public synchronized void paintIcon( Component c, Graphics g, int x, int y ) {
getCurrentIcon().paintIcon( c, g, x, y );
}
@Override
public Image getImage() {
return getCurrentIcon().getImage();
}
}
//---- class ColorIcon ----------------------------------------------------
private static class ColorIcon
extends ImageIcon
{
ColorIcon( Color color ) {
super( createColorImage( color ) );
}
private static Image createColorImage( Color color ) {
if( color == null )
color = Color.black;
BufferedImage image = new BufferedImage( UIScale.scale( 16 ), UIScale.scale( 16 ), BufferedImage.TYPE_INT_ARGB );
Graphics2D g = image.createGraphics();
try {
g.setColor( color );
g.fillRect( UIScale.scale( 1 ), UIScale.scale( 2 ), UIScale.scale( 14 ), UIScale.scale( 12 ) );
} finally {
g.dispose();
}
return image;
}
}
//---- class IntelliJFilterController ------------------------------------
private static class IntelliJFilterController
extends JPanel
{
int defaultBrightness;
int defaultContrast;
private IntelliJFilterController() {
initComponents();
}
private void changed() {
int brightness = intellijBrightnessSlider.getValue();
int contrast = intellijContrastSlider.getValue();
intellijBrightnessValue.setText( String.valueOf( brightness ) );
intellijContrastValue.setText( String.valueOf( contrast ) );
RGBImageFilter filter = new IntelliJGrayFilter( brightness, contrast, 100 );
firePropertyChange( "filter", null, filter );
}
private void reset() {
intellijBrightnessSlider.setValue( defaultBrightness );
intellijContrastSlider.setValue( defaultContrast );
changed();
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
JLabel intellijBrightnessLabel = new JLabel();
intellijBrightnessSlider = new JSlider();
intellijBrightnessValue = new JLabel();
JLabel intellijContrastLabel = new JLabel();
intellijContrastSlider = new JSlider();
intellijContrastValue = new JLabel();
JButton intellijLightResetButton = new JButton();
//======== this ========
setLayout(new MigLayout(
"insets 0,hidemode 3,gap 0 0",
// columns
"[60,fill]" +
"[fill]" +
"[25,right]rel" +
"[fill]",
// rows
"[center]" +
"[center]"));
//---- intellijBrightnessLabel ----
intellijBrightnessLabel.setText("Brightness");
add(intellijBrightnessLabel, "cell 0 0");
//---- intellijBrightnessSlider ----
intellijBrightnessSlider.setMinimum(-100);
intellijBrightnessSlider.addChangeListener(e -> changed());
add(intellijBrightnessSlider, "cell 1 0");
//---- intellijBrightnessValue ----
intellijBrightnessValue.setText("000");
add(intellijBrightnessValue, "cell 2 0");
//---- intellijContrastLabel ----
intellijContrastLabel.setText("Contrast");
add(intellijContrastLabel, "cell 0 1");
//---- intellijContrastSlider ----
intellijContrastSlider.setMinimum(-100);
intellijContrastSlider.addChangeListener(e -> changed());
add(intellijContrastSlider, "cell 1 1");
//---- intellijContrastValue ----
intellijContrastValue.setText("-000");
add(intellijContrastValue, "cell 2 1");
//---- intellijLightResetButton ----
intellijLightResetButton.setText("Reset");
intellijLightResetButton.addActionListener(e -> reset());
add(intellijLightResetButton, "cell 3 0 1 2");
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JSlider intellijBrightnessSlider;
private JLabel intellijBrightnessValue;
private JSlider intellijContrastSlider;
private JLabel intellijContrastValue;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
//---- class FilterButton -------------------------------------------------
private static class FilterButton
extends JToggleButton
{
private RGBImageFilter filter;
FilterButton( RGBImageFilter filter, Icon icon ) {
this.filter = filter;
setEnabled( false );
setIcon( icon );
}
@Override
public void setIcon( Icon defaultIcon ) {
super.setIcon( defaultIcon );
if( filter != null )
updateDisabledIcon();
}
void setFilter( RGBImageFilter filter ) {
this.filter = filter;
updateDisabledIcon();
}
@Override
public void updateUI() {
super.updateUI();
updateDisabledIcon();
}
private void updateDisabledIcon() {
setDisabledIcon( createDisabledIcon( getIcon() ) );
}
protected Icon createDisabledIcon( Icon icon ) {
if( !(icon instanceof ImageIcon) )
return null;
Image image = ((ImageIcon) icon).getImage();
ImageProducer producer = new FilteredImageSource( image.getSource(), filter );
Image disabledImage = Toolkit.getDefaultToolkit().createImage( producer );
return new ImageIcon( disabledImage );
}
}
//---- class PlasticRGBGrayFilter -----------------------------------------
// from https://github.com/openjdk/jdk/blob/6bab0f539fba8fb441697846347597b4a0ade428/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalUtils.java#L415-L434
// license https://github.com/openjdk/jdk/blob/master/LICENSE
private static class MetalDisabledButtonImageFilter
extends RGBImageFilter
{
private final float min;
private final float factor;
MetalDisabledButtonImageFilter(int min, int max) {
canFilterIndexColorModel = true;
this.min = min;
this.factor = (max - min) / 255f;
}
@Override
public int filterRGB(int x, int y, int rgb) {
// Coefficients are from the sRGB color space:
int gray = Math.min(255, (int)(((0.2125f * ((rgb >> 16) & 0xFF)) +
(0.7154f * ((rgb >> 8) & 0xFF)) +
(0.0721f * (rgb & 0xFF)) + .5f) * factor + min));
return (rgb & 0xff000000) | (gray << 16) | (gray << 8) |
(gray << 0);
}
}
//---- class PlasticRGBGrayFilter -----------------------------------------
// from https://github.com/JFormDesigner/swing-jgoodies-looks/blob/master/src/main/java/com/jgoodies/looks/common/RGBGrayFilter.java
// license https://github.com/JFormDesigner/swing-jgoodies-looks/blob/master/LICENSE.txt
private static final class PlasticRGBGrayFilter
extends RGBImageFilter
{
private PlasticRGBGrayFilter() {
canFilterIndexColorModel = true;
}
@Override
public int filterRGB(int x, int y, int rgb) {
// Find the average of red, green, and blue.
float avg = (((rgb >> 16) & 0xff) / 255f +
((rgb >> 8) & 0xff) / 255f +
(rgb & 0xff) / 255f) / 3;
// Pull out the alpha channel.
float alpha = (((rgb >> 24) & 0xff) / 255f);
// Calculate the average.
// Sun's formula: Math.min(1.0f, (1f - avg) / (100.0f / 35.0f) + avg);
// The following formula uses fewer operations and hence is faster.
avg = Math.min(1.0f, 0.35f + 0.65f * avg);
// Convert back into RGB.
return (int) (alpha * 255f) << 24 |
(int) (avg * 255f) << 16 |
(int) (avg * 255f) << 8 |
(int) (avg * 255f);
}
}
//---- class IntelliJGrayFilter -------------------------------------------
// from https://github.com/JetBrains/intellij-community/blob/3840eab54746f5c4f301bb3ac78f00a980b5fd6e/platform/util/ui/src/com/intellij/util/ui/UIUtil.java#L253-L347
// license https://github.com/JetBrains/intellij-community/blob/master/LICENSE.txt
private static class IntelliJGrayFilter
extends RGBImageFilter
{
private float brightness;
private float contrast;
private int alpha;
private int origContrast;
private int origBrightness;
/**
* @param brightness in range [-100..100] where 0 has no effect
* @param contrast in range [-100..100] where 0 has no effect
* @param alpha in range [0..100] where 0 is transparent, 100 has no effect
*/
public IntelliJGrayFilter(int brightness, int contrast, int alpha) {
setBrightness(brightness);
setContrast(contrast);
setAlpha(alpha);
}
private void setBrightness(int brightness) {
origBrightness = Math.max(-100, Math.min(100, brightness));
this.brightness = (float)(Math.pow(origBrightness, 3) / (100f * 100f)); // cubic in [0..100]
}
private void setContrast(int contrast) {
origContrast = Math.max(-100, Math.min(100, contrast));
this.contrast = origContrast / 100f;
}
private void setAlpha(int alpha) {
this.alpha = Math.max(0, Math.min(100, alpha));
}
@Override
public int filterRGB(int x, int y, int rgb) {
// Use NTSC conversion formula.
int gray = (int)(0.30 * (rgb >> 16 & 0xff) +
0.59 * (rgb >> 8 & 0xff) +
0.11 * (rgb & 0xff));
if (brightness >= 0) {
gray = (int)((gray + brightness * 255) / (1 + brightness));
}
else {
gray = (int)(gray / (1 - brightness));
}
if (contrast >= 0) {
if (gray >= 127) {
gray = (int)(gray + (255 - gray) * contrast);
}
else {
gray = (int)(gray - gray * contrast);
}
}
else {
gray = (int)(127 + (gray - 127) * (contrast + 1));
}
int a = ((rgb >> 24) & 0xff) * alpha / 100;
return (a << 24) | (gray << 16) | (gray << 8) | gray;
}
}
//---- NetBeansDisabledButtonFilter ---------------------------------------
// from https://github.com/apache/netbeans/blob/166e2bb491c29f6778223c6e9e16f70664252bce/platform/openide.util.ui/src/org/openide/util/ImageUtilities.java#L1202-L1221
// license https://github.com/apache/netbeans/blob/master/LICENSE
private static class NetBeansDisabledButtonFilter
extends RGBImageFilter
{
NetBeansDisabledButtonFilter() {
canFilterIndexColorModel = true;
}
@Override
public int filterRGB(int x, int y, int rgb) {
// Reduce the color bandwidth in quarter (>> 2) and Shift 0x88.
return (rgb & 0xff000000) + 0x888888 + ((((rgb >> 16) & 0xff) >> 2) << 16) + ((((rgb >> 8) & 0xff) >> 2) << 8) + ((rgb & 0xff) >> 2);
}
}
}
| JFormDesigner/FlatLaf | flatlaf-testing/src/main/java/com/formdev/flatlaf/testing/FlatDisabledIconsTest.java |
214,222 | /*
* Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.misc;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
import jdk.internal.access.SharedSecrets;
public class CDS {
// Must be in sync with cdsConfig.hpp
private static final int IS_DUMPING_ARCHIVE = 1 << 0;
private static final int IS_DUMPING_STATIC_ARCHIVE = 1 << 1;
private static final int IS_LOGGING_LAMBDA_FORM_INVOKERS = 1 << 2;
private static final int IS_USING_ARCHIVE = 1 << 3;
private static final int configStatus = getCDSConfigStatus();
/**
* Should we log the use of lambda form invokers?
*/
public static boolean isLoggingLambdaFormInvokers() {
return (configStatus & IS_LOGGING_LAMBDA_FORM_INVOKERS) != 0;
}
/**
* Is the VM writing to a (static or dynamic) CDS archive.
*/
public static boolean isDumpingArchive() {
return (configStatus & IS_DUMPING_ARCHIVE) != 0;
}
/**
* Is the VM using at least one CDS archive?
*/
public static boolean isUsingArchive() {
return (configStatus & IS_USING_ARCHIVE) != 0;
}
/**
* Is dumping static archive.
*/
public static boolean isDumpingStaticArchive() {
return (configStatus & IS_DUMPING_STATIC_ARCHIVE) != 0;
}
private static native int getCDSConfigStatus();
private static native void logLambdaFormInvoker(String line);
/**
* Initialize archived static fields in the given Class using archived
* values from CDS dump time. Also initialize the classes of objects in
* the archived graph referenced by those fields.
*
* Those static fields remain as uninitialized if there is no mapped CDS
* java heap data or there is any error during initialization of the
* object class in the archived graph.
*/
public static native void initializeFromArchive(Class<?> c);
/**
* Ensure that the native representation of all archived java.lang.Module objects
* are properly restored.
*/
public static native void defineArchivedModules(ClassLoader platformLoader, ClassLoader systemLoader);
/**
* Returns a predictable "random" seed derived from the VM's build ID and version,
* to be used by java.util.ImmutableCollections to ensure that archived
* ImmutableCollections are always sorted the same order for the same VM build.
*/
public static native long getRandomSeedForDumping();
/**
* log lambda form invoker holder, name and method type
*/
public static void logLambdaFormInvoker(String prefix, String holder, String name, String type) {
if (isLoggingLambdaFormInvokers()) {
logLambdaFormInvoker(prefix + " " + holder + " " + name + " " + type);
}
}
/**
* log species
*/
public static void logSpeciesType(String prefix, String cn) {
if (isLoggingLambdaFormInvokers()) {
logLambdaFormInvoker(prefix + " " + cn);
}
}
static final String DIRECT_HOLDER_CLASS_NAME = "java.lang.invoke.DirectMethodHandle$Holder";
static final String DELEGATING_HOLDER_CLASS_NAME = "java.lang.invoke.DelegatingMethodHandle$Holder";
static final String BASIC_FORMS_HOLDER_CLASS_NAME = "java.lang.invoke.LambdaForm$Holder";
static final String INVOKERS_HOLDER_CLASS_NAME = "java.lang.invoke.Invokers$Holder";
private static boolean isValidHolderName(String name) {
return name.equals(DIRECT_HOLDER_CLASS_NAME) ||
name.equals(DELEGATING_HOLDER_CLASS_NAME) ||
name.equals(BASIC_FORMS_HOLDER_CLASS_NAME) ||
name.equals(INVOKERS_HOLDER_CLASS_NAME);
}
private static boolean isBasicTypeChar(char c) {
return "LIJFDV".indexOf(c) >= 0;
}
private static boolean isValidMethodType(String type) {
String[] typeParts = type.split("_");
// check return type (second part)
if (typeParts.length != 2 || typeParts[1].length() != 1
|| !isBasicTypeChar(typeParts[1].charAt(0))) {
return false;
}
// first part
if (!isBasicTypeChar(typeParts[0].charAt(0))) {
return false;
}
for (int i = 1; i < typeParts[0].length(); i++) {
char c = typeParts[0].charAt(i);
if (!isBasicTypeChar(c)) {
if (!(c >= '0' && c <= '9')) {
return false;
}
}
}
return true;
}
// Throw exception on invalid input
private static void validateInputLines(String[] lines) {
for (String s: lines) {
if (!s.startsWith("[LF_RESOLVE]") && !s.startsWith("[SPECIES_RESOLVE]")) {
throw new IllegalArgumentException("Wrong prefix: " + s);
}
String[] parts = s.split(" ");
boolean isLF = s.startsWith("[LF_RESOLVE]");
if (isLF) {
if (parts.length != 4) {
throw new IllegalArgumentException("Incorrect number of items in the line: " + parts.length);
}
if (!isValidHolderName(parts[1])) {
throw new IllegalArgumentException("Invalid holder class name: " + parts[1]);
}
if (!isValidMethodType(parts[3])) {
throw new IllegalArgumentException("Invalid method type: " + parts[3]);
}
} else {
if (parts.length != 2) {
throw new IllegalArgumentException("Incorrect number of items in the line: " + parts.length);
}
}
}
}
/**
* called from vm to generate MethodHandle holder classes
* @return {@code Object[]} if holder classes can be generated.
* @param lines in format of LF_RESOLVE or SPECIES_RESOLVE output
*/
private static Object[] generateLambdaFormHolderClasses(String[] lines) {
Objects.requireNonNull(lines);
validateInputLines(lines);
Stream<String> lineStream = Arrays.stream(lines);
Map<String, byte[]> result = SharedSecrets.getJavaLangInvokeAccess().generateHolderClasses(lineStream);
int size = result.size();
Object[] retArray = new Object[size * 2];
int index = 0;
for (Map.Entry<String, byte[]> entry : result.entrySet()) {
retArray[index++] = entry.getKey();
retArray[index++] = entry.getValue();
};
return retArray;
}
private static native void dumpClassList(String listFileName);
private static native void dumpDynamicArchive(String archiveFileName);
private static String drainOutput(InputStream stream, long pid, String tail, List<String> cmds) {
String fileName = "java_pid" + pid + "_" + tail;
new Thread( ()-> {
try (InputStreamReader isr = new InputStreamReader(stream);
BufferedReader rdr = new BufferedReader(isr);
PrintStream prt = new PrintStream(fileName)) {
prt.println("Command:");
for (String s : cmds) {
prt.print(s + " ");
}
prt.println("");
String line;
while((line = rdr.readLine()) != null) {
prt.println(line);
}
} catch (IOException e) {
throw new RuntimeException("IOException happens during drain stream to file " +
fileName + ": " + e.getMessage());
}}).start();
return fileName;
}
private static String[] excludeFlags = {
"-XX:DumpLoadedClassList=",
"-XX:+RecordDynamicDumpInfo",
"-Xshare:",
"-XX:SharedClassListFile=",
"-XX:SharedArchiveFile=",
"-XX:ArchiveClassesAtExit="};
private static boolean containsExcludedFlags(String testStr) {
for (String e : excludeFlags) {
if (testStr.contains(e)) {
return true;
}
}
return false;
}
/**
* called from jcmd VM.cds to dump static or dynamic shared archive
* @param isStatic true for dump static archive or false for dynnamic archive.
* @param fileName user input archive name, can be null.
* @return The archive name if successfully dumped.
*/
private static String dumpSharedArchive(boolean isStatic, String fileName) throws Exception {
String cwd = new File("").getAbsolutePath(); // current dir used for printing message.
String currentPid = String.valueOf(ProcessHandle.current().pid());
String archiveFileName = fileName != null ? fileName :
"java_pid" + currentPid + (isStatic ? "_static.jsa" : "_dynamic.jsa");
String tempArchiveFileName = archiveFileName + ".temp";
File tempArchiveFile = new File(tempArchiveFileName);
// The operation below may cause exception if the file or its dir is protected.
if (!tempArchiveFile.exists()) {
tempArchiveFile.createNewFile();
}
tempArchiveFile.delete();
if (isStatic) {
String listFileName = archiveFileName + ".classlist";
File listFile = new File(listFileName);
if (listFile.exists()) {
listFile.delete();
}
dumpClassList(listFileName);
String jdkHome = System.getProperty("java.home");
String classPath = System.getProperty("java.class.path");
List<String> cmds = new ArrayList<String>();
cmds.add(jdkHome + File.separator + "bin" + File.separator + "java"); // java
cmds.add("-cp");
cmds.add(classPath);
cmds.add("-Xlog:cds");
cmds.add("-Xshare:dump");
cmds.add("-XX:SharedClassListFile=" + listFileName);
cmds.add("-XX:SharedArchiveFile=" + tempArchiveFileName);
// All runtime args.
String[] vmArgs = VM.getRuntimeArguments();
if (vmArgs != null) {
for (String arg : vmArgs) {
if (arg != null && !containsExcludedFlags(arg)) {
cmds.add(arg);
}
}
}
Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[0]));
// Drain stdout/stderr to files in new threads.
String stdOutFileName = drainOutput(proc.getInputStream(), proc.pid(), "stdout", cmds);
String stdErrFileName = drainOutput(proc.getErrorStream(), proc.pid(), "stderr", cmds);
proc.waitFor();
// done, delete classlist file.
listFile.delete();
// Check if archive has been successfully dumped. We won't reach here if exception happens.
// Throw exception if file is not created.
if (!tempArchiveFile.exists()) {
throw new RuntimeException("Archive file " + tempArchiveFileName +
" is not created, please check stdout file " +
cwd + File.separator + stdOutFileName + " or stderr file " +
cwd + File.separator + stdErrFileName + " for more detail");
}
} else {
dumpDynamicArchive(tempArchiveFileName);
if (!tempArchiveFile.exists()) {
throw new RuntimeException("Archive file " + tempArchiveFileName +
" is not created, please check current working directory " +
cwd + " for process " +
currentPid + " output for more detail");
}
}
// Override the existing archive file
File archiveFile = new File(archiveFileName);
if (archiveFile.exists()) {
archiveFile.delete();
}
if (!tempArchiveFile.renameTo(archiveFile)) {
throw new RuntimeException("Cannot rename temp file " + tempArchiveFileName + " to archive file" + archiveFileName);
}
// Everything goes well, print out the file name.
String archiveFilePath = new File(archiveFileName).getAbsolutePath();
System.out.println("The process was attached by jcmd and dumped a " + (isStatic ? "static" : "dynamic") + " archive " + archiveFilePath);
return archiveFilePath;
}
}
| openjdk/jdk | src/java.base/share/classes/jdk/internal/misc/CDS.java |
214,223 | import android.text.TextUtils;
import com.tencent.common.app.AppInterface;
import com.tencent.mobileqq.audiotrans.AudioTransClientTransInfo.InfoC2SCreateSessionReq;
import com.tencent.mobileqq.audiotrans.AudioTransClientTransInfo.InfoHead;
import com.tencent.mobileqq.audiotrans.AudioTransClientTransInfo.InfoReqBody;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBoolField;
import com.tencent.mobileqq.pb.PBEnumField;
import com.tencent.mobileqq.pb.PBRepeatField;
import com.tencent.mobileqq.pb.PBStringField;
import com.tencent.mobileqq.pb.PBUInt32Field;
import com.tencent.qphone.base.remote.ToServiceMsg;
import com.tencent.qphone.base.util.QLog;
import java.util.Arrays;
import java.util.Random;
import mqq.app.MobileQQ;
public abstract class ijg
extends accg
{
static long lr;
private boolean RG;
private ijh.a a = ijh.a.a();
private ijf b = ijf.a();
private Random mRandom = new Random();
public ijg(AppInterface paramAppInterface)
{
super(paramAppInterface);
}
abstract void D(long paramLong1, long paramLong2);
public void a(String paramString1, String paramString2, long paramLong, String paramString3)
{
ToServiceMsg localToServiceMsg = createToServiceMsg(paramString2);
AudioTransClientTransInfo.InfoHead localInfoHead = new AudioTransClientTransInfo.InfoHead();
Object localObject2 = localInfoHead.str_session_id;
if (TextUtils.isEmpty(paramString3)) {}
for (Object localObject1 = "0";; localObject1 = paramString3)
{
((PBStringField)localObject2).set((String)localObject1);
localInfoHead.str_uin.set(this.mApp.getCurrentAccountUin());
localInfoHead.uint32_seq.set((int)paramLong);
localInfoHead.enum_body_type.set(1);
localObject1 = new AudioTransClientTransInfo.InfoReqBody();
localObject2 = new AudioTransClientTransInfo.InfoC2SCreateSessionReq();
String str = ay();
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).enum_business_type.set(1);
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).rpt_member_list.set(Arrays.asList(new String[] { localInfoHead.str_uin.get(), str }));
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).enum_business_direction.set(4);
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).enum_term.set(4);
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).uint32_client_ver.set(getVersion());
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).enum_net_type.set(getNetType());
((AudioTransClientTransInfo.InfoC2SCreateSessionReq)localObject2).bool_translate.set(ts());
((AudioTransClientTransInfo.InfoReqBody)localObject1).msg_create_session_req.set((MessageMicro)localObject2);
localObject2 = this.b;
localToServiceMsg.putWupBuffer(ijf.g(localInfoHead.toByteArray(), ((AudioTransClientTransInfo.InfoReqBody)localObject1).toByteArray()));
boolean bool = aqiw.isNetworkAvailable(this.mApp.getApplication().getApplicationContext());
if (bool) {
sendPbReq(localToServiceMsg);
}
long l1 = System.currentTimeMillis();
long l2 = lr;
lr = l1;
QLog.w("AudioTransClientInfoHandler", 1, "sendCmdToService, cmd[" + paramString2 + "], seq[" + paramLong + "], sessionID[" + paramString3 + "], isNetworkAvailable[" + bool + "], from[" + paramString1 + "], sendInterval[" + (l1 - l2) + "]");
return;
}
}
public void anc()
{
this.RG = false;
}
abstract String ay();
abstract int getNetType();
public String getSessionId()
{
return String.valueOf(this.a.mSessionId);
}
abstract int getVersion();
abstract boolean isSender();
protected Class<? extends acci> observerClass()
{
return null;
}
/* Error */
public void onReceive(ToServiceMsg paramToServiceMsg, com.tencent.qphone.base.remote.FromServiceMsg paramFromServiceMsg, Object paramObject)
{
// Byte code:
// 0: aload_2
// 1: invokevirtual 276 com/tencent/qphone/base/remote/FromServiceMsg:isSuccess ()Z
// 4: ifeq +641 -> 645
// 7: aload_0
// 8: getfield 32 ijg:b Lijf;
// 11: astore_1
// 12: aload_2
// 13: invokevirtual 279 com/tencent/qphone/base/remote/FromServiceMsg:getWupBuffer ()[B
// 16: invokestatic 282 ijf:a ([B)Lijf$a;
// 19: astore_2
// 20: aload_2
// 21: getfield 288 ijf$a:head [B
// 24: astore_1
// 25: aload_2
// 26: getfield 291 ijf$a:body [B
// 29: astore_2
// 30: new 49 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead
// 33: dup
// 34: invokespecial 50 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead:<init> ()V
// 37: astore_3
// 38: aload_3
// 39: aload_1
// 40: invokevirtual 295 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead:mergeFrom ([B)Lcom/tencent/mobileqq/pb/MessageMicro;
// 43: checkcast 49 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead
// 46: astore_1
// 47: aload_1
// 48: getfield 85 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead:uint32_seq Lcom/tencent/mobileqq/pb/PBUInt32Field;
// 51: invokevirtual 297 com/tencent/mobileqq/pb/PBUInt32Field:get ()I
// 54: istore 4
// 56: aload_1
// 57: getfield 300 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead:uint32_error_no Lcom/tencent/mobileqq/pb/PBUInt32Field;
// 60: invokevirtual 303 com/tencent/mobileqq/pb/PBUInt32Field:has ()Z
// 63: ifeq +572 -> 635
// 66: new 305 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoRspBody
// 69: dup
// 70: invokespecial 306 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoRspBody:<init> ()V
// 73: aload_2
// 74: invokevirtual 307 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoRspBody:mergeFrom ([B)Lcom/tencent/mobileqq/pb/MessageMicro;
// 77: checkcast 305 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoRspBody
// 80: astore_2
// 81: aload_1
// 82: getfield 300 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead:uint32_error_no Lcom/tencent/mobileqq/pb/PBUInt32Field;
// 85: invokevirtual 297 com/tencent/mobileqq/pb/PBUInt32Field:get ()I
// 88: ifne +462 -> 550
// 91: aload_2
// 92: getfield 311 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoRspBody:msg_create_session_rsp Lcom/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SCreateSessionRsp;
// 95: invokevirtual 316 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SCreateSessionRsp:get ()Lcom/tencent/mobileqq/pb/MessageMicro;
// 98: checkcast 313 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SCreateSessionRsp
// 101: astore_2
// 102: aload_0
// 103: getfield 39 ijg:a Lijh$a;
// 106: aload_2
// 107: getfield 319 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SCreateSessionRsp:enum_channel_type Lcom/tencent/mobileqq/pb/PBEnumField;
// 110: invokevirtual 320 com/tencent/mobileqq/pb/PBEnumField:get ()I
// 113: putfield 324 ijh$a:mChannelType I
// 116: aload_0
// 117: getfield 39 ijg:a Lijh$a;
// 120: aload_2
// 121: getfield 327 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SCreateSessionRsp:enum_translator_type Lcom/tencent/mobileqq/pb/PBEnumField;
// 124: invokevirtual 320 com/tencent/mobileqq/pb/PBEnumField:get ()I
// 127: putfield 330 ijh$a:anH I
// 130: aload_0
// 131: getfield 39 ijg:a Lijh$a;
// 134: aload_1
// 135: getfield 54 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoHead:str_session_id Lcom/tencent/mobileqq/pb/PBStringField;
// 138: invokevirtual 118 com/tencent/mobileqq/pb/PBStringField:get ()Ljava/lang/String;
// 141: invokestatic 335 java/lang/Long:valueOf (Ljava/lang/String;)Ljava/lang/Long;
// 144: invokevirtual 338 java/lang/Long:longValue ()J
// 147: putfield 256 ijh$a:mSessionId J
// 150: aload_2
// 151: getfield 342 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SCreateSessionRsp:rpt_msg_interface_list Lcom/tencent/mobileqq/pb/PBRepeatMessageField;
// 154: invokevirtual 347 com/tencent/mobileqq/pb/PBRepeatMessageField:get ()Ljava/util/List;
// 157: astore_1
// 158: aload_0
// 159: getfield 39 ijg:a Lijh$a;
// 162: new 349 java/util/ArrayList
// 165: dup
// 166: invokespecial 350 java/util/ArrayList:<init> ()V
// 169: putfield 354 ijh$a:eM Ljava/util/List;
// 172: aload_0
// 173: invokevirtual 356 ijg:isSender ()Z
// 176: istore 5
// 178: ldc 213
// 180: iconst_1
// 181: new 215 java/lang/StringBuilder
// 184: dup
// 185: invokespecial 216 java/lang/StringBuilder:<init> ()V
// 188: ldc_w 358
// 191: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 194: iload 4
// 196: invokevirtual 361 java/lang/StringBuilder:append (I)Ljava/lang/StringBuilder;
// 199: ldc_w 363
// 202: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 205: aload_0
// 206: getfield 39 ijg:a Lijh$a;
// 209: invokevirtual 366 java/lang/StringBuilder:append (Ljava/lang/Object;)Ljava/lang/StringBuilder;
// 212: ldc_w 368
// 215: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 218: iload 5
// 220: invokevirtual 234 java/lang/StringBuilder:append (Z)Ljava/lang/StringBuilder;
// 223: ldc_w 370
// 226: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 229: aload_0
// 230: getfield 252 ijg:RG Z
// 233: invokevirtual 234 java/lang/StringBuilder:append (Z)Ljava/lang/StringBuilder;
// 236: ldc 240
// 238: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 241: invokevirtual 243 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 244: invokestatic 249 com/tencent/qphone/base/util/QLog:w (Ljava/lang/String;ILjava/lang/String;)V
// 247: aload_1
// 248: invokeinterface 376 1 0
// 253: astore_1
// 254: aload_1
// 255: invokeinterface 381 1 0
// 260: ifeq +233 -> 493
// 263: aload_1
// 264: invokeinterface 385 1 0
// 269: checkcast 387 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr
// 272: astore_2
// 273: new 389 com/tencent/av/business/handler/NetAddr
// 276: dup
// 277: invokespecial 390 com/tencent/av/business/handler/NetAddr:<init> ()V
// 280: astore_3
// 281: aload_3
// 282: aload_2
// 283: getfield 394 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:fixed32_IP Lcom/tencent/mobileqq/pb/PBFixed32Field;
// 286: invokevirtual 397 com/tencent/mobileqq/pb/PBFixed32Field:get ()I
// 289: putfield 399 com/tencent/av/business/handler/NetAddr:fixed32_IP I
// 292: aload_3
// 293: aload_2
// 294: getfield 402 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:uint32_port Lcom/tencent/mobileqq/pb/PBUInt32Field;
// 297: invokevirtual 297 com/tencent/mobileqq/pb/PBUInt32Field:get ()I
// 300: putfield 404 com/tencent/av/business/handler/NetAddr:uint32_port I
// 303: aload_3
// 304: aload_2
// 305: getfield 407 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:enum_proto_type Lcom/tencent/mobileqq/pb/PBEnumField;
// 308: invokevirtual 320 com/tencent/mobileqq/pb/PBEnumField:get ()I
// 311: putfield 409 com/tencent/av/business/handler/NetAddr:enum_proto_type I
// 314: aload_3
// 315: aload_2
// 316: getfield 412 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:fixed32_inner_IP Lcom/tencent/mobileqq/pb/PBFixed32Field;
// 319: invokevirtual 397 com/tencent/mobileqq/pb/PBFixed32Field:get ()I
// 322: putfield 414 com/tencent/av/business/handler/NetAddr:fixed32_inner_IP I
// 325: aload_0
// 326: getfield 39 ijg:a Lijh$a;
// 329: getfield 354 ijh$a:eM Ljava/util/List;
// 332: aload_3
// 333: invokeinterface 418 2 0
// 338: pop
// 339: new 215 java/lang/StringBuilder
// 342: dup
// 343: invokespecial 216 java/lang/StringBuilder:<init> ()V
// 346: ldc_w 420
// 349: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 352: astore_3
// 353: aload_0
// 354: getfield 32 ijg:b Lijf;
// 357: astore 6
// 359: aload_3
// 360: aload_2
// 361: getfield 394 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:fixed32_IP Lcom/tencent/mobileqq/pb/PBFixed32Field;
// 364: invokevirtual 397 com/tencent/mobileqq/pb/PBFixed32Field:get ()I
// 367: invokestatic 424 ijf:aH (I)Ljava/lang/String;
// 370: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 373: ldc_w 426
// 376: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 379: aload_2
// 380: getfield 402 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:uint32_port Lcom/tencent/mobileqq/pb/PBUInt32Field;
// 383: invokevirtual 297 com/tencent/mobileqq/pb/PBUInt32Field:get ()I
// 386: invokevirtual 361 java/lang/StringBuilder:append (I)Ljava/lang/StringBuilder;
// 389: ldc_w 426
// 392: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 395: aload_2
// 396: getfield 407 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:enum_proto_type Lcom/tencent/mobileqq/pb/PBEnumField;
// 399: invokevirtual 320 com/tencent/mobileqq/pb/PBEnumField:get ()I
// 402: invokevirtual 361 java/lang/StringBuilder:append (I)Ljava/lang/StringBuilder;
// 405: ldc_w 426
// 408: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 411: astore_3
// 412: aload_0
// 413: getfield 32 ijg:b Lijf;
// 416: astore 6
// 418: ldc 213
// 420: iconst_2
// 421: aload_3
// 422: aload_2
// 423: getfield 412 com/tencent/mobileqq/audiotrans/AudioTransCommon$NetAddr:fixed32_inner_IP Lcom/tencent/mobileqq/pb/PBFixed32Field;
// 426: invokevirtual 397 com/tencent/mobileqq/pb/PBFixed32Field:get ()I
// 429: invokestatic 424 ijf:aH (I)Ljava/lang/String;
// 432: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 435: invokevirtual 243 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 438: invokestatic 429 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;)V
// 441: goto -187 -> 254
// 444: astore_1
// 445: aload_1
// 446: invokevirtual 432 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException:printStackTrace ()V
// 449: ldc 213
// 451: iconst_2
// 452: new 215 java/lang/StringBuilder
// 455: dup
// 456: invokespecial 216 java/lang/StringBuilder:<init> ()V
// 459: ldc_w 434
// 462: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 465: aload_1
// 466: invokevirtual 437 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException:getMessage ()Ljava/lang/String;
// 469: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 472: invokevirtual 243 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 475: invokestatic 440 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 478: return
// 479: astore_1
// 480: ldc 213
// 482: iconst_1
// 483: ldc_w 442
// 486: aload_1
// 487: invokestatic 445 com/tencent/qphone/base/util/QLog:w (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V
// 490: goto -340 -> 150
// 493: aload_0
// 494: getfield 75 ijg:mApp Lcom/tencent/common/app/AppInterface;
// 497: iconst_0
// 498: invokevirtual 449 com/tencent/common/app/AppInterface:getBusinessHandler (I)Ljava/lang/Object;
// 501: checkcast 451 iji
// 504: iload 4
// 506: i2l
// 507: iconst_1
// 508: aload_0
// 509: getfield 39 ijg:a Lijh$a;
// 512: getfield 354 ijh$a:eM Ljava/util/List;
// 515: aload_0
// 516: getfield 39 ijg:a Lijh$a;
// 519: getfield 256 ijh$a:mSessionId J
// 522: invokevirtual 454 iji:a (JZLjava/util/List;J)V
// 525: aload_0
// 526: iconst_1
// 527: putfield 252 ijg:RG Z
// 530: iload 5
// 532: ifeq -54 -> 478
// 535: aload_0
// 536: iload 4
// 538: i2l
// 539: aload_0
// 540: getfield 39 ijg:a Lijh$a;
// 543: getfield 256 ijh$a:mSessionId J
// 546: invokevirtual 456 ijg:D (JJ)V
// 549: return
// 550: aload_2
// 551: getfield 460 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoRspBody:msg_failed_rsp Lcom/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SFailedRsp;
// 554: invokevirtual 463 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SFailedRsp:get ()Lcom/tencent/mobileqq/pb/MessageMicro;
// 557: checkcast 462 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SFailedRsp
// 560: astore_1
// 561: ldc 213
// 563: iconst_2
// 564: ldc_w 465
// 567: invokestatic 429 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;)V
// 570: ldc 213
// 572: iconst_2
// 573: new 215 java/lang/StringBuilder
// 576: dup
// 577: invokespecial 216 java/lang/StringBuilder:<init> ()V
// 580: ldc_w 467
// 583: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 586: aload_1
// 587: getfield 470 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SFailedRsp:uint32_errcode Lcom/tencent/mobileqq/pb/PBUInt32Field;
// 590: invokevirtual 297 com/tencent/mobileqq/pb/PBUInt32Field:get ()I
// 593: invokevirtual 361 java/lang/StringBuilder:append (I)Ljava/lang/StringBuilder;
// 596: invokevirtual 243 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 599: invokestatic 429 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;)V
// 602: ldc 213
// 604: iconst_2
// 605: new 215 java/lang/StringBuilder
// 608: dup
// 609: invokespecial 216 java/lang/StringBuilder:<init> ()V
// 612: ldc_w 472
// 615: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 618: aload_1
// 619: getfield 475 com/tencent/mobileqq/audiotrans/AudioTransClientTransInfo$InfoC2SFailedRsp:str_errmsg Lcom/tencent/mobileqq/pb/PBStringField;
// 622: invokevirtual 118 com/tencent/mobileqq/pb/PBStringField:get ()Ljava/lang/String;
// 625: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 628: invokevirtual 243 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 631: invokestatic 429 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;)V
// 634: return
// 635: ldc 213
// 637: iconst_2
// 638: ldc_w 477
// 641: invokestatic 440 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 644: return
// 645: ldc 213
// 647: iconst_2
// 648: new 215 java/lang/StringBuilder
// 651: dup
// 652: invokespecial 216 java/lang/StringBuilder:<init> ()V
// 655: ldc_w 479
// 658: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 661: aload_2
// 662: invokevirtual 482 com/tencent/qphone/base/remote/FromServiceMsg:getBusinessFailMsg ()Ljava/lang/String;
// 665: invokevirtual 222 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 668: invokevirtual 243 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 671: invokestatic 440 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 674: return
// Local variable table:
// start length slot name signature
// 0 675 0 this ijg
// 0 675 1 paramToServiceMsg ToServiceMsg
// 0 675 2 paramFromServiceMsg com.tencent.qphone.base.remote.FromServiceMsg
// 0 675 3 paramObject Object
// 54 483 4 i int
// 176 355 5 bool boolean
// 357 60 6 localijf ijf
// Exception table:
// from to target type
// 38 130 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 130 150 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 150 254 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 254 441 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 480 490 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 493 530 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 535 549 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 550 634 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 635 644 444 com/tencent/mobileqq/pb/InvalidProtocolBufferMicroException
// 130 150 479 java/lang/Exception
}
public boolean tr()
{
return this.RG;
}
abstract boolean ts();
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.tim\classes13.jar
* Qualified Name: ijg
* JD-Core Version: 0.7.0.1
*/ | tsuzcx/qq_apk | com.tencent.tim/classes.jar/ijg.java |
214,224 | /*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.lang.invoke;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Arrays;
import java.util.HashMap;
import sun.invoke.util.Wrapper;
import java.lang.reflect.Field;
import static java.lang.invoke.LambdaForm.BasicType.*;
import static java.lang.invoke.MethodHandleStatics.*;
import static java.lang.invoke.MethodHandleNatives.Constants.*;
/**
* The symbolic, non-executable form of a method handle's invocation semantics.
* It consists of a series of names.
* The first N (N=arity) names are parameters,
* while any remaining names are temporary values.
* Each temporary specifies the application of a function to some arguments.
* The functions are method handles, while the arguments are mixes of
* constant values and local names.
* The result of the lambda is defined as one of the names, often the last one.
* <p>
* Here is an approximate grammar:
* <blockquote><pre>{@code
* LambdaForm = "(" ArgName* ")=>{" TempName* Result "}"
* ArgName = "a" N ":" T
* TempName = "t" N ":" T "=" Function "(" Argument* ");"
* Function = ConstantValue
* Argument = NameRef | ConstantValue
* Result = NameRef | "void"
* NameRef = "a" N | "t" N
* N = (any whole number)
* T = "L" | "I" | "J" | "F" | "D" | "V"
* }</pre></blockquote>
* Names are numbered consecutively from left to right starting at zero.
* (The letters are merely a taste of syntax sugar.)
* Thus, the first temporary (if any) is always numbered N (where N=arity).
* Every occurrence of a name reference in an argument list must refer to
* a name previously defined within the same lambda.
* A lambda has a void result if and only if its result index is -1.
* If a temporary has the type "V", it cannot be the subject of a NameRef,
* even though possesses a number.
* Note that all reference types are erased to "L", which stands for {@code Object}.
* All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}.
* The other types stand for the usual primitive types.
* <p>
* Function invocation closely follows the static rules of the Java verifier.
* Arguments and return values must exactly match when their "Name" types are
* considered.
* Conversions are allowed only if they do not change the erased type.
* <ul>
* <li>L = Object: casts are used freely to convert into and out of reference types
* <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments})
* <li>J = long: no implicit conversions
* <li>F = float: no implicit conversions
* <li>D = double: no implicit conversions
* <li>V = void: a function result may be void if and only if its Name is of type "V"
* </ul>
* Although implicit conversions are not allowed, explicit ones can easily be
* encoded by using temporary expressions which call type-transformed identity functions.
* <p>
* Examples:
* <blockquote><pre>{@code
* (a0:J)=>{ a0 }
* == identity(long)
* (a0:I)=>{ t1:V = System.out#println(a0); void }
* == System.out#println(int)
* (a0:L)=>{ t1:V = System.out#println(a0); a0 }
* == identity, with printing side-effect
* (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
* t3:L = BoundMethodHandle#target(a0);
* t4:L = MethodHandle#invoke(t3, t2, a1); t4 }
* == general invoker for unary insertArgument combination
* (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0);
* t3:L = MethodHandle#invoke(t2, a1);
* t4:L = FilterMethodHandle#target(a0);
* t5:L = MethodHandle#invoke(t4, t3); t5 }
* == general invoker for unary filterArgument combination
* (a0:L, a1:L)=>{ ...(same as previous example)...
* t5:L = MethodHandle#invoke(t4, t3, a1); t5 }
* == general invoker for unary/unary foldArgument combination
* (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 }
* == invoker for identity method handle which performs i2l
* (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
* t3:L = Class#cast(t2,a1); t3 }
* == invoker for identity method handle which performs cast
* }</pre></blockquote>
* <p>
* @author John Rose, JSR 292 EG
*/
class LambdaForm {
final int arity;
final int result;
final boolean forceInline;
final MethodHandle customized;
@Stable final Name[] names;
final String debugName;
MemberName vmentry; // low-level behavior, or null if not yet prepared
private boolean isCompiled;
// Either a LambdaForm cache (managed by LambdaFormEditor) or a link to uncustomized version (for customized LF)
volatile Object transformCache;
public static final int VOID_RESULT = -1, LAST_RESULT = -2;
enum BasicType {
L_TYPE('L', Object.class, Wrapper.OBJECT), // all reference types
I_TYPE('I', int.class, Wrapper.INT),
J_TYPE('J', long.class, Wrapper.LONG),
F_TYPE('F', float.class, Wrapper.FLOAT),
D_TYPE('D', double.class, Wrapper.DOUBLE), // all primitive types
V_TYPE('V', void.class, Wrapper.VOID); // not valid in all contexts
static final BasicType[] ALL_TYPES = BasicType.values();
static final BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1);
static final int ARG_TYPE_LIMIT = ARG_TYPES.length;
static final int TYPE_LIMIT = ALL_TYPES.length;
private final char btChar;
private final Class<?> btClass;
private final Wrapper btWrapper;
private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) {
this.btChar = btChar;
this.btClass = btClass;
this.btWrapper = wrapper;
}
char basicTypeChar() {
return btChar;
}
Class<?> basicTypeClass() {
return btClass;
}
Wrapper basicTypeWrapper() {
return btWrapper;
}
int basicTypeSlots() {
return btWrapper.stackSlots();
}
static BasicType basicType(byte type) {
return ALL_TYPES[type];
}
static BasicType basicType(char type) {
switch (type) {
case 'L': return L_TYPE;
case 'I': return I_TYPE;
case 'J': return J_TYPE;
case 'F': return F_TYPE;
case 'D': return D_TYPE;
case 'V': return V_TYPE;
// all subword types are represented as ints
case 'Z':
case 'B':
case 'S':
case 'C':
return I_TYPE;
default:
throw newInternalError("Unknown type char: '"+type+"'");
}
}
static BasicType basicType(Wrapper type) {
char c = type.basicTypeChar();
return basicType(c);
}
static BasicType basicType(Class<?> type) {
if (!type.isPrimitive()) return L_TYPE;
return basicType(Wrapper.forPrimitiveType(type));
}
static char basicTypeChar(Class<?> type) {
return basicType(type).btChar;
}
static BasicType[] basicTypes(List<Class<?>> types) {
BasicType[] btypes = new BasicType[types.size()];
for (int i = 0; i < btypes.length; i++) {
btypes[i] = basicType(types.get(i));
}
return btypes;
}
static BasicType[] basicTypes(String types) {
BasicType[] btypes = new BasicType[types.length()];
for (int i = 0; i < btypes.length; i++) {
btypes[i] = basicType(types.charAt(i));
}
return btypes;
}
static byte[] basicTypesOrd(BasicType[] btypes) {
byte[] ords = new byte[btypes.length];
for (int i = 0; i < btypes.length; i++) {
ords[i] = (byte)btypes[i].ordinal();
}
return ords;
}
static boolean isBasicTypeChar(char c) {
return "LIJFDV".indexOf(c) >= 0;
}
static boolean isArgBasicTypeChar(char c) {
return "LIJFD".indexOf(c) >= 0;
}
static { assert(checkBasicType()); }
private static boolean checkBasicType() {
for (int i = 0; i < ARG_TYPE_LIMIT; i++) {
assert ARG_TYPES[i].ordinal() == i;
assert ARG_TYPES[i] == ALL_TYPES[i];
}
for (int i = 0; i < TYPE_LIMIT; i++) {
assert ALL_TYPES[i].ordinal() == i;
}
assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE;
assert !Arrays.asList(ARG_TYPES).contains(V_TYPE);
return true;
}
}
LambdaForm(String debugName,
int arity, Name[] names, int result) {
this(debugName, arity, names, result, /*forceInline=*/true, /*customized=*/null);
}
LambdaForm(String debugName,
int arity, Name[] names, int result, boolean forceInline, MethodHandle customized) {
assert(namesOK(arity, names));
this.arity = arity;
this.result = fixResult(result, names);
this.names = names.clone();
this.debugName = fixDebugName(debugName);
this.forceInline = forceInline;
this.customized = customized;
int maxOutArity = normalize();
if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) {
// Cannot use LF interpreter on very high arity expressions.
assert(maxOutArity <= MethodType.MAX_JVM_ARITY);
compileToBytecode();
}
}
LambdaForm(String debugName,
int arity, Name[] names) {
this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null);
}
LambdaForm(String debugName,
int arity, Name[] names, boolean forceInline) {
this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null);
}
LambdaForm(String debugName,
Name[] formals, Name[] temps, Name result) {
this(debugName,
formals.length, buildNames(formals, temps, result), LAST_RESULT, /*forceInline=*/true, /*customized=*/null);
}
LambdaForm(String debugName,
Name[] formals, Name[] temps, Name result, boolean forceInline) {
this(debugName,
formals.length, buildNames(formals, temps, result), LAST_RESULT, forceInline, /*customized=*/null);
}
private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
int arity = formals.length;
int length = arity + temps.length + (result == null ? 0 : 1);
Name[] names = Arrays.copyOf(formals, length);
System.arraycopy(temps, 0, names, arity, temps.length);
if (result != null)
names[length - 1] = result;
return names;
}
private LambdaForm(String sig) {
// Make a blank lambda form, which returns a constant zero or null.
// It is used as a template for managing the invocation of similar forms that are non-empty.
// Called only from getPreparedForm.
assert(isValidSignature(sig));
this.arity = signatureArity(sig);
this.result = (signatureReturn(sig) == V_TYPE ? -1 : arity);
this.names = buildEmptyNames(arity, sig);
this.debugName = "LF.zero";
this.forceInline = true;
this.customized = null;
assert(nameRefsAreLegal());
assert(isEmpty());
assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature();
}
private static Name[] buildEmptyNames(int arity, String basicTypeSignature) {
assert(isValidSignature(basicTypeSignature));
int resultPos = arity + 1; // skip '_'
if (arity < 0 || basicTypeSignature.length() != resultPos+1)
throw new IllegalArgumentException("bad arity for "+basicTypeSignature);
int numRes = (basicType(basicTypeSignature.charAt(resultPos)) == V_TYPE ? 0 : 1);
Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity));
for (int i = 0; i < numRes; i++) {
Name zero = new Name(constantZero(basicType(basicTypeSignature.charAt(resultPos + i))));
names[arity + i] = zero.newIndex(arity + i);
}
return names;
}
private static int fixResult(int result, Name[] names) {
if (result == LAST_RESULT)
result = names.length - 1; // might still be void
if (result >= 0 && names[result].type == V_TYPE)
result = VOID_RESULT;
return result;
}
private static String fixDebugName(String debugName) {
if (DEBUG_NAME_COUNTERS != null) {
int under = debugName.indexOf('_');
int length = debugName.length();
if (under < 0) under = length;
String debugNameStem = debugName.substring(0, under);
Integer ctr;
synchronized (DEBUG_NAME_COUNTERS) {
ctr = DEBUG_NAME_COUNTERS.get(debugNameStem);
if (ctr == null) ctr = 0;
DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1);
}
StringBuilder buf = new StringBuilder(debugNameStem);
buf.append('_');
int leadingZero = buf.length();
buf.append((int) ctr);
for (int i = buf.length() - leadingZero; i < 3; i++)
buf.insert(leadingZero, '0');
if (under < length) {
++under; // skip "_"
while (under < length && Character.isDigit(debugName.charAt(under))) {
++under;
}
if (under < length && debugName.charAt(under) == '_') ++under;
if (under < length)
buf.append('_').append(debugName, under, length);
}
return buf.toString();
}
return debugName;
}
private static boolean namesOK(int arity, Name[] names) {
for (int i = 0; i < names.length; i++) {
Name n = names[i];
assert(n != null) : "n is null";
if (i < arity)
assert( n.isParam()) : n + " is not param at " + i;
else
assert(!n.isParam()) : n + " is param at " + i;
}
return true;
}
/** Customize LambdaForm for a particular MethodHandle */
LambdaForm customize(MethodHandle mh) {
LambdaForm customForm = new LambdaForm(debugName, arity, names, result, forceInline, mh);
if (COMPILE_THRESHOLD > 0 && isCompiled) {
// If shared LambdaForm has been compiled, compile customized version as well.
customForm.compileToBytecode();
}
customForm.transformCache = this; // LambdaFormEditor should always use uncustomized form.
return customForm;
}
/** Get uncustomized flavor of the LambdaForm */
LambdaForm uncustomize() {
if (customized == null) {
return this;
}
assert(transformCache != null); // Customized LambdaForm should always has a link to uncustomized version.
LambdaForm uncustomizedForm = (LambdaForm)transformCache;
if (COMPILE_THRESHOLD > 0 && isCompiled) {
// If customized LambdaForm has been compiled, compile uncustomized version as well.
uncustomizedForm.compileToBytecode();
}
return uncustomizedForm;
}
/** Renumber and/or replace params so that they are interned and canonically numbered.
* @return maximum argument list length among the names (since we have to pass over them anyway)
*/
private int normalize() {
Name[] oldNames = null;
int maxOutArity = 0;
int changesStart = 0;
for (int i = 0; i < names.length; i++) {
Name n = names[i];
if (!n.initIndex(i)) {
if (oldNames == null) {
oldNames = names.clone();
changesStart = i;
}
names[i] = n.cloneWithIndex(i);
}
if (n.arguments != null && maxOutArity < n.arguments.length)
maxOutArity = n.arguments.length;
}
if (oldNames != null) {
int startFixing = arity;
if (startFixing <= changesStart)
startFixing = changesStart+1;
for (int i = startFixing; i < names.length; i++) {
Name fixed = names[i].replaceNames(oldNames, names, changesStart, i);
names[i] = fixed.newIndex(i);
}
}
assert(nameRefsAreLegal());
int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
boolean needIntern = false;
for (int i = 0; i < maxInterned; i++) {
Name n = names[i], n2 = internArgument(n);
if (n != n2) {
names[i] = n2;
needIntern = true;
}
}
if (needIntern) {
for (int i = arity; i < names.length; i++) {
names[i].internArguments();
}
}
assert(nameRefsAreLegal());
return maxOutArity;
}
/**
* Check that all embedded Name references are localizable to this lambda,
* and are properly ordered after their corresponding definitions.
* <p>
* Note that a Name can be local to multiple lambdas, as long as
* it possesses the same index in each use site.
* This allows Name references to be freely reused to construct
* fresh lambdas, without confusion.
*/
boolean nameRefsAreLegal() {
assert(arity >= 0 && arity <= names.length);
assert(result >= -1 && result < names.length);
// Do all names possess an index consistent with their local definition order?
for (int i = 0; i < arity; i++) {
Name n = names[i];
assert(n.index() == i) : Arrays.asList(n.index(), i);
assert(n.isParam());
}
// Also, do all local name references
for (int i = arity; i < names.length; i++) {
Name n = names[i];
assert(n.index() == i);
for (Object arg : n.arguments) {
if (arg instanceof Name) {
Name n2 = (Name) arg;
int i2 = n2.index;
assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
assert(i2 < i); // ref must come after def!
}
}
}
return true;
}
/** Invoke this form on the given arguments. */
// final Object invoke(Object... args) throws Throwable {
// // NYI: fit this into the fast path?
// return interpretWithArguments(args);
// }
/** Report the return type. */
BasicType returnType() {
if (result < 0) return V_TYPE;
Name n = names[result];
return n.type;
}
/** Report the N-th argument type. */
BasicType parameterType(int n) {
return parameter(n).type;
}
/** Report the N-th argument name. */
Name parameter(int n) {
assert(n < arity);
Name param = names[n];
assert(param.isParam());
return param;
}
/** Report the N-th argument type constraint. */
Object parameterConstraint(int n) {
return parameter(n).constraint;
}
/** Report the arity. */
int arity() {
return arity;
}
/** Report the number of expressions (non-parameter names). */
int expressionCount() {
return names.length - arity;
}
/** Return the method type corresponding to my basic type signature. */
MethodType methodType() {
return signatureType(basicTypeSignature());
}
/** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
final String basicTypeSignature() {
StringBuilder buf = new StringBuilder(arity() + 3);
for (int i = 0, a = arity(); i < a; i++)
buf.append(parameterType(i).basicTypeChar());
return buf.append('_').append(returnType().basicTypeChar()).toString();
}
static int signatureArity(String sig) {
assert(isValidSignature(sig));
return sig.indexOf('_');
}
static BasicType signatureReturn(String sig) {
return basicType(sig.charAt(signatureArity(sig) + 1));
}
static boolean isValidSignature(String sig) {
int arity = sig.indexOf('_');
if (arity < 0) return false; // must be of the form *_*
int siglen = sig.length();
if (siglen != arity + 2) return false; // *_X
for (int i = 0; i < siglen; i++) {
if (i == arity) continue; // skip '_'
char c = sig.charAt(i);
if (c == 'V')
return (i == siglen - 1 && arity == siglen - 2);
if (!isArgBasicTypeChar(c)) return false; // must be [LIJFD]
}
return true; // [LIJFD]*_[LIJFDV]
}
static MethodType signatureType(String sig) {
Class<?>[] ptypes = new Class<?>[signatureArity(sig)];
for (int i = 0; i < ptypes.length; i++)
ptypes[i] = basicType(sig.charAt(i)).btClass;
Class<?> rtype = signatureReturn(sig).btClass;
return MethodType.methodType(rtype, ptypes);
}
/*
* Code generation issues:
*
* Compiled LFs should be reusable in general.
* The biggest issue is how to decide when to pull a name into
* the bytecode, versus loading a reified form from the MH data.
*
* For example, an asType wrapper may require execution of a cast
* after a call to a MH. The target type of the cast can be placed
* as a constant in the LF itself. This will force the cast type
* to be compiled into the bytecodes and native code for the MH.
* Or, the target type of the cast can be erased in the LF, and
* loaded from the MH data. (Later on, if the MH as a whole is
* inlined, the data will flow into the inlined instance of the LF,
* as a constant, and the end result will be an optimal cast.)
*
* This erasure of cast types can be done with any use of
* reference types. It can also be done with whole method
* handles. Erasing a method handle might leave behind
* LF code that executes correctly for any MH of a given
* type, and load the required MH from the enclosing MH's data.
* Or, the erasure might even erase the expected MT.
*
* Also, for direct MHs, the MemberName of the target
* could be erased, and loaded from the containing direct MH.
* As a simple case, a LF for all int-valued non-static
* field getters would perform a cast on its input argument
* (to non-constant base type derived from the MemberName)
* and load an integer value from the input object
* (at a non-constant offset also derived from the MemberName).
* Such MN-erased LFs would be inlinable back to optimized
* code, whenever a constant enclosing DMH is available
* to supply a constant MN from its data.
*
* The main problem here is to keep LFs reasonably generic,
* while ensuring that hot spots will inline good instances.
* "Reasonably generic" means that we don't end up with
* repeated versions of bytecode or machine code that do
* not differ in their optimized form. Repeated versions
* of machine would have the undesirable overheads of
* (a) redundant compilation work and (b) extra I$ pressure.
* To control repeated versions, we need to be ready to
* erase details from LFs and move them into MH data,
* whevener those details are not relevant to significant
* optimization. "Significant" means optimization of
* code that is actually hot.
*
* Achieving this may require dynamic splitting of MHs, by replacing
* a generic LF with a more specialized one, on the same MH,
* if (a) the MH is frequently executed and (b) the MH cannot
* be inlined into a containing caller, such as an invokedynamic.
*
* Compiled LFs that are no longer used should be GC-able.
* If they contain non-BCP references, they should be properly
* interlinked with the class loader(s) that their embedded types
* depend on. This probably means that reusable compiled LFs
* will be tabulated (indexed) on relevant class loaders,
* or else that the tables that cache them will have weak links.
*/
/**
* Make this LF directly executable, as part of a MethodHandle.
* Invariant: Every MH which is invoked must prepare its LF
* before invocation.
* (In principle, the JVM could do this very lazily,
* as a sort of pre-invocation linkage step.)
*/
public void prepare() {
if (COMPILE_THRESHOLD == 0 && !isCompiled) {
compileToBytecode();
}
if (this.vmentry != null) {
// already prepared (e.g., a primitive DMH invoker form)
return;
}
LambdaForm prep = getPreparedForm(basicTypeSignature());
this.vmentry = prep.vmentry;
// TO DO: Maybe add invokeGeneric, invokeWithArguments
}
/** Generate optimizable bytecode for this form. */
MemberName compileToBytecode() {
if (vmentry != null && isCompiled) {
return vmentry; // already compiled somehow
}
MethodType invokerType = methodType();
assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
try {
vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
if (TRACE_INTERPRETER)
traceInterpreter("compileToBytecode", this);
isCompiled = true;
return vmentry;
} catch (Error | Exception ex) {
throw newInternalError(this.toString(), ex);
}
}
private static void computeInitialPreparedForms() {
// Find all predefined invokers and associate them with canonical empty lambda forms.
for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
if (!m.isStatic() || !m.isPackage()) continue;
MethodType mt = m.getMethodType();
if (mt.parameterCount() > 0 &&
mt.parameterType(0) == MethodHandle.class &&
m.getName().startsWith("interpret_")) {
String sig = basicTypeSignature(mt);
assert(m.getName().equals("interpret" + sig.substring(sig.indexOf('_'))));
LambdaForm form = new LambdaForm(sig);
form.vmentry = m;
form = mt.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, form);
}
}
}
// Set this false to disable use of the interpret_L methods defined in this file.
private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true;
// The following are predefined exact invokers. The system must build
// a separate invoker for each distinct signature.
static Object interpret_L(MethodHandle mh) throws Throwable {
Object[] av = {mh};
String sig = null;
assert(argumentTypesMatch(sig = "L_L", av));
Object res = mh.form.interpretWithArguments(av);
assert(returnTypesMatch(sig, av, res));
return res;
}
static Object interpret_L(MethodHandle mh, Object x1) throws Throwable {
Object[] av = {mh, x1};
String sig = null;
assert(argumentTypesMatch(sig = "LL_L", av));
Object res = mh.form.interpretWithArguments(av);
assert(returnTypesMatch(sig, av, res));
return res;
}
static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable {
Object[] av = {mh, x1, x2};
String sig = null;
assert(argumentTypesMatch(sig = "LLL_L", av));
Object res = mh.form.interpretWithArguments(av);
assert(returnTypesMatch(sig, av, res));
return res;
}
private static LambdaForm getPreparedForm(String sig) {
MethodType mtype = signatureType(sig);
LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET);
if (prep != null) return prep;
assert(isValidSignature(sig));
prep = new LambdaForm(sig);
prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig);
return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep);
}
// The next few routines are called only from assert expressions
// They verify that the built-in invokers process the correct raw data types.
private static boolean argumentTypesMatch(String sig, Object[] av) {
int arity = signatureArity(sig);
assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0];
MethodHandle mh = (MethodHandle) av[0];
MethodType mt = mh.type();
assert(mt.parameterCount() == arity-1);
for (int i = 0; i < av.length; i++) {
Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
assert(valueMatches(basicType(sig.charAt(i)), pt, av[i]));
}
return true;
}
private static boolean valueMatches(BasicType tc, Class<?> type, Object x) {
// The following line is needed because (...)void method handles can use non-void invokers
if (type == void.class) tc = V_TYPE; // can drop any kind of value
assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
switch (tc) {
case I_TYPE: assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break;
case J_TYPE: assert x instanceof Long : "instanceof Long: " + x; break;
case F_TYPE: assert x instanceof Float : "instanceof Float: " + x; break;
case D_TYPE: assert x instanceof Double : "instanceof Double: " + x; break;
case L_TYPE: assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break;
case V_TYPE: break; // allow anything here; will be dropped
default: assert(false);
}
return true;
}
private static boolean returnTypesMatch(String sig, Object[] av, Object res) {
MethodHandle mh = (MethodHandle) av[0];
return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
}
private static boolean checkInt(Class<?> type, Object x) {
assert(x instanceof Integer);
if (type == int.class) return true;
Wrapper w = Wrapper.forBasicType(type);
assert(w.isSubwordOrInt());
Object x1 = Wrapper.INT.wrap(w.wrap(x));
return x.equals(x1);
}
private static boolean checkRef(Class<?> type, Object x) {
assert(!type.isPrimitive());
if (x == null) return true;
if (type.isInterface()) return true;
return type.isInstance(x);
}
/** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
private static final int COMPILE_THRESHOLD;
static {
COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD);
}
private int invocationCounter = 0;
@Hidden
@DontInline
/** Interpretively invoke this form on the given arguments. */
Object interpretWithArguments(Object... argumentValues) throws Throwable {
if (TRACE_INTERPRETER)
return interpretWithArgumentsTracing(argumentValues);
checkInvocationCounter();
assert(arityCheck(argumentValues));
Object[] values = Arrays.copyOf(argumentValues, names.length);
for (int i = argumentValues.length; i < values.length; i++) {
values[i] = interpretName(names[i], values);
}
Object rv = (result < 0) ? null : values[result];
assert(resultCheck(argumentValues, rv));
return rv;
}
@Hidden
@DontInline
/** Evaluate a single Name within this form, applying its function to its arguments. */
Object interpretName(Name name, Object[] values) throws Throwable {
if (TRACE_INTERPRETER)
traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
for (int i = 0; i < arguments.length; i++) {
Object a = arguments[i];
if (a instanceof Name) {
int i2 = ((Name)a).index();
assert(names[i2] == a);
a = values[i2];
arguments[i] = a;
}
}
return name.function.invokeWithArguments(arguments);
}
private void checkInvocationCounter() {
if (COMPILE_THRESHOLD != 0 &&
invocationCounter < COMPILE_THRESHOLD) {
invocationCounter++; // benign race
if (invocationCounter >= COMPILE_THRESHOLD) {
// Replace vmentry with a bytecode version of this LF.
compileToBytecode();
}
}
}
Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable {
traceInterpreter("[ interpretWithArguments", this, argumentValues);
if (invocationCounter < COMPILE_THRESHOLD) {
int ctr = invocationCounter++; // benign race
traceInterpreter("| invocationCounter", ctr);
if (invocationCounter >= COMPILE_THRESHOLD) {
compileToBytecode();
}
}
Object rval;
try {
assert(arityCheck(argumentValues));
Object[] values = Arrays.copyOf(argumentValues, names.length);
for (int i = argumentValues.length; i < values.length; i++) {
values[i] = interpretName(names[i], values);
}
rval = (result < 0) ? null : values[result];
} catch (Throwable ex) {
traceInterpreter("] throw =>", ex);
throw ex;
}
traceInterpreter("] return =>", rval);
return rval;
}
static void traceInterpreter(String event, Object obj, Object... args) {
if (TRACE_INTERPRETER) {
System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
}
}
static void traceInterpreter(String event, Object obj) {
traceInterpreter(event, obj, (Object[])null);
}
private boolean arityCheck(Object[] argumentValues) {
assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
// also check that the leading (receiver) argument is somehow bound to this LF:
assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
MethodHandle mh = (MethodHandle) argumentValues[0];
assert(mh.internalForm() == this);
// note: argument #0 could also be an interface wrapper, in the future
argumentTypesMatch(basicTypeSignature(), argumentValues);
return true;
}
private boolean resultCheck(Object[] argumentValues, Object result) {
MethodHandle mh = (MethodHandle) argumentValues[0];
MethodType mt = mh.type();
assert(valueMatches(returnType(), mt.returnType(), result));
return true;
}
private boolean isEmpty() {
if (result < 0)
return (names.length == arity);
else if (result == arity && names.length == arity + 1)
return names[arity].isConstantZero();
else
return false;
}
public String toString() {
StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
for (int i = 0; i < names.length; i++) {
if (i == arity) buf.append(")=>{");
Name n = names[i];
if (i >= arity) buf.append("\n ");
buf.append(n.paramString());
if (i < arity) {
if (i+1 < arity) buf.append(",");
continue;
}
buf.append("=").append(n.exprString());
buf.append(";");
}
if (arity == names.length) buf.append(")=>{");
buf.append(result < 0 ? "void" : names[result]).append("}");
if (TRACE_INTERPRETER) {
// Extra verbosity:
buf.append(":").append(basicTypeSignature());
buf.append("/").append(vmentry);
}
return buf.toString();
}
@Override
public boolean equals(Object obj) {
return obj instanceof LambdaForm && equals((LambdaForm)obj);
}
public boolean equals(LambdaForm that) {
if (this.result != that.result) return false;
return Arrays.equals(this.names, that.names);
}
public int hashCode() {
return result + 31 * Arrays.hashCode(names);
}
LambdaFormEditor editor() {
return LambdaFormEditor.lambdaFormEditor(this);
}
boolean contains(Name name) {
int pos = name.index();
if (pos >= 0) {
return pos < names.length && name.equals(names[pos]);
}
for (int i = arity; i < names.length; i++) {
if (name.equals(names[i]))
return true;
}
return false;
}
LambdaForm addArguments(int pos, BasicType... types) {
// names array has MH in slot 0; skip it.
int argpos = pos + 1;
assert(argpos <= arity);
int length = names.length;
int inTypes = types.length;
Name[] names2 = Arrays.copyOf(names, length + inTypes);
int arity2 = arity + inTypes;
int result2 = result;
if (result2 >= argpos)
result2 += inTypes;
// Note: The LF constructor will rename names2[argpos...].
// Make space for new arguments (shift temporaries).
System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
for (int i = 0; i < inTypes; i++) {
names2[argpos + i] = new Name(types[i]);
}
return new LambdaForm(debugName, arity2, names2, result2);
}
LambdaForm addArguments(int pos, List<Class<?>> types) {
return addArguments(pos, basicTypes(types));
}
LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) {
// Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg.
// The types are the types of the new (incoming) arguments.
int length = names.length;
int inTypes = types.length;
int outArgs = reorder.length;
assert(skip+outArgs == arity);
assert(permutedTypesMatch(reorder, types, names, skip));
int pos = 0;
// skip trivial first part of reordering:
while (pos < outArgs && reorder[pos] == pos) pos += 1;
Name[] names2 = new Name[length - outArgs + inTypes];
System.arraycopy(names, 0, names2, 0, skip+pos);
// copy the body:
int bodyLength = length - arity;
System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength);
int arity2 = names2.length - bodyLength;
int result2 = result;
if (result2 >= 0) {
if (result2 < skip+outArgs) {
// return the corresponding inArg
result2 = reorder[result2-skip];
} else {
result2 = result2 - outArgs + inTypes;
}
}
// rework names in the body:
for (int j = pos; j < outArgs; j++) {
Name n = names[skip+j];
int i = reorder[j];
// replace names[skip+j] by names2[skip+i]
Name n2 = names2[skip+i];
if (n2 == null)
names2[skip+i] = n2 = new Name(types[i]);
else
assert(n2.type == types[i]);
for (int k = arity2; k < names2.length; k++) {
names2[k] = names2[k].replaceName(n, n2);
}
}
// some names are unused, but must be filled in
for (int i = skip+pos; i < arity2; i++) {
if (names2[i] == null)
names2[i] = argument(i, types[i - skip]);
}
for (int j = arity; j < names.length; j++) {
int i = j - arity + arity2;
// replace names2[i] by names[j]
Name n = names[j];
Name n2 = names2[i];
if (n != n2) {
for (int k = i+1; k < names2.length; k++) {
names2[k] = names2[k].replaceName(n, n2);
}
}
}
return new LambdaForm(debugName, arity2, names2, result2);
}
static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) {
int inTypes = types.length;
int outArgs = reorder.length;
for (int i = 0; i < outArgs; i++) {
assert(names[skip+i].isParam());
assert(names[skip+i].type == types[reorder[i]]);
}
return true;
}
static class NamedFunction {
final MemberName member;
@Stable MethodHandle resolvedHandle;
@Stable MethodHandle invoker;
NamedFunction(MethodHandle resolvedHandle) {
this(resolvedHandle.internalMemberName(), resolvedHandle);
}
NamedFunction(MemberName member, MethodHandle resolvedHandle) {
this.member = member;
this.resolvedHandle = resolvedHandle;
// The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
//assert(!isInvokeBasic(member));
}
NamedFunction(MethodType basicInvokerType) {
assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
this.member = resolvedHandle.internalMemberName();
} else {
// necessary to pass BigArityTest
this.member = Invokers.invokeBasicMethod(basicInvokerType);
}
assert(isInvokeBasic(member));
}
private static boolean isInvokeBasic(MemberName member) {
return member != null &&
member.getDeclaringClass() == MethodHandle.class &&
"invokeBasic".equals(member.getName());
}
// The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc.
// Any LambdaForm containing such a member is not interpretable.
// This is OK, since all such LFs are prepared with special primitive vmentry points.
// And even without the resolvedHandle, the name can still be compiled and optimized.
NamedFunction(Method method) {
this(new MemberName(method));
}
NamedFunction(Field field) {
this(new MemberName(field));
}
NamedFunction(MemberName member) {
this.member = member;
this.resolvedHandle = null;
}
MethodHandle resolvedHandle() {
if (resolvedHandle == null) resolve();
return resolvedHandle;
}
void resolve() {
resolvedHandle = DirectMethodHandle.make(member);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
if (!(other instanceof NamedFunction)) return false;
NamedFunction that = (NamedFunction) other;
return this.member != null && this.member.equals(that.member);
}
@Override
public int hashCode() {
if (member != null)
return member.hashCode();
return super.hashCode();
}
// Put the predefined NamedFunction invokers into the table.
static void initializeInvokers() {
for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
if (!m.isStatic() || !m.isPackage()) continue;
MethodType type = m.getMethodType();
if (type.equals(INVOKER_METHOD_TYPE) &&
m.getName().startsWith("invoke_")) {
String sig = m.getName().substring("invoke_".length());
int arity = LambdaForm.signatureArity(sig);
MethodType srcType = MethodType.genericMethodType(arity);
if (LambdaForm.signatureReturn(sig) == V_TYPE)
srcType = srcType.changeReturnType(void.class);
MethodTypeForm typeForm = srcType.form();
typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m));
}
}
}
// The following are predefined NamedFunction invokers. The system must build
// a separate invoker for each distinct signature.
/** void return type invokers. */
@Hidden
static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(0, void.class, mh, a));
mh.invokeBasic();
return null;
}
@Hidden
static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(1, void.class, mh, a));
mh.invokeBasic(a[0]);
return null;
}
@Hidden
static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(2, void.class, mh, a));
mh.invokeBasic(a[0], a[1]);
return null;
}
@Hidden
static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(3, void.class, mh, a));
mh.invokeBasic(a[0], a[1], a[2]);
return null;
}
@Hidden
static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(4, void.class, mh, a));
mh.invokeBasic(a[0], a[1], a[2], a[3]);
return null;
}
@Hidden
static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(5, void.class, mh, a));
mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
return null;
}
/** Object return type invokers. */
@Hidden
static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(0, mh, a));
return mh.invokeBasic();
}
@Hidden
static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(1, mh, a));
return mh.invokeBasic(a[0]);
}
@Hidden
static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(2, mh, a));
return mh.invokeBasic(a[0], a[1]);
}
@Hidden
static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(3, mh, a));
return mh.invokeBasic(a[0], a[1], a[2]);
}
@Hidden
static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(4, mh, a));
return mh.invokeBasic(a[0], a[1], a[2], a[3]);
}
@Hidden
static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(5, mh, a));
return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
}
private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
return arityCheck(arity, Object.class, mh, a);
}
private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
assert(a.length == arity)
: Arrays.asList(a.length, arity);
assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
: Arrays.asList(mh, rtype, arity);
MemberName member = mh.internalMemberName();
if (isInvokeBasic(member)) {
assert(arity > 0);
assert(a[0] instanceof MethodHandle);
MethodHandle mh2 = (MethodHandle) a[0];
assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
: Arrays.asList(member, mh2, rtype, arity);
}
return true;
}
static final MethodType INVOKER_METHOD_TYPE =
MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
typeForm = typeForm.basicType().form(); // normalize to basic type
MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
if (mh != null) return mh;
MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while
mh = DirectMethodHandle.make(invoker);
MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
if (mh2 != null) return mh2; // benign race
if (!mh.type().equals(INVOKER_METHOD_TYPE))
throw newInternalError(mh.debugString());
return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh);
}
@Hidden
Object invokeWithArguments(Object... arguments) throws Throwable {
// If we have a cached invoker, call it right away.
// NOTE: The invoker always returns a reference value.
if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments);
assert(checkArgumentTypes(arguments, methodType()));
return invoker().invokeBasic(resolvedHandle(), arguments);
}
@Hidden
Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
Object rval;
try {
traceInterpreter("[ call", this, arguments);
if (invoker == null) {
traceInterpreter("| getInvoker", this);
invoker();
}
if (resolvedHandle == null) {
traceInterpreter("| resolve", this);
resolvedHandle();
}
assert(checkArgumentTypes(arguments, methodType()));
rval = invoker().invokeBasic(resolvedHandle(), arguments);
} catch (Throwable ex) {
traceInterpreter("] throw =>", ex);
throw ex;
}
traceInterpreter("] return =>", rval);
return rval;
}
private MethodHandle invoker() {
if (invoker != null) return invoker;
// Get an invoker and cache it.
return invoker = computeInvoker(methodType().form());
}
private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) {
if (true) return true; // FIXME
MethodType dstType = methodType.form().erasedType();
MethodType srcType = dstType.basicType().wrap();
Class<?>[] ptypes = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Object arg = arguments[i];
Class<?> ptype = arg == null ? Object.class : arg.getClass();
// If the dest. type is a primitive we keep the
// argument type.
ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class;
}
MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap();
assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType;
return true;
}
MethodType methodType() {
if (resolvedHandle != null)
return resolvedHandle.type();
else
// only for certain internal LFs during bootstrapping
return member.getInvocationType();
}
MemberName member() {
assert(assertMemberIsConsistent());
return member;
}
// Called only from assert.
private boolean assertMemberIsConsistent() {
if (resolvedHandle instanceof DirectMethodHandle) {
MemberName m = resolvedHandle.internalMemberName();
assert(m.equals(member));
}
return true;
}
Class<?> memberDeclaringClassOrNull() {
return (member == null) ? null : member.getDeclaringClass();
}
BasicType returnType() {
return basicType(methodType().returnType());
}
BasicType parameterType(int n) {
return basicType(methodType().parameterType(n));
}
int arity() {
return methodType().parameterCount();
}
public String toString() {
if (member == null) return String.valueOf(resolvedHandle);
return member.getDeclaringClass().getSimpleName()+"."+member.getName();
}
public boolean isIdentity() {
return this.equals(identity(returnType()));
}
public boolean isConstantZero() {
return this.equals(constantZero(returnType()));
}
public MethodHandleImpl.Intrinsic intrinsicName() {
return resolvedHandle == null ? MethodHandleImpl.Intrinsic.NONE
: resolvedHandle.intrinsicName();
}
}
public static String basicTypeSignature(MethodType type) {
char[] sig = new char[type.parameterCount() + 2];
int sigp = 0;
for (Class<?> pt : type.parameterList()) {
sig[sigp++] = basicTypeChar(pt);
}
sig[sigp++] = '_';
sig[sigp++] = basicTypeChar(type.returnType());
assert(sigp == sig.length);
return String.valueOf(sig);
}
public static String shortenSignature(String signature) {
// Hack to make signatures more readable when they show up in method names.
final int NO_CHAR = -1, MIN_RUN = 3;
int c0, c1 = NO_CHAR, c1reps = 0;
StringBuilder buf = null;
int len = signature.length();
if (len < MIN_RUN) return signature;
for (int i = 0; i <= len; i++) {
// shift in the next char:
c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i));
if (c1 == c0) { ++c1reps; continue; }
// shift in the next count:
int c0reps = c1reps; c1reps = 1;
// end of a character run
if (c0reps < MIN_RUN) {
if (buf != null) {
while (--c0reps >= 0)
buf.append((char)c0);
}
continue;
}
// found three or more in a row
if (buf == null)
buf = new StringBuilder().append(signature, 0, i - c0reps);
buf.append((char)c0).append(c0reps);
}
return (buf == null) ? signature : buf.toString();
}
static final class Name {
final BasicType type;
private short index;
final NamedFunction function;
final Object constraint; // additional type information, if not null
@Stable final Object[] arguments;
private Name(int index, BasicType type, NamedFunction function, Object[] arguments) {
this.index = (short)index;
this.type = type;
this.function = function;
this.arguments = arguments;
this.constraint = null;
assert(this.index == index);
}
private Name(Name that, Object constraint) {
this.index = that.index;
this.type = that.type;
this.function = that.function;
this.arguments = that.arguments;
this.constraint = constraint;
assert(constraint == null || isParam()); // only params have constraints
assert(constraint == null || constraint instanceof BoundMethodHandle.SpeciesData || constraint instanceof Class);
}
Name(MethodHandle function, Object... arguments) {
this(new NamedFunction(function), arguments);
}
Name(MethodType functionType, Object... arguments) {
this(new NamedFunction(functionType), arguments);
assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE);
}
Name(MemberName function, Object... arguments) {
this(new NamedFunction(function), arguments);
}
Name(NamedFunction function, Object... arguments) {
this(-1, function.returnType(), function, arguments = Arrays.copyOf(arguments, arguments.length, Object[].class));
assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
for (int i = 0; i < arguments.length; i++)
assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
}
/** Create a raw parameter of the given type, with an expected index. */
Name(int index, BasicType type) {
this(index, type, null, null);
}
/** Create a raw parameter of the given type. */
Name(BasicType type) { this(-1, type); }
BasicType type() { return type; }
int index() { return index; }
boolean initIndex(int i) {
if (index != i) {
if (index != -1) return false;
index = (short)i;
}
return true;
}
char typeChar() {
return type.btChar;
}
void resolve() {
if (function != null)
function.resolve();
}
Name newIndex(int i) {
if (initIndex(i)) return this;
return cloneWithIndex(i);
}
Name cloneWithIndex(int i) {
Object[] newArguments = (arguments == null) ? null : arguments.clone();
return new Name(i, type, function, newArguments).withConstraint(constraint);
}
Name withConstraint(Object constraint) {
if (constraint == this.constraint) return this;
return new Name(this, constraint);
}
Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly
if (oldName == newName) return this;
@SuppressWarnings("LocalVariableHidesMemberVariable")
Object[] arguments = this.arguments;
if (arguments == null) return this;
boolean replaced = false;
for (int j = 0; j < arguments.length; j++) {
if (arguments[j] == oldName) {
if (!replaced) {
replaced = true;
arguments = arguments.clone();
}
arguments[j] = newName;
}
}
if (!replaced) return this;
return new Name(function, arguments);
}
/** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i].
* Limit such replacements to {@code start<=i<end}. Return possibly changed self.
*/
Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
if (start >= end) return this;
@SuppressWarnings("LocalVariableHidesMemberVariable")
Object[] arguments = this.arguments;
boolean replaced = false;
eachArg:
for (int j = 0; j < arguments.length; j++) {
if (arguments[j] instanceof Name) {
Name n = (Name) arguments[j];
int check = n.index;
// harmless check to see if the thing is already in newNames:
if (check >= 0 && check < newNames.length && n == newNames[check])
continue eachArg;
// n might not have the correct index: n != oldNames[n.index].
for (int i = start; i < end; i++) {
if (n == oldNames[i]) {
if (n == newNames[i])
continue eachArg;
if (!replaced) {
replaced = true;
arguments = arguments.clone();
}
arguments[j] = newNames[i];
continue eachArg;
}
}
}
}
if (!replaced) return this;
return new Name(function, arguments);
}
void internArguments() {
@SuppressWarnings("LocalVariableHidesMemberVariable")
Object[] arguments = this.arguments;
for (int j = 0; j < arguments.length; j++) {
if (arguments[j] instanceof Name) {
Name n = (Name) arguments[j];
if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
arguments[j] = internArgument(n);
}
}
}
boolean isParam() {
return function == null;
}
boolean isConstantZero() {
return !isParam() && arguments.length == 0 && function.isConstantZero();
}
public String toString() {
return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar();
}
public String debugString() {
String s = paramString();
return (function == null) ? s : s + "=" + exprString();
}
public String paramString() {
String s = toString();
Object c = constraint;
if (c == null)
return s;
if (c instanceof Class) c = ((Class<?>)c).getSimpleName();
return s + "/" + c;
}
public String exprString() {
if (function == null) return toString();
StringBuilder buf = new StringBuilder(function.toString());
buf.append("(");
String cma = "";
for (Object a : arguments) {
buf.append(cma); cma = ",";
if (a instanceof Name || a instanceof Integer)
buf.append(a);
else
buf.append("(").append(a).append(")");
}
buf.append(")");
return buf.toString();
}
static boolean typesMatch(BasicType parameterType, Object object) {
if (object instanceof Name) {
return ((Name)object).type == parameterType;
}
switch (parameterType) {
case I_TYPE: return object instanceof Integer;
case J_TYPE: return object instanceof Long;
case F_TYPE: return object instanceof Float;
case D_TYPE: return object instanceof Double;
}
assert(parameterType == L_TYPE);
return true;
}
/** Return the index of the last occurrence of n in the argument array.
* Return -1 if the name is not used.
*/
int lastUseIndex(Name n) {
if (arguments == null) return -1;
for (int i = arguments.length; --i >= 0; ) {
if (arguments[i] == n) return i;
}
return -1;
}
/** Return the number of occurrences of n in the argument array.
* Return 0 if the name is not used.
*/
int useCount(Name n) {
if (arguments == null) return 0;
int count = 0;
for (int i = arguments.length; --i >= 0; ) {
if (arguments[i] == n) ++count;
}
return count;
}
boolean contains(Name n) {
return this == n || lastUseIndex(n) >= 0;
}
public boolean equals(Name that) {
if (this == that) return true;
if (isParam())
// each parameter is a unique atom
return false; // this != that
return
//this.index == that.index &&
this.type == that.type &&
this.function.equals(that.function) &&
Arrays.equals(this.arguments, that.arguments);
}
@Override
public boolean equals(Object x) {
return x instanceof Name && equals((Name)x);
}
@Override
public int hashCode() {
if (isParam())
return index | (type.ordinal() << 8);
return function.hashCode() ^ Arrays.hashCode(arguments);
}
}
/** Return the index of the last name which contains n as an argument.
* Return -1 if the name is not used. Return names.length if it is the return value.
*/
int lastUseIndex(Name n) {
int ni = n.index, nmax = names.length;
assert(names[ni] == n);
if (result == ni) return nmax; // live all the way beyond the end
for (int i = nmax; --i > ni; ) {
if (names[i].lastUseIndex(n) >= 0)
return i;
}
return -1;
}
/** Return the number of times n is used as an argument or return value. */
int useCount(Name n) {
int ni = n.index, nmax = names.length;
int end = lastUseIndex(n);
if (end < 0) return 0;
int count = 0;
if (end == nmax) { count++; end--; }
int beg = n.index() + 1;
if (beg < arity) beg = arity;
for (int i = beg; i <= end; i++) {
count += names[i].useCount(n);
}
return count;
}
static Name argument(int which, char type) {
return argument(which, basicType(type));
}
static Name argument(int which, BasicType type) {
if (which >= INTERNED_ARGUMENT_LIMIT)
return new Name(which, type);
return INTERNED_ARGUMENTS[type.ordinal()][which];
}
static Name internArgument(Name n) {
assert(n.isParam()) : "not param: " + n;
assert(n.index < INTERNED_ARGUMENT_LIMIT);
if (n.constraint != null) return n;
return argument(n.index, n.type);
}
static Name[] arguments(int extra, String types) {
int length = types.length();
Name[] names = new Name[length + extra];
for (int i = 0; i < length; i++)
names[i] = argument(i, types.charAt(i));
return names;
}
static Name[] arguments(int extra, char... types) {
int length = types.length;
Name[] names = new Name[length + extra];
for (int i = 0; i < length; i++)
names[i] = argument(i, types[i]);
return names;
}
static Name[] arguments(int extra, List<Class<?>> types) {
int length = types.size();
Name[] names = new Name[length + extra];
for (int i = 0; i < length; i++)
names[i] = argument(i, basicType(types.get(i)));
return names;
}
static Name[] arguments(int extra, Class<?>... types) {
int length = types.length;
Name[] names = new Name[length + extra];
for (int i = 0; i < length; i++)
names[i] = argument(i, basicType(types[i]));
return names;
}
static Name[] arguments(int extra, MethodType types) {
int length = types.parameterCount();
Name[] names = new Name[length + extra];
for (int i = 0; i < length; i++)
names[i] = argument(i, basicType(types.parameterType(i)));
return names;
}
static final int INTERNED_ARGUMENT_LIMIT = 10;
private static final Name[][] INTERNED_ARGUMENTS
= new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT];
static {
for (BasicType type : BasicType.ARG_TYPES) {
int ord = type.ordinal();
for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) {
INTERNED_ARGUMENTS[ord][i] = new Name(i, type);
}
}
}
private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
static LambdaForm identityForm(BasicType type) {
return LF_identityForm[type.ordinal()];
}
static LambdaForm zeroForm(BasicType type) {
return LF_zeroForm[type.ordinal()];
}
static NamedFunction identity(BasicType type) {
return NF_identity[type.ordinal()];
}
static NamedFunction constantZero(BasicType type) {
return NF_zero[type.ordinal()];
}
private static final LambdaForm[] LF_identityForm = new LambdaForm[TYPE_LIMIT];
private static final LambdaForm[] LF_zeroForm = new LambdaForm[TYPE_LIMIT];
private static final NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT];
private static final NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT];
private static void createIdentityForms() {
for (BasicType type : BasicType.ALL_TYPES) {
int ord = type.ordinal();
char btChar = type.basicTypeChar();
boolean isVoid = (type == V_TYPE);
Class<?> btClass = type.btClass;
MethodType zeType = MethodType.methodType(btClass);
MethodType idType = isVoid ? zeType : zeType.appendParameterTypes(btClass);
// Look up some symbolic names. It might not be necessary to have these,
// but if we need to emit direct references to bytecodes, it helps.
// Zero is built from a call to an identity function with a constant zero input.
MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic);
MemberName zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic);
try {
zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class);
idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class);
} catch (IllegalAccessException|NoSuchMethodException ex) {
throw newInternalError(ex);
}
NamedFunction idFun = new NamedFunction(idMem);
LambdaForm idForm;
if (isVoid) {
Name[] idNames = new Name[] { argument(0, L_TYPE) };
idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT);
} else {
Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
idForm = new LambdaForm(idMem.getName(), 2, idNames, 1);
}
LF_identityForm[ord] = idForm;
NF_identity[ord] = idFun;
NamedFunction zeFun = new NamedFunction(zeMem);
LambdaForm zeForm;
if (isVoid) {
zeForm = idForm;
} else {
Object zeValue = Wrapper.forBasicType(btChar).zero();
Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) };
zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1);
}
LF_zeroForm[ord] = zeForm;
NF_zero[ord] = zeFun;
assert(idFun.isIdentity());
assert(zeFun.isConstantZero());
assert(new Name(zeFun).isConstantZero());
}
// Do this in a separate pass, so that SimpleMethodHandle.make can see the tables.
for (BasicType type : BasicType.ALL_TYPES) {
int ord = type.ordinal();
NamedFunction idFun = NF_identity[ord];
LambdaForm idForm = LF_identityForm[ord];
MemberName idMem = idFun.member;
idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm);
NamedFunction zeFun = NF_zero[ord];
LambdaForm zeForm = LF_zeroForm[ord];
MemberName zeMem = zeFun.member;
zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm);
assert(idFun.isIdentity());
assert(zeFun.isConstantZero());
assert(new Name(zeFun).isConstantZero());
}
}
// Avoid appealing to ValueConversions at bootstrap time:
private static int identity_I(int x) { return x; }
private static long identity_J(long x) { return x; }
private static float identity_F(float x) { return x; }
private static double identity_D(double x) { return x; }
private static Object identity_L(Object x) { return x; }
private static void identity_V() { return; } // same as zeroV, but that's OK
private static int zero_I() { return 0; }
private static long zero_J() { return 0; }
private static float zero_F() { return 0; }
private static double zero_D() { return 0; }
private static Object zero_L() { return null; }
private static void zero_V() { return; }
/**
* Internal marker for byte-compiled LambdaForms.
*/
/*non-public*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Compiled {
}
/**
* Internal marker for LambdaForm interpreter frames.
*/
/*non-public*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Hidden {
}
private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
static {
if (debugEnabled())
DEBUG_NAME_COUNTERS = new HashMap<>();
else
DEBUG_NAME_COUNTERS = null;
}
// Put this last, so that previous static inits can run before.
static {
createIdentityForms();
if (USE_PREDEFINED_INTERPRET_METHODS)
computeInitialPreparedForms();
NamedFunction.initializeInvokers();
}
// The following hack is necessary in order to suppress TRACE_INTERPRETER
// during execution of the static initializes of this class.
// Turning on TRACE_INTERPRETER too early will cause
// stack overflows and other misbehavior during attempts to trace events
// that occur during LambdaForm.<clinit>.
// Therefore, do not move this line higher in this file, and do not remove.
private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
}
| wupeixuan/JDKSourceCode1.8 | src/java/lang/invoke/LambdaForm.java |
214,225 | /*
* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.invoke;
import static jdk.internal.org.objectweb.asm.Opcodes.*;
import static java.lang.invoke.LambdaForm.*;
import static java.lang.invoke.LambdaForm.BasicType.*;
import static java.lang.invoke.MethodHandleStatics.*;
import java.lang.invoke.LambdaForm.NamedFunction;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.function.Function;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import sun.invoke.util.ValueConversions;
import sun.invoke.util.Wrapper;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.MethodVisitor;
/**
* The flavor of method handle which emulates an invoke instruction
* on a predetermined argument. The JVM dispatches to the correct method
* when the handle is created, not when it is invoked.
*
* All bound arguments are encapsulated in dedicated species.
*/
/*non-public*/ abstract class BoundMethodHandle extends MethodHandle {
/*non-public*/ BoundMethodHandle(MethodType type, LambdaForm form) {
super(type, form);
assert(speciesData() == speciesData(form));
}
//
// BMH API and internals
//
static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, BasicType xtype, Object x) {
// for some type signatures, there exist pre-defined concrete BMH classes
try {
switch (xtype) {
case L_TYPE:
return bindSingle(type, form, x); // Use known fast path.
case I_TYPE:
return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(I_TYPE).constructor().invokeBasic(type, form, ValueConversions.widenSubword(x));
case J_TYPE:
return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(J_TYPE).constructor().invokeBasic(type, form, (long) x);
case F_TYPE:
return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(F_TYPE).constructor().invokeBasic(type, form, (float) x);
case D_TYPE:
return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(D_TYPE).constructor().invokeBasic(type, form, (double) x);
default : throw newInternalError("unexpected xtype: " + xtype);
}
} catch (Throwable t) {
throw newInternalError(t);
}
}
/*non-public*/
LambdaFormEditor editor() {
return form.editor();
}
static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, Object x) {
return Species_L.make(type, form, x);
}
@Override // there is a default binder in the super class, for 'L' types only
/*non-public*/
BoundMethodHandle bindArgumentL(int pos, Object value) {
return editor().bindArgumentL(this, pos, value);
}
/*non-public*/
BoundMethodHandle bindArgumentI(int pos, int value) {
return editor().bindArgumentI(this, pos, value);
}
/*non-public*/
BoundMethodHandle bindArgumentJ(int pos, long value) {
return editor().bindArgumentJ(this, pos, value);
}
/*non-public*/
BoundMethodHandle bindArgumentF(int pos, float value) {
return editor().bindArgumentF(this, pos, value);
}
/*non-public*/
BoundMethodHandle bindArgumentD(int pos, double value) {
return editor().bindArgumentD(this, pos, value);
}
@Override
BoundMethodHandle rebind() {
if (!tooComplex()) {
return this;
}
return makeReinvoker(this);
}
private boolean tooComplex() {
return (fieldCount() > FIELD_COUNT_THRESHOLD ||
form.expressionCount() > FORM_EXPRESSION_THRESHOLD);
}
private static final int FIELD_COUNT_THRESHOLD = 12; // largest convenient BMH field count
private static final int FORM_EXPRESSION_THRESHOLD = 24; // largest convenient BMH expression count
/**
* A reinvoker MH has this form:
* {@code lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) }}
*/
static BoundMethodHandle makeReinvoker(MethodHandle target) {
LambdaForm form = DelegatingMethodHandle.makeReinvokerForm(
target, MethodTypeForm.LF_REBIND,
Species_L.SPECIES_DATA, Species_L.SPECIES_DATA.getterFunction(0));
return Species_L.make(target.type(), form, target);
}
/**
* Return the {@link SpeciesData} instance representing this BMH species. All subclasses must provide a
* static field containing this value, and they must accordingly implement this method.
*/
/*non-public*/ abstract SpeciesData speciesData();
/*non-public*/ static SpeciesData speciesData(LambdaForm form) {
Object c = form.names[0].constraint;
if (c instanceof SpeciesData)
return (SpeciesData) c;
// if there is no BMH constraint, then use the null constraint
return SpeciesData.EMPTY;
}
/**
* Return the number of fields in this BMH. Equivalent to speciesData().fieldCount().
*/
/*non-public*/ abstract int fieldCount();
@Override
Object internalProperties() {
return "\n& BMH="+internalValues();
}
@Override
final Object internalValues() {
Object[] boundValues = new Object[speciesData().fieldCount()];
for (int i = 0; i < boundValues.length; ++i) {
boundValues[i] = arg(i);
}
return Arrays.asList(boundValues);
}
/*non-public*/ final Object arg(int i) {
try {
switch (speciesData().fieldType(i)) {
case L_TYPE: return speciesData().getters[i].invokeBasic(this);
case I_TYPE: return (int) speciesData().getters[i].invokeBasic(this);
case J_TYPE: return (long) speciesData().getters[i].invokeBasic(this);
case F_TYPE: return (float) speciesData().getters[i].invokeBasic(this);
case D_TYPE: return (double) speciesData().getters[i].invokeBasic(this);
}
} catch (Throwable ex) {
throw newInternalError(ex);
}
throw new InternalError("unexpected type: " + speciesData().typeChars+"."+i);
}
//
// cloning API
//
/*non-public*/ abstract BoundMethodHandle copyWith(MethodType mt, LambdaForm lf);
/*non-public*/ abstract BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg);
/*non-public*/ abstract BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg);
/*non-public*/ abstract BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg);
/*non-public*/ abstract BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg);
/*non-public*/ abstract BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg);
//
// concrete BMH classes required to close bootstrap loops
//
private // make it private to force users to access the enclosing class first
static final class Species_L extends BoundMethodHandle {
final Object argL0;
private Species_L(MethodType mt, LambdaForm lf, Object argL0) {
super(mt, lf);
this.argL0 = argL0;
}
@Override
/*non-public*/ SpeciesData speciesData() {
return SPECIES_DATA;
}
@Override
/*non-public*/ int fieldCount() {
return 1;
}
/*non-public*/ static final SpeciesData SPECIES_DATA = new SpeciesData("L", Species_L.class);
/*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) {
return new Species_L(mt, lf, argL0);
}
@Override
/*non-public*/ final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
return new Species_L(mt, lf, argL0);
}
@Override
/*non-public*/ final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
try {
return (BoundMethodHandle) SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
} catch (Throwable ex) {
throw uncaughtException(ex);
}
}
@Override
/*non-public*/ final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
try {
return (BoundMethodHandle) SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
} catch (Throwable ex) {
throw uncaughtException(ex);
}
}
@Override
/*non-public*/ final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
try {
return (BoundMethodHandle) SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
} catch (Throwable ex) {
throw uncaughtException(ex);
}
}
@Override
/*non-public*/ final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
try {
return (BoundMethodHandle) SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
} catch (Throwable ex) {
throw uncaughtException(ex);
}
}
@Override
/*non-public*/ final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
try {
return (BoundMethodHandle) SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
} catch (Throwable ex) {
throw uncaughtException(ex);
}
}
}
//
// BMH species meta-data
//
/**
* Meta-data wrapper for concrete BMH types.
* Each BMH type corresponds to a given sequence of basic field types (LIJFD).
* The fields are immutable; their values are fully specified at object construction.
* Each BMH type supplies an array of getter functions which may be used in lambda forms.
* A BMH is constructed by cloning a shorter BMH and adding one or more new field values.
* The shortest possible BMH has zero fields; its class is SimpleMethodHandle.
* BMH species are not interrelated by subtyping, even though it would appear that
* a shorter BMH could serve as a supertype of a longer one which extends it.
*/
static class SpeciesData {
private final String typeChars;
private final BasicType[] typeCodes;
private final Class<? extends BoundMethodHandle> clazz;
// Bootstrapping requires circular relations MH -> BMH -> SpeciesData -> MH
// Therefore, we need a non-final link in the chain. Use array elements.
@Stable private final MethodHandle[] constructor;
@Stable private final MethodHandle[] getters;
@Stable private final NamedFunction[] nominalGetters;
@Stable private final SpeciesData[] extensions;
/*non-public*/ int fieldCount() {
return typeCodes.length;
}
/*non-public*/ BasicType fieldType(int i) {
return typeCodes[i];
}
/*non-public*/ char fieldTypeChar(int i) {
return typeChars.charAt(i);
}
Object fieldSignature() {
return typeChars;
}
public Class<? extends BoundMethodHandle> fieldHolder() {
return clazz;
}
public String toString() {
return "SpeciesData<"+fieldSignature()+">";
}
/**
* Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that
* represents a MH bound to a generic invoker, which in turn forwards to the corresponding
* getter.
*/
NamedFunction getterFunction(int i) {
NamedFunction nf = nominalGetters[i];
assert(nf.memberDeclaringClassOrNull() == fieldHolder());
assert(nf.returnType() == fieldType(i));
return nf;
}
NamedFunction[] getterFunctions() {
return nominalGetters;
}
MethodHandle[] getterHandles() { return getters; }
MethodHandle constructor() {
return constructor[0];
}
static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class);
SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
this.typeChars = types;
this.typeCodes = basicTypes(types);
this.clazz = clazz;
if (!INIT_DONE) {
this.constructor = new MethodHandle[1]; // only one ctor
this.getters = new MethodHandle[types.length()];
this.nominalGetters = new NamedFunction[types.length()];
} else {
this.constructor = Factory.makeCtors(clazz, types, null);
this.getters = Factory.makeGetters(clazz, types, null);
this.nominalGetters = Factory.makeNominalGetters(types, null, this.getters);
}
this.extensions = new SpeciesData[ARG_TYPE_LIMIT];
}
private void initForBootstrap() {
assert(!INIT_DONE);
if (constructor() == null) {
String types = typeChars;
CACHE.put(types, this);
Factory.makeCtors(clazz, types, this.constructor);
Factory.makeGetters(clazz, types, this.getters);
Factory.makeNominalGetters(types, this.nominalGetters, this.getters);
}
}
private static final ConcurrentMap<String, SpeciesData> CACHE = new ConcurrentHashMap<>();
private static final boolean INIT_DONE; // set after <clinit> finishes...
SpeciesData extendWith(byte type) {
return extendWith(BasicType.basicType(type));
}
SpeciesData extendWith(BasicType type) {
int ord = type.ordinal();
SpeciesData d = extensions[ord];
if (d != null) return d;
extensions[ord] = d = get(typeChars+type.basicTypeChar());
return d;
}
private static SpeciesData get(String types) {
return CACHE.computeIfAbsent(types, new Function<String, SpeciesData>() {
@Override
public SpeciesData apply(String types) {
Class<? extends BoundMethodHandle> bmhcl = Factory.getConcreteBMHClass(types);
// SpeciesData instantiation may throw VirtualMachineError because of
// code cache overflow...
SpeciesData speciesData = new SpeciesData(types, bmhcl);
// CHM.computeIfAbsent ensures only one SpeciesData will be set
// successfully on the concrete BMH class if ever
Factory.setSpeciesDataToConcreteBMHClass(bmhcl, speciesData);
// the concrete BMH class is published via SpeciesData instance
// returned here only after it's SPECIES_DATA field is set
return speciesData;
}
});
}
/**
* This is to be called when assertions are enabled. It checks whether SpeciesData for all of the statically
* defined species subclasses of BoundMethodHandle has been added to the SpeciesData cache. See below in the
* static initializer for
*/
static boolean speciesDataCachePopulated() {
Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;
try {
for (Class<?> c : rootCls.getDeclaredClasses()) {
if (rootCls.isAssignableFrom(c)) {
final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
SpeciesData d = Factory.getSpeciesDataFromConcreteBMHClass(cbmh);
assert(d != null) : cbmh.getName();
assert(d.clazz == cbmh);
assert(CACHE.get(d.typeChars) == d);
}
}
} catch (Throwable e) {
throw newInternalError(e);
}
return true;
}
static {
// Pre-fill the BMH species-data cache with EMPTY and all BMH's inner subclasses.
EMPTY.initForBootstrap();
Species_L.SPECIES_DATA.initForBootstrap();
// check that all static SpeciesData instances have been initialized
assert speciesDataCachePopulated();
// Note: Do not simplify this, because INIT_DONE must not be
// a compile-time constant during bootstrapping.
INIT_DONE = Boolean.TRUE;
}
}
static SpeciesData getSpeciesData(String types) {
return SpeciesData.get(types);
}
/**
* Generation of concrete BMH classes.
*
* A concrete BMH species is fit for binding a number of values adhering to a
* given type pattern. Reference types are erased.
*
* BMH species are cached by type pattern.
*
* A BMH species has a number of fields with the concrete (possibly erased) types of
* bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,
* which can be included as names in lambda forms.
*/
static class Factory {
static final String JLO_SIG = "Ljava/lang/Object;";
static final String JLS_SIG = "Ljava/lang/String;";
static final String JLC_SIG = "Ljava/lang/Class;";
static final String MH = "java/lang/invoke/MethodHandle";
static final String MH_SIG = "L"+MH+";";
static final String BMH = "java/lang/invoke/BoundMethodHandle";
static final String BMH_SIG = "L"+BMH+";";
static final String SPECIES_DATA = "java/lang/invoke/BoundMethodHandle$SpeciesData";
static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
static final String STABLE_SIG = "Ljava/lang/invoke/Stable;";
static final String SPECIES_PREFIX_NAME = "Species_";
static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
static final String VOID_SIG = "()V";
static final String INT_SIG = "()I";
static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
static final ConcurrentMap<String, Class<? extends BoundMethodHandle>> CLASS_CACHE = new ConcurrentHashMap<>();
/**
* Get a concrete subclass of BMH for a given combination of bound types.
*
* @param types the type signature, wherein reference types are erased to 'L'
* @return the concrete BMH class
*/
static Class<? extends BoundMethodHandle> getConcreteBMHClass(String types) {
// CHM.computeIfAbsent ensures generateConcreteBMHClass is called
// only once per key.
return CLASS_CACHE.computeIfAbsent(
types, new Function<String, Class<? extends BoundMethodHandle>>() {
@Override
public Class<? extends BoundMethodHandle> apply(String types) {
return generateConcreteBMHClass(types);
}
});
}
/**
* Generate a concrete subclass of BMH for a given combination of bound types.
*
* A concrete BMH species adheres to the following schema:
*
* <pre>
* class Species_[[types]] extends BoundMethodHandle {
* [[fields]]
* final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
* }
* </pre>
*
* The {@code [[types]]} signature is precisely the string that is passed to this
* method.
*
* The {@code [[fields]]} section consists of one field definition per character in
* the type signature, adhering to the naming schema described in the definition of
* {@link #makeFieldName}.
*
* For example, a concrete BMH species for two reference and one integral bound values
* would have the following shape:
*
* <pre>
* class BoundMethodHandle { ... private static
* final class Species_LLI extends BoundMethodHandle {
* final Object argL0;
* final Object argL1;
* final int argI2;
* private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
* super(mt, lf);
* this.argL0 = argL0;
* this.argL1 = argL1;
* this.argI2 = argI2;
* }
* final SpeciesData speciesData() { return SPECIES_DATA; }
* final int fieldCount() { return 3; }
* @Stable static SpeciesData SPECIES_DATA; // injected afterwards
* static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
* return new Species_LLI(mt, lf, argL0, argL1, argI2);
* }
* final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
* return new Species_LLI(mt, lf, argL0, argL1, argI2);
* }
* final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
* return SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
* }
* final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
* return SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
* }
* final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
* return SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
* }
* final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
* return SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
* }
* public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
* return SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
* }
* }
* </pre>
*
* @param types the type signature, wherein reference types are erased to 'L'
* @return the generated concrete BMH class
*/
static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String types) {
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
String shortTypes = LambdaForm.shortenSignature(types);
final String className = SPECIES_PREFIX_PATH + shortTypes;
final String sourceFile = SPECIES_PREFIX_NAME + shortTypes;
final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC
cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null);
cw.visitSource(sourceFile, null);
// emit static types and SPECIES_DATA fields
FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null);
fw.visitAnnotation(STABLE_SIG, true);
fw.visitEnd();
// emit bound argument fields
for (int i = 0; i < types.length(); ++i) {
final char t = types.charAt(i);
final String fieldName = makeFieldName(types, i);
final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t);
cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd();
}
MethodVisitor mv;
// emit constructor
mv = cw.visitMethod(ACC_PRIVATE, "<init>", makeSignature(types, true), null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0); // this
mv.visitVarInsn(ALOAD, 1); // type
mv.visitVarInsn(ALOAD, 2); // form
mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true), false);
for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
// i counts the arguments, j counts corresponding argument slots
char t = types.charAt(i);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3
mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t));
if (t == 'J' || t == 'D') {
++j; // adjust argument register access
}
}
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
// emit implementation of speciesData()
mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null);
mv.visitCode();
mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
mv.visitInsn(ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
// emit implementation of fieldCount()
mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null);
mv.visitCode();
int fc = types.length();
if (fc <= (ICONST_5 - ICONST_0)) {
mv.visitInsn(ICONST_0 + fc);
} else {
mv.visitIntInsn(SIPUSH, fc);
}
mv.visitInsn(IRETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
// emit make() ...factory method wrapping constructor
mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, false), null, null);
mv.visitCode();
// make instance
mv.visitTypeInsn(NEW, className);
mv.visitInsn(DUP);
// load mt, lf
mv.visitVarInsn(ALOAD, 0); // type
mv.visitVarInsn(ALOAD, 1); // form
// load factory method arguments
for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
// i counts the arguments, j counts corresponding argument slots
char t = types.charAt(i);
mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3
if (t == 'J' || t == 'D') {
++j; // adjust argument register access
}
}
// finally, invoke the constructor and return
mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
mv.visitInsn(ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
// emit copyWith()
mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null);
mv.visitCode();
// make instance
mv.visitTypeInsn(NEW, className);
mv.visitInsn(DUP);
// load mt, lf
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 2);
// put fields on the stack
emitPushFields(types, className, mv);
// finally, invoke the constructor and return
mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
mv.visitInsn(ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
// for each type, emit copyWithExtendT()
for (BasicType type : BasicType.ARG_TYPES) {
int ord = type.ordinal();
char btChar = type.basicTypeChar();
mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + btChar, makeSignature(String.valueOf(btChar), false), null, E_THROWABLE);
mv.visitCode();
// return SPECIES_DATA.extendWith(t).constructor().invokeBasic(mt, lf, argL0, ..., narg)
// obtain constructor
mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
int iconstInsn = ICONST_0 + ord;
assert(iconstInsn <= ICONST_5);
mv.visitInsn(iconstInsn);
mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false);
mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "constructor", "()" + MH_SIG, false);
// load mt, lf
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 2);
// put fields on the stack
emitPushFields(types, className, mv);
// put narg on stack
mv.visitVarInsn(typeLoadOp(btChar), 3);
// finally, invoke the constructor and return
mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + btChar, false), false);
mv.visitInsn(ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
cw.visitEnd();
// load class
final byte[] classFile = cw.toByteArray();
InvokerBytecodeGenerator.maybeDump(className, classFile);
Class<? extends BoundMethodHandle> bmhClass =
//UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
UNSAFE.defineClass(className, classFile, 0, classFile.length,
BoundMethodHandle.class.getClassLoader(), null)
.asSubclass(BoundMethodHandle.class);
return bmhClass;
}
private static int typeLoadOp(char t) {
switch (t) {
case 'L': return ALOAD;
case 'I': return ILOAD;
case 'J': return LLOAD;
case 'F': return FLOAD;
case 'D': return DLOAD;
default : throw newInternalError("unrecognized type " + t);
}
}
private static void emitPushFields(String types, String className, MethodVisitor mv) {
for (int i = 0; i < types.length(); ++i) {
char tc = types.charAt(i);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));
}
}
static String typeSig(char t) {
return t == 'L' ? JLO_SIG : String.valueOf(t);
}
//
// Getter MH generation.
//
private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) {
String fieldName = makeFieldName(types, index);
Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType();
try {
return LOOKUP.findGetter(cbmhClass, fieldName, fieldType);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw newInternalError(e);
}
}
static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) {
if (mhs == null) mhs = new MethodHandle[types.length()];
for (int i = 0; i < mhs.length; ++i) {
mhs[i] = makeGetter(cbmhClass, types, i);
assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass);
}
return mhs;
}
static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) {
if (mhs == null) mhs = new MethodHandle[1];
if (types.equals("")) return mhs; // hack for empty BMH species
mhs[0] = makeCbmhCtor(cbmh, types);
return mhs;
}
static NamedFunction[] makeNominalGetters(String types, NamedFunction[] nfs, MethodHandle[] getters) {
if (nfs == null) nfs = new NamedFunction[types.length()];
for (int i = 0; i < nfs.length; ++i) {
nfs[i] = new NamedFunction(getters[i]);
}
return nfs;
}
//
// Auxiliary methods.
//
static SpeciesData getSpeciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) {
try {
Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
return (SpeciesData) F_SPECIES_DATA.get(null);
} catch (ReflectiveOperationException ex) {
throw newInternalError(ex);
}
}
static void setSpeciesDataToConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh, SpeciesData speciesData) {
try {
Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
assert F_SPECIES_DATA.getDeclaredAnnotation(Stable.class) != null;
F_SPECIES_DATA.set(null, speciesData);
} catch (ReflectiveOperationException ex) {
throw newInternalError(ex);
}
}
/**
* Field names in concrete BMHs adhere to this pattern:
* arg + type + index
* where type is a single character (L, I, J, F, D).
*/
private static String makeFieldName(String types, int index) {
assert index >= 0 && index < types.length();
return "arg" + types.charAt(index) + index;
}
private static String makeSignature(String types, boolean ctor) {
StringBuilder buf = new StringBuilder(SIG_INCIPIT);
for (char c : types.toCharArray()) {
buf.append(typeSig(c));
}
return buf.append(')').append(ctor ? "V" : BMH_SIG).toString();
}
static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) {
try {
return LOOKUP.findStatic(cbmh, "make", MethodType.fromMethodDescriptorString(makeSignature(types, false), null));
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
throw newInternalError(e);
}
}
}
private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
/**
* All subclasses must provide such a value describing their type signature.
*/
static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY;
private static final SpeciesData[] SPECIES_DATA_CACHE = new SpeciesData[5];
private static SpeciesData checkCache(int size, String types) {
int idx = size - 1;
SpeciesData data = SPECIES_DATA_CACHE[idx];
if (data != null) return data;
SPECIES_DATA_CACHE[idx] = data = getSpeciesData(types);
return data;
}
static SpeciesData speciesData_L() { return checkCache(1, "L"); }
static SpeciesData speciesData_LL() { return checkCache(2, "LL"); }
static SpeciesData speciesData_LLL() { return checkCache(3, "LLL"); }
static SpeciesData speciesData_LLLL() { return checkCache(4, "LLLL"); }
static SpeciesData speciesData_LLLLL() { return checkCache(5, "LLLLL"); }
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/java/lang/invoke/BoundMethodHandle.java |
214,226 | package com.android.server.autofill;
import java.util.function.Consumer;
/* renamed from: com.android.server.autofill.-$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk reason: invalid class name */
/* compiled from: lambda */
public final /* synthetic */ class $$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk implements Consumer {
public static final /* synthetic */ $$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk INSTANCE = new $$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk();
private /* synthetic */ $$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk() {
}
public final void accept(Object obj) {
((RemoteFillService) obj).handleBinderDied();
}
}
| dstmath/HWFramework | Mate20-9.0/src/main/java/com/android/server/autofill/$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk.java |
214,227 | /*
* Copyright © 2015-2016
*
* This file is part of Spoofax for IntelliJ.
*
* 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.metaborg.intellij.vfs;
import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.metaborg.util.collection.ImList;
import java.util.Collection;
/**
* IntelliJ file system provider.
*/
public class IntelliJFileProvider extends AbstractOriginatingFileProvider {
// @formatter:off
public static final Collection<Capability> capabilities = ImList.Immutable.of(
Capability.CREATE,
Capability.DELETE,
Capability.RENAME,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.WRITE_CONTENT
);
// @formatter:on
/**
* Initializes a new instance of the {@link IntelliJFileProvider} class.
*/
public IntelliJFileProvider() {
}
/**
* {@inheritDoc}
*/
@Override
public final Collection<Capability> getCapabilities() {
return capabilities;
}
/**
* {@inheritDoc}
*/
@Override
protected FileSystem doCreateFileSystem(final FileName rootName,
final FileSystemOptions fileSystemOptions)
throws FileSystemException {
return new IntelliJFileSystem(rootName, fileSystemOptions);
}
}
| metaborg/spoofax-intellij | spoofax-common/src/main/java/org/metaborg/intellij/vfs/IntelliJFileProvider.java |
214,228 | package fi.aalto.cs.apluscourses.intellij.utils;
import fi.aalto.cs.apluscourses.intellij.services.PluginSettings;
import fi.aalto.cs.apluscourses.presentation.filter.Filter;
import fi.aalto.cs.apluscourses.presentation.filter.Option;
import javax.swing.Icon;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class IntelliJFilterOption extends Option {
private final PluginSettings.LocalIdeSettingsNames setting;
private final PluginSettings.PropertiesManager propertiesManager;
/**
* An option, that is, a filter that when not selected, filters out those that match to the filter
* given to this constructor.
*/
public IntelliJFilterOption(@NotNull PluginSettings.PropertiesManager propertiesManager,
@NotNull PluginSettings.LocalIdeSettingsNames setting,
@NotNull String name,
@Nullable Icon icon,
@NotNull Filter filter) {
super(name, icon, filter);
this.setting = setting;
this.propertiesManager = propertiesManager;
isSelected.addValueObserver(this, IntelliJFilterOption::selectionChanged);
}
@Override
public IntelliJFilterOption init() {
isSelected.set(propertiesManager.getBoolean(setting.getName(), true), this);
return this;
}
private void selectionChanged(@Nullable Boolean value) {
if (value != null) { // if initialized
propertiesManager.setValue(setting.getName(), value, true);
}
}
}
| Aalto-LeTech/aplus-courses | src/main/java/fi/aalto/cs/apluscourses/intellij/utils/IntelliJFilterOption.java |
214,229 | package fitnesse.idea.rt;
import fitnesse.reporting.Formatter;
import fitnesse.testrunner.TestsRunnerListener;
import fitnesse.testrunner.WikiTestPageUtil;
import fitnesse.testsystems.*;
import fitnesse.wiki.WikiPage;
import fitnesse.wiki.fs.FileSystemPage;
import org.apache.commons.lang3.StringEscapeUtils;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.Text;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import static java.lang.String.format;
/**
* This Formatter produces output in a format understood by IntelliJ.
*/
public class IntelliJFormatter implements Formatter, TestsRunnerListener {
private static final String NEWLINE = System.getProperty("line.separator");
private static final String CSI = "\u001B["; // "Control Sequence Initiator"
private static final Pattern ANSI_ESCAPE_PATTERN = Pattern.compile("\u001B\\[.*?m");
private final PrintStream out;
private ExceptionResult exceptionOccurred;
public IntelliJFormatter() {
this(System.out);
}
public IntelliJFormatter(PrintStream out) {
this.out = out;
}
@Override
public void testSystemStarted(TestSystem testSystem) {
log("##teamcity[testSuiteStarted name='%s' locationHint='' captureStandardOutput='true']", testSystem.getName());
}
@Override
public void testStarted(TestPage testPage) {
log("##teamcity[testStarted name='%s' locationHint='%s' captureStandardOutput='true']", testPage.getFullPath(), locationHint(testPage));
}
private String locationHint(TestPage testPage) {
WikiPage wikiPage = WikiTestPageUtil.getSourcePage(testPage);
if (wikiPage instanceof FileSystemPage) {
File fileSystemPath = ((FileSystemPage) wikiPage).getFileSystemPath();
try {
return "fitnesse://" + new File(fileSystemPath, "content.txt").getCanonicalPath();
} catch (IOException e) {
error("Can not determine canonical file location for " + fileSystemPath, e);
return "";
}
}
return "";
}
@Override
public void testOutputChunk(String output) {
try {
NodeList nodes = new Parser(new Lexer(output)).parse(null);
print(translate(nodes));
} catch (ParserException e) {
log("Unparsable wiki output: %s", output);
}
}
private String translate(NodeList nodes) {
StringBuilder sb = new StringBuilder();
translate(nodes, sb);
return sb.toString();
}
private void translate(NodeList nodes, StringBuilder sb) {
if (nodes == null) return;
for (Node node : nodeListIterator(nodes)) {
if (node instanceof TableTag) {
sb.append(translateTable(node.getChildren()));
} else if (node instanceof Span) {
Span span = (Span) node;
sb.append(colorResult(span.getAttribute("class")))
.append(span.getChildrenHTML())
.append(CSI + "0m");
} else if (node instanceof Tag && "BR".equals(((Tag) node).getTagName())) {
sb.append(NEWLINE);
} else if (node.getChildren() != null) {
translate(node.getChildren(), sb);
} else if (node instanceof Text){
sb.append(node.getText());
}
}
}
// See https://en.wikipedia.org/wiki/ANSI_escape_code for the codes
private String colorResult(String result) {
if ("pass".equals(result)) {
return CSI + "30;42m";
} else if ("fail".equals(result)) {
return CSI + "30;41m";
} else if ("error".equals(result)) {
return CSI + "30;43m";
} else if ("ignore".equals(result)) {
return CSI + "30;46m";
}
return "";
}
private String translateTable(NodeList nodes) {
List<List<Integer>> table = new ArrayList<List<Integer>>();
for (Node row : rowIterator(nodes)) {
List<Integer> tableRow = new ArrayList<Integer>();
for (Node cell : columnIterator(row)) {
tableRow.add(cellLength(translate(cell.getChildren())));
}
table.add(tableRow);
}
TableFormatter tableFormatter = new TableFormatter(table);
StringBuilder sb = new StringBuilder();
int rowNr = 0;
for (Node row : rowIterator(nodes)) {
int colNr = 0;
for (Node cell : columnIterator(row)) {
sb.append("|")
.append(tableFormatter.leftPaddingString())
.append(translate(cell.getChildren()))
.append(tableFormatter.rightPaddingString(rowNr, colNr));
colNr++;
}
sb.append("|\n");
rowNr++;
}
return sb.toString();
}
private Iterable<Node> columnIterator(Node row) {
return nodeListIterator(row.getChildren().extractAllNodesThatMatch(new NodeClassFilter(TableColumn.class)));
}
private Iterable<Node> rowIterator(NodeList nodes) {
return nodeListIterator(nodes.extractAllNodesThatMatch(new NodeClassFilter(TableRow.class)));
}
private Iterable<Node> nodeListIterator(NodeList nodes) {
final SimpleNodeIterator iter = nodes.elements();
return new Iterable<Node>() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
@Override public boolean hasNext() { return iter.hasMoreNodes(); }
@Override public Node next() { return iter.nextNode(); }
@Override public void remove() { throw new IllegalStateException("NodeList iterator.remove() should not have been called"); }
};
}
};
}
@Override
public void testComplete(TestPage testPage, TestSummary summary) {
String fullPath = testPage.getFullPath();
if (exceptionOccurred != null) {
log("##teamcity[testFailed name='%s' message='%s' error='true']", fullPath, exceptionOccurred.getMessage() != null ? exceptionOccurred.getMessage().replace("'", "|'") : exceptionOccurred.toString());
exceptionOccurred = null;
} else if (summary.getWrong() > 0 || summary.getExceptions() > 0) {
log("##teamcity[testFailed name='%s' message='Test failed: R:%d W:%d I:%d E:%d']", fullPath, summary.getRight(), summary.getWrong(), summary.getIgnores(), summary.getExceptions());
} else {
log("##teamcity[testFinished name='%s']", fullPath);
}
}
@Override
public void testAssertionVerified(Assertion assertion, TestResult testResult) {
// Nothing to do here
}
@Override
public void testExceptionOccurred(Assertion assertion, ExceptionResult exceptionResult) {
if (exceptionOccurred == null) {
exceptionOccurred = exceptionResult;
}
}
@Override
public void testSystemStopped(TestSystem testSystem, Throwable cause) {
log("##teamcity[testSuiteFinished name='%s']", testSystem.getName());
}
@Override
public void announceNumberTestsToRun(int i) {
log("##teamcity[testCount count='%d']", i);
}
@Override
public void unableToStartTestSystem(String s, Throwable throwable) {
log("Unable to start test system %s", s);
throwable.printStackTrace(out);
}
private void log(String s, Object... args) {
out.println(format(s, args));
out.flush();
}
private void print(String s) {
OutputStreamWriter writer = new OutputStreamWriter(out);
try {
StringEscapeUtils.UNESCAPE_XML.translate(s, writer);
writer.flush();
} catch (IOException e) {
error("Unable to write output", e);
}
}
private void error(String message, Throwable cause) {
System.err.println(message);
cause.printStackTrace(System.err);
}
private static int cellLength(String tableCell) {
return ANSI_ESCAPE_PATTERN.matcher(tableCell.split("\n")[0]).replaceAll("").length();
}
}
| gshakhn/idea-fitnesse | idea-fitnesse_rt/src/main/java/fitnesse/idea/rt/IntelliJFormatter.java |
214,230 | package com.android.server.autofill;
import java.util.function.Consumer;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk implements Consumer {
public static final /* synthetic */ -$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk INSTANCE = new -$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk();
private /* synthetic */ -$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk() {
}
public final void accept(Object obj) {
((RemoteFillService) obj).handleBinderDied();
}
}
| SivanLiu/HwFrameWorkSource | Mate20_9_0_0/src/main/java/com/android/server/autofill/-$$Lambda$RemoteFillService$1sGSxm1GNkRnOTqlIJFPKrlV6Bk.java |
214,231 | 404: Not Found | microsoft/azure-tools-for-java | PluginsAndFeatures/azure-toolkit-for-intellij/azure-intellij-plugin-appservice/src/main/java/com/microsoft/azure/toolkit/intellij/legacy/function/runner/IntelliJFunctionContext.java |
214,232 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.lang.invoke;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;
import sun.invoke.util.Wrapper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* Helper class to assist the GenerateJLIClassesPlugin to get access to
* generate classes ahead of time.
*/
class GenerateJLIClassesHelper {
static byte[] generateBasicFormsClassBytes(String className) {
ArrayList<LambdaForm> forms = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
HashSet<String> dedupSet = new HashSet<>();
for (LambdaForm.BasicType type : LambdaForm.BasicType.values()) {
LambdaForm zero = LambdaForm.zeroForm(type);
String name = zero.kind.defaultLambdaName
+ "_" + zero.returnType().basicTypeChar();
if (dedupSet.add(name)) {
names.add(name);
forms.add(zero);
}
LambdaForm identity = LambdaForm.identityForm(type);
name = identity.kind.defaultLambdaName
+ "_" + identity.returnType().basicTypeChar();
if (dedupSet.add(name)) {
names.add(name);
forms.add(identity);
}
}
return generateCodeBytesForLFs(className,
names.toArray(new String[0]),
forms.toArray(new LambdaForm[0]));
}
static byte[] generateDirectMethodHandleHolderClassBytes(String className,
MethodType[] methodTypes, int[] types) {
ArrayList<LambdaForm> forms = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < methodTypes.length; i++) {
LambdaForm form = DirectMethodHandle
.makePreparedLambdaForm(methodTypes[i], types[i]);
forms.add(form);
names.add(form.kind.defaultLambdaName);
}
for (Wrapper wrapper : Wrapper.values()) {
if (wrapper == Wrapper.VOID) {
continue;
}
for (byte b = DirectMethodHandle.AF_GETFIELD; b < DirectMethodHandle.AF_LIMIT; b++) {
int ftype = DirectMethodHandle.ftypeKind(wrapper.primitiveType());
LambdaForm form = DirectMethodHandle
.makePreparedFieldLambdaForm(b, /*isVolatile*/false, ftype);
if (form.kind != LambdaForm.Kind.GENERIC) {
forms.add(form);
names.add(form.kind.defaultLambdaName);
}
// volatile
form = DirectMethodHandle
.makePreparedFieldLambdaForm(b, /*isVolatile*/true, ftype);
if (form.kind != LambdaForm.Kind.GENERIC) {
forms.add(form);
names.add(form.kind.defaultLambdaName);
}
}
}
return generateCodeBytesForLFs(className,
names.toArray(new String[0]),
forms.toArray(new LambdaForm[0]));
}
static byte[] generateDelegatingMethodHandleHolderClassBytes(String className,
MethodType[] methodTypes) {
HashSet<MethodType> dedupSet = new HashSet<>();
ArrayList<LambdaForm> forms = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < methodTypes.length; i++) {
// generate methods representing the DelegatingMethodHandle
if (dedupSet.add(methodTypes[i])) {
// reinvokers are variant with the associated SpeciesData
// and shape of the target LF, but we can easily pregenerate
// the basic reinvokers associated with Species_L. Ultimately we
// may want to consider pregenerating more of these, which will
// require an even more complex naming scheme
LambdaForm reinvoker = makeReinvokerFor(methodTypes[i]);
forms.add(reinvoker);
String speciesSig = BoundMethodHandle.speciesDataFor(reinvoker).key();
assert(speciesSig.equals("L"));
names.add(reinvoker.kind.defaultLambdaName + "_" + speciesSig);
LambdaForm delegate = makeDelegateFor(methodTypes[i]);
forms.add(delegate);
names.add(delegate.kind.defaultLambdaName);
}
}
return generateCodeBytesForLFs(className,
names.toArray(new String[0]),
forms.toArray(new LambdaForm[0]));
}
static byte[] generateInvokersHolderClassBytes(String className,
MethodType[] invokerMethodTypes, MethodType[] callSiteMethodTypes) {
HashSet<MethodType> dedupSet = new HashSet<>();
ArrayList<LambdaForm> forms = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
int[] types = {
MethodTypeForm.LF_EX_LINKER,
MethodTypeForm.LF_EX_INVOKER,
MethodTypeForm.LF_GEN_LINKER,
MethodTypeForm.LF_GEN_INVOKER
};
for (int i = 0; i < invokerMethodTypes.length; i++) {
// generate methods representing invokers of the specified type
if (dedupSet.add(invokerMethodTypes[i])) {
for (int type : types) {
LambdaForm invokerForm = Invokers.invokeHandleForm(invokerMethodTypes[i],
/*customized*/false, type);
forms.add(invokerForm);
names.add(invokerForm.kind.defaultLambdaName);
}
}
}
dedupSet = new HashSet<>();
for (int i = 0; i < callSiteMethodTypes.length; i++) {
// generate methods representing invokers of the specified type
if (dedupSet.add(callSiteMethodTypes[i])) {
LambdaForm callSiteForm = Invokers.callSiteForm(callSiteMethodTypes[i], true);
forms.add(callSiteForm);
names.add(callSiteForm.kind.defaultLambdaName);
LambdaForm methodHandleForm = Invokers.callSiteForm(callSiteMethodTypes[i], false);
forms.add(methodHandleForm);
names.add(methodHandleForm.kind.defaultLambdaName);
}
}
return generateCodeBytesForLFs(className,
names.toArray(new String[0]),
forms.toArray(new LambdaForm[0]));
}
/*
* Generate customized code for a set of LambdaForms of specified types into
* a class with a specified name.
*/
private static byte[] generateCodeBytesForLFs(String className,
String[] names, LambdaForm[] forms) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
className, null, InvokerBytecodeGenerator.INVOKER_SUPER_NAME, null);
cw.visitSource(className.substring(className.lastIndexOf('/') + 1), null);
for (int i = 0; i < forms.length; i++) {
addMethod(className, names[i], forms[i],
forms[i].methodType(), cw);
}
return cw.toByteArray();
}
private static void addMethod(String className, String methodName, LambdaForm form,
MethodType type, ClassWriter cw) {
InvokerBytecodeGenerator g
= new InvokerBytecodeGenerator(className, methodName, form, type);
g.setClassWriter(cw);
g.addMethod();
}
private static LambdaForm makeReinvokerFor(MethodType type) {
MethodHandle emptyHandle = MethodHandles.empty(type);
return DelegatingMethodHandle.makeReinvokerForm(emptyHandle,
MethodTypeForm.LF_REBIND,
BoundMethodHandle.speciesData_L(),
BoundMethodHandle.speciesData_L().getterFunction(0));
}
private static LambdaForm makeDelegateFor(MethodType type) {
MethodHandle handle = MethodHandles.empty(type);
return DelegatingMethodHandle.makeReinvokerForm(
handle,
MethodTypeForm.LF_DELEGATE,
DelegatingMethodHandle.class,
DelegatingMethodHandle.NF_getTarget);
}
@SuppressWarnings({"rawtypes", "unchecked"})
static Map.Entry<String, byte[]> generateConcreteBMHClassBytes(final String types) {
for (char c : types.toCharArray()) {
if ("LIJFD".indexOf(c) < 0) {
throw new IllegalArgumentException("All characters must "
+ "correspond to a basic field type: LIJFD");
}
}
final BoundMethodHandle.SpeciesData species = BoundMethodHandle.SPECIALIZER.findSpecies(types);
final String className = species.speciesCode().getName();
final ClassSpecializer.Factory factory = BoundMethodHandle.SPECIALIZER.factory();
final byte[] code = factory.generateConcreteSpeciesCodeFile(className, species);
return Map.entry(className.replace('.', '/'), code);
}
}
| zxiaofan/JDK | jdk-12/src/java.base/java/lang/invoke/GenerateJLIClassesHelper.java |
214,234 | 404: Not Found | ccnio/Warehouse | app/src/main/java/com/ware/systip/CameraCropActivity.java |
214,238 | package com.xkj.mlrc.clean.file;
import com.xkj.mlrc.clean.domain.ParamOption;
import com.xkj.mlrc.clean.util.ArgsUtil;
import com.xkj.mlrc.clean.util.HdfsUtils;
import com.xkj.mlrc.fsimage.GetFromFsImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.spark.api.java.function.ForeachFunction;
import org.apache.spark.sql.*;
import java.io.IOException;
/**
* hdfs文件清理
* @author [email protected]
* @date 2020/4/21 14:06
* @desc
*/
@Slf4j
public class HdfsFileClean {
public static void main(String[] args) {
SparkSession spark = getSparkSession();
ParamOption option = ArgsUtil.getOption(args);
GetFromFsImageInfo fsImageInfo = GetFromFsImageInfo.builder()
.spark(spark)
.avoidPrefix(option.avoidPrefix)
.avoidSuffix(option.avoidSuffix)
.avoidPath(option.avoidPath)
.expire(option.expire)
.targetPath(option.targetPath)
.hdfsroot(option.hdfsroot)
.build();
Dataset<Row> allFiles = fsImageInfo.getAllFiles();
allFiles.foreach(new ForeachFunction<Row>() {
@Override
public void call(Row row) throws Exception {
String path = row.getAs("path").toString();
try {
HdfsUtils.trashPath(path);
log.info("删除路径成功:" + path);
} catch (IOException e) {
log.info("删除路径失败:" + path);
e.printStackTrace();
}
}
});
}
private static SparkSession getSparkSession() {
return SparkSession
.builder()
.master("local[2]")
.appName(HdfsFileClean.class.getSimpleName())
.enableHiveSupport()
.getOrCreate();
}
}
| lijufeng2016/data-manager | src/main/java/com/xkj/mlrc/clean/file/HdfsFileClean.java |
214,239 | package ui;
import domain.Cirkel;
import domain.LijnStuk;
import domain.Punt;
import domain.Rechthoek;
import domain.Tekening;
import domain.Vorm;
public class TekeningHangMan extends Tekening {
private int aantalZichtbaar = 4;
public TekeningHangMan() {
super("HangMan");
Vorm galgBodem = new Rechthoek(new Punt(10, 350), 300, 40);
Vorm galgStaaf = new LijnStuk(new Punt(160, 350), new Punt(160, 50));
Vorm hangbar = new LijnStuk(new Punt(160, 50), new Punt(280, 50));
Vorm koord = new LijnStuk(new Punt(280, 50), new Punt(280, 100));
Vorm hoofd = new Cirkel(new Punt(280, 125), 25);
Vorm oogLinks = new Cirkel(new Punt(270, 118), 2);
Vorm oogRechts = new Cirkel(new Punt(290, 118), 2);
Vorm neus = new Cirkel(new Punt(280, 128), 2);
Vorm mond = new LijnStuk(new Punt(270, 138), new Punt(290, 138));
Vorm lijf = new LijnStuk(new Punt(280, 150), new Punt(280, 250));
Vorm beenLinks = new LijnStuk(new Punt(280, 250), new Punt(240, 310));
Vorm beenRechts = new LijnStuk(new Punt(280, 250), new Punt(320, 310));
Vorm voetLinks = new Cirkel(new Punt(240, 310), 5);
Vorm voetRechts = new Cirkel(new Punt(320, 310), 5);
Vorm armLinks = new LijnStuk(new Punt(280, 200), new Punt(230, 170));
Vorm armRechts = new LijnStuk(new Punt(280, 200), new Punt(330, 170));
Vorm handLinks = new Cirkel(new Punt(230, 170), 5);
Vorm handRechts = new Cirkel(new Punt(330, 170), 5);
hoofd.setZichtbaar(false);
oogLinks.setZichtbaar(false);
oogRechts.setZichtbaar(false);
neus.setZichtbaar(false);
mond.setZichtbaar(false);
lijf.setZichtbaar(false);
beenLinks.setZichtbaar(false);
beenRechts.setZichtbaar(false);
voetLinks.setZichtbaar(false);
voetRechts.setZichtbaar(false);
armLinks.setZichtbaar(false);
armRechts.setZichtbaar(false);
handLinks.setZichtbaar(false);
handRechts.setZichtbaar(false);
super.voegToe(galgBodem);
super.voegToe(galgStaaf);
super.voegToe(hangbar);
super.voegToe(koord);
super.voegToe(hoofd);
super.voegToe(oogLinks);
super.voegToe(oogRechts);
super.voegToe(neus);
super.voegToe(mond);
super.voegToe(lijf);
super.voegToe(beenLinks);
super.voegToe(beenRechts);
super.voegToe(voetLinks);
super.voegToe(voetRechts);
super.voegToe(armLinks);
super.voegToe(armRechts);
super.voegToe(handLinks);
super.voegToe(handRechts);
}
public int getAantalOnzichtbaar() {
return getAantalVormen() - aantalZichtbaar;
}
public void zetVolgendeZichtbaar() {
if(alleVormenZichtbaar()) {
throw new UiException("Alle vormen zijn al zichtbaar");
}
getVorm(aantalZichtbaar).setZichtbaar(true);
aantalZichtbaar++;
}
public boolean alleVormenZichtbaar() {
return aantalZichtbaar == getAantalVormen();
}
public void reset() {
for(int i = 4; i < getAantalVormen(); i++) {
getVorm(i).setZichtbaar(false);
}
}
@Override
public void voegToe(Vorm vorm) {
throw new UiException("Er mogen geen vormen toegevoegd worden aan de hangman tekening");
}
@Override
public void verwijder(Vorm vorm) {
throw new UiException("Er mogen geen vormen verwijderd worden van de hangman tekening");
}
}
| TuurDutoit/GameSuiteHangman | GamesuiteHangman/src/ui/TekeningHangMan.java |
214,242 | package nl.topicus.eduarte.dao.hibernate;
import nl.topicus.cobra.dao.hibernate.AbstractZoekFilterDataAccessHelper;
import nl.topicus.cobra.dao.hibernate.CriteriaBuilder;
import nl.topicus.cobra.dao.hibernate.QueryInterceptor;
import nl.topicus.cobra.dao.hibernate.HibernateSessionProvider;
import nl.topicus.cobra.util.Asserts;
import nl.topicus.eduarte.dao.helpers.VerblijfsvergunningDataAccessHelper;
import nl.topicus.eduarte.entities.landelijk.Verblijfsvergunning;
import nl.topicus.eduarte.zoekfilters.LandelijkCodeNaamZoekFilter;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
public class VerblijfsvergunningHibernateDataAccessHelper
extends
AbstractZoekFilterDataAccessHelper<Verblijfsvergunning, LandelijkCodeNaamZoekFilter<Verblijfsvergunning>>
implements VerblijfsvergunningDataAccessHelper
{
public VerblijfsvergunningHibernateDataAccessHelper(HibernateSessionProvider provider,
QueryInterceptor interceptor)
{
super(provider, interceptor);
}
@Override
protected Criteria createCriteria(LandelijkCodeNaamZoekFilter<Verblijfsvergunning> filter)
{
Criteria criteria = createCriteria(Verblijfsvergunning.class);
CriteriaBuilder builder = new CriteriaBuilder(criteria);
builder.addILikeCheckWildcard("naam", filter.getNaam(), MatchMode.ANYWHERE);
builder.addEquals("code", filter.getCode());
filter.addQuickSearchCriteria(builder, "code", "naam");
return criteria;
}
@Override
public Verblijfsvergunning get(String code)
{
Asserts.assertNotEmpty("code", code);
Criteria criteria = createCriteria(Verblijfsvergunning.class);
criteria.add(Restrictions.eq("code", code));
return cachedTypedUnique(criteria);
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/core/src/main/java/nl/topicus/eduarte/dao/hibernate/VerblijfsvergunningHibernateDataAccessHelper.java |
214,245 | package saros.intellij.filesystem;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import saros.filesystem.IContainer;
import saros.filesystem.IFile;
import saros.filesystem.IPath;
import saros.filesystem.IProject;
import saros.filesystem.IResource;
public final class IntelliJFileImpl extends IntelliJResourceImpl implements IFile {
private static final int BUFFER_SIZE = 32 * 1024;
/** Relative path from the given project */
private final IPath path;
private final IntelliJProjectImpl project;
public IntelliJFileImpl(@NotNull final IntelliJProjectImpl project, @NotNull final IPath path) {
this.project = project;
this.path = path;
}
/**
* Returns whether this file exists.
*
* <p><b>Note:</b> An ignored file is treated as being nonexistent.
*
* @return <code>true</code> if the resource exists, is a file, and is not ignored, <code>false
* </code> otherwise
* @see #isIgnored()
*/
@Override
public boolean exists() {
final VirtualFile file = project.findVirtualFile(path);
return file != null && file.exists() && !file.isDirectory();
}
@NotNull
@Override
public IPath getFullPath() {
return project.getFullPath().append(path);
}
@NotNull
@Override
public String getName() {
return path.lastSegment();
}
/**
* Returns the parent of this file.
*
* <p><b>Note:</b> The interface specification for this method does allow <code>null</code> as a
* return value. This implementation, however, can not return null values, as suggested by its
* NotNull tag.
*
* @return an <code>IContainer</code> object for the parent of this file
*/
@NotNull
@Override
public IContainer getParent() {
if (path.segmentCount() == 1) return project;
return new IntelliJFolderImpl(project, path.removeLastSegments(1));
}
@NotNull
@Override
public IProject getProject() {
return project;
}
@NotNull
@Override
public IPath getProjectRelativePath() {
return path;
}
@Override
public int getType() {
return IResource.FILE;
}
@Override
public void delete(final int updateFlags) throws IOException {
Filesystem.runWriteAction(
new ThrowableComputable<Void, IOException>() {
@Override
public Void compute() throws IOException {
final VirtualFile file = project.findVirtualFile(path);
if (file == null)
throw new FileNotFoundException(
IntelliJFileImpl.this + " does not exist or is ignored");
if (file.isDirectory()) throw new IOException(this + " is not a file");
file.delete(IntelliJFileImpl.this);
return null;
}
},
ModalityState.defaultModalityState());
}
@Override
public void move(@NotNull final IPath destination, final boolean force) throws IOException {
throw new IOException("NYI");
}
@NotNull
@Override
public IPath getLocation() {
// TODO might return a wrong location
return project.getLocation().append(path);
}
@Nullable
@Override
public String getCharset() throws IOException {
final VirtualFile file = project.findVirtualFile(path);
return file == null ? null : file.getCharset().name();
}
@NotNull
@Override
public InputStream getContents() throws IOException {
/*
* TODO maybe this needs to be wrapped, the core logic assumes that it
* can read from any thread
*/
final VirtualFile file = project.findVirtualFile(path);
if (file == null) throw new FileNotFoundException(this + " does not exist or is ignored");
return file.getInputStream();
}
/**
* Sets the content of this file in the local filesystem.
*
* <p><b>Note:</b> The force flag is not supported.
*
* @param input new contents of the file
* @param force not supported
* @param keepHistory not supported
* @throws IOException if the file does not exist
*/
@Override
public void setContents(final InputStream input, final boolean force, final boolean keepHistory)
throws IOException {
Filesystem.runWriteAction(
new ThrowableComputable<Void, IOException>() {
@Override
public Void compute() throws IOException {
final VirtualFile file = project.findVirtualFile(path);
if (file == null) {
String exceptionText = IntelliJFileImpl.this + " does not exist or is ignored";
if (force) exceptionText += ", force option is not supported";
throw new FileNotFoundException(exceptionText);
}
final OutputStream out = file.getOutputStream(IntelliJFileImpl.this);
final InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input;
final byte[] buffer = new byte[BUFFER_SIZE];
int read = 0;
try {
while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read);
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
return null;
}
},
ModalityState.defaultModalityState());
}
/**
* Creates this file in the local filesystem with the given content.
*
* <p><b>Note:</b> The force flag is not supported. It does not allow the re-creation of an
* already existing file.
*
* @param input contents of the new file
* @param force not supported
* @throws FileAlreadyExistsException if the file already exists
* @throws FileNotFoundException if the parent directory of this file does not exist
*/
@Override
public void create(@Nullable final InputStream input, final boolean force) throws IOException {
Filesystem.runWriteAction(
new ThrowableComputable<Void, IOException>() {
@Override
public Void compute() throws IOException {
final IResource parent = getParent();
final VirtualFile parentFile = project.findVirtualFile(parent.getProjectRelativePath());
if (parentFile == null)
throw new FileNotFoundException(
parent
+ " does not exist or is ignored, cannot create file "
+ IntelliJFileImpl.this);
final VirtualFile file = parentFile.findChild(getName());
if (file != null) {
String exceptionText = IntelliJFileImpl.this + " already exists";
if (force) exceptionText += ", force option is not supported";
throw new FileAlreadyExistsException(exceptionText);
}
parentFile.createChildData(IntelliJFileImpl.this, getName());
if (input != null) setContents(input, force, true);
return null;
}
},
ModalityState.defaultModalityState());
}
@Override
public long getSize() throws IOException {
final VirtualFile file = project.findVirtualFile(path);
return file == null ? 0L : file.getLength();
}
@Override
public int hashCode() {
return project.hashCode() + 31 * path.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
IntelliJFileImpl other = (IntelliJFileImpl) obj;
return project.equals(other.project) && path.equals(other.path);
}
@Override
public String toString() {
return getClass().getSimpleName() + " : " + path + " - " + project;
}
}
| Flowdalic/saros | intellij/src/saros/intellij/filesystem/IntelliJFileImpl.java |
214,248 | package nl.topicus.eduarte.web.components.panels.datapanel.table;
import nl.topicus.cobra.web.components.datapanel.CustomDataPanelContentDescription;
import nl.topicus.cobra.web.components.datapanel.columns.CustomPropertyColumn;
import nl.topicus.eduarte.entities.landelijk.Verblijfsvergunning;
/**
* Tabel met de mogelijke kolommen voor verblijfsvergunningen.
*
* @author schimmel
*/
public class VerblijfsvergunningTable extends
CustomDataPanelContentDescription<Verblijfsvergunning>
{
private static final long serialVersionUID = 1L;
public VerblijfsvergunningTable()
{
super("Verblijfsvergunningen");
createColumns();
}
private void createColumns()
{
addColumn(new CustomPropertyColumn<Verblijfsvergunning>("Code", "Code", "code", "code"));
addColumn(new CustomPropertyColumn<Verblijfsvergunning>("Naam", "Naam", "naam", "naam"));
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/core/src/main/java/nl/topicus/eduarte/web/components/panels/datapanel/table/VerblijfsvergunningTable.java |
214,249 | /*
* Copyright (c) 2007, Topicus B.V.
* All rights reserved.
*/
package nl.topicus.eduarte.web.components.panels.filter;
import java.util.Arrays;
import nl.topicus.eduarte.entities.landelijk.Verblijfsvergunning;
import nl.topicus.eduarte.zoekfilters.LandelijkCodeNaamZoekFilter;
import org.apache.wicket.markup.html.navigation.paging.IPageable;
/**
* @author schimmel
*/
public class VerblijfsvergunningZoekFilterPanel extends
AutoZoekFilterPanel<LandelijkCodeNaamZoekFilter<Verblijfsvergunning>>
{
private static final long serialVersionUID = 1L;
public VerblijfsvergunningZoekFilterPanel(String id,
LandelijkCodeNaamZoekFilter<Verblijfsvergunning> filter, final IPageable pageable)
{
super(id, filter, pageable);
setPropertyNames(Arrays.asList("code", "naam"));
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/core/src/main/java/nl/topicus/eduarte/web/components/panels/filter/VerblijfsvergunningZoekFilterPanel.java |
214,250 | package saros.intellij.filesystem;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.roots.ModuleFileIndex;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import saros.filesystem.IContainer;
import saros.filesystem.IFolder;
import saros.filesystem.IPath;
import saros.filesystem.IProject;
import saros.filesystem.IResource;
import saros.intellij.project.filesystem.IntelliJPathImpl;
public final class IntelliJFolderImpl extends IntelliJResourceImpl implements IFolder {
/** Relative path from the given project */
private final IPath path;
private final IntelliJProjectImpl project;
public IntelliJFolderImpl(@NotNull final IntelliJProjectImpl project, @NotNull final IPath path) {
this.project = project;
this.path = path;
}
@Override
public boolean exists(@NotNull IPath path) {
return project.exists(this.path.append(path));
}
@NotNull
@Override
public IResource[] members() throws IOException {
// TODO run as read action
final VirtualFile folder = project.findVirtualFile(path);
if (folder == null || !folder.exists())
throw new FileNotFoundException(this + " does not exist or is ignored");
if (!folder.isDirectory()) throw new IOException(this + " is a file");
final List<IResource> result = new ArrayList<>();
final VirtualFile[] children = folder.getChildren();
ModuleFileIndex moduleFileIndex =
ModuleRootManager.getInstance(project.getModule()).getFileIndex();
for (final VirtualFile child : children) {
if (!moduleFileIndex.isInContent(child)) {
continue;
}
final IPath childPath = path.append(IntelliJPathImpl.fromString(child.getName()));
result.add(
child.isDirectory()
? new IntelliJFolderImpl(project, childPath)
: new IntelliJFileImpl(project, childPath));
}
return result.toArray(new IResource[result.size()]);
}
@NotNull
@Override
public IResource[] members(final int memberFlags) throws IOException {
return members();
}
@Nullable
@Override
public String getDefaultCharset() throws IOException {
// TODO retrieve encoding for the module or use the project settings
return getParent().getDefaultCharset();
}
/**
* Returns whether this folder exists.
*
* <p><b>Note:</b> An ignored folder is treated as being nonexistent.
*
* @return <code>true</code> if the resource exists, is a folder, and is not ignored, <code>false
* </code> otherwise
* @see #isIgnored()
*/
@Override
public boolean exists() {
final VirtualFile file = project.findVirtualFile(path);
return file != null && file.exists() && file.isDirectory();
}
@NotNull
@Override
public IPath getFullPath() {
return project.getFullPath().append(path);
}
@NotNull
@Override
public String getName() {
return path.lastSegment();
}
/**
* Returns the parent of this folder.
*
* <p><b>Note:</b> The interface specification for this method does allow <code>null</code> as a
* return value. This implementation, however, can not return null values, as suggested by its
* NotNull tag.
*
* @return an <code>IContainer</code> object for the parent of this folder
*/
@NotNull
@Override
public IContainer getParent() {
if (path.segmentCount() == 1) return project;
return new IntelliJFolderImpl(project, path.removeLastSegments(1));
}
@NotNull
@Override
public IProject getProject() {
return project;
}
@NotNull
@Override
public IPath getProjectRelativePath() {
return path;
}
@Override
public int getType() {
return IResource.FOLDER;
}
@Override
public void delete(final int updateFlags) throws IOException {
Filesystem.runWriteAction(
new ThrowableComputable<Void, IOException>() {
@Override
public Void compute() throws IOException {
final VirtualFile file = project.findVirtualFile(path);
if (file == null)
throw new FileNotFoundException(
IntelliJFolderImpl.this + " does not exist or is ignored");
if (!file.isDirectory()) throw new IOException(this + " is not a folder");
file.delete(IntelliJFolderImpl.this);
return null;
}
},
ModalityState.defaultModalityState());
}
@Override
public void move(final IPath destination, final boolean force) throws IOException {
throw new IOException("NYI");
}
@NotNull
@Override
public IPath getLocation() {
// TODO might return a wrong location
return project.getLocation().append(path);
}
@Override
public void create(final int updateFlags, final boolean local) throws IOException {
this.create((updateFlags & IResource.FORCE) != 0, local);
}
/**
* Creates this folder in the local filesystem.
*
* <p><b>Note:</b> The force flag is not supported. It does not allow the re-creation of an
* already existing folder.
*
* @param force not supported
* @param local not supported
* @throws FileAlreadyExistsException if the folder already exists
* @throws FileNotFoundException if the parent directory of this folder does not exist
*/
@Override
public void create(final boolean force, final boolean local) throws IOException {
Filesystem.runWriteAction(
new ThrowableComputable<Void, IOException>() {
@Override
public Void compute() throws IOException {
final IResource parent = getParent();
final VirtualFile parentFile = project.findVirtualFile(parent.getProjectRelativePath());
if (parentFile == null)
throw new FileNotFoundException(
parent
+ " does not exist or is ignored, cannot create folder "
+ IntelliJFolderImpl.this);
final VirtualFile file = parentFile.findChild(getName());
if (file != null) {
String exceptionText = IntelliJFolderImpl.this + " already exists";
if (force) exceptionText += ", force option is not supported";
throw new FileAlreadyExistsException(exceptionText);
}
parentFile.createChildDirectory(IntelliJFolderImpl.this, getName());
return null;
}
},
ModalityState.defaultModalityState());
}
@Override
public int hashCode() {
return project.hashCode() + 31 * path.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
IntelliJFolderImpl other = (IntelliJFolderImpl) obj;
return project.equals(other.project) && path.equals(other.path);
}
@Override
public String toString() {
return getClass().getSimpleName() + " : " + path + " - " + project;
}
}
| Flowdalic/saros | intellij/src/saros/intellij/filesystem/IntelliJFolderImpl.java |
214,251 | package com.syntax.class17;
public class IntellijFeatures2 {
public static void main(String[] args) {
boolean flag=true;
if(!flag==true){
System.out.println("This can be simplified i ma writing complex code");
}else{
System.out.println("Intellij Will help");
}
}
}
| mrdagdemir/Class17 | IntellijFeatures2.java |