X stringlengths 236 264k | y stringlengths 5 74 |
|---|---|
/*
* Copyright (c) 2023, 2025, 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.graal.compiler.nodes.extended;
import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0;
import jdk.graal.compiler.graph.IterableNodeType;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph. [MASK] ;
import jdk.graal.compiler.graph.spi.NodeWithIdentity;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodeinfo.NodeInfo;
import jdk.graal.compiler.nodes.GraphState.StageFlag;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.spi.Canonicalizable;
import jdk.graal.compiler.nodes.spi.CanonicalizerTool;
import jdk.graal.compiler.nodes.spi.LIRLowerable;
import jdk.graal.compiler.phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an OpaqueValueNode.
* <p>
* This node accepts an optional {@link StageFlag} argument. If set, the node will canonicalize away
* after that stage has been applied to the graph.
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the graph before LIR
* generation. {@link OpaqueValueNode}s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class OpaqueValueNode extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final [MASK] <OpaqueValueNode> TYPE = [MASK] .create(OpaqueValueNode.class);
@Input(InputType.Value) private ValueNode value;
private final StageFlag foldAfter;
public OpaqueValueNode(ValueNode value) {
this(value, null);
}
public OpaqueValueNode(ValueNode value, StageFlag foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@Override
public ValueNode getValue() {
return value;
}
@Override
public void setValue(ValueNode value) {
this.updateUsages(this.value, value);
this.value = value;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this.graph() != null && this.graph().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| NodeClass |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.skywalking.generator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import lombok.Data;
@JsonDeserialize(builder = StringGenerator.Builder.class)
public final class StringGenerator implements Generator<String, String> {
private final int length;
private final String prefix;
private final boolean letters;
private final boolean numbers;
private final boolean limitedDomain;
private final Random random = ThreadLocalRandom.current();
private final Set<String> domain = new HashSet<>();
public StringGenerator(Builder builder) {
length = builder.length;
prefix = builder.prefix;
letters = builder.letters;
numbers = builder.numbers;
limitedDomain = builder.domainSize > 0;
if (limitedDomain) {
while (domain.size() < builder.domainSize) {
final String r = RandomStringUtils.random(length, letters, numbers);
if (!Strings.isNullOrEmpty(builder.prefix)) {
domain.add(builder.prefix + r);
} else {
domain.add(r);
}
}
}
}
@Override
public String next(String [MASK] ) {
if (Strings.isNullOrEmpty( [MASK] )) {
[MASK] = "";
} else {
[MASK] += "-";
}
if (!limitedDomain) {
return [MASK] + Strings.nullToEmpty(prefix)
+ RandomStringUtils.random(length, letters, numbers);
}
return [MASK] + domain
.stream()
.skip(random.nextInt(domain.size()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Should never happen"));
}
@Override
public String toString() {
return String.valueOf(next(null));
}
@Data
public static class Builder {
private int length;
private String prefix;
private boolean letters;
private boolean numbers;
private int domainSize;
public StringGenerator build() {
return new StringGenerator(this);
}
}
}
| parent |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> [MASK] = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
[MASK] .add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if ( [MASK] .isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if ( [MASK] .size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString( [MASK] ));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString( [MASK] ));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| missingAliases |
/*
* Copyright (c) 2023, 2025, 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.graal.compiler.nodes.extended;
import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0;
import jdk.graal.compiler. [MASK] .IterableNodeType;
import jdk.graal.compiler. [MASK] .Node;
import jdk.graal.compiler. [MASK] .NodeClass;
import jdk.graal.compiler. [MASK] .spi.NodeWithIdentity;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodeinfo.NodeInfo;
import jdk.graal.compiler.nodes.GraphState.StageFlag;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.spi.Canonicalizable;
import jdk.graal.compiler.nodes.spi.CanonicalizerTool;
import jdk.graal.compiler.nodes.spi.LIRLowerable;
import jdk.graal.compiler.phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an OpaqueValueNode.
* <p>
* This node accepts an optional {@link StageFlag} argument. If set, the node will canonicalize away
* after that stage has been applied to the [MASK] .
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the [MASK] before LIR
* generation. {@link OpaqueValueNode}s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class OpaqueValueNode extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final NodeClass<OpaqueValueNode> TYPE = NodeClass.create(OpaqueValueNode.class);
@Input(InputType.Value) private ValueNode value;
private final StageFlag foldAfter;
public OpaqueValueNode(ValueNode value) {
this(value, null);
}
public OpaqueValueNode(ValueNode value, StageFlag foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@Override
public ValueNode getValue() {
return value;
}
@Override
public void setValue(ValueNode value) {
this.updateUsages(this.value, value);
this.value = value;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this. [MASK] () != null && this. [MASK] ().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| graph |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
[MASK] reference =
new [MASK] (descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional< [MASK] > find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set< [MASK] > findAll() {
return Collections.singleton(reference);
}
};
}
}
| ModuleReference |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.skywalking.generator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import lombok.Data;
@JsonDeserialize(builder = StringGenerator.Builder.class)
public final class StringGenerator implements Generator<String, String> {
private final int length;
private final String prefix;
private final boolean letters;
private final boolean numbers;
private final boolean limitedDomain;
private final Random [MASK] = ThreadLocalRandom.current();
private final Set<String> domain = new HashSet<>();
public StringGenerator(Builder builder) {
length = builder.length;
prefix = builder.prefix;
letters = builder.letters;
numbers = builder.numbers;
limitedDomain = builder.domainSize > 0;
if (limitedDomain) {
while (domain.size() < builder.domainSize) {
final String r = RandomStringUtils. [MASK] (length, letters, numbers);
if (!Strings.isNullOrEmpty(builder.prefix)) {
domain.add(builder.prefix + r);
} else {
domain.add(r);
}
}
}
}
@Override
public String next(String parent) {
if (Strings.isNullOrEmpty(parent)) {
parent = "";
} else {
parent += "-";
}
if (!limitedDomain) {
return parent + Strings.nullToEmpty(prefix)
+ RandomStringUtils. [MASK] (length, letters, numbers);
}
return parent + domain
.stream()
.skip( [MASK] .nextInt(domain.size()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Should never happen"));
}
@Override
public String toString() {
return String.valueOf(next(null));
}
@Data
public static class Builder {
private int length;
private String prefix;
private boolean letters;
private boolean numbers;
private int domainSize;
public StringGenerator build() {
return new StringGenerator(this);
}
}
}
| random |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile. [MASK] (toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()). [MASK] (
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile(). [MASK] (toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| equals |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
[MASK] xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
[MASK] tool [MASK] = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = tool [MASK] .getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
[MASK] plugin [MASK] = ( [MASK] ) object;
Attribute classAttribute = plugin [MASK] .getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + plugin [MASK] .getAttributeValue("CLASS") +
" from tool: " + template.getName());
tool [MASK] .removeContent(plugin [MASK] );
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
[MASK] element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
[MASK] root = doc.getRoot [MASK] ();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
[MASK] root = doc.getRoot [MASK] ();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| Element |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap. [MASK] Set()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases. [MASK] Set()
.stream()
.flatMap( [MASK] -> [MASK] .getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var [MASK] : responseAliasMap. [MASK] Set()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains( [MASK] .getKey())) {
builder.startObject( [MASK] .getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : [MASK] .getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var [MASK] : dataStreamAliases. [MASK] Set()) {
builder.startObject( [MASK] .getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : [MASK] .getValue()) {
builder.startObject(alias.getName());
if ( [MASK] .getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter( [MASK] .getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter( [MASK] .getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| entry |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.skywalking.generator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import org.apache.commons.lang3. [MASK] ;
import lombok.Data;
@JsonDeserialize(builder = StringGenerator.Builder.class)
public final class StringGenerator implements Generator<String, String> {
private final int length;
private final String prefix;
private final boolean letters;
private final boolean numbers;
private final boolean limitedDomain;
private final Random random = ThreadLocalRandom.current();
private final Set<String> domain = new HashSet<>();
public StringGenerator(Builder builder) {
length = builder.length;
prefix = builder.prefix;
letters = builder.letters;
numbers = builder.numbers;
limitedDomain = builder.domainSize > 0;
if (limitedDomain) {
while (domain.size() < builder.domainSize) {
final String r = [MASK] .random(length, letters, numbers);
if (!Strings.isNullOrEmpty(builder.prefix)) {
domain.add(builder.prefix + r);
} else {
domain.add(r);
}
}
}
}
@Override
public String next(String parent) {
if (Strings.isNullOrEmpty(parent)) {
parent = "";
} else {
parent += "-";
}
if (!limitedDomain) {
return parent + Strings.nullToEmpty(prefix)
+ [MASK] .random(length, letters, numbers);
}
return parent + domain
.stream()
.skip(random.nextInt(domain.size()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Should never happen"));
}
@Override
public String toString() {
return String.valueOf(next(null));
}
@Data
public static class Builder {
private int length;
private String prefix;
private boolean letters;
private boolean numbers;
private int domainSize;
public StringGenerator build() {
return new StringGenerator(this);
}
}
}
| RandomStringUtils |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.client.registration.cli.commands;
import org.keycloak.client.cli.common.BaseGlobalOptionsCmd;
import org.keycloak.client.registration.cli.KcRegMain;
import java.io.PrintWriter;
import java.io. [MASK] ;
import picocli.CommandLine.Command;
import static org.keycloak.client.cli.util.OsUtil.PROMPT;
import static org.keycloak.client.registration.cli.KcRegMain.CMD;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
@Command(name = "kcreg",
header = {
"Keycloak - Open Source Identity and Access Management",
"",
"Find more information at: https://www.keycloak.org/docs/latest"
},
description = {
"%nCOMMAND [ARGUMENTS]"
},
subcommands = {
HelpCmd.class,
ConfigCmd.class,
CreateCmd.class,
GetCmd.class,
UpdateCmd.class,
DeleteCmd.class,
AttrsCmd.class,
UpdateTokenCmd.class
})
public class KcRegCmd extends BaseGlobalOptionsCmd {
@Override
protected boolean nothingToDo() {
return true;
}
@Override
protected String help() {
return usage();
}
public static String usage() {
[MASK] sb = new [MASK] ();
PrintWriter out = new PrintWriter(sb);
out.println("Keycloak Client Registration CLI");
out.println();
out.println("Use '" + CMD + " config credentials' command with username and password to start a session against a specific");
out.println("server and realm.");
out.println();
out.println("For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " config credentials --server http://localhost:8080 --realm master --user admin");
out.println(" Enter password: ");
out.println(" Logging into http://localhost:8080 as user admin of realm master");
out.println();
out.println("Any configured username can be used for login, but to perform client registration operations the user");
out.println("needs proper roles, otherwise attempts to create, update, read, or delete clients will fail.");
out.println("Alternatively, the user without the necessary roles can use an Initial Access Token provided by realm");
out.println("administrator when creating a new client with 'create' command. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " create -f my_client.json -t -");
out.println(" Enter Initial Access Token: ");
out.println(" Registered new client with client_id 'my_client'");
out.println();
out.println("When Initial Access Token is used the server issues a Registration Access Token which is automatically");
out.println("handled by " + CMD + ", saved into a local config file, and automatically used for any follow-up operations");
out.println("on the same client. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " get my_client");
out.println(" " + PROMPT + " " + CMD + " update my_client -s enabled=false");
out.println(" " + PROMPT + " " + CMD + " delete my_client");
out.println();
out.println();
out.println("Usage: " + CMD + " COMMAND [ARGUMENTS]");
out.println();
out.println("Global options:");
out.println(" -x Print full stack trace when exiting with error");
out.println(" --help Print help for specific command");
out.println(" --config Path to the config file (" + KcRegMain.DEFAULT_CONFIG_FILE_STRING + " by default)");
out.println(" --no-config Don't use config file - no authentication info is loaded or saved");
out.println();
out.println("Commands: ");
out.println(" config Set up credentials, and other configuration settings using the config file");
out.println(" create Register a new client");
out.println(" get Get configuration of existing client in Keycloak or OIDC format, or adapter install configuration");
out.println(" update Update a client configuration");
out.println(" delete Delete a client");
out.println(" attrs List available attributes");
out.println(" update-token Update Registration Access Token for a client");
out.println(" help This help");
out.println();
out.println("Use '" + CMD + " help <command>' for more information about a given command.");
return sb.toString();
}
}
| StringWriter |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.transaction.operation;
import org.redisson.RedissonKeys;
import org.redisson.RedissonLock;
import org.redisson.api.RKeys;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.transaction.RedissonTransactionalLock;
import org.redisson.transaction.RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class [MASK] extends TransactionalOperation {
private String writeLockName;
private String lockName;
private String transactionId;
public [MASK] (String name) {
this(name, null, 0, null);
}
public [MASK] (String name, String lockName, long threadId, String transactionId) {
super(name, null, threadId);
this.lockName = lockName;
this.transactionId = transactionId;
}
public [MASK] (String name, String lockName, String writeLockName, long threadId, String transactionId) {
this(name, lockName, threadId, transactionId);
this.writeLockName = writeLockName;
}
@Override
public void commit(CommandAsyncExecutor commandExecutor) {
RKeys keys = new RedissonKeys(commandExecutor);
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor commandExecutor) {
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| UnlinkOperation |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak. [MASK] .registration.cli.commands;
import org.keycloak. [MASK] .cli.common.BaseGlobalOptionsCmd;
import org.keycloak. [MASK] .registration.cli.KcRegMain;
import java.io.PrintWriter;
import java.io.StringWriter;
import picocli.CommandLine.Command;
import static org.keycloak. [MASK] .cli.util.OsUtil.PROMPT;
import static org.keycloak. [MASK] .registration.cli.KcRegMain.CMD;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
@Command(name = "kcreg",
header = {
"Keycloak - Open Source Identity and Access Management",
"",
"Find more information at: https://www.keycloak.org/docs/latest"
},
description = {
"%nCOMMAND [ARGUMENTS]"
},
subcommands = {
HelpCmd.class,
ConfigCmd.class,
CreateCmd.class,
GetCmd.class,
UpdateCmd.class,
DeleteCmd.class,
AttrsCmd.class,
UpdateTokenCmd.class
})
public class KcRegCmd extends BaseGlobalOptionsCmd {
@Override
protected boolean nothingToDo() {
return true;
}
@Override
protected String help() {
return usage();
}
public static String usage() {
StringWriter sb = new StringWriter();
PrintWriter out = new PrintWriter(sb);
out.println("Keycloak Client Registration CLI");
out.println();
out.println("Use '" + CMD + " config credentials' command with username and password to start a session against a specific");
out.println("server and realm.");
out.println();
out.println("For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " config credentials --server http://localhost:8080 --realm master --user admin");
out.println(" Enter password: ");
out.println(" Logging into http://localhost:8080 as user admin of realm master");
out.println();
out.println("Any configured username can be used for login, but to perform [MASK] registration operations the user");
out.println("needs proper roles, otherwise attempts to create, update, read, or delete [MASK] s will fail.");
out.println("Alternatively, the user without the necessary roles can use an Initial Access Token provided by realm");
out.println("administrator when creating a new [MASK] with 'create' command. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " create -f my_ [MASK] .json -t -");
out.println(" Enter Initial Access Token: ");
out.println(" Registered new [MASK] with [MASK] _id 'my_ [MASK] '");
out.println();
out.println("When Initial Access Token is used the server issues a Registration Access Token which is automatically");
out.println("handled by " + CMD + ", saved into a local config file, and automatically used for any follow-up operations");
out.println("on the same [MASK] . For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " get my_ [MASK] ");
out.println(" " + PROMPT + " " + CMD + " update my_ [MASK] -s enabled=false");
out.println(" " + PROMPT + " " + CMD + " delete my_ [MASK] ");
out.println();
out.println();
out.println("Usage: " + CMD + " COMMAND [ARGUMENTS]");
out.println();
out.println("Global options:");
out.println(" -x Print full stack trace when exiting with error");
out.println(" --help Print help for specific command");
out.println(" --config Path to the config file (" + KcRegMain.DEFAULT_CONFIG_FILE_STRING + " by default)");
out.println(" --no-config Don't use config file - no authentication info is loaded or saved");
out.println();
out.println("Commands: ");
out.println(" config Set up credentials, and other configuration settings using the config file");
out.println(" create Register a new [MASK] ");
out.println(" get Get configuration of existing [MASK] in Keycloak or OIDC format, or adapter install configuration");
out.println(" update Update a [MASK] configuration");
out.println(" delete Delete a [MASK] ");
out.println(" attrs List available attributes");
out.println(" update-token Update Registration Access Token for a [MASK] ");
out.println(" help This help");
out.println();
out.println("Use '" + CMD + " help <command>' for more information about a given command.");
return sb.toString();
}
}
| client |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> [MASK] ;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* ' [MASK] ' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if ( [MASK] != null) {
return [MASK] ;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames(" [MASK] ", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
[MASK] = Collections.unmodifiableSet(set);
return [MASK] ;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* ' [MASK] ' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| defaultTools |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
[MASK] (
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
[MASK] ("net.bytebuddy", "net.bytebuddy"),
[MASK] ("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder [MASK] (String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| automaticModule |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class [MASK] {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger( [MASK] .class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private [MASK] () {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = [MASK] .readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
[MASK] .deleteTool(toolTemplate);
toolTemplate.setName(newName);
[MASK] .writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while ( [MASK] .getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| ToolUtils |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www. [MASK] .org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org. [MASK] .commons.lang3.StringUtils;
import org. [MASK] .logging.log4j.LogManager;
import org. [MASK] .logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| apache |
package cn.binarywang.wx.miniapp.api.impl;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaStableAccessTokenRequest;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import me.chanjar.weixin.common.util.http.HttpType;
import me.chanjar.weixin.common.util.http.okhttp.DefaultOkHttpClientBuilder;
import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.Objects;
/**
* okhttp实现.
*/
public class WxMaServiceOkHttpImpl extends BaseWxMaServiceImpl<OkHttpClient, OkHttpProxyInfo> {
private OkHttpClient httpClient;
private OkHttpProxyInfo httpProxy;
@Override
public void initHttp() {
WxMaConfig wxMpConfigStorage = this.getWxMaConfig();
//设置代理
if (wxMpConfigStorage.getHttpProxyHost() != null && wxMpConfigStorage.getHttpProxyPort() > 0) {
httpProxy = OkHttpProxyInfo.httpProxy(wxMpConfigStorage.getHttpProxyHost(),
wxMpConfigStorage.getHttpProxyPort(),
wxMpConfigStorage.getHttpProxyUsername(),
wxMpConfigStorage.getHttpProxyPassword());
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.proxy(getRequestHttpProxy().getProxy());
//设置授权
clientBuilder.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response [MASK] ) throws IOException {
String credential = Credentials.basic(httpProxy.getProxyUsername(), httpProxy.getProxyPassword());
return [MASK] .request().newBuilder()
.header("Authorization", credential)
.build();
}
});
httpClient = clientBuilder.build();
} else {
httpClient = DefaultOkHttpClientBuilder.get().build();
}
}
@Override
public OkHttpClient getRequestHttpClient() {
return httpClient;
}
@Override
public OkHttpProxyInfo getRequestHttpProxy() {
return httpProxy;
}
@Override
public HttpType getRequestType() {
return HttpType.OK_HTTP;
}
@Override
protected String doGetAccessTokenRequest() throws IOException {
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
WxMaService.GET_ACCESS_TOKEN_URL.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
WxMaService.GET_ACCESS_TOKEN_URL;
url = String.format(url, this.getWxMaConfig().getAppid(), this.getWxMaConfig().getSecret());
Request request = new Request.Builder().url(url).get().build();
try (Response [MASK] = getRequestHttpClient().newCall(request).execute()) {
return Objects.requireNonNull( [MASK] .body()).string();
}
}
@Override
protected String doGetStableAccessTokenRequest(boolean forceRefresh) throws IOException {
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
GET_STABLE_ACCESS_TOKEN.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
GET_STABLE_ACCESS_TOKEN;
WxMaStableAccessTokenRequest wxMaAccessTokenRequest = new WxMaStableAccessTokenRequest();
wxMaAccessTokenRequest.setAppid(this.getWxMaConfig().getAppid());
wxMaAccessTokenRequest.setSecret(this.getWxMaConfig().getSecret());
wxMaAccessTokenRequest.setGrantType("client_credential");
wxMaAccessTokenRequest.setForceRefresh(forceRefresh);
RequestBody body = RequestBody.Companion.create(wxMaAccessTokenRequest.toJson(), MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder().url(url).post(body).build();
try (Response [MASK] = getRequestHttpClient().newCall(request).execute()) {
return Objects.requireNonNull( [MASK] .body()).string();
}
}
}
| response |
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.commons.io;
import java.io.Serializable;
import java.io. [MASK] ;
/**
* Copy from apache commons-io.
*
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
*/
public class StringBuilder [MASK] extends [MASK] implements Serializable {
private static final long serialVersionUID = -146927496096066153L;
private final StringBuilder builder;
/**
* Constructs a new {@link StringBuilder} instance with default capacity.
*/
public StringBuilder [MASK] () {
this.builder = new StringBuilder();
}
/**
* Constructs a new {@link StringBuilder} instance with the specified capacity.
* @param capacity The initial capacity of the underlying {@link StringBuilder}
*/
public StringBuilder [MASK] (final int capacity) {
this.builder = new StringBuilder(capacity);
}
/**
* Constructs a new instance with the specified {@link StringBuilder}.
*
* <p>
* If {@code builder} is null a new instance with default capacity will be created.
* </p>
* @param builder The String builder. May be null.
*/
public StringBuilder [MASK] (final StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
/**
* Appends a single character to this [MASK] .
* @param value The character to append
* @return This writer instance
*/
@Override
public [MASK] append(final char value) {
builder.append(value);
return this;
}
/**
* Appends a character sequence to this [MASK] .
* @param value The character to append
* @return This writer instance
*/
@Override
public [MASK] append(final CharSequence value) {
builder.append(value);
return this;
}
/**
* Appends a portion of a character sequence to the {@link StringBuilder}.
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public [MASK] append(final CharSequence value, final int start, final int end) {
builder.append(value, start, end);
return this;
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
// no-op
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
// no-op
}
/**
* Writes a String to the {@link StringBuilder}.
* @param value The value to write
*/
@Override
public void write(final String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Writes a portion of a character array to the {@link StringBuilder}.
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(final char[] value, final int offset, final int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
/**
* Returns the underlying builder.
* @return The underlying builder
*/
public StringBuilder getBuilder() {
return builder;
}
/**
* Returns {@link StringBuilder#toString()}.
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
| Writer |
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.commons.io;
import java.io.Serializable;
import java.io.Writer;
/**
* Copy from apache commons-io.
*
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
*/
public class [MASK] Writer extends Writer implements Serializable {
private static final long serialVersionUID = -146927496096066153L;
private final [MASK] builder;
/**
* Constructs a new {@link [MASK] } instance with default capacity.
*/
public [MASK] Writer() {
this.builder = new [MASK] ();
}
/**
* Constructs a new {@link [MASK] } instance with the specified capacity.
* @param capacity The initial capacity of the underlying {@link [MASK] }
*/
public [MASK] Writer(final int capacity) {
this.builder = new [MASK] (capacity);
}
/**
* Constructs a new instance with the specified {@link [MASK] }.
*
* <p>
* If {@code builder} is null a new instance with default capacity will be created.
* </p>
* @param builder The String builder. May be null.
*/
public [MASK] Writer(final [MASK] builder) {
this.builder = builder != null ? builder : new [MASK] ();
}
/**
* Appends a single character to this Writer.
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(final char value) {
builder.append(value);
return this;
}
/**
* Appends a character sequence to this Writer.
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(final CharSequence value) {
builder.append(value);
return this;
}
/**
* Appends a portion of a character sequence to the {@link [MASK] }.
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer append(final CharSequence value, final int start, final int end) {
builder.append(value, start, end);
return this;
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
// no-op
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
// no-op
}
/**
* Writes a String to the {@link [MASK] }.
* @param value The value to write
*/
@Override
public void write(final String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Writes a portion of a character array to the {@link [MASK] }.
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(final char[] value, final int offset, final int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
/**
* Returns the underlying builder.
* @return The underlying builder
*/
public [MASK] getBuilder() {
return builder;
}
/**
* Returns {@link [MASK] #toString()}.
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
| StringBuilder |
/*
* Copyright (c) 2023, 2025, 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.graal.compiler. [MASK] .extended;
import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0;
import jdk.graal.compiler.graph.IterableNodeType;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph.NodeClass;
import jdk.graal.compiler.graph.spi.NodeWithIdentity;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodeinfo.NodeInfo;
import jdk.graal.compiler. [MASK] .GraphState.StageFlag;
import jdk.graal.compiler. [MASK] .NodeView;
import jdk.graal.compiler. [MASK] .ValueNode;
import jdk.graal.compiler. [MASK] .spi.Canonicalizable;
import jdk.graal.compiler. [MASK] .spi.CanonicalizerTool;
import jdk.graal.compiler. [MASK] .spi.LIRLowerable;
import jdk.graal.compiler.phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an OpaqueValueNode.
* <p>
* This node accepts an optional {@link StageFlag} argument. If set, the node will canonicalize away
* after that stage has been applied to the graph.
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the graph before LIR
* generation. {@link OpaqueValueNode}s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class OpaqueValueNode extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final NodeClass<OpaqueValueNode> TYPE = NodeClass.create(OpaqueValueNode.class);
@Input(InputType.Value) private ValueNode value;
private final StageFlag foldAfter;
public OpaqueValueNode(ValueNode value) {
this(value, null);
}
public OpaqueValueNode(ValueNode value, StageFlag foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@Override
public ValueNode getValue() {
return value;
}
@Override
public void setValue(ValueNode value) {
this.updateUsages(this.value, value);
this.value = value;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this.graph() != null && this.graph().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| nodes |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin. [MASK] ;
import org.elasticsearch.action.admin. [MASK] .alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin. [MASK] .alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> [MASK] ToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display [MASK] that have aliases
[MASK] ToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || [MASK] ToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to [MASK] (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] [MASK] = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest. [MASK] ( [MASK] );
getAliasesRequest. [MASK] Options(IndicesOptions.fromRequest(request, getAliasesRequest. [MASK] Options()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
. [MASK] ()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| indices |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson. [MASK] .operation;
import org.redisson.RedissonKeys;
import org.redisson.RedissonLock;
import org.redisson.api.RKeys;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson. [MASK] .RedissonTransactionalLock;
import org.redisson. [MASK] .RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class UnlinkOperation extends TransactionalOperation {
private String writeLockName;
private String lockName;
private String [MASK] Id;
public UnlinkOperation(String name) {
this(name, null, 0, null);
}
public UnlinkOperation(String name, String lockName, long threadId, String [MASK] Id) {
super(name, null, threadId);
this.lockName = lockName;
this. [MASK] Id = [MASK] Id;
}
public UnlinkOperation(String name, String lockName, String writeLockName, long threadId, String [MASK] Id) {
this(name, lockName, threadId, [MASK] Id);
this.writeLockName = writeLockName;
}
@Override
public void commit(CommandAsyncExecutor commandExecutor) {
RKeys keys = new RedissonKeys(commandExecutor);
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, [MASK] Id);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, [MASK] Id);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor commandExecutor) {
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, [MASK] Id);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, [MASK] Id);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| transaction |
/*
* Copyright (c) 2023, 2025, 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.graal.compiler.nodes.extended;
import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0;
import jdk.graal.compiler.graph.IterableNodeType;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph.NodeClass;
import jdk.graal.compiler.graph.spi.NodeWithIdentity;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodeinfo.NodeInfo;
import jdk.graal.compiler.nodes.GraphState. [MASK] ;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.spi.Canonicalizable;
import jdk.graal.compiler.nodes.spi.CanonicalizerTool;
import jdk.graal.compiler.nodes.spi.LIRLowerable;
import jdk.graal.compiler.phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an OpaqueValueNode.
* <p>
* This node accepts an optional {@link [MASK] } argument. If set, the node will canonicalize away
* after that stage has been applied to the graph.
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the graph before LIR
* generation. {@link OpaqueValueNode}s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class OpaqueValueNode extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final NodeClass<OpaqueValueNode> TYPE = NodeClass.create(OpaqueValueNode.class);
@Input(InputType.Value) private ValueNode value;
private final [MASK] foldAfter;
public OpaqueValueNode(ValueNode value) {
this(value, null);
}
public OpaqueValueNode(ValueNode value, [MASK] foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@Override
public ValueNode getValue() {
return value;
}
@Override
public void setValue(ValueNode value) {
this.updateUsages(this.value, value);
this.value = value;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this.graph() != null && this.graph().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| StageFlag |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.skywalking.generator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import lombok.Data;
@JsonDeserialize(builder = StringGenerator. [MASK] .class)
public final class StringGenerator implements Generator<String, String> {
private final int length;
private final String prefix;
private final boolean letters;
private final boolean numbers;
private final boolean limitedDomain;
private final Random random = ThreadLocalRandom.current();
private final Set<String> domain = new HashSet<>();
public StringGenerator( [MASK] builder) {
length = builder.length;
prefix = builder.prefix;
letters = builder.letters;
numbers = builder.numbers;
limitedDomain = builder.domainSize > 0;
if (limitedDomain) {
while (domain.size() < builder.domainSize) {
final String r = RandomStringUtils.random(length, letters, numbers);
if (!Strings.isNullOrEmpty(builder.prefix)) {
domain.add(builder.prefix + r);
} else {
domain.add(r);
}
}
}
}
@Override
public String next(String parent) {
if (Strings.isNullOrEmpty(parent)) {
parent = "";
} else {
parent += "-";
}
if (!limitedDomain) {
return parent + Strings.nullToEmpty(prefix)
+ RandomStringUtils.random(length, letters, numbers);
}
return parent + domain
.stream()
.skip(random.nextInt(domain.size()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Should never happen"));
}
@Override
public String toString() {
return String.valueOf(next(null));
}
@Data
public static class [MASK] {
private int length;
private String prefix;
private boolean letters;
private boolean numbers;
private int domainSize;
public StringGenerator build() {
return new StringGenerator(this);
}
}
}
| Builder |
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.commons.io;
import java.io.Serializable;
import java.io.Writer;
/**
* Copy from apache commons-io.
*
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
*/
public class StringBuilderWriter extends Writer implements Serializable {
private static final long serialVersionUID = -146927496096066153L;
private final StringBuilder builder;
/**
* Constructs a new {@link StringBuilder} instance with default capacity.
*/
public StringBuilderWriter() {
this.builder = new StringBuilder();
}
/**
* Constructs a new {@link StringBuilder} instance with the specified capacity.
* @param capacity The initial capacity of the underlying {@link StringBuilder}
*/
public StringBuilderWriter(final int capacity) {
this.builder = new StringBuilder(capacity);
}
/**
* Constructs a new instance with the specified {@link StringBuilder}.
*
* <p>
* If {@code builder} is null a new instance with default capacity will be created.
* </p>
* @param builder The String builder. May be null.
*/
public StringBuilderWriter(final StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
/**
* Appends a single character to this Writer.
* @param value The character to [MASK]
* @return This writer instance
*/
@Override
public Writer [MASK] (final char value) {
builder. [MASK] (value);
return this;
}
/**
* Appends a character sequence to this Writer.
* @param value The character to [MASK]
* @return This writer instance
*/
@Override
public Writer [MASK] (final CharSequence value) {
builder. [MASK] (value);
return this;
}
/**
* Appends a portion of a character sequence to the {@link StringBuilder}.
* @param value The character to [MASK]
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer [MASK] (final CharSequence value, final int start, final int end) {
builder. [MASK] (value, start, end);
return this;
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
// no-op
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
// no-op
}
/**
* Writes a String to the {@link StringBuilder}.
* @param value The value to write
*/
@Override
public void write(final String value) {
if (value != null) {
builder. [MASK] (value);
}
}
/**
* Writes a portion of a character array to the {@link StringBuilder}.
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(final char[] value, final int offset, final int length) {
if (value != null) {
builder. [MASK] (value, offset, length);
}
}
/**
* Returns the underlying builder.
* @return The underlying builder
*/
public StringBuilder getBuilder() {
return builder;
}
/**
* Returns {@link StringBuilder#toString()}.
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
| append |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference [MASK] =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of( [MASK] ) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton( [MASK] );
}
};
}
}
| reference |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging. [MASK] ;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final [MASK] DEPRECATION_LOGGER = [MASK] .getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| DeprecationLogger |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all [MASK] but only roots and [MASK] that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... [MASK] ) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
. [MASK] (new HashSet<>(Arrays.asList( [MASK] )))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| packages |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util. [MASK] ;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format( [MASK] .ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format( [MASK] .ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| Locale |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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. [MASK] .transaction.operation;
import org. [MASK] .RedissonKeys;
import org. [MASK] .RedissonLock;
import org. [MASK] .api.RKeys;
import org. [MASK] .command.CommandAsyncExecutor;
import org. [MASK] .transaction.RedissonTransactionalLock;
import org. [MASK] .transaction.RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class UnlinkOperation extends TransactionalOperation {
private String writeLockName;
private String lockName;
private String transactionId;
public UnlinkOperation(String name) {
this(name, null, 0, null);
}
public UnlinkOperation(String name, String lockName, long threadId, String transactionId) {
super(name, null, threadId);
this.lockName = lockName;
this.transactionId = transactionId;
}
public UnlinkOperation(String name, String lockName, String writeLockName, long threadId, String transactionId) {
this(name, lockName, threadId, transactionId);
this.writeLockName = writeLockName;
}
@Override
public void commit(CommandAsyncExecutor commandExecutor) {
RKeys keys = new RedissonKeys(commandExecutor);
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor commandExecutor) {
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| redisson |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new [MASK] <>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new [MASK] <>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new [MASK] <>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| HashSet |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common. [MASK] .XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch. [MASK] .ToXContent;
import org.elasticsearch. [MASK] .XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| xcontent |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] [MASK] ,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = [MASK] .length;
for (int i = 0; i < [MASK] .length; i++) {
if (Regex.isSimpleMatchPattern( [MASK] [i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < [MASK] .length; i++) {
if (Metadata.ALL.equals( [MASK] [i])
|| Regex.isSimpleMatchPattern( [MASK] [i])
|| (i > firstWildcardIndex && [MASK] [i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < [MASK] .length; j++) {
if ( [MASK] [j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch( [MASK] [j].substring(1), [MASK] [i])
|| Metadata.ALL.equals( [MASK] [j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == [MASK] .length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains( [MASK] [i])) {
// aliases[i] is not in the result set
missingAliases.add( [MASK] [i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| requestedAliases |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different [MASK]
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String [MASK] ) {
int period = [MASK] .lastIndexOf('.');
if (period == -1) {
return [MASK] ;
}
return [MASK] .substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| filename |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.transaction.operation;
import org.redisson.RedissonKeys;
import org.redisson.RedissonLock;
import org.redisson.api.RKeys;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.transaction.RedissonTransactionalLock;
import org.redisson.transaction.RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class UnlinkOperation extends TransactionalOperation {
private String [MASK] ;
private String lockName;
private String transactionId;
public UnlinkOperation(String name) {
this(name, null, 0, null);
}
public UnlinkOperation(String name, String lockName, long threadId, String transactionId) {
super(name, null, threadId);
this.lockName = lockName;
this.transactionId = transactionId;
}
public UnlinkOperation(String name, String lockName, String [MASK] , long threadId, String transactionId) {
this(name, lockName, threadId, transactionId);
this. [MASK] = [MASK] ;
}
@Override
public void commit(CommandAsyncExecutor commandExecutor) {
RKeys keys = new RedissonKeys(commandExecutor);
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if ( [MASK] != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, [MASK] , transactionId);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor commandExecutor) {
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if ( [MASK] != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, [MASK] , transactionId);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| writeLockName |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources. [MASK] ;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = [MASK] .getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = [MASK] .getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = [MASK] .getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| ResourceManager |
/*
* Copyright (c) 2016, 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.
*
* 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.
*/
/*
* @test
* @bug 8144008
* @library /test/lib
* @summary Setting NO_PROXY on HTTP URL connections does not stop proxying
* @run main/othervm NoProxyTest
*/
import java.io. [MASK] ;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import jdk.test.lib.net.URIBuilder;
public class NoProxyTest {
static class NoProxyTestSelector extends ProxySelector {
@Override
public List<Proxy> select(URI uri) {
throw new RuntimeException("Should not reach here as proxy==Proxy.NO_PROXY");
}
@Override
public void connectFailed(URI u, SocketAddress s, [MASK] e) { }
}
public static void main(String args[]) throws MalformedURLException {
ProxySelector.setDefault(new NoProxyTestSelector());
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.path("/")
.toURLUnchecked();
System.out.println("URL: " + url);
URLConnection connection;
try {
connection = url.openConnection(Proxy.NO_PROXY);
connection.connect();
} catch ( [MASK] ignore) {
//ignore
}
}
}
| IOException |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@ [MASK]
public ModuleReader open() {
return new ModuleReader() {
@ [MASK]
public Optional<URI> find(String name) {
return Optional.empty();
}
@ [MASK]
public Stream<String> list() {
return Stream.empty();
}
@ [MASK]
public void close() {}
};
}
};
return new ModuleFinder() {
@ [MASK]
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@ [MASK]
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| Override |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch. [MASK] .Strings;
import org.elasticsearch. [MASK] .logging.DeprecationCategory;
import org.elasticsearch. [MASK] .logging.DeprecationLogger;
import org.elasticsearch. [MASK] .regex.Regex;
import org.elasticsearch. [MASK] .xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| common |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL. [MASK] (requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL. [MASK] (requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey(). [MASK] (alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| equals |
/*
* Copyright (c) 2016, 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.
*
* 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.
*/
/*
* @test
* @bug 8144008
* @library /test/lib
* @summary Setting NO_PROXY on HTTP URL connections does not stop proxying
* @run main/othervm No [MASK] Test
*/
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net. [MASK] ;
import java.net. [MASK] Selector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import jdk.test.lib.net.URIBuilder;
public class No [MASK] Test {
static class No [MASK] TestSelector extends [MASK] Selector {
@Override
public List< [MASK] > select(URI uri) {
throw new RuntimeException("Should not reach here as proxy== [MASK] .NO_PROXY");
}
@Override
public void connectFailed(URI u, SocketAddress s, IOException e) { }
}
public static void main(String args[]) throws MalformedURLException {
[MASK] Selector.setDefault(new No [MASK] TestSelector());
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.path("/")
.toURLUnchecked();
System.out.println("URL: " + url);
URLConnection connection;
try {
connection = url.openConnection( [MASK] .NO_PROXY);
connection.connect();
} catch (IOException ignore) {
//ignore
}
}
}
| Proxy |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> [MASK] =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
[MASK] =
[MASK] .defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return [MASK]
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| typeBuilder |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch. [MASK] .internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient [MASK] ) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient( [MASK] , request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| client |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get. [MASK] ;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final [MASK] getAliasesRequest = new [MASK] (masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| GetAliasesRequest |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File [MASK] = getToolFile(toolTemplate.getName());
if ( [MASK] .equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension( [MASK] .getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if ( [MASK] .getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| correctToolFile |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.skywalking.generator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import lombok.Data;
@JsonDeserialize(builder = StringGenerator.Builder.class)
public final class StringGenerator implements Generator<String, String> {
private final int length;
private final String [MASK] ;
private final boolean letters;
private final boolean numbers;
private final boolean limitedDomain;
private final Random random = ThreadLocalRandom.current();
private final Set<String> domain = new HashSet<>();
public StringGenerator(Builder builder) {
length = builder.length;
[MASK] = builder. [MASK] ;
letters = builder.letters;
numbers = builder.numbers;
limitedDomain = builder.domainSize > 0;
if (limitedDomain) {
while (domain.size() < builder.domainSize) {
final String r = RandomStringUtils.random(length, letters, numbers);
if (!Strings.isNullOrEmpty(builder. [MASK] )) {
domain.add(builder. [MASK] + r);
} else {
domain.add(r);
}
}
}
}
@Override
public String next(String parent) {
if (Strings.isNullOrEmpty(parent)) {
parent = "";
} else {
parent += "-";
}
if (!limitedDomain) {
return parent + Strings.nullToEmpty( [MASK] )
+ RandomStringUtils.random(length, letters, numbers);
}
return parent + domain
.stream()
.skip(random.nextInt(domain.size()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Should never happen"));
}
@Override
public String toString() {
return String.valueOf(next(null));
}
@Data
public static class Builder {
private int length;
private String [MASK] ;
private boolean letters;
private boolean numbers;
private int domainSize;
public StringGenerator build() {
return new StringGenerator(this);
}
}
}
| prefix |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases. [MASK] ;
for (int i = 0; i < requestedAliases. [MASK] ; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases. [MASK] ; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases. [MASK] ; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases. [MASK] ) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| length |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller [MASK] =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
[MASK] .addReads(
[MASK]
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return [MASK] .layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| controller |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration [MASK] =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot(). [MASK] ()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
[MASK] ,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| configuration |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_ [MASK] "),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_ [MASK] _action";
}
static RestResponse buildRestResponse(
boolean [MASK] ExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if ( [MASK] ExplicitlyRequested) {
// only display indices that have [MASK]
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested [MASK] that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested [MASK] will be called out as missing (404)
continue;
}
// check if [MASK] [i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// [MASK] [i] is excluded by [MASK] [j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested [MASK] [i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// [MASK] [i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, " [MASK] [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if ( [MASK] ExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject(" [MASK] ");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for [MASK] pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject(" [MASK] ");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] [MASK] = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, [MASK] );
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get- [MASK] -local",
"the [?local={}] query parameter to get- [MASK] requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided [MASK] , which will
// not always be available there (they may get replaced so retrieving request. [MASK] is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, [MASK] , response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| aliases |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common. [MASK] ;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", [MASK] .collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", [MASK] .collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = [MASK] .splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| Strings |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster. [MASK] .AliasMetadata;
import org.elasticsearch.cluster. [MASK] .DataStreamAlias;
import org.elasticsearch.cluster. [MASK] .Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| metadata |
/*
* Copyright (c) 2016, 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.
*
* 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.
*/
/*
* @test
* @bug 8144008
* @library /test/lib
* @summary Setting NO_PROXY on HTTP URL connections does not stop proxying
* @run main/othervm NoProxyTest
*/
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net. [MASK] ;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import jdk.test.lib.net.URIBuilder;
public class NoProxyTest {
static class NoProxyTestSelector extends [MASK] {
@Override
public List<Proxy> select(URI uri) {
throw new RuntimeException("Should not reach here as proxy==Proxy.NO_PROXY");
}
@Override
public void connectFailed(URI u, SocketAddress s, IOException e) { }
}
public static void main(String args[]) throws MalformedURLException {
[MASK] .setDefault(new NoProxyTestSelector());
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.path("/")
.toURLUnchecked();
System.out.println("URL: " + url);
URLConnection connection;
try {
connection = url.openConnection(Proxy.NO_PROXY);
connection.connect();
} catch (IOException ignore) {
//ignore
}
}
}
| ProxySelector |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.transaction.operation;
import org.redisson.RedissonKeys;
import org.redisson.RedissonLock;
import org.redisson.api.RKeys;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.transaction.RedissonTransactionalLock;
import org.redisson.transaction.RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class UnlinkOperation extends TransactionalOperation {
private String writeLockName;
private String lockName;
private String transactionId;
public UnlinkOperation(String name) {
this(name, null, 0, null);
}
public UnlinkOperation(String name, String lockName, long threadId, String transactionId) {
super(name, null, threadId);
this.lockName = lockName;
this.transactionId = transactionId;
}
public UnlinkOperation(String name, String lockName, String writeLockName, long threadId, String transactionId) {
this(name, lockName, threadId, transactionId);
this.writeLockName = writeLockName;
}
@Override
public void commit(CommandAsyncExecutor [MASK] ) {
RKeys keys = new RedissonKeys( [MASK] );
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock( [MASK] , lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock( [MASK] , writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor [MASK] ) {
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock( [MASK] , lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock( [MASK] , writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| commandExecutor |
/*
* Copyright (c) 2023, 2025, 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.graal.compiler.nodes.extended;
import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0;
import jdk.graal.compiler.graph.IterableNodeType;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph.NodeClass;
import jdk.graal.compiler.graph.spi.NodeWithIdentity;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodeinfo.NodeInfo;
import jdk.graal.compiler.nodes.GraphState.StageFlag;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes. [MASK] ;
import jdk.graal.compiler.nodes.spi.Canonicalizable;
import jdk.graal.compiler.nodes.spi.CanonicalizerTool;
import jdk.graal.compiler.nodes.spi.LIRLowerable;
import jdk.graal.compiler.phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an Opaque [MASK] .
* <p>
* This node accepts an optional {@link StageFlag} argument. If set, the node will canonicalize away
* after that stage has been applied to the graph.
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the graph before LIR
* generation. {@link Opaque [MASK] }s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class Opaque [MASK] extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final NodeClass<Opaque [MASK] > TYPE = NodeClass.create(Opaque [MASK] .class);
@Input(InputType.Value) private [MASK] value;
private final StageFlag foldAfter;
public Opaque [MASK] ( [MASK] value) {
this(value, null);
}
public Opaque [MASK] ( [MASK] value, StageFlag foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@Override
public [MASK] getValue() {
return value;
}
@Override
public void setValue( [MASK] value) {
this.updateUsages(this.value, value);
this.value = value;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this.graph() != null && this.graph().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| ValueNode |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.client.registration.cli.commands;
import org.keycloak.client.cli.common.BaseGlobalOptionsCmd;
import org.keycloak.client.registration.cli.KcRegMain;
import java.io.PrintWriter;
import java.io.StringWriter;
import picocli.CommandLine.Command;
import static org.keycloak.client.cli.util.OsUtil. [MASK] ;
import static org.keycloak.client.registration.cli.KcRegMain.CMD;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
@Command(name = "kcreg",
header = {
"Keycloak - Open Source Identity and Access Management",
"",
"Find more information at: https://www.keycloak.org/docs/latest"
},
description = {
"%nCOMMAND [ARGUMENTS]"
},
subcommands = {
HelpCmd.class,
ConfigCmd.class,
CreateCmd.class,
GetCmd.class,
UpdateCmd.class,
DeleteCmd.class,
AttrsCmd.class,
UpdateTokenCmd.class
})
public class KcRegCmd extends BaseGlobalOptionsCmd {
@Override
protected boolean nothingToDo() {
return true;
}
@Override
protected String help() {
return usage();
}
public static String usage() {
StringWriter sb = new StringWriter();
PrintWriter out = new PrintWriter(sb);
out.println("Keycloak Client Registration CLI");
out.println();
out.println("Use '" + CMD + " config credentials' command with username and password to start a session against a specific");
out.println("server and realm.");
out.println();
out.println("For example:");
out.println();
out.println(" " + [MASK] + " " + CMD + " config credentials --server http://localhost:8080 --realm master --user admin");
out.println(" Enter password: ");
out.println(" Logging into http://localhost:8080 as user admin of realm master");
out.println();
out.println("Any configured username can be used for login, but to perform client registration operations the user");
out.println("needs proper roles, otherwise attempts to create, update, read, or delete clients will fail.");
out.println("Alternatively, the user without the necessary roles can use an Initial Access Token provided by realm");
out.println("administrator when creating a new client with 'create' command. For example:");
out.println();
out.println(" " + [MASK] + " " + CMD + " create -f my_client.json -t -");
out.println(" Enter Initial Access Token: ");
out.println(" Registered new client with client_id 'my_client'");
out.println();
out.println("When Initial Access Token is used the server issues a Registration Access Token which is automatically");
out.println("handled by " + CMD + ", saved into a local config file, and automatically used for any follow-up operations");
out.println("on the same client. For example:");
out.println();
out.println(" " + [MASK] + " " + CMD + " get my_client");
out.println(" " + [MASK] + " " + CMD + " update my_client -s enabled=false");
out.println(" " + [MASK] + " " + CMD + " delete my_client");
out.println();
out.println();
out.println("Usage: " + CMD + " COMMAND [ARGUMENTS]");
out.println();
out.println("Global options:");
out.println(" -x Print full stack trace when exiting with error");
out.println(" --help Print help for specific command");
out.println(" --config Path to the config file (" + KcRegMain.DEFAULT_CONFIG_FILE_STRING + " by default)");
out.println(" --no-config Don't use config file - no authentication info is loaded or saved");
out.println();
out.println("Commands: ");
out.println(" config Set up credentials, and other configuration settings using the config file");
out.println(" create Register a new client");
out.println(" get Get configuration of existing client in Keycloak or OIDC format, or adapter install configuration");
out.println(" update Update a client configuration");
out.println(" delete Delete a client");
out.println(" attrs List available attributes");
out.println(" update-token Update Registration Access Token for a client");
out.println(" help This help");
out.println();
out.println("Use '" + CMD + " help <command>' for more information about a given command.");
return sb.toString();
}
}
| PROMPT |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean [MASK] , boolean isExported, boolean isOpened)
throws IOException {
return modularJar( [MASK] , isExported, isOpened, false);
}
public static Path modularJar(
boolean [MASK] , boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type( [MASK] , addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean [MASK] , boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge( [MASK] ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| isPublic |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections. [MASK] (set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections. [MASK] (set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections. [MASK] (set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| unmodifiableSet |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static [MASK] layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList( [MASK] .boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
[MASK] .Controller controller =
[MASK] .defineModules(
configuration,
Collections.singletonList( [MASK] .boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| ModuleLayer |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.skywalking.generator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import lombok.Data;
@JsonDeserialize(builder = StringGenerator.Builder.class)
public final class StringGenerator implements Generator<String, String> {
private final int [MASK] ;
private final String prefix;
private final boolean letters;
private final boolean numbers;
private final boolean limitedDomain;
private final Random random = ThreadLocalRandom.current();
private final Set<String> domain = new HashSet<>();
public StringGenerator(Builder builder) {
[MASK] = builder. [MASK] ;
prefix = builder.prefix;
letters = builder.letters;
numbers = builder.numbers;
limitedDomain = builder.domainSize > 0;
if (limitedDomain) {
while (domain.size() < builder.domainSize) {
final String r = RandomStringUtils.random( [MASK] , letters, numbers);
if (!Strings.isNullOrEmpty(builder.prefix)) {
domain.add(builder.prefix + r);
} else {
domain.add(r);
}
}
}
}
@Override
public String next(String parent) {
if (Strings.isNullOrEmpty(parent)) {
parent = "";
} else {
parent += "-";
}
if (!limitedDomain) {
return parent + Strings.nullToEmpty(prefix)
+ RandomStringUtils.random( [MASK] , letters, numbers);
}
return parent + domain
.stream()
.skip(random.nextInt(domain.size()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Should never happen"));
}
@Override
public String toString() {
return String.valueOf(next(null));
}
@Data
public static class Builder {
private int [MASK] ;
private String prefix;
private boolean letters;
private boolean numbers;
private int domainSize;
public StringGenerator build() {
return new StringGenerator(this);
}
}
}
| length |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.client.registration.cli.commands;
import org.keycloak.client.cli.common.BaseGlobalOptionsCmd;
import org.keycloak.client.registration.cli.KcRegMain;
import java.io. [MASK] ;
import java.io.StringWriter;
import picocli.CommandLine.Command;
import static org.keycloak.client.cli.util.OsUtil.PROMPT;
import static org.keycloak.client.registration.cli.KcRegMain.CMD;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
@Command(name = "kcreg",
header = {
"Keycloak - Open Source Identity and Access Management",
"",
"Find more information at: https://www.keycloak.org/docs/latest"
},
description = {
"%nCOMMAND [ARGUMENTS]"
},
subcommands = {
HelpCmd.class,
ConfigCmd.class,
CreateCmd.class,
GetCmd.class,
UpdateCmd.class,
DeleteCmd.class,
AttrsCmd.class,
UpdateTokenCmd.class
})
public class KcRegCmd extends BaseGlobalOptionsCmd {
@Override
protected boolean nothingToDo() {
return true;
}
@Override
protected String help() {
return usage();
}
public static String usage() {
StringWriter sb = new StringWriter();
[MASK] out = new [MASK] (sb);
out.println("Keycloak Client Registration CLI");
out.println();
out.println("Use '" + CMD + " config credentials' command with username and password to start a session against a specific");
out.println("server and realm.");
out.println();
out.println("For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " config credentials --server http://localhost:8080 --realm master --user admin");
out.println(" Enter password: ");
out.println(" Logging into http://localhost:8080 as user admin of realm master");
out.println();
out.println("Any configured username can be used for login, but to perform client registration operations the user");
out.println("needs proper roles, otherwise attempts to create, update, read, or delete clients will fail.");
out.println("Alternatively, the user without the necessary roles can use an Initial Access Token provided by realm");
out.println("administrator when creating a new client with 'create' command. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " create -f my_client.json -t -");
out.println(" Enter Initial Access Token: ");
out.println(" Registered new client with client_id 'my_client'");
out.println();
out.println("When Initial Access Token is used the server issues a Registration Access Token which is automatically");
out.println("handled by " + CMD + ", saved into a local config file, and automatically used for any follow-up operations");
out.println("on the same client. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " get my_client");
out.println(" " + PROMPT + " " + CMD + " update my_client -s enabled=false");
out.println(" " + PROMPT + " " + CMD + " delete my_client");
out.println();
out.println();
out.println("Usage: " + CMD + " COMMAND [ARGUMENTS]");
out.println();
out.println("Global options:");
out.println(" -x Print full stack trace when exiting with error");
out.println(" --help Print help for specific command");
out.println(" --config Path to the config file (" + KcRegMain.DEFAULT_CONFIG_FILE_STRING + " by default)");
out.println(" --no-config Don't use config file - no authentication info is loaded or saved");
out.println();
out.println("Commands: ");
out.println(" config Set up credentials, and other configuration settings using the config file");
out.println(" create Register a new client");
out.println(" get Get configuration of existing client in Keycloak or OIDC format, or adapter install configuration");
out.println(" update Update a client configuration");
out.println(" delete Delete a client");
out.println(" attrs List available attributes");
out.println(" update-token Update Registration Access Token for a client");
out.println(" help This help");
out.println();
out.println("Use '" + CMD + " help <command>' for more information about a given command.");
return sb.toString();
}
}
| PrintWriter |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element [MASK] = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = [MASK] .getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml( [MASK] );
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| xmlRoot |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder. [MASK] ();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder. [MASK] (entry.getKey());
{
builder. [MASK] ("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder. [MASK] (entry.getKey());
{
builder. [MASK] ("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder. [MASK] (alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| startObject |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.test.e2e.framework.param.model;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.infra.database.core.type.DatabaseType;
import org.apache.shardingsphere.test.e2e.cases.casse.E2ETestCaseContext;
import org.apache.shardingsphere.test.e2e.framework.type.SQLCommandType;
import org.apache.shardingsphere.test.e2e.framework.type.SQLExecuteType;
import org.apache.shardingsphere.test.e2e.cases.casse.assertion.E2ETestCaseAssertion;
/**
* Assertion test parameter.
*/
@RequiredArgsConstructor
@Getter
public final class AssertionTestParameter implements E2ETestParameter {
private final E2ETestCaseContext testCaseContext;
private final E2ETestCaseAssertion assertion;
private final [MASK] adapter;
private final [MASK] scenario;
private final [MASK] mode;
private final DatabaseType databaseType;
private final SQLExecuteType sqlExecuteType;
private final SQLCommandType sqlCommandType;
@Override
public [MASK] to [MASK] () {
[MASK] sql = null == testCaseContext ? null : testCaseContext.getTestCase().getSql();
[MASK] type = null == databaseType ? null : databaseType.getType();
return [MASK] .format("%s: %s -> %s -> %s -> %s", adapter, scenario, type, sqlExecuteType, sql);
}
}
| String |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger [MASK] = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
[MASK] .info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error( [MASK] , "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error( [MASK] , "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error( [MASK] , "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error( [MASK] , "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error( [MASK] , "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
[MASK] .trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| LOGGER |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] [MASK] edAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly [MASK] ed aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = [MASK] edAliases.length;
for (int i = 0; i < [MASK] edAliases.length; i++) {
if (Regex.isSimpleMatchPattern( [MASK] edAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < [MASK] edAliases.length; i++) {
if (Metadata.ALL.equals( [MASK] edAliases[i])
|| Regex.isSimpleMatchPattern( [MASK] edAliases[i])
|| (i > firstWildcardIndex && [MASK] edAliases[i].charAt(0) == '-')) {
// only explicitly [MASK] ed aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < [MASK] edAliases.length; j++) {
if ( [MASK] edAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch( [MASK] edAliases[j].substring(1), [MASK] edAliases[i])
|| Metadata.ALL.equals( [MASK] edAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == [MASK] edAliases.length) {
// explicitly [MASK] ed aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains( [MASK] edAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add( [MASK] edAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest [MASK] , final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = [MASK] .hasParam("name");
final String[] aliases = [MASK] .paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout( [MASK] );
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray( [MASK] .param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest( [MASK] , getAliasesRequest.indicesOptions()));
if ( [MASK] .getRestApiVersion() == RestApiVersion.V_8) {
if ( [MASK] .hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = [MASK] .paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases [MASK] s has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving [MASK] .aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, [MASK] .getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| request |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder [MASK]
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
[MASK] .startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
[MASK] .field("error", message);
[MASK] .field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
[MASK] .startObject(entry.getKey());
{
[MASK] .startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, [MASK] , ToXContent.EMPTY_PARAMS);
}
}
[MASK] .endObject();
}
[MASK] .endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
[MASK] .startObject(entry.getKey());
{
[MASK] .startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
[MASK] .startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
[MASK] .field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
[MASK] .field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
[MASK] .endObject();
}
}
[MASK] .endObject();
}
[MASK] .endObject();
}
}
[MASK] .endObject();
return new RestResponse(status, [MASK] );
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder [MASK] ) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), [MASK] );
}
});
}
}
| builder |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package [MASK] .framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import [MASK] .framework.model.ProjectManager;
import [MASK] .framework.model.ToolTemplate;
import [MASK] .framework.project.tool.GhidraToolTemplate;
import [MASK] .util.*;
import [MASK] .util.exception.AssertException;
import [MASK] .util.xml.GenericXMLOutputter;
import [MASK] .util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| ghidra |
/*
* Copyright (c) 2023, 2025, 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.graal.compiler.nodes.extended;
import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0;
import jdk.graal.compiler.graph.IterableNodeType;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph.NodeClass;
import jdk.graal.compiler.graph.spi.NodeWithIdentity;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodeinfo.NodeInfo;
import jdk.graal.compiler.nodes.GraphState.StageFlag;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.spi.Canonicalizable;
import jdk.graal.compiler.nodes.spi.CanonicalizerTool;
import jdk.graal.compiler.nodes.spi.LIRLowerable;
import jdk.graal.compiler.phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an OpaqueValueNode.
* <p>
* This node accepts an optional {@link StageFlag} argument. If set, the node will canonicalize away
* after that stage has been applied to the graph.
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the graph before LIR
* generation. {@link OpaqueValueNode}s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class OpaqueValueNode extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final NodeClass<OpaqueValueNode> TYPE = NodeClass.create(OpaqueValueNode.class);
@Input(InputType.Value) private ValueNode value;
private final StageFlag foldAfter;
public OpaqueValueNode(ValueNode value) {
this(value, null);
}
public OpaqueValueNode(ValueNode value, StageFlag foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@ [MASK]
public ValueNode getValue() {
return value;
}
@ [MASK]
public void setValue(ValueNode value) {
this.updateUsages(this.value, value);
this.value = value;
}
@ [MASK]
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this.graph() != null && this.graph().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| Override |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus [MASK] ;
builder.startObject();
{
if (missingAliases.isEmpty()) {
[MASK] = RestStatus.OK;
} else {
[MASK] = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field(" [MASK] ", [MASK] .getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse( [MASK] , builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| status |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar. [MASK] ;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try ( [MASK] out = new [MASK] (Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| JarOutputStream |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.transaction.operation;
import org.redisson.RedissonKeys;
import org.redisson.RedissonLock;
import org.redisson.api.RKeys;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.transaction.RedissonTransactionalLock;
import org.redisson.transaction.RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class UnlinkOperation extends TransactionalOperation {
private String writeLockName;
private String lockName;
private String transactionId;
public UnlinkOperation(String name) {
this(name, null, 0, null);
}
public UnlinkOperation(String name, String lockName, long [MASK] , String transactionId) {
super(name, null, [MASK] );
this.lockName = lockName;
this.transactionId = transactionId;
}
public UnlinkOperation(String name, String lockName, String writeLockName, long [MASK] , String transactionId) {
this(name, lockName, [MASK] , transactionId);
this.writeLockName = writeLockName;
}
@Override
public void commit(CommandAsyncExecutor commandExecutor) {
RKeys keys = new RedissonKeys(commandExecutor);
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor commandExecutor) {
if (lockName != null) {
RedissonLock lock = new RedissonTransactionalLock(commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| threadId |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent. [MASK] ;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
[MASK] builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, [MASK] builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| XContentBuilder |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org. [MASK] .client.registration.cli.commands;
import org. [MASK] .client.cli.common.BaseGlobalOptionsCmd;
import org. [MASK] .client.registration.cli.KcRegMain;
import java.io.PrintWriter;
import java.io.StringWriter;
import picocli.CommandLine.Command;
import static org. [MASK] .client.cli.util.OsUtil.PROMPT;
import static org. [MASK] .client.registration.cli.KcRegMain.CMD;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
@Command(name = "kcreg",
header = {
"Keycloak - Open Source Identity and Access Management",
"",
"Find more information at: https://www. [MASK] .org/docs/latest"
},
description = {
"%nCOMMAND [ARGUMENTS]"
},
subcommands = {
HelpCmd.class,
ConfigCmd.class,
CreateCmd.class,
GetCmd.class,
UpdateCmd.class,
DeleteCmd.class,
AttrsCmd.class,
UpdateTokenCmd.class
})
public class KcRegCmd extends BaseGlobalOptionsCmd {
@Override
protected boolean nothingToDo() {
return true;
}
@Override
protected String help() {
return usage();
}
public static String usage() {
StringWriter sb = new StringWriter();
PrintWriter out = new PrintWriter(sb);
out.println("Keycloak Client Registration CLI");
out.println();
out.println("Use '" + CMD + " config credentials' command with username and password to start a session against a specific");
out.println("server and realm.");
out.println();
out.println("For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " config credentials --server http://localhost:8080 --realm master --user admin");
out.println(" Enter password: ");
out.println(" Logging into http://localhost:8080 as user admin of realm master");
out.println();
out.println("Any configured username can be used for login, but to perform client registration operations the user");
out.println("needs proper roles, otherwise attempts to create, update, read, or delete clients will fail.");
out.println("Alternatively, the user without the necessary roles can use an Initial Access Token provided by realm");
out.println("administrator when creating a new client with 'create' command. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " create -f my_client.json -t -");
out.println(" Enter Initial Access Token: ");
out.println(" Registered new client with client_id 'my_client'");
out.println();
out.println("When Initial Access Token is used the server issues a Registration Access Token which is automatically");
out.println("handled by " + CMD + ", saved into a local config file, and automatically used for any follow-up operations");
out.println("on the same client. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " get my_client");
out.println(" " + PROMPT + " " + CMD + " update my_client -s enabled=false");
out.println(" " + PROMPT + " " + CMD + " delete my_client");
out.println();
out.println();
out.println("Usage: " + CMD + " COMMAND [ARGUMENTS]");
out.println();
out.println("Global options:");
out.println(" -x Print full stack trace when exiting with error");
out.println(" --help Print help for specific command");
out.println(" --config Path to the config file (" + KcRegMain.DEFAULT_CONFIG_FILE_STRING + " by default)");
out.println(" --no-config Don't use config file - no authentication info is loaded or saved");
out.println();
out.println("Commands: ");
out.println(" config Set up credentials, and other configuration settings using the config file");
out.println(" create Register a new client");
out.println(" get Get configuration of existing client in Keycloak or OIDC format, or adapter install configuration");
out.println(" update Update a client configuration");
out.println(" delete Delete a client");
out.println(" attrs List available attributes");
out.println(" update-token Update Registration Access Token for a client");
out.println(" help This help");
out.println();
out.println("Use '" + CMD + " help <command>' for more information about a given command.");
return sb.toString();
}
}
| keycloak |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.test.e2e. [MASK] .param.model;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.infra.database.core.type.DatabaseType;
import org.apache.shardingsphere.test.e2e.cases.casse.E2ETestCaseContext;
import org.apache.shardingsphere.test.e2e. [MASK] .type.SQLCommandType;
import org.apache.shardingsphere.test.e2e. [MASK] .type.SQLExecuteType;
import org.apache.shardingsphere.test.e2e.cases.casse.assertion.E2ETestCaseAssertion;
/**
* Assertion test parameter.
*/
@RequiredArgsConstructor
@Getter
public final class AssertionTestParameter implements E2ETestParameter {
private final E2ETestCaseContext testCaseContext;
private final E2ETestCaseAssertion assertion;
private final String adapter;
private final String scenario;
private final String mode;
private final DatabaseType databaseType;
private final SQLExecuteType sqlExecuteType;
private final SQLCommandType sqlCommandType;
@Override
public String toString() {
String sql = null == testCaseContext ? null : testCaseContext.getTestCase().getSql();
String type = null == databaseType ? null : databaseType.getType();
return String.format("%s: %s -> %s -> %s -> %s", adapter, scenario, type, sqlExecuteType, sql);
}
}
| framework |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices. [MASK] .get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices. [MASK] .get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get [MASK] and head [MASK] APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_ [MASK] "),
new Route(GET, "/_ [MASK] es"),
new Route(GET, "/_ [MASK] /{name}"),
new Route(HEAD, "/_ [MASK] /{name}"),
new Route(GET, "/{index}/_ [MASK] "),
new Route(HEAD, "/{index}/_ [MASK] "),
new Route(GET, "/{index}/_ [MASK] /{name}"),
new Route(HEAD, "/{index}/_ [MASK] /{name}")
);
}
@Override
public String getName() {
return "get_ [MASK] es_action";
}
static RestResponse buildRestResponse(
boolean [MASK] esExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata [MASK] Metadata : cursor.getValue()) {
if ( [MASK] esExplicitlyRequested) {
// only display indices that have [MASK] es
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add( [MASK] Metadata. [MASK] ());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested [MASK] es that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an [MASK] name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested [MASK] es will be called out as missing (404)
continue;
}
// check if [MASK] es[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// [MASK] es[i] is excluded by [MASK] es[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested [MASK] es[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// [MASK] es[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, " [MASK] [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, " [MASK] es [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if ( [MASK] esExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject(" [MASK] es");
{
for (final AliasMetadata [MASK] : entry.getValue()) {
AliasMetadata.Builder.toXContent( [MASK] , builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for [MASK] es pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject(" [MASK] es");
{
for (DataStreamAlias [MASK] : entry.getValue()) {
builder.startObject( [MASK] .getName());
if (entry.getKey().equals( [MASK] .getWriteDataStream())) {
builder.field("is_write_index", true);
}
if ( [MASK] .getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap( [MASK] .getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] [MASK] es = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, [MASK] es);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get- [MASK] es-local",
"the [?local={}] query parameter to get- [MASK] es requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided [MASK] es, which will
// not always be available there (they may get replaced so retrieving request. [MASK] es is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, [MASK] es, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| alias |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest. [MASK] .admin.indices;
import org.elasticsearch. [MASK] .admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch. [MASK] .admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch. [MASK] .support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest. [MASK] .RestBuilderListener;
import org.elasticsearch.rest. [MASK] .RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_ [MASK] ";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| action |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest. [MASK] ;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final [MASK] status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = [MASK] .OK;
} else {
status = [MASK] .NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| RestStatus |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net. [MASK] .ByteBuddy;
import net. [MASK] .description.modifier.Visibility;
import net. [MASK] .dynamic.DynamicType;
import net. [MASK] .implementation.FixedValue;
import net. [MASK] .jar.asm.ClassWriter;
import net. [MASK] .jar.asm.ModuleVisitor;
import net. [MASK] .jar.asm.Opcodes;
import net. [MASK] .utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net. [MASK] .matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net. [MASK] ");
modules.add("net. [MASK] .agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation. [MASK] "),
automaticModule("net. [MASK] ", "net. [MASK] "),
automaticModule("net. [MASK] .agent", "net. [MASK] .agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| bytebuddy |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
[MASK] .singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
[MASK] .singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return [MASK] .singleton(reference);
}
};
}
}
| Collections |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils. [MASK] (toolTemplate);
}
public static boolean [MASK] (ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
[MASK] (toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| writeToolTemplate |
package cn.binarywang.wx.miniapp.api.impl;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaStableAccessTokenRequest;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import me.chanjar.weixin.common.util.http.HttpType;
import me.chanjar.weixin.common.util.http.okhttp.DefaultOkHttpClientBuilder;
import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.Objects;
/**
* okhttp实现.
*/
public class WxMaServiceOkHttpImpl extends BaseWxMaServiceImpl<OkHttpClient, OkHttpProxyInfo> {
private OkHttpClient httpClient;
private OkHttpProxyInfo httpProxy;
@Override
public void initHttp() {
WxMaConfig wxMpConfigStorage = this.getWxMaConfig();
//设置代理
if (wxMpConfigStorage.getHttpProxyHost() != null && wxMpConfigStorage.getHttpProxyPort() > 0) {
httpProxy = OkHttpProxyInfo.httpProxy(wxMpConfigStorage.getHttpProxyHost(),
wxMpConfigStorage.getHttpProxyPort(),
wxMpConfigStorage.getHttpProxyUsername(),
wxMpConfigStorage.getHttpProxyPassword());
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.proxy(getRequestHttpProxy().getProxy());
//设置授权
clientBuilder.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(httpProxy.getProxyUsername(), httpProxy.getProxyPassword());
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
});
httpClient = clientBuilder.build();
} else {
httpClient = DefaultOkHttpClientBuilder.get().build();
}
}
@Override
public OkHttpClient getRequestHttpClient() {
return httpClient;
}
@Override
public OkHttpProxyInfo getRequestHttpProxy() {
return httpProxy;
}
@Override
public HttpType getRequestType() {
return HttpType.OK_HTTP;
}
@Override
protected String doGetAccessTokenRequest() throws IOException {
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
WxMaService.GET_ACCESS_TOKEN_URL.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
WxMaService.GET_ACCESS_TOKEN_URL;
url = String.format(url, this.getWxMaConfig().getAppid(), this.getWxMaConfig().getSecret());
Request request = new Request.Builder().url(url).get().build();
try (Response response = getRequestHttpClient().newCall(request).execute()) {
return Objects.requireNonNull(response.body()).string();
}
}
@Override
protected String doGetStableAccessTokenRequest(boolean forceRefresh) throws IOException {
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
GET_STABLE_ACCESS_TOKEN.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
GET_STABLE_ACCESS_TOKEN;
WxMaStableAccessTokenRequest [MASK] = new WxMaStableAccessTokenRequest();
[MASK] .setAppid(this.getWxMaConfig().getAppid());
[MASK] .setSecret(this.getWxMaConfig().getSecret());
[MASK] .setGrantType("client_credential");
[MASK] .setForceRefresh(forceRefresh);
RequestBody body = RequestBody.Companion.create( [MASK] .toJson(), MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder().url(url).post(body).build();
try (Response response = getRequestHttpClient().newCall(request).execute()) {
return Objects.requireNonNull(response.body()).string();
}
}
}
| wxMaAccessTokenRequest |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm. [MASK] ;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
[MASK] classWriter = new [MASK] (OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| ClassWriter |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action. [MASK] .indices;
import org.elasticsearch.action. [MASK] .indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action. [MASK] .indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()). [MASK] ()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| admin |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> [MASK] = new HashSet<>();
[MASK] .add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
[MASK] .add("org.mockito");
[MASK] .add("net.bytebuddy");
[MASK] .add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two [MASK] . This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
[MASK] );
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| modules |
package cn.hutool.extra.pinyin;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class [MASK] Test {
@Test
public void getPinyinTest(){
final String pinyin = [MASK] .getPinyin("你好怡", " ");
assertEquals("ni hao yi", pinyin);
}
@Test
public void getFirstLetterTest(){
final String result = [MASK] .getFirstLetter("H是第一个", ", ");
assertEquals("h, s, d, y, g", result);
}
@Test
public void getFirstLetterTest2(){
final String result = [MASK] .getFirstLetter("崞阳", ", ");
assertEquals("g, y", result);
}
}
| PinyinUtil |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm. [MASK] ;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, [MASK] .ACC_PRIVATE | [MASK] .ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit( [MASK] .V9, [MASK] .ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", [MASK] .ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| Opcodes |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.client.registration.cli.commands;
import org.keycloak.client.cli.common.BaseGlobalOptionsCmd;
import org.keycloak.client.registration.cli. [MASK] ;
import java.io.PrintWriter;
import java.io.StringWriter;
import picocli.CommandLine.Command;
import static org.keycloak.client.cli.util.OsUtil.PROMPT;
import static org.keycloak.client.registration.cli. [MASK] .CMD;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
@Command(name = "kcreg",
header = {
"Keycloak - Open Source Identity and Access Management",
"",
"Find more information at: https://www.keycloak.org/docs/latest"
},
description = {
"%nCOMMAND [ARGUMENTS]"
},
subcommands = {
HelpCmd.class,
ConfigCmd.class,
CreateCmd.class,
GetCmd.class,
UpdateCmd.class,
DeleteCmd.class,
AttrsCmd.class,
UpdateTokenCmd.class
})
public class KcRegCmd extends BaseGlobalOptionsCmd {
@Override
protected boolean nothingToDo() {
return true;
}
@Override
protected String help() {
return usage();
}
public static String usage() {
StringWriter sb = new StringWriter();
PrintWriter out = new PrintWriter(sb);
out.println("Keycloak Client Registration CLI");
out.println();
out.println("Use '" + CMD + " config credentials' command with username and password to start a session against a specific");
out.println("server and realm.");
out.println();
out.println("For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " config credentials --server http://localhost:8080 --realm master --user admin");
out.println(" Enter password: ");
out.println(" Logging into http://localhost:8080 as user admin of realm master");
out.println();
out.println("Any configured username can be used for login, but to perform client registration operations the user");
out.println("needs proper roles, otherwise attempts to create, update, read, or delete clients will fail.");
out.println("Alternatively, the user without the necessary roles can use an Initial Access Token provided by realm");
out.println("administrator when creating a new client with 'create' command. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " create -f my_client.json -t -");
out.println(" Enter Initial Access Token: ");
out.println(" Registered new client with client_id 'my_client'");
out.println();
out.println("When Initial Access Token is used the server issues a Registration Access Token which is automatically");
out.println("handled by " + CMD + ", saved into a local config file, and automatically used for any follow-up operations");
out.println("on the same client. For example:");
out.println();
out.println(" " + PROMPT + " " + CMD + " get my_client");
out.println(" " + PROMPT + " " + CMD + " update my_client -s enabled=false");
out.println(" " + PROMPT + " " + CMD + " delete my_client");
out.println();
out.println();
out.println("Usage: " + CMD + " COMMAND [ARGUMENTS]");
out.println();
out.println("Global options:");
out.println(" -x Print full stack trace when exiting with error");
out.println(" --help Print help for specific command");
out.println(" --config Path to the config file (" + [MASK] .DEFAULT_CONFIG_FILE_STRING + " by default)");
out.println(" --no-config Don't use config file - no authentication info is loaded or saved");
out.println();
out.println("Commands: ");
out.println(" config Set up credentials, and other configuration settings using the config file");
out.println(" create Register a new client");
out.println(" get Get configuration of existing client in Keycloak or OIDC format, or adapter install configuration");
out.println(" update Update a client configuration");
out.println(" delete Delete a client");
out.println(" attrs List available attributes");
out.println(" update-token Update Registration Access Token for a client");
out.println(" help This help");
out.println();
out.println("Use '" + CMD + " help <command>' for more information about a given command.");
return sb.toString();
}
}
| KcRegMain |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate [MASK] = ToolUtils.readToolTemplate(toolFile);
if ( [MASK] != null) {
map.put( [MASK] .getName(), [MASK] );
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate [MASK] ) {
// parse the XML to see what plugins are loaded
Element xmlRoot = [MASK] .saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + [MASK] .getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
[MASK] .restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate [MASK] ) {
USER_TOOLS_DIR.mkdirs();
String name = [MASK] .getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate [MASK] ) {
USER_TOOLS_DIR.mkdirs();
String toolName = [MASK] .getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = [MASK] .saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool [MASK] for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the [MASK]
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool [MASK] for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate [MASK] ) {
String name = [MASK] .getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| template |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] [MASK] = USER_TOOLS_DIR.listFiles(filter);
if ( [MASK] != null) {
for (File toolFile : [MASK] ) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| toolFiles |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set< [MASK] > modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule( [MASK] moduleName, [MASK] ... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find( [MASK] name) {
return Optional.empty();
}
@Override
public Stream< [MASK] > list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find( [MASK] name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| String |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest. [MASK] ;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest. [MASK] .Method.GET;
import static org.elasticsearch.rest. [MASK] .Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@Override
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final [MASK] request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| RestRequest |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean [MASK] )
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, [MASK] ));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean [MASK] ) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if ( [MASK] ) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
.layer()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller.layer();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| addField |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.UpdateForV10;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
@ServerlessScope(Scope.PUBLIC)
public class RestGetAliasesAction extends BaseRestHandler {
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(RestGetAliasesAction.class);
@ [MASK]
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}")
);
}
@ [MASK]
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(
boolean aliasesExplicitlyRequested,
String[] requestedAliases,
Map<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases,
XContentBuilder builder
) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final Map.Entry<String, List<AliasMetadata>> cursor : responseAliasMap.entrySet()) {
for (final AliasMetadata aliasMetadata : cursor.getValue()) {
if (aliasesExplicitlyRequested) {
// only display indices that have aliases
indicesToDisplay.add(cursor.getKey());
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
dataStreamAliases.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.forEach(dataStreamAlias -> returnedAliasNames.add(dataStreamAlias.getName()));
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.isSimpleMatchPattern(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i])
|| Regex.isSimpleMatchPattern(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.collectionToCommaDelimitedString(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap.entrySet()) {
if (aliasesExplicitlyRequested == false || indicesToDisplay.contains(entry.getKey())) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.getValue()) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
// No need to do filtering like is done for aliases pointing to indices (^),
// because this already happens in TransportGetAliasesAction.
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
if (entry.getKey().equals(alias.getWriteDataStream())) {
builder.field("is_write_index", true);
}
if (alias.getFilter(entry.getKey()) != null) {
builder.field(
"filter",
XContentHelper.convertToMap(alias.getFilter(entry.getKey()).uncompressed(), true).v2()
);
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new RestResponse(status, builder);
}
@ [MASK]
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // remove the BWC support for the deprecated ?local parameter
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The TransportGetAliasesAction was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(masterNodeTimeout, aliases);
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
if (request.getRestApiVersion() == RestApiVersion.V_8) {
if (request.hasParam("local")) {
// consume this param just for validation when in BWC mode for V_8
final var localParam = request.paramAsBoolean("local", false);
DEPRECATION_LOGGER.critical(
DeprecationCategory.API,
"get-aliases-local",
"the [?local={}] query parameter to get-aliases requests has no effect and will be removed in a future version",
localParam
);
}
}
// we may want to move this logic to TransportGetAliasesAction but it is based on the original provided aliases, which will
// not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestBuilderListener<>(channel) {
@ [MASK]
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.getDataStreamAliases(), builder);
}
});
}
}
| Override |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3. [MASK] Utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final [MASK] TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set< [MASK] > toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for ( [MASK] toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set< [MASK] > extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for ( [MASK] toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map< [MASK] , ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map< [MASK] , ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
[MASK] value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
[MASK] name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, [MASK] newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
[MASK] toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean status = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
status = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return status;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static [MASK] removeLastExtension( [MASK] filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate( [MASK] resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool( [MASK] toolName) {
if (allowTestTools) {
return false;
}
if ( [MASK] Utils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static [MASK] getUniqueToolName(ToolTemplate template) {
[MASK] name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, [MASK] toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile( [MASK] name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static [MASK] getApplicationToolDirPath() {
[MASK] userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| String |
/*
* Copyright (c) 2020 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.moduletest;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.ModuleVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.utility.OpenedClassReader;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.module.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ModuleUtil {
public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened)
throws IOException {
return modularJar(isPublic, isExported, isOpened, false);
}
public static Path modularJar(
boolean isPublic, boolean isExported, boolean isOpened, boolean addField)
throws IOException {
Path jar = Files.createTempFile("sample-module", ".jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("module-info.class"));
out.write(moduleInfo(isExported, isOpened));
out.closeEntry();
out.putNextEntry(new JarEntry("sample/MyCallable.class"));
out.write(type(isPublic, addField));
out.closeEntry();
}
return jar;
}
private static byte[] type(boolean isPublic, boolean addField) {
DynamicType.Builder<?> typeBuilder =
new ByteBuddy()
.subclass(Callable.class)
.name("sample.MyCallable")
.merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE);
if (addField) {
typeBuilder =
typeBuilder.defineField(
"runnable", Runnable.class, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL);
}
return typeBuilder
.method(named("call"))
.intercept(FixedValue.value("foo"))
.make()
.getBytes();
}
private static byte[] moduleInfo(boolean isExported, boolean isOpened) {
ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API);
classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null);
mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null);
mv.visitPackage("sample");
if (isExported) {
mv.visitExport("sample", 0);
}
if (isOpened) {
mv.visitOpen("sample", 0);
}
mv.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
public static ModuleLayer [MASK] (Path jar, boolean canRead, boolean namedModules)
throws MalformedURLException {
Set<String> modules = new HashSet<>();
modules.add("mockito.test");
ModuleFinder moduleFinder = ModuleFinder.of(jar);
if (namedModules) {
modules.add("org.mockito");
modules.add("net.bytebuddy");
modules.add("net.bytebuddy.agent");
// We do not list all packages but only roots and packages that interact with the mock
// where
// we attempt to validate an interaction of two modules. This is of course a bit hacky
// as those
// libraries would normally be entirely encapsulated in an automatic module with all
// their classes
// but it is sufficient for the test and saves us a significant amount of code.
moduleFinder =
ModuleFinder.compose(
moduleFinder,
automaticModule(
"org.mockito",
"org.mockito",
"org.mockito.internal.creation.bytebuddy"),
automaticModule("net.bytebuddy", "net.bytebuddy"),
automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent"));
}
Configuration configuration =
Configuration.resolve(
moduleFinder,
Collections.singletonList(ModuleLayer.boot().configuration()),
ModuleFinder.of(),
modules);
ClassLoader classLoader = new ReplicatingClassLoader(jar);
ModuleLayer.Controller controller =
ModuleLayer.defineModules(
configuration,
Collections.singletonList(ModuleLayer.boot()),
module -> classLoader);
if (canRead) {
controller.addReads(
controller
. [MASK] ()
.findModule("mockito.test")
.orElseThrow(IllegalStateException::new),
Mockito.class.getModule());
}
return controller. [MASK] ();
}
private static ModuleFinder automaticModule(String moduleName, String... packages) {
ModuleDescriptor descriptor =
ModuleDescriptor.newAutomaticModule(moduleName)
.packages(new HashSet<>(Arrays.asList(packages)))
.build();
ModuleReference reference =
new ModuleReference(descriptor, null) {
@Override
public ModuleReader open() {
return new ModuleReader() {
@Override
public Optional<URI> find(String name) {
return Optional.empty();
}
@Override
public Stream<String> list() {
return Stream.empty();
}
@Override
public void close() {}
};
}
};
return new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
return name.equals(moduleName) ? Optional.of(reference) : Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(reference);
}
};
}
}
| layer |
/*
* Copyright (c) 2023, 2025, 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.graal. [MASK] .nodes.extended;
import static jdk.graal. [MASK] .nodeinfo.NodeCycles.CYCLES_0;
import static jdk.graal. [MASK] .nodeinfo.NodeSize.SIZE_0;
import jdk.graal. [MASK] .graph.IterableNodeType;
import jdk.graal. [MASK] .graph.Node;
import jdk.graal. [MASK] .graph.NodeClass;
import jdk.graal. [MASK] .graph.spi.NodeWithIdentity;
import jdk.graal. [MASK] .nodeinfo.InputType;
import jdk.graal. [MASK] .nodeinfo.NodeInfo;
import jdk.graal. [MASK] .nodes.GraphState.StageFlag;
import jdk.graal. [MASK] .nodes.NodeView;
import jdk.graal. [MASK] .nodes.ValueNode;
import jdk.graal. [MASK] .nodes.spi.Canonicalizable;
import jdk.graal. [MASK] .nodes.spi.CanonicalizerTool;
import jdk.graal. [MASK] .nodes.spi.LIRLowerable;
import jdk.graal. [MASK] .phases.common.RemoveOpaqueValuePhase;
/**
* This node type acts as an optimization barrier between its input node and its usages. For
* example, a MulNode with two ConstantNodes as input will be canonicalized to a ConstantNode. This
* optimization will be prevented if either of the two constants is wrapped by an OpaqueValueNode.
* <p>
* This node accepts an optional {@link StageFlag} argument. If set, the node will canonicalize away
* after that stage has been applied to the graph.
* <p>
* This node is not {@link LIRLowerable}, so it should be removed from the graph before LIR
* generation. {@link OpaqueValueNode}s that don't fold away will be removed by
* {@link RemoveOpaqueValuePhase} at the end of low tier.r
*/
@NodeInfo(cycles = CYCLES_0, size = SIZE_0)
public final class OpaqueValueNode extends OpaqueNode implements NodeWithIdentity, GuardingNode, IterableNodeType, Canonicalizable {
public static final NodeClass<OpaqueValueNode> TYPE = NodeClass.create(OpaqueValueNode.class);
@Input(InputType.Value) private ValueNode value;
private final StageFlag foldAfter;
public OpaqueValueNode(ValueNode value) {
this(value, null);
}
public OpaqueValueNode(ValueNode value, StageFlag foldAfter) {
super(TYPE, value.stamp(NodeView.DEFAULT).unrestricted());
this.foldAfter = foldAfter;
this.value = value;
}
@Override
public ValueNode getValue() {
return value;
}
@Override
public void setValue(ValueNode value) {
this.updateUsages(this.value, value);
this.value = value;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (foldAfter != null && this.graph() != null && this.graph().isAfterStage(foldAfter)) {
// delete this node
return value;
}
return this;
}
}
| compiler |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import ghidra.framework.model.ProjectManager;
import ghidra.framework.model.ToolTemplate;
import ghidra.framework.project.tool.GhidraToolTemplate;
import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import resources.ResourceManager;
public class ToolUtils {
public static final String TOOL_EXTENSION = ".tool";
private static final Logger LOGGER = LogManager.getLogger(ToolUtils.class);
private static final File USER_TOOLS_DIR = new File(getApplicationToolDirPath());
private static Set<ToolTemplate> allTools;
private static Set<ToolTemplate> defaultTools;
private static Set<ToolTemplate> extraTools;
// this can be changed reflectively
private static boolean allowTestTools = SystemUtilities.isInTestingMode();
private ToolUtils() {
// utils class
}
public static File getUserToolsDirectory() {
return USER_TOOLS_DIR;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory
*
* @return the default tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getDefaultApplicationTools() {
if (defaultTools != null) {
return defaultTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> toolNames = ResourceManager.getResourceNames("defaultTools", ".tool");
for (String toolName : toolNames) {
if (skipTool(toolName)) {
continue;
}
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
defaultTools = Collections.unmodifiableSet(set);
return defaultTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'extraTools' directory
*
* @return the extra tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getExtraApplicationTools() {
if (extraTools != null) {
return extraTools;
}
Set<ToolTemplate> set = new HashSet<>();
Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");
for (String toolName : extraToolsList) {
ToolTemplate tool = readToolTemplate(toolName);
if (tool != null) {
set.add(tool);
}
}
extraTools = Collections.unmodifiableSet(set);
return extraTools;
}
/**
* Returns all tools found in the classpath that live under a root
* 'defaultTools' directory or a root 'extraTools' directory
*
* @return the tools
*/
// synchronized to protect loading of static set
public static synchronized Set<ToolTemplate> getAllApplicationTools() {
if (allTools != null) {
return allTools;
}
Set<ToolTemplate> set = new HashSet<>();
set.addAll(getDefaultApplicationTools());
set.addAll(getExtraApplicationTools());
allTools = Collections.unmodifiableSet(set);
return allTools;
}
public static Map<String, ToolTemplate> loadUserTools() {
FilenameFilter filter =
(dir, name) -> name.endsWith(ProjectManager.APPLICATION_TOOL_EXTENSION);
// we want sorting by tool name, so use a sorted map
Map<String, ToolTemplate> map = new TreeMap<>();
File[] toolFiles = USER_TOOLS_DIR.listFiles(filter);
if (toolFiles != null) {
for (File toolFile : toolFiles) {
ToolTemplate template = ToolUtils.readToolTemplate(toolFile);
if (template != null) {
map.put(template.getName(), template);
}
}
}
return map;
}
public static void removeInvalidPlugins(ToolTemplate template) {
// parse the XML to see what plugins are loaded
Element xmlRoot = template.saveToXml();
// get out the tool element of the high-level tool
Element toolElement = xmlRoot.getChild("TOOL");
// the content of the tool xml consists of:
// -option manager content
// -plugin manager content
// -window manager content
// plugins are stored by adding content from SaveState objects, one per
// plugin
List<?> children = toolElement.getChildren("PLUGIN");
Object[] childArray = children.toArray(); // we may modify this list,
// so we need an array
for (Object object : childArray) {
Element pluginElement = (Element) object;
Attribute classAttribute = pluginElement.getAttribute("CLASS");
String value = classAttribute.getValue();
// check to see if we can still find the plugin class (it may have
// been removed)
try {
Class.forName(value);
}
catch (Throwable t) {
// oh well, leave it out
// TOOL: should we inform the user about these at some point?
LOGGER.info("Removing invalid plugin " + pluginElement.getAttributeValue("CLASS") +
" from tool: " + template.getName());
toolElement.removeContent(pluginElement);
}
}
// force the changes
template.restoreFromXml(xmlRoot);
}
public static void deleteTool(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String name = template.getName();
File toolFile = getToolFile(name);
if (toolFile == null) {
return;
}
toolFile.delete();
}
public static void renameToolTemplate(ToolTemplate toolTemplate, String newName) {
ToolUtils.deleteTool(toolTemplate);
toolTemplate.setName(newName);
ToolUtils.writeToolTemplate(toolTemplate);
}
public static boolean writeToolTemplate(ToolTemplate template) {
USER_TOOLS_DIR.mkdirs();
String toolName = template.getName();
File toolFile = getToolFile(toolName);
boolean [MASK] = false;
try (OutputStream os = new FileOutputStream(toolFile)) {
Element element = template.saveToXml();
Document doc = new Document(element);
XMLOutputter xmlout = new GenericXMLOutputter();
xmlout.output(doc, os);
os.close();
[MASK] = true;
}
catch (Exception e) {
Msg.error(LOGGER, "Error saving tool: " + toolName, e);
}
return [MASK] ;
}
public static ToolTemplate readToolTemplate(File toolFile) {
GhidraToolTemplate toolTemplate = null;
try (FileInputStream is = new FileInputStream(toolFile)) {
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
toolTemplate = new GhidraToolTemplate(root, toolFile.getAbsolutePath());
}
catch (FileNotFoundException e) {
throw new AssertException(
"We should only be passed valid files. Cannot find: " + toolFile.getAbsolutePath());
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for " + toolFile, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for " + toolFile, e);
}
updateFilenameToMatchToolName(toolFile, toolTemplate);
return toolTemplate;
}
private static void updateFilenameToMatchToolName(File toolFile,
GhidraToolTemplate toolTemplate) {
if (toolTemplate == null) {
return; // there must have been a problem creating the template
}
File correctToolFile = getToolFile(toolTemplate.getName());
if (correctToolFile.equals(toolFile)) {
return; // nothing to update
}
if (removeLastExtension(correctToolFile.getName()).equals(
NamingUtilities.mangle(toolTemplate.getName()))) {
return; // nothing to update
}
// If we get here, then we have two differently named files (the new one needs to replace
// the outdated old one). Make sure the files live in the same directory (otherwise,
// we can't delete the old one (this implies it is a default tool)).
if (correctToolFile.getParentFile().equals(toolFile.getParentFile())) {
// same parent directory, but different filename
toolFile.delete();
}
writeToolTemplate(toolTemplate);
}
private static String removeLastExtension(String filename) {
int period = filename.lastIndexOf('.');
if (period == -1) {
return filename;
}
return filename.substring(0, period);
}
public static ToolTemplate readToolTemplate(String resourceFileName) {
try (InputStream is = ResourceManager.getResourceAsStream(resourceFileName)) {
if (is == null) {
return null;
}
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Document doc = sax.build(is);
Element root = doc.getRootElement();
return new GhidraToolTemplate(root, resourceFileName);
}
catch (JDOMException e) {
Msg.error(LOGGER, "Error reading XML for resource " + resourceFileName, e);
}
catch (Exception e) {
Msg.error(LOGGER, "Can't read tool template for resource " + resourceFileName, e);
}
return null;
}
private static boolean skipTool(String toolName) {
if (allowTestTools) {
return false;
}
if (StringUtils.containsIgnoreCase(toolName, "test")) {
LOGGER.trace("Not adding default 'test' tool: " + toolName);
return true;
}
return false;
}
public static String getUniqueToolName(ToolTemplate template) {
String name = template.getName();
int n = 1;
while (ToolUtils.getToolFile(name).exists()) {
name = name + "_" + n++;
}
return name;
}
private static File getToolFile(File dir, String toolName) {
return new File(dir,
NamingUtilities.mangle(toolName) + ProjectManager.APPLICATION_TOOL_EXTENSION);
}
public static File getToolFile(String name) {
return getToolFile(USER_TOOLS_DIR, name);
}
/**
* Returns the user's personal tool chest directory path
* @return the path
*/
public static String getApplicationToolDirPath() {
String userSettingsPath = Application.getUserSettingsDirectory().getAbsolutePath();
return userSettingsPath + File.separatorChar + ProjectManager.APPLICATION_TOOLS_DIR_NAME;
}
}
| status |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.transaction.operation;
import org.redisson.RedissonKeys;
import org.redisson.RedissonLock;
import org.redisson.api.RKeys;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.transaction. [MASK] ;
import org.redisson.transaction.RedissonTransactionalWriteLock;
/**
*
* @author Nikita Koksharov
*
*/
public class UnlinkOperation extends TransactionalOperation {
private String writeLockName;
private String lockName;
private String transactionId;
public UnlinkOperation(String name) {
this(name, null, 0, null);
}
public UnlinkOperation(String name, String lockName, long threadId, String transactionId) {
super(name, null, threadId);
this.lockName = lockName;
this.transactionId = transactionId;
}
public UnlinkOperation(String name, String lockName, String writeLockName, long threadId, String transactionId) {
this(name, lockName, threadId, transactionId);
this.writeLockName = writeLockName;
}
@Override
public void commit(CommandAsyncExecutor commandExecutor) {
RKeys keys = new RedissonKeys(commandExecutor);
keys.unlinkAsync(getName());
if (lockName != null) {
RedissonLock lock = new [MASK] (commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
@Override
public void rollback(CommandAsyncExecutor commandExecutor) {
if (lockName != null) {
RedissonLock lock = new [MASK] (commandExecutor, lockName, transactionId);
lock.unlockAsync(getThreadId());
}
if (writeLockName != null) {
RedissonLock lock = new RedissonTransactionalWriteLock(commandExecutor, writeLockName, transactionId);
lock.unlockAsync(getThreadId());
}
}
public String getLockName() {
return lockName;
}
}
| RedissonTransactionalLock |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.