repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
csuarez/gridcake | src/org/glite/gridcake/gridftp/GridFTPService.java | 4948 | /*
* 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.glite.gridcake.gridftp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.globus.ftp.DataSinkStream;
import org.globus.ftp.DataSourceStream;
import org.globus.ftp.GridFTPClient;
import org.globus.ftp.Marker;
import org.globus.ftp.MarkerListener;
import org.globus.gsi.GlobusCredential;
import org.globus.gsi.gssapi.GlobusGSSCredentialImpl;
import org.ietf.jgss.GSSCredential;
/**
* Class for easy use of a GridFTP service.
* @author csuarez
*/
public class GridFTPService {
/**
* Hostname of the storage element.
*/
private String hostname;
/**
* Port of the GRIDFtp service.
*/
private int port;
/**
* Public constructor.
* @param hostname Hostname of the storage element.
* @param port Port of the GRIDFtp service.
*/
public GridFTPService(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
/**
* Downloads a file from a storage element using GRIDFtp.
* @param proxy Credentials to access to the service as a GlobusCredential object.
* @param urlTarget URL of the file to download.
* @return The file as a byte array.
* @throws Exception If something fails.
*/
public byte[] download(GlobusCredential proxy, String urlTarget) throws Exception {
byte[] digitalContent = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataSinkStream datasink = new DataSinkStream(bos);
GSSCredential credential = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT);
GridFTPClient client = new GridFTPClient(hostname, port);
client.authenticate(credential);
client.setType(org.globus.ftp.Session.TYPE_IMAGE);
client.setPassiveMode(true);
client.setMode(org.globus.ftp.Session.MODE_STREAM);
client.get(urlTarget.toString(), datasink, new MarkerListener() {
public void markerArrived(Marker arg0) {
}
});
client.close();
digitalContent = bos.toByteArray();
return digitalContent;
}
/**
* Uploads a file to a storage element using GRIDFtp.
* @param proxy Credentials to access to the service as a GlobusCredential object.
* @param digitalContent The file we want to upload as a byte array.
* @param urlTarget URL of the path where we want to upload our file.
* @throws Exception If something fails.
*/
public void upload(GlobusCredential proxy, byte[] digitalContent, String urlTarget) throws Exception {
GSSCredential credential = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT);
ByteArrayInputStream bis = new ByteArrayInputStream(digitalContent);
DataSourceStream source = new DataSourceStream(bis);
GridFTPClient client = new GridFTPClient(hostname, port);
client.authenticate(credential);
client.setType(org.globus.ftp.Session.TYPE_IMAGE);
client.setPassiveMode(true);
client.setMode(org.globus.ftp.Session.MODE_STREAM);
client.extendedPut(urlTarget.toString(), source,
new MarkerListener() {
public void markerArrived(Marker arg0) {
}
});
client.close();
}
/**
* Deletes a file from a storage element using GRIDFtp.
* @param proxy Credentials to access to the service as a GlobusCredential object.
* @param urlTarget URL of the file to download.
* @throws Exception If something fails.
*/
public void delete(GlobusCredential proxy, String urlTarget) throws Exception {
GSSCredential credential = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT);
GridFTPClient client = new GridFTPClient(hostname, port);
client.authenticate(credential);
client.setPassiveMode(true);
client.setType(org.globus.ftp.Session.TYPE_IMAGE);
client.setMode(org.globus.ftp.Session.MODE_STREAM);
client.deleteFile(urlTarget.toString());
client.close();
}
}
| apache-2.0 |
SergeyZhernovoy/Java-education | PartX/lesson2/src/test/java/ru/szhernovoy/carstore/dao/CarPartyDBManagerTest.java | 1667 | package ru.szhernovoy.carstore.dao;
import org.junit.Assert;
import org.junit.Test;
import ru.szhernovoy.carstore.model.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
/**
* Created by Admin on 25.01.2017.
*/
public class CarPartyDBManagerTest {
@Test
public void whenWeCreatePartyCarWeMustGetId() throws Exception {
Model model = new Model();
Transmission transmission = new Transmission();
Body body = new Body();
Engine engine = new Engine();
DriveType driveType = new DriveType();
model.setName("test model");
transmission.setName("test transmission");
body.setName("test bosy");
engine.setName("test engine");
driveType.setName("test drive");
model = new ModelDBManager().create(model);
body = new BodyDBManager().create(body);
transmission = new TranssmDBManger().create(transmission);
engine = new EngineDBManager().create(engine);
driveType = new DriveDBManager().create(driveType);
int id = 1;
Car car = new Car();
car.setName("test car");
car.setBody(body);
car.setDriveType(driveType);
car.setEngine(engine);
car.setModel(model);
car.setTransmission(transmission);
car = new CarDBManager().create(car);
Assert.assertThat(id,is(model.getId()));
Assert.assertThat(id,is(body.getId()));
Assert.assertThat(id,is(transmission.getId()));
Assert.assertThat(id,is(driveType.getId()));
Assert.assertThat(id,is(engine.getId()));
Assert.assertThat(id,is(car.getId()));
}
} | apache-2.0 |
k21/buck | src/com/facebook/buck/python/CxxPythonExtensionDescription.java | 19331 | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.python;
import com.facebook.buck.cxx.CxxConstructorArg;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxFlags;
import com.facebook.buck.cxx.CxxLinkableEnhancer;
import com.facebook.buck.cxx.CxxPreprocessAndCompile;
import com.facebook.buck.cxx.CxxPreprocessables;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.CxxSource;
import com.facebook.buck.cxx.CxxSourceRuleFactory;
import com.facebook.buck.cxx.toolchain.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.CxxPlatforms;
import com.facebook.buck.cxx.toolchain.HeaderSymlinkTree;
import com.facebook.buck.cxx.toolchain.HeaderVisibility;
import com.facebook.buck.cxx.toolchain.LinkerMapMode;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.linker.Linkers;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkTarget;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkTargetMode;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorConvertible;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.Optionals;
import com.facebook.buck.util.RichStream;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.facebook.buck.versions.VersionPropagator;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimaps;
import java.nio.file.Path;
import java.util.Optional;
import java.util.stream.Stream;
import org.immutables.value.Value;
public class CxxPythonExtensionDescription
implements Description<CxxPythonExtensionDescriptionArg>,
ImplicitDepsInferringDescription<
CxxPythonExtensionDescription.AbstractCxxPythonExtensionDescriptionArg>,
VersionPropagator<CxxPythonExtensionDescriptionArg> {
public enum Type implements FlavorConvertible {
EXTENSION(CxxDescriptionEnhancer.SHARED_FLAVOR),
SANDBOX_TREE(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR),
;
private final Flavor flavor;
Type(Flavor flavor) {
this.flavor = flavor;
}
@Override
public Flavor getFlavor() {
return flavor;
}
}
private static final FlavorDomain<Type> LIBRARY_TYPE =
FlavorDomain.from("C/C++ Library Type", Type.class);
private final FlavorDomain<PythonPlatform> pythonPlatforms;
private final CxxBuckConfig cxxBuckConfig;
private final FlavorDomain<CxxPlatform> cxxPlatforms;
public CxxPythonExtensionDescription(
FlavorDomain<PythonPlatform> pythonPlatforms,
CxxBuckConfig cxxBuckConfig,
FlavorDomain<CxxPlatform> cxxPlatforms) {
this.pythonPlatforms = pythonPlatforms;
this.cxxBuckConfig = cxxBuckConfig;
this.cxxPlatforms = cxxPlatforms;
}
@Override
public Class<CxxPythonExtensionDescriptionArg> getConstructorArgType() {
return CxxPythonExtensionDescriptionArg.class;
}
@VisibleForTesting
static BuildTarget getExtensionTarget(
BuildTarget target, Flavor pythonPlatform, Flavor platform) {
return CxxDescriptionEnhancer.createSharedLibraryBuildTarget(
target.withAppendedFlavors(pythonPlatform), platform, Linker.LinkType.SHARED);
}
@VisibleForTesting
static String getExtensionName(String moduleName) {
// .so is used on OS X too (as opposed to dylib).
return String.format("%s.so", moduleName);
}
private Path getExtensionPath(
ProjectFilesystem filesystem,
BuildTarget target,
String moduleName,
Flavor pythonPlatform,
Flavor platform) {
return BuildTargets.getGenPath(
filesystem, getExtensionTarget(target, pythonPlatform, platform), "%s")
.resolve(getExtensionName(moduleName));
}
private ImmutableList<com.facebook.buck.rules.args.Arg> getExtensionArgs(
BuildTarget target,
ProjectFilesystem projectFilesystem,
BuildRuleResolver ruleResolver,
SourcePathResolver pathResolver,
SourcePathRuleFinder ruleFinder,
CellPathResolver cellRoots,
CxxPlatform cxxPlatform,
CxxPythonExtensionDescriptionArg args,
ImmutableSet<BuildRule> deps) {
// Extract all C/C++ sources from the constructor arg.
ImmutableMap<String, CxxSource> srcs =
CxxDescriptionEnhancer.parseCxxSources(
target, ruleResolver, ruleFinder, pathResolver, cxxPlatform, args);
ImmutableMap<Path, SourcePath> headers =
CxxDescriptionEnhancer.parseHeaders(
target, ruleResolver, ruleFinder, pathResolver, Optional.of(cxxPlatform), args);
// Setup the header symlink tree and combine all the preprocessor input from this rule
// and all dependencies.
HeaderSymlinkTree headerSymlinkTree =
CxxDescriptionEnhancer.requireHeaderSymlinkTree(
target,
projectFilesystem,
ruleResolver,
cxxPlatform,
headers,
HeaderVisibility.PRIVATE,
true);
Optional<SymlinkTree> sandboxTree = Optional.empty();
if (cxxBuckConfig.sandboxSources()) {
sandboxTree = CxxDescriptionEnhancer.createSandboxTree(target, ruleResolver, cxxPlatform);
}
ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput =
CxxDescriptionEnhancer.collectCxxPreprocessorInput(
target,
cxxPlatform,
deps,
ImmutableListMultimap.copyOf(
Multimaps.transformValues(
CxxFlags.getLanguageFlagsWithMacros(
args.getPreprocessorFlags(),
args.getPlatformPreprocessorFlags(),
args.getLangPreprocessorFlags(),
cxxPlatform),
f ->
CxxDescriptionEnhancer.toStringWithMacrosArgs(
target, cellRoots, ruleResolver, cxxPlatform, f))),
ImmutableList.of(headerSymlinkTree),
ImmutableSet.of(),
CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform, deps),
args.getIncludeDirs(),
sandboxTree);
// Generate rule to build the object files.
ImmutableMultimap<CxxSource.Type, Arg> compilerFlags =
ImmutableListMultimap.copyOf(
Multimaps.transformValues(
CxxFlags.getLanguageFlagsWithMacros(
args.getCompilerFlags(),
args.getPlatformCompilerFlags(),
args.getLangCompilerFlags(),
cxxPlatform),
f ->
CxxDescriptionEnhancer.toStringWithMacrosArgs(
target, cellRoots, ruleResolver, cxxPlatform, f)));
ImmutableMap<CxxPreprocessAndCompile, SourcePath> picObjects =
CxxSourceRuleFactory.of(
projectFilesystem,
target,
ruleResolver,
pathResolver,
ruleFinder,
cxxBuckConfig,
cxxPlatform,
cxxPreprocessorInput,
compilerFlags,
args.getPrefixHeader(),
args.getPrecompiledHeader(),
CxxSourceRuleFactory.PicType.PIC,
sandboxTree)
.requirePreprocessAndCompileRules(srcs);
ImmutableList.Builder<com.facebook.buck.rules.args.Arg> argsBuilder = ImmutableList.builder();
CxxFlags.getFlagsWithMacrosWithPlatformMacroExpansion(
args.getLinkerFlags(), args.getPlatformLinkerFlags(), cxxPlatform)
.stream()
.map(
f ->
CxxDescriptionEnhancer.toStringWithMacrosArgs(
target, cellRoots, ruleResolver, cxxPlatform, f))
.forEach(argsBuilder::add);
// Embed a origin-relative library path into the binary so it can find the shared libraries.
argsBuilder.addAll(
StringArg.from(
Linkers.iXlinker(
"-rpath",
String.format("%s/", cxxPlatform.getLd().resolve(ruleResolver).libOrigin()))));
// Add object files into the args.
argsBuilder.addAll(SourcePathArg.from(picObjects.values()));
return argsBuilder.build();
}
private ImmutableSet<BuildRule> getPlatformDeps(
BuildRuleResolver ruleResolver,
PythonPlatform pythonPlatform,
CxxPlatform cxxPlatform,
CxxPythonExtensionDescriptionArg args) {
ImmutableSet.Builder<BuildRule> rules = ImmutableSet.builder();
// Add declared deps.
rules.addAll(args.getCxxDeps().get(ruleResolver, cxxPlatform));
// Add platform specific deps.
rules.addAll(
ruleResolver.getAllRules(
Iterables.concat(
args.getPlatformDeps().getMatchingValues(pythonPlatform.getFlavor().toString()))));
// Add a dep on the python C/C++ library.
if (pythonPlatform.getCxxLibrary().isPresent()) {
rules.add(ruleResolver.getRule(pythonPlatform.getCxxLibrary().get()));
}
return rules.build();
}
private BuildRule createExtensionBuildRule(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver ruleResolver,
CellPathResolver cellRoots,
PythonPlatform pythonPlatform,
CxxPlatform cxxPlatform,
CxxPythonExtensionDescriptionArg args) {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
String moduleName = args.getModuleName().orElse(buildTarget.getShortName());
String extensionName = getExtensionName(moduleName);
Path extensionPath =
getExtensionPath(
projectFilesystem,
buildTarget,
moduleName,
pythonPlatform.getFlavor(),
cxxPlatform.getFlavor());
ImmutableSet<BuildRule> deps = getPlatformDeps(ruleResolver, pythonPlatform, cxxPlatform, args);
return CxxLinkableEnhancer.createCxxLinkableBuildRule(
cxxBuckConfig,
cxxPlatform,
projectFilesystem,
ruleResolver,
pathResolver,
ruleFinder,
getExtensionTarget(buildTarget, pythonPlatform.getFlavor(), cxxPlatform.getFlavor()),
Linker.LinkType.SHARED,
Optional.of(extensionName),
extensionPath,
Linker.LinkableDepType.SHARED,
/* thinLto */ false,
RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
args.getCxxRuntimeType(),
Optional.empty(),
ImmutableSet.of(),
ImmutableSet.of(),
NativeLinkableInput.builder()
.setArgs(
getExtensionArgs(
buildTarget.withoutFlavors(LinkerMapMode.FLAVOR_DOMAIN.getFlavors()),
projectFilesystem,
ruleResolver,
pathResolver,
ruleFinder,
cellRoots,
cxxPlatform,
args,
deps))
.setFrameworks(args.getFrameworks())
.setLibraries(args.getLibraries())
.build(),
Optional.empty());
}
@Override
public BuildRule createBuildRule(
TargetGraph targetGraph,
BuildTarget buildTarget,
final ProjectFilesystem projectFilesystem,
BuildRuleParams params,
final BuildRuleResolver ruleResolver,
CellPathResolver cellRoots,
final CxxPythonExtensionDescriptionArg args) {
// See if we're building a particular "type" of this library, and if so, extract it as an enum.
final Optional<Type> type = LIBRARY_TYPE.getValue(buildTarget);
if (type.isPresent()) {
// If we *are* building a specific type of this lib, call into the type specific rule builder
// methods.
switch (type.get()) {
case SANDBOX_TREE:
return CxxDescriptionEnhancer.createSandboxTreeBuildRule(
ruleResolver,
args,
cxxPlatforms.getRequiredValue(buildTarget),
buildTarget,
projectFilesystem);
case EXTENSION:
return createExtensionBuildRule(
buildTarget,
projectFilesystem,
ruleResolver,
cellRoots,
pythonPlatforms.getRequiredValue(buildTarget),
cxxPlatforms.getRequiredValue(buildTarget),
args);
}
}
// Otherwise, we return the generic placeholder of this library, that dependents can use
// get the real build rules via querying the action graph.
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
final SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
Path baseModule = PythonUtil.getBasePath(buildTarget, args.getBaseModule());
String moduleName = args.getModuleName().orElse(buildTarget.getShortName());
final Path module = baseModule.resolve(getExtensionName(moduleName));
return new CxxPythonExtension(buildTarget, projectFilesystem, params) {
@Override
protected BuildRule getExtension(PythonPlatform pythonPlatform, CxxPlatform cxxPlatform) {
return ruleResolver.requireRule(
getBuildTarget()
.withAppendedFlavors(
pythonPlatform.getFlavor(),
cxxPlatform.getFlavor(),
CxxDescriptionEnhancer.SHARED_FLAVOR));
}
@Override
public Path getModule() {
return module;
}
@Override
public Iterable<BuildRule> getPythonPackageDeps(
PythonPlatform pythonPlatform, CxxPlatform cxxPlatform) {
return PythonUtil.getDeps(
pythonPlatform, cxxPlatform, args.getDeps(), args.getPlatformDeps())
.stream()
.map(ruleResolver::getRule)
.filter(PythonPackagable.class::isInstance)
.collect(MoreCollectors.toImmutableList());
}
@Override
public PythonPackageComponents getPythonPackageComponents(
PythonPlatform pythonPlatform, CxxPlatform cxxPlatform) {
BuildRule extension = getExtension(pythonPlatform, cxxPlatform);
SourcePath output = extension.getSourcePathToOutput();
return PythonPackageComponents.of(
ImmutableMap.of(module, output),
ImmutableMap.of(),
ImmutableMap.of(),
ImmutableSet.of(),
Optional.of(false));
}
@Override
public NativeLinkTarget getNativeLinkTarget(final PythonPlatform pythonPlatform) {
return new NativeLinkTarget() {
@Override
public BuildTarget getBuildTarget() {
return buildTarget.withAppendedFlavors(pythonPlatform.getFlavor());
}
@Override
public NativeLinkTargetMode getNativeLinkTargetMode(CxxPlatform cxxPlatform) {
return NativeLinkTargetMode.library();
}
@Override
public Iterable<? extends NativeLinkable> getNativeLinkTargetDeps(
CxxPlatform cxxPlatform) {
return RichStream.from(getPlatformDeps(ruleResolver, pythonPlatform, cxxPlatform, args))
.filter(NativeLinkable.class)
.toImmutableList();
}
@Override
public NativeLinkableInput getNativeLinkTargetInput(CxxPlatform cxxPlatform) {
return NativeLinkableInput.builder()
.addAllArgs(
getExtensionArgs(
buildTarget.withAppendedFlavors(
pythonPlatform.getFlavor(), CxxDescriptionEnhancer.SHARED_FLAVOR),
projectFilesystem,
ruleResolver,
pathResolver,
ruleFinder,
cellRoots,
cxxPlatform,
args,
getPlatformDeps(ruleResolver, pythonPlatform, cxxPlatform, args)))
.addAllFrameworks(args.getFrameworks())
.build();
}
@Override
public Optional<Path> getNativeLinkTargetOutputPath(CxxPlatform cxxPlatform) {
return Optional.empty();
}
};
}
@Override
public Stream<BuildTarget> getRuntimeDeps(SourcePathRuleFinder ruleFinder) {
return getDeclaredDeps().stream().map(BuildRule::getBuildTarget);
}
};
}
@Override
public void findDepsForTargetFromConstructorArgs(
BuildTarget buildTarget,
CellPathResolver cellRoots,
AbstractCxxPythonExtensionDescriptionArg constructorArg,
ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
// Get any parse time deps from the C/C++ platforms.
extraDepsBuilder.addAll(CxxPlatforms.getParseTimeDeps(cxxPlatforms.getValues()));
for (PythonPlatform pythonPlatform : pythonPlatforms.getValues()) {
Optionals.addIfPresent(pythonPlatform.getCxxLibrary(), extraDepsBuilder);
}
}
@BuckStyleImmutable
@Value.Immutable
interface AbstractCxxPythonExtensionDescriptionArg extends CxxConstructorArg {
Optional<String> getBaseModule();
Optional<String> getModuleName();
}
}
| apache-2.0 |
sstafford/gerrit-rest-java-client | src/main/java/com/urswolfer/gerrit/client/rest/http/accounts/AccountsRestClient.java | 3021 | /*
* Copyright 2013-2014 Urs Wolfer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.urswolfer.gerrit.client.rest.http.accounts;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.Url;
import com.google.gson.JsonElement;
import com.urswolfer.gerrit.client.rest.accounts.AccountApi;
import com.urswolfer.gerrit.client.rest.accounts.Accounts;
import com.urswolfer.gerrit.client.rest.http.GerritRestClient;
import java.util.List;
/**
* @author Urs Wolfer
*/
public class AccountsRestClient extends Accounts.NotImplemented implements Accounts {
private final GerritRestClient gerritRestClient;
private final AccountsParser accountsParser;
public AccountsRestClient(GerritRestClient gerritRestClient, AccountsParser accountsParser) {
this.gerritRestClient = gerritRestClient;
this.accountsParser = accountsParser;
}
@Override
public AccountApi id(String id) throws RestApiException {
return new AccountApiRestClient(gerritRestClient, accountsParser, id);
}
@Override
public AccountApi id(int id) throws RestApiException {
return id(String.valueOf(id));
}
@Override
public AccountApi self() throws RestApiException {
return id("self");
}
/**
* Added in Gerrit 2.11.
*/
@Override
public SuggestAccountsRequest suggestAccounts() throws RestApiException {
return new SuggestAccountsRequest() {
@Override
public List<AccountInfo> get() throws RestApiException {
return AccountsRestClient.this.suggestAccounts(this);
}
};
}
/**
* Added in Gerrit 2.11.
*/
@Override
public SuggestAccountsRequest suggestAccounts(String query) throws RestApiException {
return suggestAccounts().withQuery(query);
}
private List<AccountInfo> suggestAccounts(SuggestAccountsRequest r) throws RestApiException {
String encodedQuery = Url.encode(r.getQuery());
return getSuggestAccounts(String.format("q=%s&n=%s", encodedQuery, r.getLimit()));
}
private List<AccountInfo> getSuggestAccounts(String queryPart) throws RestApiException {
String request = String.format("/accounts/?%s", queryPart);
JsonElement suggestedReviewers = gerritRestClient.getRequest(request);
return accountsParser.parseAccountInfos(suggestedReviewers);
}
}
| apache-2.0 |
taktos/ea2ddl | ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/TObjecteffortCQ.java | 1647 | package jp.sourceforge.ea2ddl.dao.cbean.cq;
import jp.sourceforge.ea2ddl.dao.cbean.cq.bs.BsTObjecteffortCQ;
import org.seasar.dbflute.cbean.ConditionQuery;
import org.seasar.dbflute.cbean.sqlclause.SqlClause;
/**
* The condition-query of t_objecteffort.
* <p>
* You can implement your original methods here.
* This class is NOT overrided when re-generating.
* </p>
* @author DBFlute(AutoGenerator)
*/
@SuppressWarnings("unchecked")
public class TObjecteffortCQ extends BsTObjecteffortCQ {
// ===================================================================================
// Constructor
// ===========
/**
* Constructor.
* @param childQuery Child query as abstract class. (Nullable: If null, this is base instance.)
* @param sqlClause SQL clause instance. (NotNull)
* @param aliasName My alias name. (NotNull)
* @param nestLevel Nest level.
*/
public TObjecteffortCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(childQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// Arrange Method
// ==============
// You can make original arrange query methods here.
// public void arranegeXxx() {
// ...
// }
}
| apache-2.0 |
shybovycha/buck | src-gen/com/facebook/buck/distributed/thrift/SetBuckDotFilePathsRequest.java | 18218 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.facebook.buck.distributed.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2017-09-22")
public class SetBuckDotFilePathsRequest implements org.apache.thrift.TBase<SetBuckDotFilePathsRequest, SetBuckDotFilePathsRequest._Fields>, java.io.Serializable, Cloneable, Comparable<SetBuckDotFilePathsRequest> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("SetBuckDotFilePathsRequest");
private static final org.apache.thrift.protocol.TField STAMPEDE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("stampedeId", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final org.apache.thrift.protocol.TField DOT_FILES_FIELD_DESC = new org.apache.thrift.protocol.TField("dotFiles", org.apache.thrift.protocol.TType.LIST, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new SetBuckDotFilePathsRequestStandardSchemeFactory());
schemes.put(TupleScheme.class, new SetBuckDotFilePathsRequestTupleSchemeFactory());
}
public StampedeId stampedeId; // optional
public List<PathInfo> dotFiles; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
STAMPEDE_ID((short)1, "stampedeId"),
DOT_FILES((short)2, "dotFiles");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // STAMPEDE_ID
return STAMPEDE_ID;
case 2: // DOT_FILES
return DOT_FILES;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final _Fields optionals[] = {_Fields.STAMPEDE_ID,_Fields.DOT_FILES};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.STAMPEDE_ID, new org.apache.thrift.meta_data.FieldMetaData("stampedeId", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, StampedeId.class)));
tmpMap.put(_Fields.DOT_FILES, new org.apache.thrift.meta_data.FieldMetaData("dotFiles", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PathInfo.class))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SetBuckDotFilePathsRequest.class, metaDataMap);
}
public SetBuckDotFilePathsRequest() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public SetBuckDotFilePathsRequest(SetBuckDotFilePathsRequest other) {
if (other.isSetStampedeId()) {
this.stampedeId = new StampedeId(other.stampedeId);
}
if (other.isSetDotFiles()) {
List<PathInfo> __this__dotFiles = new ArrayList<PathInfo>(other.dotFiles.size());
for (PathInfo other_element : other.dotFiles) {
__this__dotFiles.add(new PathInfo(other_element));
}
this.dotFiles = __this__dotFiles;
}
}
public SetBuckDotFilePathsRequest deepCopy() {
return new SetBuckDotFilePathsRequest(this);
}
@Override
public void clear() {
this.stampedeId = null;
this.dotFiles = null;
}
public StampedeId getStampedeId() {
return this.stampedeId;
}
public SetBuckDotFilePathsRequest setStampedeId(StampedeId stampedeId) {
this.stampedeId = stampedeId;
return this;
}
public void unsetStampedeId() {
this.stampedeId = null;
}
/** Returns true if field stampedeId is set (has been assigned a value) and false otherwise */
public boolean isSetStampedeId() {
return this.stampedeId != null;
}
public void setStampedeIdIsSet(boolean value) {
if (!value) {
this.stampedeId = null;
}
}
public int getDotFilesSize() {
return (this.dotFiles == null) ? 0 : this.dotFiles.size();
}
public java.util.Iterator<PathInfo> getDotFilesIterator() {
return (this.dotFiles == null) ? null : this.dotFiles.iterator();
}
public void addToDotFiles(PathInfo elem) {
if (this.dotFiles == null) {
this.dotFiles = new ArrayList<PathInfo>();
}
this.dotFiles.add(elem);
}
public List<PathInfo> getDotFiles() {
return this.dotFiles;
}
public SetBuckDotFilePathsRequest setDotFiles(List<PathInfo> dotFiles) {
this.dotFiles = dotFiles;
return this;
}
public void unsetDotFiles() {
this.dotFiles = null;
}
/** Returns true if field dotFiles is set (has been assigned a value) and false otherwise */
public boolean isSetDotFiles() {
return this.dotFiles != null;
}
public void setDotFilesIsSet(boolean value) {
if (!value) {
this.dotFiles = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case STAMPEDE_ID:
if (value == null) {
unsetStampedeId();
} else {
setStampedeId((StampedeId)value);
}
break;
case DOT_FILES:
if (value == null) {
unsetDotFiles();
} else {
setDotFiles((List<PathInfo>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case STAMPEDE_ID:
return getStampedeId();
case DOT_FILES:
return getDotFiles();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case STAMPEDE_ID:
return isSetStampedeId();
case DOT_FILES:
return isSetDotFiles();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof SetBuckDotFilePathsRequest)
return this.equals((SetBuckDotFilePathsRequest)that);
return false;
}
public boolean equals(SetBuckDotFilePathsRequest that) {
if (that == null)
return false;
boolean this_present_stampedeId = true && this.isSetStampedeId();
boolean that_present_stampedeId = true && that.isSetStampedeId();
if (this_present_stampedeId || that_present_stampedeId) {
if (!(this_present_stampedeId && that_present_stampedeId))
return false;
if (!this.stampedeId.equals(that.stampedeId))
return false;
}
boolean this_present_dotFiles = true && this.isSetDotFiles();
boolean that_present_dotFiles = true && that.isSetDotFiles();
if (this_present_dotFiles || that_present_dotFiles) {
if (!(this_present_dotFiles && that_present_dotFiles))
return false;
if (!this.dotFiles.equals(that.dotFiles))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_stampedeId = true && (isSetStampedeId());
list.add(present_stampedeId);
if (present_stampedeId)
list.add(stampedeId);
boolean present_dotFiles = true && (isSetDotFiles());
list.add(present_dotFiles);
if (present_dotFiles)
list.add(dotFiles);
return list.hashCode();
}
@Override
public int compareTo(SetBuckDotFilePathsRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetStampedeId()).compareTo(other.isSetStampedeId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStampedeId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.stampedeId, other.stampedeId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetDotFiles()).compareTo(other.isSetDotFiles());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDotFiles()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.dotFiles, other.dotFiles);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("SetBuckDotFilePathsRequest(");
boolean first = true;
if (isSetStampedeId()) {
sb.append("stampedeId:");
if (this.stampedeId == null) {
sb.append("null");
} else {
sb.append(this.stampedeId);
}
first = false;
}
if (isSetDotFiles()) {
if (!first) sb.append(", ");
sb.append("dotFiles:");
if (this.dotFiles == null) {
sb.append("null");
} else {
sb.append(this.dotFiles);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (stampedeId != null) {
stampedeId.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class SetBuckDotFilePathsRequestStandardSchemeFactory implements SchemeFactory {
public SetBuckDotFilePathsRequestStandardScheme getScheme() {
return new SetBuckDotFilePathsRequestStandardScheme();
}
}
private static class SetBuckDotFilePathsRequestStandardScheme extends StandardScheme<SetBuckDotFilePathsRequest> {
public void read(org.apache.thrift.protocol.TProtocol iprot, SetBuckDotFilePathsRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // STAMPEDE_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.stampedeId = new StampedeId();
struct.stampedeId.read(iprot);
struct.setStampedeIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // DOT_FILES
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list98 = iprot.readListBegin();
struct.dotFiles = new ArrayList<PathInfo>(_list98.size);
PathInfo _elem99;
for (int _i100 = 0; _i100 < _list98.size; ++_i100)
{
_elem99 = new PathInfo();
_elem99.read(iprot);
struct.dotFiles.add(_elem99);
}
iprot.readListEnd();
}
struct.setDotFilesIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, SetBuckDotFilePathsRequest struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.stampedeId != null) {
if (struct.isSetStampedeId()) {
oprot.writeFieldBegin(STAMPEDE_ID_FIELD_DESC);
struct.stampedeId.write(oprot);
oprot.writeFieldEnd();
}
}
if (struct.dotFiles != null) {
if (struct.isSetDotFiles()) {
oprot.writeFieldBegin(DOT_FILES_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.dotFiles.size()));
for (PathInfo _iter101 : struct.dotFiles)
{
_iter101.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class SetBuckDotFilePathsRequestTupleSchemeFactory implements SchemeFactory {
public SetBuckDotFilePathsRequestTupleScheme getScheme() {
return new SetBuckDotFilePathsRequestTupleScheme();
}
}
private static class SetBuckDotFilePathsRequestTupleScheme extends TupleScheme<SetBuckDotFilePathsRequest> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, SetBuckDotFilePathsRequest struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetStampedeId()) {
optionals.set(0);
}
if (struct.isSetDotFiles()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetStampedeId()) {
struct.stampedeId.write(oprot);
}
if (struct.isSetDotFiles()) {
{
oprot.writeI32(struct.dotFiles.size());
for (PathInfo _iter102 : struct.dotFiles)
{
_iter102.write(oprot);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, SetBuckDotFilePathsRequest struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.stampedeId = new StampedeId();
struct.stampedeId.read(iprot);
struct.setStampedeIdIsSet(true);
}
if (incoming.get(1)) {
{
org.apache.thrift.protocol.TList _list103 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.dotFiles = new ArrayList<PathInfo>(_list103.size);
PathInfo _elem104;
for (int _i105 = 0; _i105 < _list103.size; ++_i105)
{
_elem104 = new PathInfo();
_elem104.read(iprot);
struct.dotFiles.add(_elem104);
}
}
struct.setDotFilesIsSet(true);
}
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-mediaconnect/src/main/java/com/amazonaws/services/mediaconnect/model/transform/DescribeOfferingRequestMarshaller.java | 2043 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.mediaconnect.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.mediaconnect.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeOfferingRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeOfferingRequestMarshaller {
private static final MarshallingInfo<String> OFFERINGARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("offeringArn").build();
private static final DescribeOfferingRequestMarshaller instance = new DescribeOfferingRequestMarshaller();
public static DescribeOfferingRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DescribeOfferingRequest describeOfferingRequest, ProtocolMarshaller protocolMarshaller) {
if (describeOfferingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeOfferingRequest.getOfferingArn(), OFFERINGARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
wenzhucjy/tomcat_source | tomcat-8.0.9-sourcecode/java/org/apache/catalina/core/AsyncListenerWrapper.java | 1686 | /*
* 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.catalina.core;
import java.io.IOException;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
public class AsyncListenerWrapper {
private AsyncListener listener = null;
public void fireOnStartAsync(AsyncEvent event) throws IOException {
listener.onStartAsync(event);
}
public void fireOnComplete(AsyncEvent event) throws IOException {
listener.onComplete(event);
}
public void fireOnTimeout(AsyncEvent event) throws IOException {
listener.onTimeout(event);
}
public void fireOnError(AsyncEvent event) throws IOException {
listener.onError(event);
}
public AsyncListener getListener() {
return listener;
}
public void setListener(AsyncListener listener) {
this.listener = listener;
}
}
| apache-2.0 |
gdutxiaoxu/git- | src/com/bjsxt/tank/Wall.java | 471 | package com.bjsxt.tank;
import java.awt.*;
public class Wall {
int x, y, w, h;
TankClient tc ;
public Wall(int x, int y, int w, int h, TankClient tc) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.tc = tc;
}
public void draw(Graphics g) {
Color c = g.getColor();
g.setColor(Color.DARK_GRAY);
g.fillRect(x, y, w, h);
g.setColor(c);
}
public Rectangle getRect() {
return new Rectangle(x, y, w, h);
}
}
| apache-2.0 |
JavaSaBr/jME3-SpaceShift-Editor | src/main/java/com/ss/editor/model/undo/impl/AddChildOperation.java | 2122 | package com.ss.editor.model.undo.impl;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.ss.editor.Messages;
import com.ss.editor.model.undo.editor.ModelChangeConsumer;
import com.ss.editor.model.undo.impl.AbstractEditorOperation;
import com.ss.editor.plugin.api.RenderFilterExtension;
import org.jetbrains.annotations.NotNull;
/**
* The implementation of the {@link AbstractEditorOperation} to add a new {@link Spatial} to a {@link Node}.
*
* @author JavaSaBr
*/
public class AddChildOperation extends AbstractEditorOperation<ModelChangeConsumer> {
/**
* The new child.
*/
@NotNull
private final Spatial newChild;
/**
* The parent.
*/
@NotNull
private final Node parent;
/**
* The flag to select added child.
*/
private final boolean needSelect;
public AddChildOperation(@NotNull final Spatial newChild, @NotNull final Node parent) {
this(newChild, parent, true);
}
public AddChildOperation(@NotNull final Spatial newChild, @NotNull final Node parent, boolean needSelect) {
this.newChild = newChild;
this.parent = parent;
this.needSelect = needSelect;
}
@Override
protected void redoImpl(@NotNull final ModelChangeConsumer editor) {
EXECUTOR_MANAGER.addJmeTask(() -> {
editor.notifyJmePreChangeProperty(newChild, Messages.MODEL_PROPERTY_TRANSFORMATION);
parent.attachChildAt(newChild, 0);
editor.notifyJmeChangedProperty(newChild, Messages.MODEL_PROPERTY_TRANSFORMATION);
final RenderFilterExtension filterExtension = RenderFilterExtension.getInstance();
filterExtension.refreshFilters();
EXECUTOR_MANAGER.addFxTask(() -> editor.notifyFxAddedChild(parent, newChild, 0, needSelect));
});
}
@Override
protected void undoImpl(@NotNull final ModelChangeConsumer editor) {
EXECUTOR_MANAGER.addJmeTask(() -> {
parent.detachChild(newChild);
EXECUTOR_MANAGER.addFxTask(() -> editor.notifyFxRemovedChild(parent, newChild));
});
}
}
| apache-2.0 |
ameron32/ProjectBandit | ProjectBandit/.apt_generated/com/ameron32/apps/projectbandit/core/trial/GridPagerFragment$$ViewInjector.java | 853 | // Generated code from Butter Knife. Do not modify!
package com.ameron32.apps.projectbandit.core.trial;
import android.view.View;
import butterknife.ButterKnife.Finder;
public class GridPagerFragment$$ViewInjector {
public static void inject(Finder finder, final com.ameron32.apps.projectbandit.core.trial.GridPagerFragment target, Object source) {
com.ameron32.apps.projectbandit.core.fragment.AbsContentFragment$$ViewInjector.inject(finder, target, source);
View view;
view = finder.findRequiredView(source, 2131296394, "field 'gridView'");
target.gridView = (com.jess.ui.TwoWayGridView) view;
}
public static void reset(com.ameron32.apps.projectbandit.core.trial.GridPagerFragment target) {
com.ameron32.apps.projectbandit.core.fragment.AbsContentFragment$$ViewInjector.reset(target);
target.gridView = null;
}
}
| apache-2.0 |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/history/AddToHistoryDialog.java | 5632 | /*
* Copyright (C) 2017 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui.history;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import javax.inject.Inject;
import net.simonvt.cathode.R;
import net.simonvt.cathode.sync.scheduler.EpisodeTaskScheduler;
import net.simonvt.cathode.sync.scheduler.MovieTaskScheduler;
import net.simonvt.cathode.sync.scheduler.SeasonTaskScheduler;
import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler;
import net.simonvt.cathode.ui.NavigationListener;
public class AddToHistoryDialog extends DialogFragment {
public static final String TAG = "net.simonvt.cathode.ui.history.AddToHistoryDialog";
private static final String ARG_TYPE = "net.simonvt.cathode.ui.history.AddToHistoryDialog.type";
private static final String ARG_ID = "net.simonvt.cathode.ui.history.AddToHistoryDialog.id";
private static final String ARG_TITLE = "net.simonvt.cathode.ui.history.AddToHistoryDialog.title";
public enum Type {
SHOW, SEASON, EPISODE, EPISODE_OLDER, MOVIE,
}
private ShowTaskScheduler showScheduler;
private SeasonTaskScheduler seasonScheduler;
private EpisodeTaskScheduler episodeScheduler;
private MovieTaskScheduler movieScheduler;
private NavigationListener navigationListener;
public static Bundle getArgs(Type type, long id, String title) {
Bundle args = new Bundle();
args.putSerializable(ARG_TYPE, type);
args.putLong(ARG_ID, id);
args.putString(ARG_TITLE, title);
return args;
}
@Inject public AddToHistoryDialog(ShowTaskScheduler showScheduler,
SeasonTaskScheduler seasonScheduler,
EpisodeTaskScheduler episodeScheduler,
MovieTaskScheduler movieScheduler) {
this.showScheduler = showScheduler;
this.seasonScheduler = seasonScheduler;
this.episodeScheduler = episodeScheduler;
this.movieScheduler = movieScheduler;
}
@Override public void onAttach(@NonNull Context context) {
super.onAttach(context);
navigationListener = (NavigationListener) requireActivity();
}
@NonNull @Override public Dialog onCreateDialog(@Nullable Bundle inState) {
final Type type = (Type) getArguments().getSerializable(ARG_TYPE);
final long id = getArguments().getLong(ARG_ID);
final String title = getArguments().getString(ARG_TITLE);
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle(R.string.history_watched_when);
builder.setNegativeButton(R.string.history_watched_other,
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
switch (type) {
case SHOW:
navigationListener.onSelectShowWatchedDate(id, title);
break;
case SEASON:
navigationListener.onSelectSeasonWatchedDate(id, title);
break;
case EPISODE:
navigationListener.onSelectEpisodeWatchedDate(id, title);
break;
case EPISODE_OLDER:
navigationListener.onSelectOlderEpisodeWatchedDate(id, title);
break;
case MOVIE:
navigationListener.onSelectMovieWatchedDate(id, title);
break;
}
}
});
builder.setNeutralButton(R.string.history_watched_release,
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
switch (type) {
case SHOW:
showScheduler.addToHistoryOnRelease(id);
break;
case SEASON:
seasonScheduler.addToHistoryOnRelease(id);
break;
case EPISODE:
episodeScheduler.addToHistoryOnRelease(id);
break;
case EPISODE_OLDER:
episodeScheduler.addOlderToHistoryOnRelease(id);
break;
case MOVIE:
movieScheduler.addToHistoryOnRelease(id);
break;
}
}
});
builder.setPositiveButton(R.string.history_watched_now, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
switch (type) {
case SHOW:
showScheduler.addToHistoryNow(id);
break;
case SEASON:
seasonScheduler.addToHistoryNow(id);
break;
case EPISODE:
episodeScheduler.addToHistoryNow(id);
break;
case EPISODE_OLDER:
episodeScheduler.addOlderToHistoryNow(id);
break;
case MOVIE:
movieScheduler.addToHistoryNow(id);
break;
}
}
});
return builder.create();
}
}
| apache-2.0 |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/activity/ZYKManhuaApplication.java | 607 | package com.zykmanhua.app.activity;
import android.app.Application;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.thinkland.sdk.android.JuheSDKInitializer;
public class ZYKManhuaApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
JuheSDKInitializer.initialize(getApplicationContext());
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(getApplicationContext())
.build();
ImageLoader.getInstance().init(configuration);
}
}
| apache-2.0 |
markusgumbel/dshl7 | hl7-javasig/src/org/hl7/types/impl/EDimpl.java | 2042 | /* The contents of this file are subject to the Health Level-7 Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.hl7.org/HPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and
* limitations under the License.
*
* The Original Code is all this file.
*
* The Initial Developer of the Original Code is .
* Portions created by Initial Developer are Copyright (C) 2002-2004
* Health Level Seven, Inc. All Rights Reserved.
*
* Contributor(s):
*/
package org.hl7.types.impl;
import java.util.Iterator;
import org.hl7.types.ANY;
import org.hl7.types.BIN;
import org.hl7.types.BL;
import org.hl7.types.CS;
import org.hl7.types.ED;
import org.hl7.types.INT;
import org.hl7.types.LIST;
import org.hl7.types.TEL;
public final class EDimpl extends ANYimpl implements ED {
private EDimpl() {
super(null);
}
/** FIXME: is NA correct or should it be derived from this and that? */
@Override
public BL equal(final ANY that) {
return BLimpl.NA;
}
public BL head() {
throw new UnsupportedOperationException();
}
public LIST<BL> tail() {
throw new UnsupportedOperationException();
}
public Iterator<BL> iterator() {
throw new UnsupportedOperationException();
}
public BL isEmpty() {
return BLimpl.NA;
}
public BL nonEmpty() {
return BLimpl.NA;
}
public INT length() {
return INTnull.NA;
}
// The ED interface
public CS mediaType() {
return CSnull.NA;
}
public CS charset() {
return CSnull.NA;
}
public CS compression() {
return CSnull.NA;
}
public CS language() {
return CSnull.NA;
}
public TEL reference() {
return TELnull.NA;
}
public BIN integrityCheck() {
return BINnull.NA;
}
public CS integrityCheckAlgorithm() {
return CSnull.NA;
}
public ED thumbnail() {
return EDnull.NA;
}
};
| apache-2.0 |
sandeepmukho/sample-data-structures | src/org/misc/BombDiffuse2.java | 2179 | package org.misc;
import java.util.HashMap;
/**
*
* There are n bombs in a road going from left to right,and each bomb has a
* value and a 'effect range'.If you detonated a bomb,you will get this bomb's
* value,but a bomb can have effect on the neighbors which the
* distance(difference between index) between them is smaller than the 'effect
* range'.It's say that the neighbor bomb will be destoryed and you could not
* get their values. You will given each bomb's value and the 'effect range',and
* you need calculate the max value you can get. eg. n=3 index 0's bomb' v is
* 2,range is 0(will not effect others).and v[1]=1,r[1]=1,v[2]=3,r[2]=1; this
* case's max value is 5.(detonate the 0's and than the 2's).
*
* <p>
* dynamic programming approach
* </p>
*
* @author sandy
*
*/
public class BombDiffuse2 {
static HashMap<String, Integer> cache = new HashMap<String, Integer>();
public static Integer getFromCache(int i, int j) {
Integer cacheValue = null;
if (i > j)
cacheValue = cache.get(i + "_" + j);
else
cacheValue = cache.get(j + "_" + i);
cacheValue = cache.get(i + "_" + j);
return cacheValue;
}
public static int maxBomb(int[] values, int[] radius, int i, int j) {
Integer max = 0;
max = cache.get(i + "_" + j);
if (max != null) {
return max;
}
if (i > j)
return 0;
int currRadius = radius[i];
int currValue = values[i];
// Max without diffusing the ith bomb
int maxWoIth = maxBomb(values, radius, i + 1, j);
// Max with diffusing the ith bomb
int maxWithIth = maxBomb(values, radius, i + 1 + currRadius, j) + currValue;
// System.out.println("(" + i + "," + j + ") - " + maxWoIth + " " +
// maxWithIth);
max = maxWoIth > maxWithIth ? maxWoIth : maxWithIth;
cache.put(i + "_" + j, max);
return max;
}
public static void main(String[] args) {
int[] values = { 4, 4 };
int[] radius = { 0, 1 };
System.out.println(maxBomb(values, radius, 0, radius.length - 1));
}
}
| apache-2.0 |
wangshijun101/JavaSenior | spider-web/src/main/java/tk/mybatis/springboot/model/City.java | 1614 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 abel533@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package tk.mybatis.springboot.model;
/**
* @author liuzh_3nofxnp
* @since 2016-01-22 22:16
*/
public class City extends BaseEntity {
private String name;
private String state;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53domains/model/transform/ViewBillingResultJsonUnmarshaller.java | 3094 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.route53domains.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.route53domains.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ViewBillingResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ViewBillingResultJsonUnmarshaller implements Unmarshaller<ViewBillingResult, JsonUnmarshallerContext> {
public ViewBillingResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ViewBillingResult viewBillingResult = new ViewBillingResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return viewBillingResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("NextPageMarker", targetDepth)) {
context.nextToken();
viewBillingResult.setNextPageMarker(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("BillingRecords", targetDepth)) {
context.nextToken();
viewBillingResult.setBillingRecords(new ListUnmarshaller<BillingRecord>(BillingRecordJsonUnmarshaller.getInstance()).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return viewBillingResult;
}
private static ViewBillingResultJsonUnmarshaller instance;
public static ViewBillingResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ViewBillingResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/BucketPolicy.java | 2501 | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Portions copyright 2006-2009 James Murty. Please see LICENSE.txt
* for applicable license terms and NOTICE.txt for applicable notices.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.s3.model;
import java.io.Serializable;
/**
* <p>
* Represents a Amazon S3 bucket policy.
* Bucket policies provide access control management at the bucket level for
* both the bucket resource and contained object resources. Only one policy may
* be specified per bucket.
* </p>
* <p>
* Buckets have no policy text until one is explicitly specified.
* Requesting the bucket policy for a newly created bucket will return a
* policy object with <code>null</code> policy text.
* </p>
* <p>
* See the <a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/">
* Amazon S3 developer guide</a> for more information on forming bucket
* polices.
* </p>
*/
public class BucketPolicy implements Serializable {
/** The raw, policy JSON text, as returned by Amazon S3 */
private String policyText;
/**
* Gets the raw policy JSON text as returned by Amazon S3. If no policy
* has been applied to the specified bucket, the policy text will be
* null.
*
* @return The raw policy JSON text as returned by Amazon S3.
* If no policy has been applied to the specified bucket, this method returns
* null policy text.
*
* @see BucketPolicy#setPolicyText(String)
*/
public String getPolicyText() {
return policyText;
}
/**
* Sets the raw policy JSON text.
* A bucket will have no policy text unless the policy text is explicitly
* provided through this method.
*
* @param policyText
* The raw policy JSON text.
*
* @see BucketPolicy#getPolicyText()
*/
public void setPolicyText(String policyText) {
this.policyText = policyText;
}
}
| apache-2.0 |
MariaSergeeva/sergeeva | soap-sample/src/main/java/net/webservicex/GeoIPServiceSoap.java | 1957 | package net.webservicex;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 3.1.12
* 2017-07-11T18:03:45.696+03:00
* Generated source version: 3.1.12
*
*/
@WebService(targetNamespace = "http://www.webservicex.net/", name = "GeoIPServiceSoap")
@XmlSeeAlso({ObjectFactory.class})
public interface GeoIPServiceSoap {
/**
* GeoIPService - GetGeoIP enables you to easily look up countries by IP addresses
*/
@WebMethod(operationName = "GetGeoIP", action = "http://www.webservicex.net/GetGeoIP")
@RequestWrapper(localName = "GetGeoIP", targetNamespace = "http://www.webservicex.net/", className = "net.webservicex.GetGeoIP")
@ResponseWrapper(localName = "GetGeoIPResponse", targetNamespace = "http://www.webservicex.net/", className = "net.webservicex.GetGeoIPResponse")
@WebResult(name = "GetGeoIPResult", targetNamespace = "http://www.webservicex.net/")
public net.webservicex.GeoIP getGeoIP(
@WebParam(name = "IPAddress", targetNamespace = "http://www.webservicex.net/")
java.lang.String ipAddress
);
/**
* GeoIPService - GetGeoIPContext enables you to easily look up countries by Context
*/
@WebMethod(operationName = "GetGeoIPContext", action = "http://www.webservicex.net/GetGeoIPContext")
@RequestWrapper(localName = "GetGeoIPContext", targetNamespace = "http://www.webservicex.net/", className = "net.webservicex.GetGeoIPContext")
@ResponseWrapper(localName = "GetGeoIPContextResponse", targetNamespace = "http://www.webservicex.net/", className = "net.webservicex.GetGeoIPContextResponse")
@WebResult(name = "GetGeoIPContextResult", targetNamespace = "http://www.webservicex.net/")
public net.webservicex.GeoIP getGeoIPContext();
}
| apache-2.0 |
gan-wang/coolweather | app/src/main/java/com/coolweather/android/util/HttpUtil.java | 430 | package com.coolweather.android.util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* Created by wang on 2017/4/25 0025.
*/
public class HttpUtil {
public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
}
| apache-2.0 |
mkwhitacre/kite-apps | kite-apps-cli/src/main/java/org/kitesdk/apps/cli/Main.java | 5446 | /**
* Copyright 2015 Cerner Corporation.
* Copyright 2015 Cloudera, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kitesdk.apps.cli;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.MissingCommandException;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Level;
import org.apache.log4j.PropertyConfigurator;
import org.kitesdk.apps.cli.commands.InstallCommand;
import org.kitesdk.apps.cli.commands.JarCommand;
import org.kitesdk.cli.Command;
import org.kitesdk.cli.Help;
import org.kitesdk.data.DatasetIOException;
import org.kitesdk.data.DatasetNotFoundException;
import org.kitesdk.data.ValidationException;
import org.kitesdk.data.spi.DefaultConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/**
* This class is based on logic from kite-tools project. Ultimately
* this logic should be factored out to eliminate this duplication.
*/
public class Main extends Configured implements Tool {
public static void main (String[] args) throws Exception {
// reconfigure logging with the kite CLI configuration
PropertyConfigurator.configure(
Main.class.getResource("/kite-apps-cli-logging.properties"));
Logger console = LoggerFactory.getLogger(Main.class);
Configuration conf = new Configuration();
conf.addResource("yarn-site.xml");
conf.addResource("hive-site.xml");
int rc = ToolRunner.run(conf, new Main(console), args);
System.exit(rc);
}
@Parameter(names = {"-v", "--verbose", "--debug"},
description = "Print extra debugging information")
private boolean debug = false;
@VisibleForTesting
@Parameter(names="--dollar-zero",
description="A way for the runtime path to be passed in", hidden=true)
String programName = DEFAULT_PROGRAM_NAME;
@VisibleForTesting
static final String DEFAULT_PROGRAM_NAME = "kite-apps";
private static Set<String> HELP_ARGS = ImmutableSet.of("-h", "-help", "--help", "help");
private final Logger console;
private final JCommander jc;
private Main(Logger console) {
this.console = console;
this.jc = new JCommander(this);
jc.addCommand("install", new InstallCommand(console));
jc.addCommand("jar", new JarCommand(console));
}
@Override
public int run(String[] args) throws Exception {
if (getConf() != null) {
DefaultConfiguration.set(getConf());
}
try {
jc.parse(args);
} catch (MissingCommandException e) {
console.error(e.getMessage());
return 1;
} catch (ParameterException e) {
console.error(e.getMessage());
return 1;
}
// configure log4j
if (debug) {
org.apache.log4j.Logger console = org.apache.log4j.Logger.getLogger(Main.class);
console.setLevel(Level.DEBUG);
}
String parsed = jc.getParsedCommand();
if (parsed == null) {
console.error("Unable to parse command.");
return 1;
}
Command command = (Command) jc.getCommands().get(parsed).getObjects().get(0);
if (command == null) {
console.error("Unable to find command.");
return 1;
}
try {
if (command instanceof Configurable) {
((Configurable) command).setConf(getConf());
}
return command.run();
} catch (IllegalArgumentException e) {
if (debug) {
console.error("Argument error", e);
} else {
console.error("Argument error: {}", e.getMessage());
}
return 1;
} catch (IllegalStateException e) {
if (debug) {
console.error("State error", e);
} else {
console.error("State error: {}", e.getMessage());
}
return 1;
} catch (ValidationException e) {
if (debug) {
console.error("Validation error", e);
} else {
console.error("Validation error: {}", e.getMessage());
}
return 1;
} catch (DatasetNotFoundException e) {
if (debug) {
console.error("Cannot find dataset", e);
} else {
// the error message already contains "No such dataset: <name>"
console.error(e.getMessage());
}
return 1;
} catch (DatasetIOException e) {
if (debug) {
console.error("IO error", e);
} else {
console.error("IO error: {}", e.getMessage());
}
return 1;
} catch (Exception e) {
if (debug) {
console.error("Unknown error", e);
} else {
console.error("Unknown error: {}", e.getMessage());
}
return 1;
}
}
}
| apache-2.0 |
EllisMin/st | ParseStarterProject/src/main/java/com/parse/starter/Register.java | 6081 | package com.parse.starter;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
public class Register extends AppCompatActivity implements View.OnClickListener {
Bitmap bitmapImage;
EditText usernameField;
EditText emailField;
EditText passwordField;
ImageView profilePhoto;
ParseFile file = null;
Boolean imageSelected = false;
// When hit back button
public void back_reg(View view){
// Goes back to Login page
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
// When hit signup button
public void signupBtn(View view){
if(imageSelected) {
// Storing image in byteArray
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
file = new ParseFile(String.valueOf(usernameField.getText()) + ".png", byteArray);
} else { // When the user does not select an image
profilePhoto.buildDrawingCache();
Bitmap bm = profilePhoto.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
file = new ParseFile(String.valueOf(usernameField.getText()) + "_default.png", byteArray);
}
ParseUser user = new ParseUser();
user.setUsername(String.valueOf(usernameField.getText()));
user.setEmail(String.valueOf(emailField.getText()));
user.setPassword(String.valueOf(passwordField.getText()));
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
Log.i("AppInfo", "Signup Successful");
//Adding the image in
Log.i("APPINFO", "" + ParseUser.getCurrentUser().getUsername() + " now has file" + file.getName());
ParseUser.getCurrentUser().put("photo", file);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
// Code to show search page
Intent i = new Intent(getApplicationContext(), Search.class);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(), e.getMessage().substring(e.getMessage().indexOf(" ")), Toast.LENGTH_LONG).show();
}
}
}
);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
usernameField = (EditText) findViewById(R.id.Username);
emailField = (EditText) findViewById(R.id.Email);
passwordField = (EditText) findViewById(R.id.password);
profilePhoto = (ImageView) findViewById(R.id.profilePhoto);
profilePhoto.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.profilePhoto){
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data !=null){
Uri selectedImage = data.getData();
try {
bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
// Displaying image
ImageView profile = (ImageView) findViewById(R.id.profilePhoto);
profile.setImageBitmap(RoundedImageView.getCroppedBitmap(bitmapImage, 440));
imageSelected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| apache-2.0 |
yangwn/ordering | showcase/base-curd/src/test/java/com/github/dactiv/showcase/test/manager/foundation/audit/TestOperatingRecordManager.java | 1607 | package com.github.dactiv.showcase.test.manager.foundation.audit;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import com.github.bean.showcase.common.enumeration.entity.OperatingState;
import com.github.bean.showcase.entity.foundation.audit.OperatingRecord;
import com.github.bean.showcase.service.foundation.SystemAuditManager;
import com.github.dactiv.showcase.test.manager.ManagerTestCaseSupport;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* 测试操作记录业务逻辑
*
* @author maurice
*
*/
public class TestOperatingRecordManager extends ManagerTestCaseSupport{
@Autowired
private SystemAuditManager systemAuditManager;
@Test
@Transactional
public void testInsertOperatingRecord() {
OperatingRecord or = new OperatingRecord();
or.setStartDate(new Date());
or.setIp("127.0.0.1");
or.setMethod("com.github.dactiv.showcase.test.manager.foundation.audit.OperatingRecordManager.testSaveOperatingRecord()");
or.setOperatingTarget("account/user/view");
or.setState(OperatingState.Success.getValue());
or.setFkUserId("SJDK3849CKMS3849DJCK2039ZMSK0026");
or.setUsername("admin");
or.setEndDate(new Date());
int beforeRow = countRowsInTable("TB_OPERATING_RECORD");
systemAuditManager.insertOperatingRecord(or);
getSessionFactory().getCurrentSession().flush();
int afterRow = countRowsInTable("TB_OPERATING_RECORD");
assertEquals(afterRow, beforeRow + 1);
}
}
| apache-2.0 |
eduosi/buessionframework | buession-core/src/main/java/com/buession/core/mcrypt/RSAMcrypt.java | 8555 | /*
* 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.
*
* =========================================================================================================
*
* This software consists of voluntary contributions made by many individuals on behalf of the
* Apache Software Foundation. For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* +-------------------------------------------------------------------------------------------------------+
* | License: http://www.apache.org/licenses/LICENSE-2.0.txt |
* | Author: Yong.Teng <webmaster@buession.com> |
* | Copyright @ 2013-2018 Buession.com Inc. |
* +-------------------------------------------------------------------------------------------------------+
*/
package com.buession.core.mcrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
/**
* RSA 加密对象
*
* @author Yong.Teng
*/
class RSAMcrypt extends AbstractMcrypt {
private static Cipher cipher = null;
private final static Logger logger = LoggerFactory.getLogger(RSAMcrypt.class);
public RSAMcrypt(){
super(Algo.RSA);
initCipher();
}
/**
* @param provider
* 信息摘要对象的提供者
*/
public RSAMcrypt(final Provider provider){
super(Algo.RSA, provider);
initCipher();
}
/**
* @param characterEncoding
* 字符编码
*/
public RSAMcrypt(final String characterEncoding){
super(Algo.RSA, characterEncoding);
initCipher();
}
/**
* @param charset
* 字符编码
*/
public RSAMcrypt(final Charset charset){
super(Algo.RSA, charset);
initCipher();
}
/**
* @param characterEncoding
* 字符编码
* @param provider
* 信息摘要对象的提供者
*/
public RSAMcrypt(final String characterEncoding, final Provider provider){
this(characterEncoding, null, provider);
}
/**
* @param charset
* 字符编码
* @param provider
* 信息摘要对象的提供者
*/
public RSAMcrypt(final Charset charset, final Provider provider){
this(charset, null, provider);
}
/**
* @param characterEncoding
* 字符编码
* @param salt
* 加密密钥
*/
public RSAMcrypt(final String characterEncoding, final String salt){
this(characterEncoding, salt, null);
}
/**
* @param charset
* 字符编码
* @param salt
* 加密密钥
*/
public RSAMcrypt(final Charset charset, final String salt){
this(charset, salt, null);
}
/**
* @param characterEncoding
* 字符编码
* @param salt
* 加密密钥
* @param provider
* 信息摘要对象的提供者
*/
public RSAMcrypt(final String characterEncoding, final String salt, final Provider provider){
super(Algo.RSA, characterEncoding, salt, provider);
initCipher();
}
/**
* @param charset
* 字符编码
* @param salt
* 加密密钥
* @param provider
* 信息摘要对象的提供者
*/
public RSAMcrypt(final Charset charset, final String salt, final Provider provider){
super(Algo.RSA, charset, salt, provider);
initCipher();
}
/**
* 对象加密
*
* @param object
* 需要加密的字符串
*
* @return 加密后的字符串
*/
@Override
public String encode(final Object object){
Key key = getKey();
if(key == null){
return null;
}
byte[] result = encode(key, ParseUtils.object2Byte(object));
logger.debug("RSAMcrypt encode string <{}> by algo <RSA>, salt <{}>", object, getSalt());
return result == null ? null : ParseUtils.byte2Hex(result);
}
/**
* 字符串解密
* 该方法需要提供信息摘要算法支持双向解密才可用
*
* @param cs
* 要被解密的 char 值序列
*
* @return 解密后的字符串
*/
@Override
public String decode(final CharSequence cs){
Key key = getKey();
if(key == null){
return null;
}
byte[] result = decode(key, ParseUtils.hex2Byte(cs.toString()));
logger.debug("RSAMcrypt decode string <{}> by algo <RSA>, salt <{}>", cs, getSalt());
return result == null ? null : new String(result);
}
private final static Cipher initCipher(){
if(cipher == null){
try{
cipher = Cipher.getInstance(Algo.RSA.getName());
}catch(NoSuchAlgorithmException e){
logger.error(e.getMessage());
}catch(NoSuchPaddingException e){
logger.error(e.getMessage());
}
}
return cipher;
}
private final SecretKeyFactory getSecretKeyFactory() throws NoSuchAlgorithmException{
Provider provider = getProvider();
return provider == null ? SecretKeyFactory.getInstance(Algo.RSA.getName()) : SecretKeyFactory.getInstance
(Algo.RSA.getName(), provider);
}
private final Key getKey(){
String salt = getSalt();
if(salt == null){
salt = "";
}
int saltLength = salt.length();
if(saltLength < 16){
for(int i = 1; i <= 16 - saltLength; i++){
salt += " ";
}
}else if(saltLength < 24){
for(int i = 1; i <= 24 - saltLength; i++){
salt += " ";
}
}else if(saltLength < 32){
for(int i = 1; i <= 32 - saltLength; i++){
salt += " ";
}
}else if(saltLength > 32){
salt = salt.substring(0, 31);
}
return new SecretKeySpec(salt.getBytes(getCharset()), Algo.RSA.name());// 转换为RSA专用密钥
}
private final byte[] encode(final Key key, final byte[] data){
if(data == null){
throw new IllegalArgumentException("RSAMcrypt encode object could not be null");
}
try{
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式的密码器
return cipher.doFinal(data);
}catch(InvalidKeyException e){
logger.error(e.getMessage());
}catch(IllegalBlockSizeException e){
logger.error(e.getMessage());
}catch(BadPaddingException e){
logger.error(e.getMessage());
}
return null;
}
private final byte[] decode(final Key key, final byte[] data){
if(data == null){
throw new IllegalArgumentException("RSAMcrypt decode object could not be null");
}
try{
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
return cipher.doFinal(data); // 明文
}catch(InvalidKeyException e){
logger.error(e.getMessage());
}catch(IllegalBlockSizeException e){
logger.error(e.getMessage());
}catch(BadPaddingException e){
logger.error(e.getMessage());
}
return null;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/ModifySnapshotAttributeResultStaxUnmarshaller.java | 2323 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.ec2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* ModifySnapshotAttributeResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ModifySnapshotAttributeResultStaxUnmarshaller implements Unmarshaller<ModifySnapshotAttributeResult, StaxUnmarshallerContext> {
public ModifySnapshotAttributeResult unmarshall(StaxUnmarshallerContext context) throws Exception {
ModifySnapshotAttributeResult modifySnapshotAttributeResult = new ModifySnapshotAttributeResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return modifySnapshotAttributeResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return modifySnapshotAttributeResult;
}
}
}
}
private static ModifySnapshotAttributeResultStaxUnmarshaller instance;
public static ModifySnapshotAttributeResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new ModifySnapshotAttributeResultStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
Activiti/Activiti | activiti-api/activiti-api-process-model/src/main/java/org/activiti/api/process/model/builders/GetProcessDefinitionsPayloadBuilder.java | 1777 | /*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.api.process.model.builders;
import java.util.HashSet;
import java.util.Set;
import org.activiti.api.process.model.payloads.GetProcessDefinitionsPayload;
public class GetProcessDefinitionsPayloadBuilder {
private String processDefinitionId;
private Set<String> processDefinitionKeys = new HashSet<>();
public GetProcessDefinitionsPayloadBuilder withProcessDefinitionKeys(Set<String> processDefinitionKeys) {
this.processDefinitionKeys = processDefinitionKeys;
return this;
}
public GetProcessDefinitionsPayloadBuilder withProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
return this;
}
public GetProcessDefinitionsPayloadBuilder withProcessDefinitionKey(String processDefinitionKey) {
if (processDefinitionKeys == null) {
processDefinitionKeys = new HashSet<>();
}
processDefinitionKeys.add(processDefinitionKey);
return this;
}
public GetProcessDefinitionsPayload build() {
return new GetProcessDefinitionsPayload(processDefinitionId, processDefinitionKeys);
}
}
| apache-2.0 |
openfurther/further-open-core | security/security-impl/src/main/java/edu/utah/further/security/impl/domain/UserPropertyEntity.java | 4384 | /**
* Copyright (C) [2013] [The FURTHeR Project]
*
* 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 edu.utah.further.security.impl.domain;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.annotations.Immutable;
import edu.utah.further.security.api.domain.Property;
import edu.utah.further.security.api.domain.User;
import edu.utah.further.security.api.domain.UserProperty;
/**
* A many to many relationship between a user and property.
* <p>
* -----------------------------------------------------------------------------------<br>
* (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah<br>
* Contact: {@code <further@utah.edu>}<br>
* Biomedical Informatics, 26 South 2000 East<br>
* Room 5775 HSEB, Salt Lake City, UT 84112<br>
* Day Phone: 1-801-581-4080<br>
* -----------------------------------------------------------------------------------
*
* @author N. Dustin Schultz {@code <dustin.schultz@utah.edu>}
* @version May 2, 2012
*/
@Entity
@Table(name = "APP_USER_PROP")
@Immutable
public class UserPropertyEntity implements UserProperty
{
/**
* Generated serial UID
*/
private static final long serialVersionUID = -8346629928787932968L;
@Id
@GeneratedValue
@Column(name = "app_user_prop_id")
private Long id;
@ManyToOne(targetEntity = UserEntity.class)
@JoinColumn(name = "app_user_id")
private User user;
@ManyToOne(cascade = CascadeType.ALL, targetEntity = PropertyEntity.class)
@JoinColumn(name = "app_prop_id")
private Property property;
@Column(name = "app_prop_val")
private String propertyValue;
/**
* Return the id property.
*
* @return the id
*/
@Override
public Long getId()
{
return id;
}
/**
* Set a new value for the id property.
*
* @param id
* the id to set
*/
public void setId(final Long id)
{
this.id = id;
}
/**
* Return the user property.
*
* @return the user
*/
@Override
public User getUser()
{
return user;
}
/**
* Set a new value for the user property.
*
* @param user
* the user to set
*/
@Override
public void setUser(final User user)
{
this.user = user;
}
/**
* Return the property property.
*
* @return the property
*/
@Override
public Property getProperty()
{
return property;
}
/**
* Set a new value for the property property.
*
* @param property
* the property to set
*/
@Override
public void setProperty(final Property property)
{
this.property = property;
}
/**
* Return the propertyValue property.
*
* @return the propertyValue
*/
@Override
public String getPropertyValue()
{
return propertyValue;
}
/**
* Set a new value for the propertyValue property.
*
* @param propertyValue
* the propertyValue to set
*/
@Override
public void setPropertyValue(final String propertyValue)
{
this.propertyValue = propertyValue;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object object)
{
if (object == null)
return false;
if (object == this)
return true;
if (getClass() != object.getClass())
return false;
final UserPropertyEntity that = (UserPropertyEntity) object;
return new EqualsBuilder().append(this.getId(), that.getId()).isEquals();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return new HashCodeBuilder().append(this.getId()).toHashCode();
}
}
| apache-2.0 |
logic-ng/LogicNG | src/main/java/org/logicng/functions/MinimumPrimeImplicantFunction.java | 5106 | ///////////////////////////////////////////////////////////////////////////
// __ _ _ ________ //
// / / ____ ____ _(_)____/ | / / ____/ //
// / / / __ \/ __ `/ / ___/ |/ / / __ //
// / /___/ /_/ / /_/ / / /__/ /| / /_/ / //
// /_____/\____/\__, /_/\___/_/ |_/\____/ //
// /____/ //
// //
// The Next Generation Logic Library //
// //
///////////////////////////////////////////////////////////////////////////
// //
// Copyright 2015-20xx Christoph Zengler //
// //
// 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.logicng.functions;
import org.logicng.datastructures.Assignment;
import org.logicng.datastructures.Tristate;
import org.logicng.formulas.Formula;
import org.logicng.formulas.FormulaFunction;
import org.logicng.formulas.Literal;
import org.logicng.formulas.Variable;
import org.logicng.solvers.MiniSat;
import org.logicng.solvers.SATSolver;
import org.logicng.solvers.functions.OptimizationFunction;
import org.logicng.solvers.sat.MiniSatConfig;
import org.logicng.transformations.LiteralSubstitution;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Computes a minimum-size prime implicant for the given formula.
* Returns {@code null} if the formula was not satisfiable.
* @version 2.0.0
* @since 2.0.0
*/
public final class MinimumPrimeImplicantFunction implements FormulaFunction<SortedSet<Literal>> {
private static final String POS = "_POS";
private static final String NEG = "_NEG";
private static final MinimumPrimeImplicantFunction INSTANCE = new MinimumPrimeImplicantFunction();
private MinimumPrimeImplicantFunction() {
// intentionally left empty
}
/**
* Returns the singleton instance of this function.
* @return an instance of this function
*/
public static MinimumPrimeImplicantFunction get() {
return INSTANCE;
}
@Override
public SortedSet<Literal> apply(final Formula formula, final boolean cache) {
final Formula nnf = formula.nnf();
final Map<Variable, Literal> newVar2oldLit = new HashMap<>();
final LiteralSubstitution substitution = new LiteralSubstitution();
for (final Literal literal : nnf.literals()) {
final Variable newVar = formula.factory().variable(literal.name() + (literal.phase() ? POS : NEG));
newVar2oldLit.put(newVar, literal);
substitution.addSubstitution(literal, newVar);
}
final Formula substitued = nnf.transform(substitution);
final SATSolver solver = MiniSat.miniSat(formula.factory(), MiniSatConfig.builder().cnfMethod(MiniSatConfig.CNFMethod.PG_ON_SOLVER).build());
solver.add(substitued);
for (final Literal literal : newVar2oldLit.values()) {
if (literal.phase() && newVar2oldLit.containsValue(literal.negate())) {
solver.add(formula.factory().amo(formula.factory().variable(literal.name() + POS), formula.factory().variable(literal.name() + NEG)));
}
}
if (solver.sat() != Tristate.TRUE) {
return null;
}
final Assignment minimumModel = solver.execute(OptimizationFunction.minimize(newVar2oldLit.keySet()));
final SortedSet<Literal> primeImplicant = new TreeSet<>();
for (final Variable variable : minimumModel.positiveVariables()) {
final Literal literal = newVar2oldLit.get(variable);
if (literal != null) {
primeImplicant.add(literal);
}
}
return primeImplicant;
}
}
| apache-2.0 |
openegovplatform/OEPv2 | oep-core-datamgt-portlet/docroot/WEB-INF/service/org/oep/core/datamgt/service/DictAttributeServiceClp.java | 2536 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
package org.oep.core.datamgt.service;
import com.liferay.portal.service.InvokableService;
/**
* @author NQMINH
* @generated
*/
public class DictAttributeServiceClp implements DictAttributeService {
public DictAttributeServiceClp(InvokableService invokableService) {
_invokableService = invokableService;
_methodName0 = "getBeanIdentifier";
_methodParameterTypes0 = new String[] { };
_methodName1 = "setBeanIdentifier";
_methodParameterTypes1 = new String[] { "java.lang.String" };
}
@Override
public java.lang.String getBeanIdentifier() {
Object returnObj = null;
try {
returnObj = _invokableService.invokeMethod(_methodName0,
_methodParameterTypes0, new Object[] { });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (java.lang.String)ClpSerializer.translateOutput(returnObj);
}
@Override
public void setBeanIdentifier(java.lang.String beanIdentifier) {
try {
_invokableService.invokeMethod(_methodName1,
_methodParameterTypes1,
new Object[] { ClpSerializer.translateInput(beanIdentifier) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable {
throw new UnsupportedOperationException();
}
private InvokableService _invokableService;
private String _methodName0;
private String[] _methodParameterTypes0;
private String _methodName1;
private String[] _methodParameterTypes1;
} | apache-2.0 |
Jason-Chen-2017/restfeel | src/main/java/com/restfeel/dto/TagDTO.java | 1086 | /*
* Copyright 2014 Ranjan Kumar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.restfeel.dto;
import org.springframework.data.mongodb.core.mapping.DBRef;
public class TagDTO extends BaseDTO {
private ColorDTO color;
@DBRef
private WorkspaceDTO workspace;
public ColorDTO getColor() {
return color;
}
public void setColor(ColorDTO color) {
this.color = color;
}
public WorkspaceDTO getWorkspace() {
return workspace;
}
public void setWorkspace(WorkspaceDTO workspace) {
this.workspace = workspace;
}
}
| apache-2.0 |
jrimum/texgit | src/main/java/org/jrimum/texgit/type/component/RecordFactory.java | 1669 | /*
* Copyright 2008 JRimum Project
*
* 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.
*
* Created at: 26/07/2008 - 12:44:41
*
* ================================================================================
*
* Direitos autorais 2008 JRimum Project
*
* Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar
* esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma
* cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que
* haja exigência legal ou acordo por escrito, a distribuição de software sob
* esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER
* TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a
* reger permissões e limitações sob esta LICENÇA.
*
* Criado em: 26/07/2008 - 12:44:41
*
*/
package org.jrimum.texgit.type.component;
import org.jrimum.texgit.Record;
/**
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @param <G>
*/
public interface RecordFactory <G extends Record>{
public abstract G create(String name);
}
| apache-2.0 |
cowthan/JavaAyo | src/com/cowthan/pattern1/builder/BMWBuilder.java | 425 | package com.cowthan.pattern1.builder;
import java.util.ArrayList;
public class BMWBuilder extends CarBuilder{
private BMW bmw = new BMW();
@Override
public void setSequence(ArrayList<String> sequence) {
this.bmw.setSequence(sequence);
}
@Override
public ICar getCar() {
return this.bmw;
}
public ICar getCar(ArrayList<String> sequence){
BMW bmw = new BMW();
bmw.setSequence(sequence);
return bmw;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/ListLabelingJobsForWorkteamSortByOptions.java | 1921 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.sagemaker.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ListLabelingJobsForWorkteamSortByOptions {
CreationTime("CreationTime");
private String value;
private ListLabelingJobsForWorkteamSortByOptions(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return ListLabelingJobsForWorkteamSortByOptions corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static ListLabelingJobsForWorkteamSortByOptions fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (ListLabelingJobsForWorkteamSortByOptions enumEntry : ListLabelingJobsForWorkteamSortByOptions.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| apache-2.0 |
fasthall/cs263w16 | base_project/base/src/main/java/cs263w16/WishlistServlet.java | 3026 | /*
* @Author Wei-Tsung Lin
* @Date 03/11/2016
* @Description Show all products in the wishlist
*/
package cs263w16;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
@SuppressWarnings("serial")
public class WishlistServlet extends HttpServlet {
/*
* List all the products on the wishlist. Not used now.
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><body>");
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user == null) {
resp.getWriter().println("Please login first!");
resp.getWriter().println("</body></html>");
return;
}
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Query query = new Query(user.getEmail());
query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
List<Entity> results = datastore.prepare(query).asList(
FetchOptions.Builder.withDefaults());
resp.getWriter().println("<table border=\"0\">");
resp.getWriter()
.println(
"<tr><b><td>Product name</td><td>Current price</td><td>History lowest</td></b></tr>");
int i = 0;
for (Entity entity : results) {
String productID = (String) entity.getKey().getName();
String productName = (String) entity.getProperty("productName");
double currentPrice = (double) entity.getProperty("currentPrice");
double lowestPrice = (double) entity.getProperty("lowestPrice");
Date lowestDate = (Date) entity.getProperty("lowestDate");
if (i % 2 == 0) {
resp.getWriter().println(
"<tr style=\"background-color: #f5f5f5\">");
} else {
resp.getWriter().println("<tr>");
}
++i;
resp.getWriter().println("<td>");
resp.getWriter().println(
"<a href=\"http://www.amazon.com/dp/" + productID
+ "\" target=\"_blank\">" + "<b>" + productName
+ "</b></a>");
resp.getWriter().println("</td>");
resp.getWriter().println("<td>");
resp.getWriter().println("$" + currentPrice);
resp.getWriter().println("</td>");
resp.getWriter().println("<td>");
resp.getWriter().println("$" + lowestPrice);
resp.getWriter().println("</td>");
resp.getWriter().println("</tr>");
}
resp.getWriter().println("</table>");
resp.getWriter().println("</body></html>");
}
} | apache-2.0 |
YY-ORG/yycloud | yy-common/yy-common-utils/src/main/java/com/yy/cloud/common/utils/reflect/criteria/expression/PropertyExpression.java | 255 | package com.yy.cloud.common.utils.reflect.criteria.expression;
import com.yy.cloud.common.utils.reflect.filter.PropertyFilter;
/**
* @author wejia
* @create Jul 6, 2016
*/
public interface PropertyExpression {
public PropertyFilter toFilter();
}
| apache-2.0 |
stone83/ping_tools | app/src/main/java/com/jj/game/boost/wifi4g/WIFI_DATA_Manager.java | 803 | package com.jj.game.boost.wifi4g;
/**
* Created by huzd on 2017/7/6.
*/
public class WIFI_DATA_Manager {
private static AbstractWIFI_DATA instance = null;
private WIFI_DATA_Manager(){
}
public static AbstractWIFI_DATA getInstance(){
if(null == instance){
synchronized (WIFI_DATA_Manager.class){
if (null == instance){
if(AbstractWIFI_DATA.getNetType().equals(Const.WIFI)){
instance = new WifiControl();
} else if(AbstractWIFI_DATA.getNetType().equals(Const.DATA)) {
instance = new DataControl();
}
}
}
}
return instance;
}
public static void release(){
instance = null;
}
}
| apache-2.0 |
googleapis/java-scheduler | google-cloud-scheduler/src/main/java/com/google/cloud/scheduler/v1beta1/stub/GrpcCloudSchedulerCallableFactory.java | 4816 | /*
* Copyright 2021 Google LLC
*
* 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.google.cloud.scheduler.v1beta1.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcCallableFactory;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientStreamingCallable;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StreamingCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.longrunning.Operation;
import com.google.longrunning.stub.OperationsStub;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC callable factory implementation for the CloudScheduler service API.
*
* <p>This class is for advanced usage.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class GrpcCloudSchedulerCallableFactory implements GrpcStubCallableFactory {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createPagedCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBatchingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
GrpcCallSettings<RequestT, Operation> grpcCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
OperationsStub operationsStub) {
return GrpcCallableFactory.createOperationCallable(
grpcCallSettings, callSettings, clientContext, operationsStub);
}
@Override
public <RequestT, ResponseT>
BidiStreamingCallable<RequestT, ResponseT> createBidiStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBidiStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createServerStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ClientStreamingCallable<RequestT, ResponseT> createClientStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createClientStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
}
| apache-2.0 |
Domonlee/Bmob_IM | src/com/bmob/im/demo/util/Constant.java | 7715 | package com.bmob.im.demo.util;
public class Constant {
public static String IMAGE_BASE_URL = "http://sp.woaisp.com/";
public static String API_KEY = "H1WWduPFjM1z6dqvTIyBrswb";
public static final String KEY = "123566646614654564L";
public static String url = "http://api.androidhive.info/contacts/";
public static final String TAG_CONTACTS = "contacts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_GENDER = "gender";
public static final String TAG_EMAI = "emal";
// ÏÞʱ¹º
public static final String XIANSHIQIANGGOU = "http://sp.woaisp.com/hlf_spapp/check!androidqg?page=1&rows=10";
public static final String XIANSHI_ID = "id";
public static final String XIANSHI_BIAOTI = "tgbiaoti";
public static final String XIANSHI_FBIAOTI = "tgfubiaoti";
public static final String XIANSHI_STARTTIME = "tgkaishi";
public static final String XIANSHI_STOPTIME = "tgend";
public static final String XIANSHI_PRICE = "tgjiage";
public static final String XIANSHI_PWD = "tgpwd";
public static final String XIANSHI_IMG = "spimg";
// »ý·Ö¶Ò»»http://sp.woaisp.com/
public static final String JIFENDUIHUAN_URL = "http://sp.woaisp.com/hlf_spapp/check!androidscore?page=1&rows=10&order=asc";
public static final String JIFEN_ID = "id";
public static final String JIFEN_NAME = "spname";
public static final String JIFEN_IMAGE = "spimg";
public static final String JIFEN_NUMBER = "spnumber";
public static final String JIFEN_SCORE = "spscore";
public static final String JIFEN_POSITION = "postion";
public static final String JIFEN_TITLE = "title";
// ÍŹº
public static final String TUANGOU_GUANGGAO_URL = "http://sp.woaisp.com/hlf_spapp/check!androidchecks";
public static final String TUANGOU_BASE_URL = "http://sp.woaisp.com/hlf_spapp/check!androidfood?";
public static final String TUANGOU_URL = "http://sp.woaisp.com/hlf_spapp/check!androidfood?";
public static final String TUANGOU_ID = "id";
public static final String TUANGOU_EPT = "ept";
public static final String TUANGOU_NMAE = "spname";
public static final String TUANGOU_PKC = "sahngpinkucui";
public static final String TUANGOU_IMG = "shangpinimg";
public static final String TUANGOU_PTEXT = "shangpintext";
public static final String TUANGOU_PJIGE = "shangpinjige";
public static final String TUANGOU_XIAOLIANG = "shangpinxiaoliang";
public static final String TUANGOU_CJTG = "cjtg";
public static final String TUANGOU_CGQG = "cjqg";
public static final String TUANGOU_TYPE = "spfenlei";
public static final String TUANGOU_KUNCUN = "kucun";
public static final String TUANGOU_XIANGLIANG = "xiaoliang";
public static final String TUANGOU_EPTNAME = "eptname";
public static final String TUANGOU_TGBIAOTI = "tgbiaoti";
public static final String TUANGOU_TGFUBIAOTI = "tgfubiaoti";
public static final String TUANGOU_YEMIAN = "yemian";
public static final String TUANGOU_TGID = "tgid";
public static final String TUANGOU_POSITIONID = "posationid";
public static final String TUANGOU_TGIMG = "tgimg";
public static final String TUANGOU_POSITIONNAME = "posationname";
public static final String TUANGOU_DIANZHU = "diznzhu";
public static final String TUANGOU_FEILEI = "fenlei";
public static final int TUANGOU_TYPE_FOOD = 1;
public static final int TUANGOU_TYPE_MEIRONG = 2;
public static final int TUANGOU_TYPE_YULE = 3;
public static final int TUANGOU_TYPE_SHEYING = 4;
public static final int TUANGOU_TYPE_JIUDIAN = 5;
public static final int TUANGOU_TYPE_QITA = 7;
// ÎҵĶ©µ¥
public static final String DINGDAN_URL = "http://sp.woaisp.com/hlf_spapp/check!androidmyorder?userid=1";
public static final String DINGDAN_ID = "id";
public static final String DINGDAN_SP = "spname";
public static final String DINGDAN_IMG = "spimg";
public static final String DINGDAN_BIANTI = "tgbiaoti";
public static final String DINGDAN_MOVERUSER = "moveuser";
public static final String DINGDAN_TIME = "valuetime";
public static final String DINGDAN_NUMBER2 = "number2";
public static final String DINGDAN_ORDERMETHOD = "ordermethod";
public static final String DINGDAN_ORDNUM = "ordernum";
public static final String DINGDAN_ORDTIME = "ordertime";
public static final String DINGDAN_REMARK = "remark";
public static final String DINGDAN_SPNAMBER = "spnumber";
public static final String DINGDAN_SPPRICE = "spprice";
public static final String DINGDAN_NUMBER3 = "number3";
public static final String DINGDAN_TGPRICE = "tgprice";
public static final String DINGDAN_SPTEXT = "sptext";
public static final String DINGDAN_SPDIANPU = "spdianpu";
public static final String DINGDAN_ZONGJIA = "zongjia";
public static final String DINGDAN_ORDERPHONE = "orderphone";
public static final String DINGDAN_FBIAOTI = "fubiaoti";
// ÎҵĶһ»
public static final String MYDUIHUAN_URL = "http://sp.woaisp.com/hlf_spapp/check!androiduserchange?";
// ÎÒµÄÍŹº¾í
public static final String MYTUANGOUJUAN_URL = "http://sp.woaisp.com/hlf_spapp/check!androidmytg?";
public static final String MYTUANGOUJUAN_ID = "id";
public static final String MYTUANGOUJUAN_STATUS = "status";
public static final String MYTUANGOUJUAN_NAME = "spname";
public static final String MYTUANGOUJUAN_BIAOTI = "tgbiaoti";
public static final String MYTUANGOUJUAN_PWD = "tgpwd";
public static final String MYTUANGOUJUAN_IMG = "spimg";
public static final String MYTUANGOUJUAN_TG = "tg";
public static final String MYTUANGOUJUAN_TIME = "valuetime";
public static final String MYTUANGOUJUAN_MOVEUSER = "moveuser";
public static final String MYTUANGOUJUAN_NUMBER = "number1";
public static final String MYTUANGOUJUAN_SPPRICE = "spprice";
public static final String MYTUANGOUJUAN_TGPRICE = "tgprice";
public static final String MYTUANGOUJUAN_TEXT = "sptext";
public static final String MYTUANGOUJUAN_DIANPU = "spdianpu";
public static final String MYTUANGOUJUAN_FBIAOTI = "fubiaoti";
public static int TUANGOU_FENLEI_TYPE = 0;
// ¾Î³¶È
public static double JINGDU = 0;
public static double WEIDU = 0;
public static int city_id = 0;
// ·¶Î§
public static final String FANWEI_BASEURL = "http://sp.woaisp.com/hlf_spapp/check!androidsearceh?";
public static int fanwei = 0;
// ´ðÌâ
public static final String DATI_URL = "http://sp.woaisp.com/hlf_spapp/check!androidquestion";
public static final String DATI_TIJIAO_URL = "http://sp.woaisp.com/hlf_spapp/check!androidanwer?";
public static final String DATI_ID = "id";
public static final String DATI_QUESTION = "question";
public static final String DATI_ANSWER1 = "anwer1";
public static final String DATI_ANSWER2 = "anwer2";
public static final String DATI_ANSWER3 = "anwer3";
public static final String DATI_ANSWER4 = "anwer4";
// Ìí¼Ó»ý·Ö
public static final String TIANJIAJIFEN = "http://sp.woaisp.com/hlf_spapp/check!androidsuopingadd?";
public static final int ITEM_TYPE_HEADVIEW = 1101;
public static final int ITEM_YYPE_PUTONGVIEW = 1102;
public static final int ITEM_YYPE_FOOTVIEW = 1103;
// ³ÇÊÐ
public static final String CITY_URL = "http://sp.woaisp.com/hlf_spapp/check!androidgetdistrict?";
public static final String CITY_BASE = "http://sp.woaisp.com/hlf_spapp/check!androidchangedistrict?";
public static final String CITY_QUYUNAME = "districtName";
public static final String CITY_ID = "cityId";
public static final String CITY_CREATED = "dateCreated";
public static final String CITY_UPDATA = "dateUpdated";
public static final String CITY_DIQUID = "districtId";
public static int URL_TYPE = 0;
public static String BEFORE_TUANGOU_URL = "";
public static String BEFORE_URL = "";
public static int COUNT = 1;
public static int visibleitemCount;
}
| apache-2.0 |
lecousin/java-framework-core | net.lecousin.core/src/main/java/net/lecousin/framework/event/SimpleListenableContainer.java | 772 | package net.lecousin.framework.event;
/** Class that implements SimpleListenable and delegate to an event of type T which is lazily instantiated on its first listener.
* @param <T> type of event
*/
public abstract class SimpleListenableContainer<T extends SimpleListenable> implements SimpleListenable {
protected T event;
protected abstract T createEvent();
@Override
public void addListener(Runnable listener) {
synchronized (this) {
if (event == null) event = createEvent();
event.addListener(listener);
}
}
@Override
public void removeListener(Runnable listener) {
synchronized (this) {
if (event == null) return;
event.removeListener(listener);
}
}
@Override
public boolean hasListeners() {
return event.hasListeners();
}
}
| apache-2.0 |
cmurat/CS434-Project | SuperMarioBros/src/smbModel/MusicPlayer.java | 2264 | package smbModel;
import java.io.File;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class MusicPlayer {
private String[] soundPaths = new String[] { "Assets/Sounds/smbTheme.MID",
"Assets/Sounds/smbJump.wav", "Assets/Sounds/smbBreakblock.wav", "Assets/Sounds/smbMarioDie.wav" };
private Sequencer musicSequencer;
private Clip jumpClip;
private Clip breakblockClip;
private Clip marioDeathClip;
private static MusicPlayer instance;
private MusicPlayer() {
instance = this;
playMusic();
initBreakblockClip();
initJumpClip();
initMarioDeathClip();
}
private void initBreakblockClip() {
try {
breakblockClip = AudioSystem.getClip();
breakblockClip.open(AudioSystem.getAudioInputStream(new File(
soundPaths[2])));
} catch (Exception e) {
}
}
private void initMarioDeathClip() {
try {
marioDeathClip = AudioSystem.getClip();
marioDeathClip.open(AudioSystem.getAudioInputStream(new File(
soundPaths[3])));
} catch (Exception e) {
}
}
public static MusicPlayer getInstance() {
if (instance == null)
instance = new MusicPlayer();
return instance;
}
private void initJumpClip() {
try {
jumpClip = AudioSystem.getClip();
jumpClip.open(AudioSystem.getAudioInputStream(new File(
soundPaths[1])));
} catch (Exception e) {
}
}
private void playMusic() {
play(soundPaths[0], Integer.MAX_VALUE);
}
private void play(String musicPath, int loopCount) {
musicSequencer = null;
try {
Sequence sequence = MidiSystem.getSequence(new File(musicPath));
musicSequencer = MidiSystem.getSequencer();
musicSequencer.open();
musicSequencer.setSequence(sequence);
musicSequencer.setLoopCount(loopCount);
musicSequencer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void playBreakblockSound() {
breakblockClip.setMicrosecondPosition(0);
breakblockClip.start();
}
public void playJumpSound() {
jumpClip.setMicrosecondPosition(0);
jumpClip.start();
}
public void playMarioDeathSound() {
musicSequencer.stop();
marioDeathClip.setMicrosecondPosition(0);
marioDeathClip.start();
}
}
| apache-2.0 |
opensingular/singular-core | lib/wicket-utils/src/main/java/org/opensingular/lib/wicket/util/bootstrap/layout/TemplatePanel.java | 5362 | /*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* 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.opensingular.lib.wicket.util.bootstrap.layout;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.IMarkupFragment;
import org.apache.wicket.markup.Markup;
import org.apache.wicket.markup.MarkupParser;
import org.apache.wicket.markup.MarkupResourceStream;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.panel.IMarkupSourcingStrategy;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.html.panel.PanelMarkupSourcingStrategy;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.resource.StringResourceStream;
import org.opensingular.lib.commons.base.SingularUtil;
import org.opensingular.lib.commons.lambda.IFunction;
import org.opensingular.lib.commons.lambda.ISupplier;
@SuppressWarnings("serial")
public class TemplatePanel extends Panel {
private IFunction<TemplatePanel, String> templateFunction;
public TemplatePanel(String id, String template) {
this(id, p -> template);
}
public TemplatePanel(String id, IModel<?> model, String template) {
this(id, model, p -> template);
}
public TemplatePanel(String id, ISupplier<String> templateSupplier) {
this(id, p -> templateSupplier.get());
}
public TemplatePanel(String id, IModel<?> model, ISupplier<String> templateSupplier) {
this(id, model, p -> templateSupplier.get());
}
public TemplatePanel(String id) {
this(id, "");
}
public TemplatePanel(String id, IModel<?> model) {
this(id, model, "");
}
public TemplatePanel(String id, IFunction<TemplatePanel, String> templateFunction) {
super(id);
this.templateFunction = templateFunction;
}
public TemplatePanel(String id, IModel<?> model, IFunction<TemplatePanel, String> templateFunction) {
super(id, model);
this.templateFunction = templateFunction;
}
protected void onBeforeComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {}
protected void onAfterComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {}
public IFunction<TemplatePanel, String> getTemplateFunction() {
return templateFunction;
}
@Override
protected IMarkupSourcingStrategy newMarkupSourcingStrategy() {
return new PanelMarkupSourcingStrategy(false) {
@Override
public IMarkupFragment getMarkup(MarkupContainer parent, Component child) {
// corrige o problema de encoding
StringResourceStream stringResourceStream = new StringResourceStream("<wicket:panel>" + getTemplateFunction().apply(TemplatePanel.this) + "</wicket:panel>", "text/html");
stringResourceStream.setCharset(Charset.forName(Optional.ofNullable(Application.get().getMarkupSettings().getDefaultMarkupEncoding()).orElse(StandardCharsets.UTF_8.name())));
MarkupParser markupParser = new MarkupParser(new MarkupResourceStream(stringResourceStream));
markupParser.setWicketNamespace(MarkupParser.WICKET);
Markup markup;
try {
markup = markupParser.parse();
} catch (Exception e) {
throw SingularUtil.propagate(e);
}
// If child == null, than return the markup fragment starting
// with <wicket:panel>
if (child == null) {
return markup;
}
// Copiado da superclasse. buscando markup do child
IMarkupFragment associatedMarkup = markup.find(child.getId());
if (associatedMarkup != null) {
return associatedMarkup;
}
associatedMarkup = searchMarkupInTransparentResolvers(parent, parent.getMarkup(), child);
if (associatedMarkup != null) {
return associatedMarkup;
}
return findMarkupInAssociatedFileHeader(parent, child);
}
@Override
public void onComponentTagBody(Component component, MarkupStream markupStream, ComponentTag openTag) {
TemplatePanel.this.onBeforeComponentTagBody(markupStream, openTag);
super.onComponentTagBody(component, markupStream, openTag);
TemplatePanel.this.onAfterComponentTagBody(markupStream, openTag);
}
};
}
}
| apache-2.0 |
nhl/bootique-linkrest | bootique-agrest-cayenne42-swagger/src/main/java/io/bootique/agrest/cayenne42/swagger/AgrestSwaggerModule.java | 1177 | /*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC 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 io.bootique.agrest.cayenne42.swagger;
import io.bootique.BaseModule;
import io.bootique.agrest.cayenne42.AgrestModuleExtender;
import io.bootique.di.Binder;
/**
* @since 2.0
*/
public class AgrestSwaggerModule extends BaseModule {
public static AgrestSwaggerModuleExtender extend(Binder binder) {
return new AgrestSwaggerModuleExtender(binder);
}
}
| apache-2.0 |
hydrator/wrangler | wrangler-core/src/main/java/io/cdap/directives/transformation/Upper.java | 2549 | /*
* Copyright © 2017-2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.directives.transformation;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.wrangler.api.Arguments;
import io.cdap.wrangler.api.Directive;
import io.cdap.wrangler.api.DirectiveExecutionException;
import io.cdap.wrangler.api.DirectiveParseException;
import io.cdap.wrangler.api.ExecutorContext;
import io.cdap.wrangler.api.Row;
import io.cdap.wrangler.api.annotations.Categories;
import io.cdap.wrangler.api.parser.ColumnName;
import io.cdap.wrangler.api.parser.TokenType;
import io.cdap.wrangler.api.parser.UsageDefinition;
import java.util.List;
/**
* A Wrangler step for upper casing the 'column' value of type String.
*/
@Plugin(type = Directive.TYPE)
@Name(Upper.NAME)
@Categories(categories = { "transform"})
@Description("Changes the column values to uppercase.")
public class Upper implements Directive {
public static final String NAME = "uppercase";
// Columns of the column to be upper-cased
private String column;
@Override
public UsageDefinition define() {
UsageDefinition.Builder builder = UsageDefinition.builder(NAME);
builder.define("column", TokenType.COLUMN_NAME);
return builder.build();
}
@Override
public void initialize(Arguments args) throws DirectiveParseException {
this.column = ((ColumnName) args.value("column")).value();
}
@Override
public void destroy() {
// no-op
}
@Override
public List<Row> execute(List<Row> rows, ExecutorContext context) throws DirectiveExecutionException {
for (Row row : rows) {
int idx = row.find(column);
if (idx != -1) {
Object object = row.getValue(idx);
if (object instanceof String) {
if (object != null) {
String value = (String) object;
row.setValue(idx, value.toUpperCase());
}
}
}
}
return rows;
}
}
| apache-2.0 |
mike10004/appengine-imaging | gaecompat-awt-imaging/src/awt-windowing/com/google/code/appengine/awt/peer/ListPeer.java | 945 | /*
* 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.
*/
/**
* @author Pavel Dolgov
*/
package com.google.code.appengine.awt.peer;
public interface ListPeer {
}
| apache-2.0 |
evanx/chronic | src/chronic/type/EventType.java | 467 | /*
* Source https://github.com/evanx by @evanxsummers
*
*/
package chronic.type;
import vellum.bundle.Bundle;
import vellum.type.Labelled;
/**
*
* @author evan.summers
*/
public enum EventType implements Labelled {
ERROR,
INITIAL;
@Override
public String getLabel() {
return Bundle.get(getClass()).getString(name());
}
public boolean isAlertable() {
return false;
}
}
| apache-2.0 |
lyandyjoe/slogan-taoxian | Wallapop/src/com/example/wallapop/utils/imageloader/core/display/FakeBitmapDisplayer.java | 1972 | /*******************************************************************************
* Copyright 2011-2013 Sergey Tarasevich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.example.wallapop.utils.imageloader.core.display;
import android.graphics.Bitmap;
import com.example.wallapop.utils.imageloader.core.DisplayImageOptions;
import com.example.wallapop.utils.imageloader.core.ImageLoader;
import com.example.wallapop.utils.imageloader.core.assist.LoadedFrom;
import com.example.wallapop.utils.imageloader.core.imageaware.ImageAware;
/**
* Fake displayer which doesn't display Bitmap in ImageView. Should be used in
* {@linkplain DisplayImageOptions display options} for
* {@link ImageLoader#loadImage(String, com.iss.imageloader.core.assist.ImageSize, com.iss.imageloader.core.DisplayImageOptions, com.iss.imageloader.core.assist.ImageLoadingListener)}
* ImageLoader.loadImage()}
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
* @since 1.6.0
*/
public final class FakeBitmapDisplayer implements BitmapDisplayer {
// @Override
// public Bitmap display(Bitmap bitmap, ImageView imageView,
// LoadedFrom loadedFrom) {
// // Do nothing
// return bitmap;
// }
@Override
public void display(Bitmap bitmap, ImageAware imageAware,
LoadedFrom loadedFrom) {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
gravel-st/gravel | src/main/java/st/gravel/support/compiler/jvm/BlockSendArgument.java | 2255 | package st.gravel.support.compiler.jvm;
/*
This file is automatically generated from typed smalltalk source. Do not edit by hand.
(C) AG5.com
*/
import java.math.BigInteger;
import st.gravel.support.jvm.NonLocalReturn;
import st.gravel.support.compiler.ast.BlockNode;
import st.gravel.support.compiler.jvm.JVMVariable;
public class BlockSendArgument extends Object implements Cloneable {
public static BlockSendArgument_Factory factory = new BlockSendArgument_Factory();
BlockNode _blockNode;
JVMVariable[] _copiedVariables;
String _name;
public static class BlockSendArgument_Factory extends st.gravel.support.jvm.SmalltalkFactory {
public BlockSendArgument basicNew() {
BlockSendArgument newInstance = new BlockSendArgument();
newInstance.initialize();
return newInstance;
}
public BlockSendArgument blockNode_copiedVariables_(final BlockNode _aBlockNode, final JVMVariable[] _anArray) {
return this.basicNew().initializeBlockNode_copiedVariables_(_aBlockNode, _anArray);
}
}
static public BlockSendArgument _blockNode_copiedVariables_(Object receiver, final BlockNode _aBlockNode, final JVMVariable[] _anArray) {
return factory.blockNode_copiedVariables_(_aBlockNode, _anArray);
}
public BlockNode blockNode() {
return _blockNode;
}
public JVMVariable[] copiedVariables() {
return _copiedVariables;
}
public BlockSendArgument copy() {
try {
BlockSendArgument _temp1 = (BlockSendArgument) this.clone();
_temp1.postCopy();
return _temp1;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public BlockSendArgument_Factory factory() {
return factory;
}
public BlockSendArgument initialize() {
return this;
}
public BlockSendArgument initializeBlockNode_copiedVariables_(final BlockNode _aBlockNode, final JVMVariable[] _anArray) {
_blockNode = _aBlockNode;
_copiedVariables = _anArray;
this.initialize();
return this;
}
public String name() {
return _name;
}
public BlockSendArgument postCopy() {
return this;
}
public BlockSendArgument pvtSetName_(final String _aString) {
_name = _aString;
return this;
}
public BlockSendArgument withName_(final String _aString) {
return this.copy().pvtSetName_(_aString);
}
}
| apache-2.0 |
MegatronKing/SVG-Android | docs/image/java/ic_center_focus_weak.java | 3592 | package com.github.megatronking.svg.iconlibs;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import com.github.megatronking.svg.support.SVGRenderer;
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SVG-Generator. It should not be modified by hand.
*/
public class ic_center_focus_weak extends SVGRenderer {
public ic_center_focus_weak(Context context) {
super(context);
mAlpha = 1.0f;
mWidth = dip2px(24.0f);
mHeight = dip2px(24.0f);
}
@Override
public void render(Canvas canvas, int w, int h, ColorFilter filter) {
final float scaleX = w / 24.0f;
final float scaleY = h / 24.0f;
mPath.reset();
mRenderPath.reset();
mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
mFinalPathMatrix.postScale(scaleX, scaleY);
mPath.moveTo(5.0f, 15.0f);
mPath.lineTo(3.0f, 15.0f);
mPath.rLineTo(0f, 4.0f);
mPath.rCubicTo(0.0f, 1.1f, 0.9f, 2.0f, 2.0f, 2.0f);
mPath.rLineTo(4.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.lineTo(5.0f, 19.0f);
mPath.rLineTo(0f, -4.0f);
mPath.close();
mPath.moveTo(5.0f, 15.0f);
mPath.moveTo(5.0f, 5.0f);
mPath.rLineTo(4.0f, 0f);
mPath.lineTo(9.0f, 3.0f);
mPath.lineTo(5.0f, 3.0f);
mPath.rCubicTo(-1.1f, 0.0f, -2.0f, 0.9f, -2.0f, 2.0f);
mPath.rLineTo(0f, 4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.lineTo(5.0f, 5.0f);
mPath.close();
mPath.moveTo(5.0f, 5.0f);
mPath.rMoveTo(14.0f, -2.0f);
mPath.rLineTo(-4.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.rLineTo(4.0f, 0f);
mPath.rLineTo(0f, 4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.lineTo(21.0f, 5.0f);
mPath.rCubicTo(0.0f, -1.1f, -0.9f, -2.0f, -2.0f, -2.0f);
mPath.close();
mPath.moveTo(19.0f, 3.0f);
mPath.rMoveTo(0.0f, 16.0f);
mPath.rLineTo(-4.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.rLineTo(4.0f, 0f);
mPath.rCubicTo(1.1f, 0.0f, 2.0f, -0.9f, 2.0f, -2.0f);
mPath.rLineTo(0f, -4.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 4.0f);
mPath.close();
mPath.moveTo(19.0f, 19.0f);
mPath.moveTo(12.0f, 8.0f);
mPath.rCubicTo(-2.21f, 0.0f, -4.0f, 1.79f, -4.0f, 4.0f);
mPath.rCubicTo(0.0f, 2.21f, 1.79f, 4.0f, 4.0f, 4.0f);
mPath.rCubicTo(2.21f, 0.0f, 4.0f, -1.79f, 4.0f, -4.0f);
mPath.rCubicTo(0.0f, -2.21f, -1.79f, -4.0f, -4.0f, -4.0f);
mPath.close();
mPath.moveTo(12.0f, 8.0f);
mPath.rMoveTo(0.0f, 6.0f);
mPath.rCubicTo(-1.1f, 0.0f, -2.0f, -0.9f, -2.0f, -2.0f);
mPath.rCubicTo(0.0f, -1.1000004f, 0.9f, -2.0f, 2.0f, -2.0f);
mPath.rCubicTo(1.1000004f, 0.0f, 2.0f, 0.9f, 2.0f, 2.0f);
mPath.rCubicTo(0.0f, 1.1000004f, -0.9f, 2.0f, -2.0f, 2.0f);
mPath.close();
mPath.moveTo(12.0f, 14.0f);
mRenderPath.addPath(mPath, mFinalPathMatrix);
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
mFillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, mFillPaint);
}
} | apache-2.0 |
MyRobotLab/myrobotlab | src/main/java/org/myrobotlab/swing/GpsGui.java | 3844 | /**
*
* @author grog (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify it under
* the terms of the Apache License 2.0 as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version (subject to the "Classpath" exception as provided in the LICENSE.txt
* file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the Apache License 2.0 for more
* details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for details.
*
* Enjoy !
*
*
*/
package org.myrobotlab.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.service.SwingGui;
import org.myrobotlab.service._TemplateService;
import org.slf4j.Logger;
public class GpsGui extends ServiceGui implements ActionListener {
static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(GpsGui.class);
private JLabel latitudeTextField = new JLabel();
private JLabel longitudeTextField = new JLabel();
private JLabel altitudeTextField = new JLabel();
private JLabel stringTypeTextField = new JLabel();
private JLabel speedTextField = new JLabel();
private JLabel headingTextField = new JLabel();
public GpsGui(final String boundServiceName, final SwingGui myService) {
super(boundServiceName, myService);
setTitle("gps");
add("gps string type:", stringTypeTextField);
add("latitude:", latitudeTextField);
add("longitude:", longitudeTextField);
add("altitude(meters):", altitudeTextField);
add("speed (knots,kph):", speedTextField);
add("heading (deg):", headingTextField);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void subscribeGui() {
subscribe("publishGGAData", "onData");
subscribe("publishGLLData", "onData");
subscribe("publishRMCData", "onData");
subscribe("publishVTGData", "onData");
}
@Override
public void unsubscribeGui() {
unsubscribe("publishGGAData", "onData");
unsubscribe("publishGLLData", "onData");
unsubscribe("publishRMCData", "onData");
unsubscribe("publishVTGData", "onData");
}
public void onData(String[] tokens) {
if (tokens[0].contains("GGA")) {
stringTypeTextField.setText(tokens[0]);
latitudeTextField.setText(tokens[2]);
longitudeTextField.setText(tokens[4]);
altitudeTextField.setText(tokens[9]);
} else if (tokens[0].contains("VTG")) {
stringTypeTextField.setText(tokens[0]);
headingTextField.setText(tokens[1]);
speedTextField.setText(tokens[5] + ", " + tokens[7]);
} else if (tokens[0].contains("RMC")) {
stringTypeTextField.setText(tokens[0]);
latitudeTextField.setText(tokens[3]);
longitudeTextField.setText(tokens[5]);
speedTextField.setText(tokens[7]);
headingTextField.setText(tokens[8]);
} else if (tokens[0].contains("GLL")) {
stringTypeTextField.setText(tokens[0]);
latitudeTextField.setText(tokens[1]);
longitudeTextField.setText(tokens[3]);
}
}
public void onState(_TemplateService template) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
}
});
}
}
| apache-2.0 |
McLeodMoores/starling | projects/core/src/test/java/com/opengamma/core/holiday/impl/SchemeAlteringHolidaySourceTest.java | 8227 | /**
* Copyright (C) 2018 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.opengamma.core.holiday.impl;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.mockito.Mockito;
import org.testng.annotations.Test;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import com.opengamma.core.holiday.Holiday;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.holiday.HolidayType;
import com.opengamma.core.holiday.WeekendType;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ExternalScheme;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.test.Assert;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
/**
* Tests for {@link SchemeAlteringHolidaySource}.
*/
@SuppressWarnings("deprecation")
@Test(groups = TestGroup.UNIT)
public class SchemeAlteringHolidaySourceTest {
private static final VersionCorrection VERSION = VersionCorrection.ofVersionAsOf(Instant.now());
private static final SimpleHolidayWithWeekend HOLIDAY =
new SimpleHolidayWithWeekend(Arrays.asList(LocalDate.of(2018, 9, 9), LocalDate.of(2018, 9, 10)), WeekendType.FRIDAY_SATURDAY);
private static final UniqueId UID_1 = UniqueId.of("hol", "1", VERSION.toString());
private static final ObjectId OID_1 = ObjectId.of("hol", "1");
private static final ExternalIdBundle EIDS_1 = ExternalIdBundle.of("TEST1", "1");
private static final Currency CCY_1 = Currency.AUD;
private static final SimpleHoliday NO_WEEKEND = new SimpleHoliday(Arrays.asList(LocalDate.of(2018, 9, 9), LocalDate.of(2018, 9, 11)));
private static final UniqueId UID_2 = UniqueId.of("hol", "2", VERSION.toString());
private static final ObjectId OID_2 = ObjectId.of("hol", "2");
private static final ExternalIdBundle EIDS_2 = ExternalIdBundle.of("test2", "2");
private static final Currency CCY_2 = Currency.BRL;
private static final HolidaySource DELEGATE = Mockito.mock(HolidaySource.class);
static {
HOLIDAY.setCurrency(CCY_1);
Mockito.when(DELEGATE.get(HolidayType.CURRENCY, EIDS_1)).thenReturn(Collections.<Holiday>singleton(HOLIDAY));
Mockito.when(DELEGATE.get(HolidayType.CURRENCY, EIDS_2)).thenReturn(Collections.<Holiday>singleton(NO_WEEKEND));
Mockito.when(DELEGATE.get(CCY_1)).thenReturn(Collections.<Holiday>singleton(HOLIDAY));
Mockito.when(DELEGATE.get(CCY_2)).thenReturn(Collections.<Holiday>singleton(NO_WEEKEND));
Mockito.when(DELEGATE.get(UID_1)).thenReturn(HOLIDAY);
Mockito.when(DELEGATE.get(UID_2)).thenReturn(NO_WEEKEND);
Mockito.when(DELEGATE.get(OID_1, VERSION)).thenReturn(HOLIDAY);
Mockito.when(DELEGATE.get(OID_2, VERSION)).thenReturn(NO_WEEKEND);
Mockito.when(DELEGATE.isHoliday(LocalDate.of(2018, 9, 7), Currency.AUD)).thenReturn(true);
Mockito.when(DELEGATE.isHoliday(LocalDate.of(2018, 9, 7), Currency.BRL)).thenReturn(false);
Mockito.when(DELEGATE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, ExternalId.of("test1", "1"))).thenReturn(true);
Mockito.when(DELEGATE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, ExternalId.of("test2", "2"))).thenReturn(false);
Mockito.when(DELEGATE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, ExternalIdBundle.of("test1", "1"))).thenReturn(true);
Mockito.when(DELEGATE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, ExternalIdBundle.of("test2", "2"))).thenReturn(false);
final Map<UniqueId, Holiday> mUid = new HashMap<>();
mUid.put(UID_1, HOLIDAY);
mUid.put(UID_2, NO_WEEKEND);
Mockito.when(DELEGATE.get(Arrays.asList(UID_1, UID_2))).thenReturn(mUid);
final Map<ObjectId, Holiday> mOid = new HashMap<>();
mOid.put(OID_1, HOLIDAY);
mOid.put(OID_2, NO_WEEKEND);
Mockito.when(DELEGATE.get(Arrays.asList(OID_1, OID_2), VERSION)).thenReturn(mOid);
}
private static final SchemeAlteringHolidaySource SOURCE = new SchemeAlteringHolidaySource(DELEGATE);
static {
SOURCE.addMapping("TEST1", "test1");
}
/**
* Tests that the underlying source cannot be null.
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullUnderlying() {
new SchemeAlteringHolidaySource(null);
}
/**
* Tests that the source scheme cannot be null.
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testAddNullSource() {
SOURCE.addMapping(null, "test3");
}
/**
* Tests that the target scheme cannot be null.
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testAddNulTarget() {
SOURCE.addMapping("test1", null);
}
/**
* Tests getting holidays by type.
*/
@Test
public void testGetByType() {
Collection<Holiday> result = SOURCE.get(HolidayType.CURRENCY, EIDS_1);
assertEquals(result.size(), 1);
assertEquals(result.iterator().next(), HOLIDAY);
result = SOURCE.get(HolidayType.CURRENCY, EIDS_2);
assertEquals(result.size(), 1);
assertEquals(result.iterator().next(), NO_WEEKEND);
}
/**
* Tests getting holidays by currency.
*/
@Test
public void testGetByCurrency() {
assertEquals(SOURCE.get(CCY_1), Collections.singleton(HOLIDAY));
assertEquals(SOURCE.get(CCY_2), Collections.singleton(NO_WEEKEND));
}
/**
* Tests getting holidays by unique id.
*/
@Test
public void testGetByUniqueId() {
assertEquals(SOURCE.get(UID_1), HOLIDAY);
assertEquals(SOURCE.get(UID_2), NO_WEEKEND);
}
/**
* Tests getting holidays by object id.
*/
@Test
public void testGetByObjectId() {
assertEquals(SOURCE.get(OID_1, VERSION), HOLIDAY);
assertEquals(SOURCE.get(OID_2, VERSION), NO_WEEKEND);
}
/**
* Tests getting holidays by a collection of unique ids.
*/
@Test
public void testGetByUniqueIds() {
final Map<UniqueId, Holiday> expected = new HashMap<>();
expected.put(UID_1, HOLIDAY);
expected.put(UID_2, NO_WEEKEND);
Assert.assertEqualsNoOrder(SOURCE.get(Arrays.asList(UID_1, UID_2)), expected);
}
/**
* Tests getting holidays by a collection of object ids.
*/
@Test
public void testGetByObjectIds() {
final Map<ObjectId, Holiday> expected = new HashMap<>();
expected.put(OID_1, HOLIDAY);
expected.put(OID_2, NO_WEEKEND);
Assert.assertEqualsNoOrder(SOURCE.get(Arrays.asList(OID_1, OID_2), VERSION), expected);
}
/**
* Tests scheme translation.
*/
@Test
public void testTranslateScheme() {
assertEquals(SOURCE.translateScheme("TEST1"), "test1");
assertEquals(SOURCE.translateScheme("test2"), "test2");
}
/**
* Tests external id translation.
*/
@Test
public void testExternalIdTranslation() {
assertEquals(SOURCE.translateExternalId(ExternalId.of("TEST1", "1")), ExternalId.of("test1", "1"));
assertEquals(SOURCE.translateExternalId(ExternalId.of("test2", "1")), ExternalId.of("test2", "1"));
}
/**
* Tests whether a date is a holiday.
*/
@Test
public void testIsHolidayByDateCurrency() {
assertTrue(SOURCE.isHoliday(LocalDate.of(2018, 9, 7), Currency.AUD));
assertFalse(SOURCE.isHoliday(LocalDate.of(2018, 9, 7), Currency.BRL));
}
/**
* Tests whether a date is a holiday.
*/
@Test
public void testIsHolidayByDateTypeId() {
final ExternalId id1 = EIDS_1.getExternalId(ExternalScheme.of("TEST1"));
assertTrue(SOURCE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, id1));
final ExternalId id2 = EIDS_2.getExternalId(ExternalScheme.of("test2"));
assertFalse(SOURCE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, id2));
}
/**
* Tests whether a date is a holiday.
*/
@Test
public void testIsHolidayByDateTypeIdBundle() {
assertTrue(SOURCE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, EIDS_1));
assertFalse(SOURCE.isHoliday(LocalDate.of(2018, 9, 7), HolidayType.CURRENCY, EIDS_2));
}
}
| apache-2.0 |
WhiteBearSolutions/WBSAirback | src/com/whitebearsolutions/imagine/wbsairback/disk/RaidManager.java | 38084 | package com.whitebearsolutions.imagine.wbsairback.disk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.whitebearsolutions.util.Command;
public class RaidManager {
private final static Logger logger = LoggerFactory.getLogger(RaidManager.class);
private static List<Map<String, String>> supportedModels = null;
static {
String manufacturer = "DELL";
supportedModels = new ArrayList<Map<String, String>>();
Map<String, String> h700 = new HashMap<String, String>();
h700.put("manufacturer", manufacturer);
h700.put("model", "H700");
supportedModels.add(h700);
Map<String, String> h710 = new HashMap<String, String>();
h710.put("manufacturer", manufacturer);
h710.put("model", "H710");
supportedModels.add(h710);
Map<String, String> h800 = new HashMap<String, String>();
h800.put("manufacturer", manufacturer);
h800.put("model", "H800");
supportedModels.add(h800);
Map<String, String> h810 = new HashMap<String, String>();
h810.put("manufacturer", manufacturer);
h810.put("model", "H810");
supportedModels.add(h810);
}
/**
* Lista de pares clave-valor Ok para cada uno de los slots que obtiene el comando pdList
*/
private static Map<String, List<String>> pdList_slotOk;
static {
pdList_slotOk = new HashMap<String, List<String>>();
pdList_slotOk.put("media_error_count", Arrays.asList(new String[]{"0"}));
pdList_slotOk.put("other_error_count", Arrays.asList(new String[]{"0"}));
pdList_slotOk.put("predictive_failure_count", Arrays.asList(new String[]{"0"}));
pdList_slotOk.put("firmware_state", Arrays.asList(new String[]{"Online, Spun Up","Hotspare, Spun Up"}));
pdList_slotOk.put("needs_ekm_attention", Arrays.asList(new String[]{"No"}));
pdList_slotOk.put("foreign_state", Arrays.asList(new String[]{"None"}));
pdList_slotOk.put("port_status", Arrays.asList(new String[]{"Active"}));;
pdList_slotOk.put("drive_has_flagged_a_smart_alert", Arrays.asList(new String[]{"No"}));
}
/**
* Lista de pares clave-valor Ok para cada adapter que obtiene adpAllInfo
*/
private static Map<String,Map<String, List<String>>> adpInfoOk;
static {
adpInfoOk = new HashMap<String, Map<String, List<String>>>();
Map<String, List<String>> devicePresentOk = new HashMap<String, List<String>>();
devicePresentOk.put("degraded", Arrays.asList(new String[]{"0"}));
devicePresentOk.put("offline", Arrays.asList(new String[]{"0"}));
devicePresentOk.put("failed_disks", Arrays.asList(new String[]{"0"}));
adpInfoOk.put("device_present", devicePresentOk);
Map<String, List<String>> errorCountersOk = new HashMap<String, List<String>>();
errorCountersOk.put("memory_correctable_errors", Arrays.asList(new String[]{"0"}));
errorCountersOk.put("memory_uncorrectable_errors", Arrays.asList(new String[]{"0"}));
adpInfoOk.put("error_counters", errorCountersOk);
Map<String, List<String>> statusOk = new HashMap<String, List<String>>();
statusOk.put("ecc_bucket_count", Arrays.asList(new String[]{"0"}));
adpInfoOk.put("status", statusOk);
}
/**
* Lista de pares clave-valor Ok para cada adapter que obtiene adpAllInfo
*/
private static Map<String, List<String>> cfgDsplVdriveOk;
private static Map<String, List<String>> cfgDsplPhysicalOk;
static {
cfgDsplVdriveOk = new HashMap<String, List<String>>();
cfgDsplVdriveOk.put("state", Arrays.asList(new String[]{"Optimal"}));
cfgDsplVdriveOk.put("bad_blocks_exist", Arrays.asList(new String[]{"No"}));
cfgDsplPhysicalOk = new HashMap<String, List<String>>();
cfgDsplPhysicalOk.put("media_error_count", Arrays.asList(new String[]{"0"}));
cfgDsplPhysicalOk.put("other_error_count", Arrays.asList(new String[]{"0"}));
cfgDsplPhysicalOk.put("predictive_failure_count", Arrays.asList(new String[]{"0"}));
cfgDsplPhysicalOk.put("firmware_state", Arrays.asList(new String[]{"Online, Spun Up","Hotspare, Spun Up"}));
cfgDsplPhysicalOk.put("locked", Arrays.asList(new String[]{"Unlocked"}));
cfgDsplPhysicalOk.put("needs_ekm_attention", Arrays.asList(new String[]{"No"}));
cfgDsplPhysicalOk.put("foreign_state", Arrays.asList(new String[]{"None"}));
cfgDsplPhysicalOk.put("port_status", Arrays.asList(new String[]{"Active"}));
cfgDsplPhysicalOk.put("drive_has_flagged_a_smart_alert", Arrays.asList(new String[]{"No"}));
}
/**
* Lista de pares clave-valor Ok para cada adapter que obtiene adpAllInfo
* Battery State : Operational
* Remaining Time Alarm : No
* Remaining Capacity Alarm: No
* Relative State of Charge: 84 %
*/
private static Map<String, List<String>> adpBbuCmdOk;
static {
adpBbuCmdOk = new HashMap<String, List<String>>();
adpBbuCmdOk.put("battery_state", Arrays.asList(new String[]{"Operational"}));
//adpBbuCmdOk.put("remaining_time_alarm", Arrays.asList(new String[]{"No"}));
//adpBbuCmdOk.put("remaining_capacity_alarm", Arrays.asList(new String[]{"No"}));
adpBbuCmdOk.put("relative_state_of_charge", Arrays.asList(new String[]{"10"}));
}
/**
* Comprueba si está presente el modulo de raid (los controladores PERC)
* @return
* @throws Exception
*/
public static boolean hasRaidController() throws Exception {
try {
String _output = Command.systemCommand("lsscsi");
//String _output = Command.systemCommand("cat /lsscsi");
StringTokenizer _st = new StringTokenizer(_output, "\n");
while (_st.hasMoreTokens()) {
String line = _st.nextToken();
for (Map<String, String> model : supportedModels) {
if (line.contains(model.get("manufacturer")) && line.contains(model.get("model"))) {
logger.info("Raid controller is present => lsscsi: {} {}", model.get("manufacturer"), model.get("model"));
return true;
}
}
}
return false;
} catch (Exception ex) {
logger.error("Error comprobando si el equipo tiene el controlador raid. Ex: {}", ex.getMessage());
return false;
}
}
/**
* Comprueba los valores que devuelve el comando adpallinfo, si todo está correcto, devuelve null, si hay algún error
* devuelve el mapa con clave-valor de lo que en ese momento ha devuelto el comando. Además, en el parámetro por valor
* se queda toda la información obtenida
*
* @param adaptersInfo
* @return
* @throws Exception
*/
public static List<Map<String, String>> checkadpBbuCmd(List<Map<String, String>> adaptersInfo) throws Exception {
List<Map<String, String>> errors = null;
if (adaptersInfo != null)
adaptersInfo.addAll(adpBbuCmd());
else
adaptersInfo = adpBbuCmd();
if (adaptersInfo != null) {
for (Map<String, String> adapter : adaptersInfo) {
String adapterId = adapter.get("id");
for (String checkingSection : adpBbuCmdOk.keySet()) {
List<String> valuesCheck = adpBbuCmdOk.get(checkingSection);
String valueAdapter = adapter.get(checkingSection);
if (valueAdapter != null) {
if (!checkingSection.equals("relative_state_of_charge")) {
if (!valuesCheck.contains(valueAdapter)) {
logger.info("Found wrong state on disk [{}]: {} = {} ",new Object[]{adapterId, checkingSection,valueAdapter});
if (errors == null)
errors = new ArrayList<Map<String, String>>();
Map<String, String> error = new HashMap<String, String>();
error.put("key", checkingSection);
error.put("val-ok", listToString(valuesCheck));
error.put("val-obtained", valueAdapter);
error.put("adapterId", adapterId);
errors.add(error);
}
} else {
if (Double.parseDouble(valueAdapter) <= Double.parseDouble(valuesCheck.get(0))) {
logger.info("Found wrong state on disk [{}]: {} = {} ",new Object[]{adapterId, checkingSection,valueAdapter});
if (errors == null)
errors = new ArrayList<Map<String, String>>();
Map<String, String> error = new HashMap<String, String>();
error.put("key", checkingSection);
error.put("val-ok", listToString(valuesCheck));
error.put("val-obtained", valueAdapter);
error.put("adapterId", adapterId);
errors.add(error);
}
}
} else {
logger.error("Checking adpBbuCmd - Section "+checkingSection+" requested for checking not found in adapter:"+adapterId);
throw new Exception("Checking adpBbuCmd - Section "+checkingSection+" requested for checking not found in adapter:"+adapterId);
}
}
}
}
return errors;
}
/**
* Comprueba los valores que devuelve el comando adpallinfo, si todo está correcto, devuelve null, si hay algún error
* devuelve el mapa con clave-valor de lo que en ese momento ha devuelto el comando. Además, en el parámetro por valor
* se queda toda la información obtenida
*
* @param adaptersInfo
* @return
* @throws Exception
*/
public static List<Map<String, String>> checkAdpAllInfo(List<Map<String, Map<String, String>>> adaptersInfo) throws Exception {
List<Map<String, String>> errors = null;
if (adaptersInfo != null)
adaptersInfo.addAll(adpAllInfo());
else
adaptersInfo = adpAllInfo();
if (adaptersInfo != null) {
for (Map<String, Map<String, String>> adapter : adaptersInfo) {
String adapterId = adapter.get("id").get("id");
for (String checkingSection : adpInfoOk.keySet()) {
Map<String, List<String>> valuesCheck = adpInfoOk.get(checkingSection);
Map<String, String> valuesAdapter = adapter.get(checkingSection);
if (valuesAdapter != null) {
for (String keyVal : valuesCheck.keySet()) {
if (valuesAdapter.get(keyVal) != null) {
if (!valuesCheck.get(keyVal).contains(valuesAdapter.get(keyVal))) {
logger.info("Found wrong state on disk [{}]: {} = {} ",new Object[]{adapterId, keyVal,valuesAdapter.get(keyVal)});
if (errors == null)
errors = new ArrayList<Map<String, String>>();
Map<String, String> error = new HashMap<String, String>();
error.put("key", keyVal);
error.put("val-ok", listToString(valuesCheck.get(keyVal)));
error.put("val-obtained", valuesAdapter.get(keyVal));
error.put("adapterId", adapterId);
errors.add(error);
}
} else {
logger.error("Checking adpAllInfo - Param "+keyVal+" requested for checking not found in adapter:"+adapterId);
throw new Exception("Checking adpAllInfo - Param "+keyVal+" requested for checking not found in adapter:"+adapterId);
}
}
} else {
logger.error("Checking adpAllInfo - Section "+checkingSection+" requested for checking not found in adapter:"+adapterId);
throw new Exception("Checking adpAllInfo - Section "+checkingSection+" requested for checking not found in adapter:"+adapterId);
}
}
}
}
return errors;
}
/**
* Comprueba los valores del comando pdlist, devuelve un listado de mapas de errores en caso de encontrar o null si todo esta ok. Rellena el objeto que recibe
* para transmitir toda la información
* @param adaptersInfo
* @return
* @throws Exception
*/
public static List<Map<String, String>> checkPdListAll(List<Map<String, Map<String, String>>> slotsInfo) throws Exception {
List<Map<String, String>> errors = null;
if (slotsInfo != null)
slotsInfo.addAll(pdListAll());
else
slotsInfo = pdListAll();
if (slotsInfo != null) {
for (Map<String, Map<String, String>> adapter : slotsInfo) {
String adapterId = adapter.get("id").get("id");
for (String keyVal : pdList_slotOk.keySet()) {
for (String slotId : adapter.keySet()) {
if (!slotId.equals("id")) {
Map<String, String> slot = adapter.get(slotId);
if (slot.get(keyVal) != null) {
if (!pdList_slotOk.get(keyVal).contains(slot.get(keyVal))) {
if (errors == null)
errors = new ArrayList<Map<String, String>>();
Map<String, String> error = new HashMap<String, String>();
logger.info("Found wrong state on disk [{}]: {} = {} ",new Object[]{adapterId, keyVal,slot.get(keyVal)});
error.put("key", keyVal);
error.put("val-ok", listToString(pdList_slotOk.get(keyVal)));
error.put("val-obtained", slot.get(keyVal));
error.put("adapterId", adapterId);
error.put("slot_number", slotId);
error.put("enclosure_device_id", slot.get("enclosure_device_id"));
error.put("enclosure_position", slot.get("enclosure_position"));
errors.add(error);
}
} else {
logger.error("Checking pdList - Param "+keyVal+" requested for checking not found in adapter:"+adapterId);
throw new Exception("Checking pdList - Param "+keyVal+" requested for checking not found in adapter:"+adapterId);
}
}
}
}
}
}
return errors;
}
/**
* Comprueba los valores del comando cfgdisplay
* @param drivesInfo
* @return
* @throws Exception
*/
public static List<Map<String, String>> checkCfgDsplay(List<Map<String, Map<String, Object>>> drivesInfo) throws Exception {
List<Map<String, String>> errors = null;
if (drivesInfo != null)
drivesInfo.addAll(cfgDisplay());
else
drivesInfo = cfgDisplay();
if (drivesInfo != null) {
for (Map<String, Map<String, Object>> adapter : drivesInfo) {
String adapterId = (String) adapter.get("id").get("id");
for (String diskGroupId : adapter.keySet()) {
if (!diskGroupId.equals("id")) {
Map<String, Object> diskGroup = adapter.get(diskGroupId);
@SuppressWarnings("unchecked")
List<Map<String, String>> vDrives = (List<Map<String, String>>) diskGroup.get("virtual_drives");
if (vDrives != null) {
for (Map<String, String> vDrive : vDrives) {
for (String key : cfgDsplVdriveOk.keySet()) {
if (vDrive.get(key) != null) {
if (!cfgDsplVdriveOk.get(key).contains(vDrive.get(key))) {
if (errors == null)
errors = new ArrayList<Map<String, String>>();
Map<String, String> error = new HashMap<String, String>();
logger.info("Found wrong state on vdrive [{}]: {} = {} ",new Object[]{adapterId, key,vDrive.get(key)});
error.put("key", key);
error.put("val-ok", listToString(cfgDsplVdriveOk.get(key)));
error.put("val-obtained", vDrive.get(key));
error.put("adapterId", adapterId);
error.put("virtual_drive", vDrive.get("virtual_drive"));
error.put("disk_group", diskGroupId);
error.put("raid_level", vDrive.get("raid_level"));
errors.add(error);
}
} else {
logger.error("Checking cfgDisplay - Param "+key+" requested for checking not found in adapter:"+adapterId+" vDrive: "+vDrive.get("virtual_drive"));
throw new Exception("Checking cfgDisplay - Param "+key+" requested for checking not found in adapter:"+adapterId+" vDrive: "+vDrive.get("virtual_drive"));
}
}
}
}
@SuppressWarnings("unchecked")
List<Map<String, String>> phDrives = (List<Map<String, String>>) diskGroup.get("physical_drives");
if (phDrives != null) {
for (Map<String, String> phDrive : phDrives) {
for (String key : cfgDsplPhysicalOk.keySet()) {
if (phDrive.get(key) != null) {
if (!cfgDsplPhysicalOk.get(key).contains(phDrive.get(key))) {
if (errors == null)
errors = new ArrayList<Map<String, String>>();
Map<String, String> error = new HashMap<String, String>();
logger.info("Found wrong state on disk [{}]: {} = {} ",new Object[]{adapterId, key,phDrive.get(key)});
error.put("key", key);
error.put("val-ok", listToString(cfgDsplPhysicalOk.get(key)));
error.put("val-obtained", phDrive.get(key));
error.put("adapterId", adapterId);
error.put("physical_disk", phDrive.get("physical_disk"));
error.put("disk_group", diskGroupId);
error.put("enclosure_device_id", phDrive.get("enclosure_device_id"));
error.put("enclosure_position", phDrive.get("enclosure_position"));
error.put("slot_number", phDrive.get("slot_number"));
error.put("drives_position", phDrive.get("drives_position"));
error.put("sequence_number", phDrive.get("sequence_number"));
error.put("pd_type", phDrive.get("pd_type"));
error.put("sas_address(0)", phDrive.get("sas_address(0)"));
errors.add(error);
}
} else {
logger.error("Checking cfgDisplay - Param "+key+" requested for checking not found in adapter:"+adapterId+" vDrive: "+phDrive.get("virtual_drive"));
throw new Exception("Checking cfgDisplay - Param "+key+" requested for checking not found in adapter:"+adapterId+" vDrive: "+phDrive.get("virtual_drive"));
}
}
}
}
}
}
}
}
return errors;
}
/**
* Este comando muestra el estado de todo
* La función interpreta el comando y lo guarda de la siguiente manera:
* adapter_1
* name_sec1 => key_1 : value 1
* key_2 : value 2
* ...
* name_sec2 => key_1 : value 1
* ...
* ...
* adapter 2
* name_sec1 => key_1 : value 1
* ...
*
* @throws Exception
*/
public static List<Map<String, Map<String, String>>> adpAllInfo() throws Exception {
//String _s = "cat /AdpAllInfo_aAll";
String _s = "megacli -AdpAllInfo -aAll";
List<Map<String, Map<String, String>>> adapters = null;
try {
String _output = Command.systemCommand(_s);
if (_output != null && _output.length()>0) {
adapters = new ArrayList<Map<String, Map<String, String>>>();
StringTokenizer _st = new StringTokenizer(_output, "\n");
Map<String, Map<String, String>> adapter = null;
Map<String, String> section = null;
String _key = null, _value = null;
while (_st.hasMoreTokens()) {
String _line = _st.nextToken();
if (_line.trim().length()>1 && !_line.contains("Exit Code")) {
if (_line.contains("#") && _line.contains("Adapter")) { //New Adapter
if (adapter != null)
adapters.add(adapter);
adapter = new HashMap<String, Map<String, String>>();
section = new HashMap<String, String> ();
section.put("name_section", "id");
section.put("id", _line.trim().substring(_line.indexOf("#")+1));
adapter.put("id", section);
section = null;
do {
_line = _st.nextToken();
} while (!_line.contains("====="));
} else if ((!_line.contains(":") || _line.contains("Image Versions in Flash")) && !_line.contains("None") && !_line.contains("Mix in Enclosure Allowed")) { //Guardo la anterior seccion y creo la nueva
if (_st.hasMoreTokens()) {
String last = _line;
_line = _st.nextToken();
if (_line.contains("====")){
last = normalize(last);
if (section != null)
adapter.put(section.get("name_section"), section);
section = new HashMap<String, String>();
section.put("name_section", last);
}
}
} else if (_line.contains(":")) {
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
_value = trimLeftRight(_value);
_key = normalize(_key);
if (_key.equals("port") && _value.equals("Address")) { // Caso especial
do {
_line = _st.nextToken();
if (!_line.contains("HW")) {
StringTokenizer _stb = new StringTokenizer(_line, " ");
String portNumber = _stb.nextToken();
portNumber = trimLeftRight(portNumber);
String address = _stb.nextToken();
address = trimLeftRight(address);
_key = "port_"+portNumber;
section.put(_key, address);
} else {
if (_st.hasMoreTokens()) {
String last = _line;
_line = _st.nextToken();
if (_line.contains("====")){
last = normalize(last);
if (section != null)
adapter.put(section.get("name_section"), section);
section = new HashMap<String, String>();
section.put("name_section", last);
}
}
}
} while (!(_line.contains("HW") || _line.contains("===")));
}
else
section.put(_key, _value);
}
}
}
}
adapter.put(section.get("name_section"), section);
adapters.add(adapter);
}
return adapters;
} catch (Exception ex) {
logger.error("Error obtaining megacli -AdpAllInfo data: "+ex.getMessage());
throw new Exception("Error obtaining megacli -AdpAllInfo data: "+ex.getMessage());
}
}
/**
* El comando pdList muestra la información de los discos físicos
* La función interpreta el comando de la siguiente manera:
* adapter_1
* id => id : id
* num_slot1 => key_1 : value 1
* key_2 : value 2
* ...
* num_slot2 => key_1 : value 1
* ...
* ...
* adapter 2
* num_slot1 => key_1 : value 1
* ...
*
*/
public static List<Map<String, Map<String, String>>> pdListAll() throws Exception {
//String _s = "cat /PDList_aAll";
String _s = "megacli -PDList -aAll";
List<Map<String, Map<String, String>>> adapters = null;
try {
String _output = Command.systemCommand(_s);
if (_output != null && _output.length()>0) {
adapters = new ArrayList<Map<String, Map<String, String>>>();
StringTokenizer _st = new StringTokenizer(_output, "\n");
Map<String, Map<String, String>> adapter = null;
Map<String, String> slot = null;
String _key = null, _value = null;
while (_st.hasMoreTokens()) {
String _line = _st.nextToken();
if (_line.trim().length()>1 && !_line.contains("Exit Code")) {
if (_line.contains("Adapter") && _line.contains("#")) { // new adapter
if (adapter != null)
adapters.add(adapter);
adapter = new HashMap<String, Map<String, String>>();
slot = new HashMap<String, String> ();
slot.put("id", _line.trim().substring(_line.indexOf("#")+1));
adapter.put("id", slot);
slot = null;
} else if (_line.contains(":")) {
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_key = normalize(_key);
_value = trimLeftRight(_value);
if (_key.equals("enclosure_device_id")) {
if (slot != null)
adapter.put(slot.get("slot_number"), slot);
slot = new HashMap<String, String>();
}
slot.put(_key, _value);
}
}
}
}
}
if (slot != null)
adapter.put(slot.get("slot_number"), slot);
if (adapter != null)
adapters.add(adapter);
}
} catch (Exception ex) {
logger.error("Error obtaining megacli -PDList data: "+ex.getMessage());
throw new Exception("Error obtaining megacli -PDList data: "+ex.getMessage());
}
return adapters;
}
/**
* El comando ldInfoAll muestra la información de los virtual disk
* La función interpreta la salida de la forma mostrada. Hay un vdrive especial, el primero, que contiene el id del dispositivo
* adapter_1
* id => id : id
* vdrive_1 => key_1 : value 1
* key_2 : value 2
* ...
* vdrive_2 => key_1 : value 1
* ...
* ...
* adapter_2
* vdrive_1 => key_1 : value 1
* ...
*
*/
public static List<Map<String, Map<String, String>>> ldInfoAll() throws Exception {
//String _s = "cat /LDInfo_Lall_aAll";
String _s = "megacli -LDInfo -Lall -aAll";
List<Map<String, Map<String, String>>> adapters = null;
try {
String _output = Command.systemCommand(_s);
if (_output != null && _output.length()>0) {
adapters = new ArrayList<Map<String, Map<String, String>>>();
StringTokenizer _st = new StringTokenizer(_output, "\n");
Map<String, Map<String, String>> adapter = null;
Map<String, String> vdrive = null;
String _key = null, _value = null;
while (_st.hasMoreTokens()) {
String _line = _st.nextToken();
if (_line.trim().length()>1 && !_line.contains("Exit Code")) {
if (_line.contains("Adapter") && _line.contains("--")) { // new adapter
if (adapter != null)
adapters.add(adapter);
adapter = new HashMap<String, Map<String, String>>();
vdrive = new HashMap<String, String> ();
vdrive.put("id", _line.trim().substring(_line.indexOf("Adapter")+8,_line.indexOf("Adapter")+9));
adapter.put("id", vdrive);
vdrive = null;
} else if (_line.contains(":")) {
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_key = normalize(_key);
_value = trimLeftRight(_value);
if (_value.contains(":"))
_value = _value.trim().substring(0,1);
if (_key.equals("virtual_drive")) {
if (vdrive != null)
adapter.put(vdrive.get("virtual_drive"), vdrive);
vdrive = new HashMap<String, String>();
}
vdrive.put(_key, _value);
}
}
}
}
}
if (vdrive != null)
adapter.put(vdrive.get("virtual_drive"), vdrive);
if (adapter != null)
adapters.add(adapter);
}
} catch (Exception ex) {
logger.error("Error obtaining megacli -LDInfo data: "+ex.getMessage());
throw new Exception("Error obtaining megacli -LDInfo data: "+ex.getMessage());
}
return adapters;
}
/**
* El comando cfgDisplay muestra toda la configuración elativa a grupos de discos - virtual drives - physical drives
* La función interpreta la salida obteniendo la información en un mapa representado así:
* adapter_1
* id => info sobre adapter
* disk_group0 => key_1 : value 1
* key_2 : value 2
* virtual_drives => vdrive_0 => key_1 : value_1
* key_2 : value_2
* vdrive_1
* ...
* physical_drives => phdrive_0 => key_1 : value_1
* key_2 : value_2
* phdrive_1
* ...
* ...
* disk_group1 => key_1 : value 1
* ...
* ...
* adapter 2
* ...
*
*/
public static List<Map<String, Map<String, Object>>> cfgDisplay() throws Exception {
//String _s = "cat /CfgDsply_aAll";
String _s = "megacli -CfgDsply -aAll";
List<Map<String, Map<String, Object>>> adapters = null;
try {
String _output = Command.systemCommand(_s);
if (_output != null && _output.length()>0) {
adapters = new ArrayList<Map<String, Map<String, Object>>>();
StringTokenizer _st = new StringTokenizer(_output, "\n");
Map<String, Map<String, Object>> adapter = null;
Map<String, Object> diskGroup = null;
Map<String, String> vDrive = null;
Map<String, String> physicalDrive = null;
String _key = null, _value = null;
List<Map<String, String>> diskGroupVdrives = null;
List<Map<String, String>> diskGroupPhysicalDrives = null;
String lastType = null;
while (_st.hasMoreTokens()) {
String _line = _st.nextToken();
if (_line.trim().length()>1 && !_line.contains("Exit Code")) {
if (_line.contains("=====")) { // new adapter
if (adapter != null)
adapters.add(adapter);
adapter = new HashMap<String, Map<String, Object>>();
diskGroup = new HashMap<String, Object> ();
do {
_line = _st.nextToken();
if (_line.contains(":")) {
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_value = trimLeftRight(_value);
_key = normalize(_key);
diskGroup.put(_key, _value);
}
}
}
} while (!_line.contains("====="));
_line = _st.nextToken();
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")) { // Number of Disk groups
_value = _line.substring(_line.indexOf(":")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_value = trimLeftRight(_value);
_key = normalize(_key);
diskGroup.put(_key, _value);
}
}
adapter.put("id", diskGroup);
diskGroup=null;
} else if (_line.contains(":")) {
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_value = trimLeftRight(_value);
_key = normalize(_key);
if (_key.equals("disk_group")) {
if (diskGroupVdrives != null && diskGroupVdrives.size()>0)
diskGroup.put("virtual_drives", diskGroupVdrives);
if (diskGroupPhysicalDrives != null && diskGroupPhysicalDrives.size()>0)
diskGroup.put("physical_drives", diskGroupPhysicalDrives);
if (diskGroup != null)
adapter.put((String) diskGroup.get("disk_group"), diskGroup);
diskGroup = new HashMap<String, Object>();
diskGroup.put(_key, _value);
lastType = "disk_group";
} else if (_key.equals("virtual_drive")) {
if (vDrive != null)
diskGroupVdrives.add(vDrive);
else
diskGroupVdrives = new ArrayList<Map<String, String>>();
vDrive = new HashMap<String, String>();
vDrive.put(_key, _value);
lastType = "virtual_drive";
} else if (_key.equals("physical_disk")) {
if (physicalDrive != null)
diskGroupPhysicalDrives.add(physicalDrive);
else
diskGroupPhysicalDrives = new ArrayList<Map<String, String>>();
physicalDrive = new HashMap<String, String>();
physicalDrive.put(_key, _value);
lastType = "physical_disk";
} else if (lastType.equals("disk_group")) {
diskGroup.put(_key, _value);
} else if (lastType.equals("virtual_drive")) {
vDrive.put(_key, _value);
} else if (lastType.equals("physical_disk")) {
physicalDrive.put(_key, _value);
}
}
}
}
}
}
// Añadimos el último elemento
if (adapter != null) {
if (vDrive != null)
diskGroupVdrives.add(vDrive);
if (physicalDrive != null)
diskGroupPhysicalDrives.add(physicalDrive);
if (diskGroup != null) {
if (diskGroupPhysicalDrives != null && diskGroupPhysicalDrives.size()>0)
diskGroup.put("physical_drives", diskGroupPhysicalDrives);
if (diskGroupVdrives != null && diskGroupVdrives.size()>0)
diskGroup.put("virtual_drives", diskGroupVdrives);
adapter.put((String) diskGroup.get("disk_group"), diskGroup);
}
adapters.add(adapter);
}
}
} catch (Exception ex) {
logger.error("Error obtaining megacli -CfgDsply data: "+ex.getMessage());
throw new Exception("Error obtaining megacli -CfgDsply data: "+ex.getMessage());
}
return adapters;
}
public static List<Map<String, String>> adpBbuCmd() throws Exception {
//String _s = "cat /bateries";
String _s = "megacli -AdpBbuCmd -aALL";
List<Map<String, String>> info = null;
try {
String _output = Command.systemCommand(_s);
if (_output != null && _output.length()>0) {
Map<String, String> adapter = null;
String _key = null;
String _value = null;
info = new ArrayList<Map<String, String>>();
StringTokenizer _st = new StringTokenizer(_output, "\n");
while (_st.hasMoreTokens()) {
String _line = _st.nextToken();
if (_line.trim().length()>1 && !_line.contains("Exit Code")) {
if (_line.contains("BBU status for Adapter:")) {
if (adapter != null)
info.add(adapter);
adapter = new HashMap<String, String>();
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
_value = trimLeftRight(_value);
}
adapter.put("id", _value);
} else if (_line.contains(":")) {
_key = _line.substring(0, _line.indexOf(":"));
if ( _line.length() > _line.indexOf(":")+1) {
_value = _line.substring(_line.indexOf(":")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_value = trimLeftRight(_value);
_key = normalize(_key);
if (!adapter.containsKey(_key)) {
if (_key.equals("relative_state_of_charge")) {
if (_value.indexOf("%") > 0) {
_value = _value.substring(0, _value.indexOf("%")).trim();
}
}
adapter.put(_key, _value);
}
}
}
} else if (_line.contains("=")) {
_key = _line.substring(0, _line.indexOf("="));
if ( _line.length() > _line.indexOf("=")+1) {
_value = _line.substring(_line.indexOf("=")+1);
if (_value.trim() != null && _value.trim().length() > 0) {
_value = trimLeftRight(_value);
_key = normalize(_key);
if (!adapter.containsKey(_key)) {
adapter.put(_key, _value);
}
}
}
}
}
}
if (adapter != null)
info.add(adapter);
}
return info;
} catch (Exception ex) {
logger.error("Error obtaining megacli -AdpBbuCmd -aALL data: "+ex.getMessage());
throw new Exception("Error obtaining megacli -AdpBbuCmd -aALL data: "+ex.getMessage());
}
}
/**
* Obtiene el log de eventos
*/
public static String adpEventLog() throws Exception {
//String _s = "cat /AdpEventLog_GetEvents_f_events_aAll";
String _s = "megacli -AdpEventLog -GetEvents -f events -aAll";
String _output = null;
try {
_output = Command.systemCommand(_s);
} catch (Exception ex) {
logger.error("Error obtaining megacli log output: "+ex.getMessage());
throw new Exception("Error obtaining megacli log output: "+ex.getMessage());
}
return _output;
}
/**
* Obtiene el fragmento html para el informe del watchdog
* @return
* @throws Exception
*/
public static String getHtmlReport() throws Exception {
String html = "";
try {
List<Map<String, Map<String, Object>>> adapters = cfgDisplay();
List<Map<String, String>> adBattery = adpBbuCmd();
logger.info("Generating html raid info report");
int i=0;
for (Map<String, Map<String, Object>> adapter : adapters) {
if (i>0)
html+="===================<br />";
Map<String, Object> idInfo = adapter.get("id");
html+="Adapter #"+i+" ["+idInfo.get("product_name")+" -- "+idInfo.get("memory")+"]<br />";
for (Map<String, String> ad : adBattery) {
if (ad.get("id").equals(String.valueOf(i))) {
html+=" Battery Charge:"+ad.get("relative_state_of_charge")+"% <br/>";
}
}
for (String idGroup : adapter.keySet()) {
if (!"id".equals(idGroup)) {
Map<String, Object> diskGroup = adapter.get(idGroup);
html+="++Disk Group:"+idGroup+" <br/>";
html+="----Physical Disks:"+diskGroup.get("number_of_pds")+" <br/>";
html+="----Virtual Disks:"+diskGroup.get("number_of_vds")+" <br/>";
html+="----Hot Spares:"+diskGroup.get("number_of_dedicated_hotspares")+" <br/>";
}
}
i++;
}
} catch (Exception ex) {
logger.error("Error generando html RAID report. Ex: {}", ex.getMessage());
}
return html;
}
/**
* Pasa una lista de errores a String
* @param errors
* @return
* @throws Exception
*/
public static String errorsToString(List<Map<String, String>> errors) throws Exception {
String sb = "";
List<String> report = new ArrayList<String>();
if (errors != null && errors.size()>0) {
for (Map<String, String> error: errors) {
if (!report.contains(error.get("adapterId")+"-"+error.get("key"))) {
sb+="Error in adapter ["+error.get("adapterId")+"]. Detected "+unormalize(error.get("key"))+"="+error.get("val-obtained")+". It should be "+error.get("val-ok")+"<br/>";
report.add(error.get("adapterId")+"-"+error.get("key"));
}
}
}
logger.info("Errors found: {}",sb);
return sb;
}
/**
* Normaliza un string:
* origen: Val. de Tal
* resultado: val_de_tal
* @param _s
* @throws Exception
*/
public static String normalize(String _s) throws Exception {
String _n = _s;
_n = _n.replaceAll(" ", "_");
_n = _n.replaceAll("\\.", "");
_n = _n.toLowerCase();
while (_n.lastIndexOf("_")+1 == _n.length())
_n = _n.substring(0, _n.length()-1);
while (_n.indexOf("_") == 0)
_n = _n.substring(1);
return _n;
}
public static String unormalize(String _s) throws Exception {
String _n = _s;
_n = _n.replaceAll("_", " ");
return _n;
}
/**
* Elimina los espacios a izquierda y derecha de una cadena
* @param _s
* @throws Exception
*/
public static String trimLeftRight(String _s) throws Exception {
String _n = _s;
while (_n.lastIndexOf(" ")+1 == _n.length())
_n = _n.substring(0, _n.length()-1);
while (_n.indexOf(" ") == 0)
_n = _n.substring(1);
return _n;
}
/**
* Devuelve una cadena a partir de una lista
* @param list
* @return
* @throws Exception
*/
public static String listToString(List<String> list) throws Exception {
StringBuilder sb = new StringBuilder();
if (list != null && list.size() > 0) {
sb.append("[");
int c = 0;
for (String el : list) {
if (c != 0)
sb.append(", ");
else
c++;
sb.append(el);
}
sb.append("]");
}
return sb.toString();
}
}
| apache-2.0 |
artoderk/elastic-jobx | elastic-jobx-spring/src/test/java/com/dangdang/ddframe/job/spring/WithoutNamespaceTest.java | 1027 | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package com.dangdang.ddframe.job.spring;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/job/withoutNamespace.xml")
public final class WithoutNamespaceTest extends AbstractJobSpringIntegrateTest {
public WithoutNamespaceTest() {
super("simpleElasticJob_no_namespace", "throughputDataFlowElasticJob_no_namespace");
}
}
| apache-2.0 |
ppavlidis/aspiredb | aspiredb/src/main/java/ubc/pavlab/aspiredb/server/service/LabelServiceImpl.java | 7233 | /*
* The aspiredb project
*
* Copyright (c) 2013 University of British Columbia
*
* 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 ubc.pavlab.aspiredb.server.service;
import java.util.ArrayList;
import java.util.Collection;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ubc.pavlab.aspiredb.server.dao.LabelDao;
import ubc.pavlab.aspiredb.server.dao.SubjectDao;
import ubc.pavlab.aspiredb.server.dao.VariantDao;
import ubc.pavlab.aspiredb.server.model.Label;
import ubc.pavlab.aspiredb.server.model.Subject;
import ubc.pavlab.aspiredb.server.model.Variant;
import ubc.pavlab.aspiredb.shared.LabelValueObject;
/**
* Label related services such delete, remove, and update.
*
* @author: anton date: 10/06/13
*/
@Component("labelService")
@Service("labelService")
@RemoteProxy(name = "LabelService")
public class LabelServiceImpl implements LabelService {
@Autowired
private LabelDao labelDao;
@Autowired
private SubjectDao subjectDao;
@Autowired
private VariantDao variantDao;
@Override
@Transactional
@RemoteMethod
public void deleteSubjectLabel( LabelValueObject label ) {
Collection<Subject> subjects = subjectDao.findByLabel( label );
Collection<Long> subjectIds = new ArrayList<>();
for ( Subject s : subjects ) {
subjectIds.add( s.getId() );
}
Collection<LabelValueObject> labels = new ArrayList<>();
labels.add( label );
removeLabelsFromSubjects( labels, subjectIds );
Label labelEntity = labelDao.load( label.getId() );
if ( labelEntity != null ) {
labelDao.remove( labelEntity );
}
}
@Override
@Transactional
@RemoteMethod
public Collection<LabelValueObject> getSubjectLabelsByProjectId( Long projectId ) {
Collection<LabelValueObject> result = new ArrayList<>();
for ( Label label : labelDao.getSubjectLabelsByProjectId( projectId ) ) {
result.add( label.toValueObject() );
}
return result;
}
@Override
@Transactional
@RemoteMethod
public Collection<LabelValueObject> getVariantLabelsByProjectId( Long projectId ) {
Collection<LabelValueObject> result = new ArrayList<>();
for ( Label label : labelDao.getVariantLabelsByProjectId( projectId ) ) {
result.add( label.toValueObject() );
}
return result;
}
@Override
@Transactional
@RemoteMethod
public Collection<LabelValueObject> getSubjectLabels() {
Collection<LabelValueObject> result = new ArrayList<>();
for ( Label label : labelDao.getSubjectLabels() ) {
result.add( label.toValueObject() );
}
return result;
}
@Override
@Transactional
@RemoteMethod
public Collection<LabelValueObject> getVariantLabels() {
Collection<LabelValueObject> result = new ArrayList<>();
for ( Label label : labelDao.getVariantLabels() ) {
result.add( label.toValueObject() );
}
return result;
}
@Override
@Transactional
@RemoteMethod
public void deleteSubjectLabels( Collection<LabelValueObject> labels ) {
for ( LabelValueObject lvo : labels ) {
deleteSubjectLabel( lvo );
}
}
@Override
@Transactional
@RemoteMethod
public void deleteVariantLabel( LabelValueObject label ) {
Collection<Variant> variants = variantDao.findByLabel( label );
Collection<Long> variantIds = new ArrayList<>();
for ( Variant v : variants ) {
variantIds.add( v.getId() );
}
Collection<LabelValueObject> labels = new ArrayList<>();
labels.add( label );
removeLabelsFromVariants( labels, variantIds );
Label labelEntity = labelDao.load( label.getId() );
labelDao.remove( labelEntity );
}
@Override
@Transactional
@RemoteMethod
public void deleteVariantLabels( Collection<LabelValueObject> labels ) {
for ( LabelValueObject lvo : labels ) {
deleteVariantLabel( lvo );
}
}
@Override
@Transactional
@RemoteMethod
public void removeLabelsFromSubjects( Collection<LabelValueObject> labels, Collection<Long> subjectIds ) {
// Collection<Label labelEntity = labelDao.load( labelIds );
Collection<Subject> subjects = subjectDao.load( subjectIds );
for ( Subject subject : subjects ) {
for ( LabelValueObject label : labels ) {
subject.getLabels().remove( labelDao.findOrCreate( label ) );
subjectDao.update( subject );
}
}
}
@Override
@Transactional
@RemoteMethod
public void removeLabelsFromVariants( Collection<LabelValueObject> labels, Collection<Long> variantIds ) {
Collection<Variant> variants = ( Collection<Variant> ) variantDao.load( variantIds );
// Collection<Label> labels = labelDao.load( labelIds );
for ( Variant variant : variants ) {
for ( LabelValueObject label : labels ) {
variant.getLabels().remove( labelDao.findOrCreate( label ) );
variantDao.update( variant );
}
}
}
/**
* update the label
*/
@Override
@Transactional
@RemoteMethod
public void updateLabel( LabelValueObject label ) {
Label labelEntity = labelDao.load( label.getId() );
labelEntity.setName( label.getName() );
labelEntity.setColour( label.getColour() );
labelEntity.setIsShown( label.getIsShown() );
labelEntity.setDescription( label.getDescription() );
labelDao.update( labelEntity );
// updateSubjectLabel( label );
}
/**
* update subject label
*/
@Override
@Transactional
@RemoteMethod
public void updateSubjectLabel( LabelValueObject label ) {
Collection<Subject> subjects = subjectDao.findByLabel( label );
for ( Subject subject : subjects ) {
Collection<Label> subjectlabels = subject.getLabels();
for ( Label subjectlabel : subjectlabels ) {
if ( subjectlabel.getId().equals( label.getId() ) ) {
subjectlabel.equals( label );
}
}
subject.setLabels( subjectlabels );
subjectDao.update( subject );
}
}
}
| apache-2.0 |
telefonicaid/fiware-cosmos-ambari | ambari-server/src/test/java/org/apache/ambari/server/configuration/ConfigurationTest.java | 9093 | /**
* 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.ambari.server.configuration;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import junit.framework.Assert;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.support.membermodification.MemberMatcher;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.*;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Properties;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Configuration.class })
public class ConfigurationTest {
private Injector injector;
@Inject
private Configuration config;
@Before
public void setup() throws Exception {
injector = Guice.createInjector(new InMemoryDefaultTestModule());
injector.injectMembers(this);
}
@After
public void teardown() throws AmbariException {
}
/**
* ambari.properties doesn't contain "security.server.two_way_ssl" option
* @throws Exception
*/
@Test
public void testDefaultTwoWayAuthNotSet() throws Exception {
Assert.assertFalse(config.getTwoWaySsl());
}
/**
* ambari.properties contains "security.server.two_way_ssl=true" option
* @throws Exception
*/
@Test
public void testTwoWayAuthTurnedOn() throws Exception {
Properties ambariProperties = new Properties();
ambariProperties.setProperty("security.server.two_way_ssl", "true");
Configuration conf = new Configuration(ambariProperties);
Assert.assertTrue(conf.getTwoWaySsl());
}
/**
* ambari.properties contains "security.server.two_way_ssl=false" option
* @throws Exception
*/
@Test
public void testTwoWayAuthTurnedOff() throws Exception {
Properties ambariProperties = new Properties();
ambariProperties.setProperty("security.server.two_way_ssl", "false");
Configuration conf = new Configuration(ambariProperties);
Assert.assertFalse(conf.getTwoWaySsl());
}
@Test
public void testGetClientSSLApiPort() throws Exception {
Properties ambariProperties = new Properties();
ambariProperties.setProperty(Configuration.CLIENT_API_SSL_PORT_KEY, "6666");
Configuration conf = new Configuration(ambariProperties);
Assert.assertEquals(6666, conf.getClientSSLApiPort());
conf = new Configuration();
Assert.assertEquals(8443, conf.getClientSSLApiPort());
}
@Test
public void testGetClientHTTPSSettings() throws IOException {
File passFile = File.createTempFile("https.pass.", "txt");
passFile.deleteOnExit();
String password = "pass12345";
FileUtils.writeStringToFile(passFile, password);
Properties ambariProperties = new Properties();
ambariProperties.setProperty(Configuration.API_USE_SSL, "true");
ambariProperties.setProperty(
Configuration.CLIENT_API_SSL_KSTR_DIR_NAME_KEY,
passFile.getParent());
ambariProperties.setProperty(
Configuration.CLIENT_API_SSL_CRT_PASS_FILE_NAME_KEY,
passFile.getName());
String oneWayPort = RandomStringUtils.randomNumeric(4);
String twoWayPort = RandomStringUtils.randomNumeric(4);
ambariProperties.setProperty(Configuration.SRVR_TWO_WAY_SSL_PORT_KEY, twoWayPort.toString());
ambariProperties.setProperty(Configuration.SRVR_ONE_WAY_SSL_PORT_KEY, oneWayPort.toString());
Configuration conf = new Configuration(ambariProperties);
Assert.assertTrue(conf.getApiSSLAuthentication());
//Different certificates for two-way SSL and HTTPS
Assert.assertFalse(conf.getConfigsMap().get(Configuration.KSTR_NAME_KEY).
equals(conf.getConfigsMap().get(Configuration.CLIENT_API_SSL_KSTR_NAME_KEY)));
Assert.assertFalse(conf.getConfigsMap().get(Configuration.SRVR_CRT_NAME_KEY).
equals(conf.getConfigsMap().get(Configuration.CLIENT_API_SSL_CRT_NAME_KEY)));
Assert.assertEquals("https.keystore.p12", conf.getConfigsMap().get(
Configuration.CLIENT_API_SSL_KSTR_NAME_KEY));
Assert.assertEquals(passFile.getName(), conf.getConfigsMap().get(
Configuration.CLIENT_API_SSL_CRT_PASS_FILE_NAME_KEY));
Assert.assertEquals(password, conf.getConfigsMap().get(Configuration.CLIENT_API_SSL_CRT_PASS_KEY));
Assert.assertEquals(Integer.parseInt(twoWayPort), conf.getTwoWayAuthPort());
Assert.assertEquals(Integer.parseInt(oneWayPort), conf.getOneWayAuthPort());
}
@Test
public void testLoadSSLParams_unencrypted() throws IOException {
Properties ambariProperties = new Properties();
String unencrypted = "fake-unencrypted-password";
String encrypted = "fake-encrypted-password";
ambariProperties.setProperty(Configuration.SSL_TRUSTSTORE_PASSWORD_KEY, unencrypted);
Configuration conf = spy(new Configuration(ambariProperties));
doReturn(null).when(conf).readPasswordFromStore(anyString());
conf.loadSSLParams();
Assert.assertEquals(System.getProperty(conf.JAVAX_SSL_TRUSTSTORE_PASSWORD, "unknown"), unencrypted);
}
@Test
public void testLoadSSLParams_encrypted() throws IOException {
Properties ambariProperties = new Properties();
String unencrypted = "fake-unencrypted-password";
String encrypted = "fake-encrypted-password";
ambariProperties.setProperty(Configuration.SSL_TRUSTSTORE_PASSWORD_KEY, unencrypted);
Configuration conf = spy(new Configuration(ambariProperties));
doReturn(encrypted).when(conf).readPasswordFromStore(anyString());
conf.loadSSLParams();
Assert.assertEquals(System.getProperty(conf.JAVAX_SSL_TRUSTSTORE_PASSWORD, "unknown"), encrypted);
}
@Test
public void testGetRcaDatabasePassword_fromStore() {
String serverJdbcRcaUserPasswdKey = "key";
String encrypted = "password";
Properties properties = new Properties();
properties.setProperty(Configuration.SERVER_JDBC_RCA_USER_PASSWD_KEY, serverJdbcRcaUserPasswdKey);
Configuration conf = spy(new Configuration(properties));
doReturn(encrypted).when(conf).readPasswordFromStore(serverJdbcRcaUserPasswdKey);
Assert.assertEquals(encrypted, conf.getRcaDatabasePassword());
}
@Test
public void testGetRcaDatabasePassword_fromFile() {
Configuration conf = spy(new Configuration(new Properties()));
Assert.assertEquals("mapred", conf.getRcaDatabasePassword());
}
@Test
public void testGetLocalDatabaseUrl() {
Properties ambariProperties = new Properties();
ambariProperties.setProperty("server.jdbc.database", "ambaritestdatabase");
Configuration conf = new Configuration(ambariProperties);
Assert.assertEquals(conf.getLocalDatabaseUrl(), Configuration.JDBC_LOCAL_URL.concat("ambaritestdatabase"));
}
@Test
public void testGetAmbariProperties() throws Exception {
Properties ambariProperties = new Properties();
ambariProperties.setProperty("name", "value");
Configuration conf = new Configuration(ambariProperties);
mockStatic(Configuration.class);
Method[] methods = MemberMatcher.methods(Configuration.class, "readConfigFile");
PowerMock.expectPrivate(Configuration.class, methods[0]).andReturn(ambariProperties);
replayAll();
Map<String, String> props = conf.getAmbariProperties();
verifyAll();
Assert.assertEquals("value", props.get("name"));
}
@Rule
public ExpectedException exception = ExpectedException.none();
@Test()
public void testGetLocalDatabaseUrlThrowException() {
Properties ambariProperties = new Properties();
Configuration conf = new Configuration(ambariProperties);
exception.expect(RuntimeException.class);
exception.expectMessage("Server DB Name is not configured!");
conf.getLocalDatabaseUrl();
}
}
| apache-2.0 |
ucare-uchicago/cass-fate-system | src/java/org/apache/cassandra/net/MessagingService.java | 18798 | /**
* 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.cassandra.net;
import java.io.IOError;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ServerSocketChannel;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.net.io.SerializerType;
import org.apache.cassandra.net.sink.SinkManager;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ExpiringMap;
import org.apache.cassandra.utils.GuidGenerator;
import org.apache.cassandra.utils.SimpleCondition;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import org.apache.cassandra.Util;
public class MessagingService
{
private static int version_ = 1;
//TODO: make this parameter dynamic somehow. Not sure if config is appropriate.
private static SerializerType serializerType_ = SerializerType.BINARY;
/** we preface every message with this number so the recipient can validate the sender is sane */
public static final int PROTOCOL_MAGIC = 0xCA552DFA;
/* This records all the results mapped by message Id */
private static ExpiringMap<String, IAsyncCallback> callbackMap_;
private static ExpiringMap<String, IAsyncResult> taskCompletionMap_;
/* Lookup table for registering message handlers based on the verb. */
private static Map<StorageService.Verb, IVerbHandler> verbHandlers_;
/* Thread pool to handle messages without a specialized stage */
private static ExecutorService defaultExecutor_;
/* Thread pool to handle messaging write activities */
private static ExecutorService streamExecutor_;
private static NonBlockingHashMap<InetAddress, OutboundTcpConnectionPool> connectionManagers_ = new NonBlockingHashMap<InetAddress, OutboundTcpConnectionPool>();
private static Logger logger_ = Logger.getLogger(MessagingService.class);
private static int LOG_DROPPED_INTERVAL_IN_MS = 1000;
public static final MessagingService instance = new MessagingService();
private SocketThread socketThread;
private SimpleCondition listenGate;
private static AtomicInteger droppedMessages = new AtomicInteger();
public Object clone() throws CloneNotSupportedException
{
//Prevents the singleton from being cloned
throw new CloneNotSupportedException();
}
protected MessagingService()
{
listenGate = new SimpleCondition();
verbHandlers_ = new HashMap<StorageService.Verb, IVerbHandler>();
/*
* Leave callbacks in the cachetable long enough that any related messages will arrive
* before the callback is evicted from the table. The concurrency level is set at 128
* which is the sum of the threads in the pool that adds shit into the table and the
* pool that retrives the callback from here.
*/
callbackMap_ = new ExpiringMap<String, IAsyncCallback>( 2 * DatabaseDescriptor.getRpcTimeout() );
taskCompletionMap_ = new ExpiringMap<String, IAsyncResult>( 2 * DatabaseDescriptor.getRpcTimeout() );
defaultExecutor_ = new JMXEnabledThreadPoolExecutor("MISCELLANEOUS-POOL");
streamExecutor_ = new JMXEnabledThreadPoolExecutor("MESSAGE-STREAMING-POOL");
TimerTask logDropped = new TimerTask()
{
public void run()
{
logDroppedMessages();
}
};
Timer timer = new Timer("DroppedMessagesLogger");
timer.schedule(logDropped, LOG_DROPPED_INTERVAL_IN_MS, LOG_DROPPED_INTERVAL_IN_MS);
}
public byte[] hash(String type, byte data[])
{
byte result[];
try
{
MessageDigest messageDigest = MessageDigest.getInstance(type);
result = messageDigest.digest(data);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return result;
}
/** called by failure detection code to notify that housekeeping should be performed on downed sockets. */
public void convict(InetAddress ep)
{
logger_.debug("Resetting pool for " + ep);
getConnectionPool(ep).reset();
}
/**
* Listen on the specified port.
* @param localEp InetAddress whose port to listen on.
*/
public void listen(InetAddress localEp) throws IOException
{
ServerSocketChannel serverChannel = ServerSocketChannel.open();
final ServerSocket ss = serverChannel.socket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(localEp, DatabaseDescriptor.getStoragePort()));
socketThread = new SocketThread(ss, "ACCEPT-" + localEp);
socketThread.start();
listenGate.signalAll();
}
public void waitUntilListening()
{
try
{
listenGate.await();
}
catch (InterruptedException ie)
{
logger_.debug("await interrupted");
}
}
public static OutboundTcpConnectionPool getConnectionPool(InetAddress to)
{
OutboundTcpConnectionPool cp = connectionManagers_.get(to);
if (cp == null)
{
connectionManagers_.putIfAbsent(to, new OutboundTcpConnectionPool(to));
cp = connectionManagers_.get(to);
}
return cp;
}
public static OutboundTcpConnection getConnection(InetAddress to, Message msg)
{
return getConnectionPool(to).getConnection(msg);
}
/**
* Register a verb and the corresponding verb handler with the
* Messaging Service.
* @param verb
* @param verbHandler handler for the specified verb
*/
public void registerVerbHandlers(StorageService.Verb verb, IVerbHandler verbHandler)
{
assert !verbHandlers_.containsKey(verb);
verbHandlers_.put(verb, verbHandler);
}
/**
* This method returns the verb handler associated with the registered
* verb. If no handler has been registered then null is returned.
* @param type for which the verb handler is sought
* @return a reference to IVerbHandler which is the handler for the specified verb
*/
public IVerbHandler getVerbHandler(StorageService.Verb type)
{
return verbHandlers_.get(type);
}
/**
* Send a message to a given endpoint.
* @param message message to be sent.
* @param to endpoint to which the message needs to be sent
* @return an reference to an IAsyncResult which can be queried for the
* response
*/
public String sendRR(Message message, InetAddress[] to, IAsyncCallback cb)
{
String messageId = message.getMessageId();
addCallback(cb, messageId);
for (InetAddress endpoint : to)
{
sendOneWay(message, endpoint);
}
return messageId;
}
public void addCallback(IAsyncCallback cb, String messageId)
{
callbackMap_.put(messageId, cb);
}
/**
* Send a message to a given endpoint. This method specifies a callback
* which is invoked with the actual response.
* @param message message to be sent.
* @param to endpoint to which the message needs to be sent
* @param cb callback interface which is used to pass the responses or
* suggest that a timeout occurred to the invoker of the send().
* suggest that a timeout occurred to the invoker of the send().
* @return an reference to message id used to match with the result
*/
public String sendRR(Message message, InetAddress to, IAsyncCallback cb)
{
String messageId = message.getMessageId();
addCallback(cb, messageId);
sendOneWay(message, to);
return messageId;
}
/**
* Send a message to a given endpoint. The ith element in the <code>messages</code>
* array is sent to the ith element in the <code>to</code> array.This method assumes
* there is a one-one mapping between the <code>messages</code> array and
* the <code>to</code> array. Otherwise an IllegalArgumentException will be thrown.
* This method also informs the MessagingService to wait for at least
* <code>howManyResults</code> responses to determine success of failure.
* @param messages messages to be sent.
* @param to endpoints to which the message needs to be sent
* @param cb callback interface which is used to pass the responses or
* suggest that a timeout occured to the invoker of the send().
* @return an reference to message id used to match with the result
*/
public String sendRR(Message[] messages, InetAddress[] to, IAsyncCallback cb)
{
if ( messages.length != to.length )
{
throw new IllegalArgumentException("Number of messages and the number of endpoints need to be same.");
}
String groupId = GuidGenerator.guid();
addCallback(cb, groupId);
for ( int i = 0; i < messages.length; ++i )
{
messages[i].setMessageId(groupId);
sendOneWay(messages[i], to[i]);
}
return groupId;
}
/**
* Send a message to a given endpoint. This method adheres to the fire and forget
* style messaging.
* @param message messages to be sent.
* @param to endpoint to which the message needs to be sent
*/
public void sendOneWay(Message message, InetAddress to)
{
// do local deliveries
if ( message.getFrom().equals(to) )
{
MessagingService.receive(message);
return;
}
// message sinks are a testing hook
Message processedMessage = SinkManager.processClientMessageSink(message);
if (processedMessage == null)
{
return;
}
// get pooled connection (really, connection queue)
OutboundTcpConnection connection = getConnection(to, message);
// pack message with header in a bytebuffer
byte[] data;
try
{
DataOutputBuffer buffer = new DataOutputBuffer();
//JINSU
Util.debug("Sending message ::\n-->" + message);
Message.serializer().serialize(message, buffer);
data = buffer.getData();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
assert data.length > 0;
ByteBuffer buffer = packIt(data , false);
// write it
connection.write(buffer);
}
public IAsyncResult sendRR(Message message, InetAddress to)
{
IAsyncResult iar = new AsyncResult();
taskCompletionMap_.put(message.getMessageId(), iar);
sendOneWay(message, to);
return iar;
}
/**
* Stream a file from source to destination. This is highly optimized
* to not hold any of the contents of the file in memory.
* @param file name of file to stream.
* @param startPosition position inside the file
* @param endPosition
* @param to endpoint to which we need to stream the file.
*/
public void stream(String file, long startPosition, long endPosition, InetAddress from, InetAddress to)
{
/* Streaming asynchronously on streamExector_ threads. */
Runnable streamingTask = new FileStreamTask(file, startPosition, endPosition, from, to);
streamExecutor_.execute(streamingTask);
}
/** blocks until the processing pools are empty and done. */
public static void waitFor() throws InterruptedException
{
while (!defaultExecutor_.isTerminated())
defaultExecutor_.awaitTermination(5, TimeUnit.SECONDS);
while (!streamExecutor_.isTerminated())
streamExecutor_.awaitTermination(5, TimeUnit.SECONDS);
}
public static void shutdown()
{
logger_.info("Shutting down MessageService...");
try
{
instance.socketThread.close();
}
catch (IOException e)
{
throw new IOError(e);
}
defaultExecutor_.shutdownNow();
streamExecutor_.shutdownNow();
/* shut down the cachetables */
taskCompletionMap_.shutdown();
callbackMap_.shutdown();
logger_.info("Shutdown complete (no further commands will be processed)");
}
public static void receive(Message message)
{
message = SinkManager.processServerMessageSink(message);
Runnable runnable = new MessageDeliveryTask(message);
ExecutorService stage = StageManager.getStage(message.getMessageType());
if (stage == null)
{
if (logger_.isDebugEnabled())
logger_.debug("Running " + message.getMessageType() + " on default stage");
defaultExecutor_.execute(runnable);
}
else
{
stage.execute(runnable);
}
}
public static IAsyncCallback getRegisteredCallback(String key)
{
return callbackMap_.get(key);
}
public static void removeRegisteredCallback(String key)
{
callbackMap_.remove(key);
}
public static IAsyncResult getAsyncResult(String key)
{
return taskCompletionMap_.remove(key);
}
public static long getRegisteredCallbackAge(String key)
{
return callbackMap_.getAge(key);
}
public static long getAsyncResultAge(String key)
{
return taskCompletionMap_.getAge(key);
}
public static void validateMagic(int magic) throws IOException
{
if (magic != PROTOCOL_MAGIC)
throw new IOException("invalid protocol header");
}
public static int getBits(int x, int p, int n)
{
return x >>> (p + 1) - n & ~(-1 << n);
}
public static ByteBuffer packIt(byte[] bytes, boolean compress)
{
/*
Setting up the protocol header. This is 4 bytes long
represented as an integer. The first 2 bits indicate
the serializer type. The 3rd bit indicates if compression
is turned on or off. It is turned off by default. The 4th
bit indicates if we are in streaming mode. It is turned off
by default. The 5th-8th bits are reserved for future use.
The next 8 bits indicate a version number. Remaining 15 bits
are not used currently.
*/
int header = 0;
// Setting up the serializer bit
header |= serializerType_.ordinal();
// set compression bit.
if (compress)
header |= 4;
// Setting up the version bit
header |= (version_ << 8);
ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 4 + bytes.length);
buffer.putInt(PROTOCOL_MAGIC);
buffer.putInt(header);
buffer.putInt(bytes.length);
buffer.put(bytes);
buffer.flip();
return buffer;
}
public static ByteBuffer constructStreamHeader(boolean compress)
{
/*
Setting up the protocol header. This is 4 bytes long
represented as an integer. The first 2 bits indicate
the serializer type. The 3rd bit indicates if compression
is turned on or off. It is turned off by default. The 4th
bit indicates if we are in streaming mode. It is turned off
by default. The following 4 bits are reserved for future use.
The next 8 bits indicate a version number. Remaining 15 bits
are not used currently.
*/
int header = 0;
// Setting up the serializer bit
header |= serializerType_.ordinal();
// set compression bit.
if ( compress )
header |= 4;
// set streaming bit
header |= 8;
// Setting up the version bit
header |= (version_ << 8);
/* Finished the protocol header setup */
ByteBuffer buffer = ByteBuffer.allocate(4 + 4);
buffer.putInt(PROTOCOL_MAGIC);
buffer.putInt(header);
buffer.flip();
return buffer;
}
public static int incrementDroppedMessages()
{
return droppedMessages.incrementAndGet();
}
private static void logDroppedMessages()
{
if (droppedMessages.get() > 0)
logger_.warn("Dropped " + droppedMessages + " messages in the last " + LOG_DROPPED_INTERVAL_IN_MS + "ms");
droppedMessages.set(0);
}
private class SocketThread extends Thread
{
private final ServerSocket server;
SocketThread(ServerSocket server, String name)
{
super(name);
this.server = server;
}
public void run()
{
while (true)
{
try
{
Socket socket = server.accept();
new IncomingTcpConnection(socket).start();
}
catch (AsynchronousCloseException e)
{
// this happens when another thread calls close().
logger_.info("MessagingService shutting down server thread.");
break;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
void close() throws IOException
{
server.close();
}
}
}
| apache-2.0 |
mojohaus/templating-maven-plugin | src/test/resources/sample-simple/src/main/java-templates/org/example/Sample.java | 111 | package org.example;
public class Sample
{
public static final String VERSION = "<${project.version}>";
}
| apache-2.0 |
PacteraMobile/pacterapulse-android | app/src/main/java/au/com/pactera/pacterapulse/helper/VoteManager.java | 2283 | /*
* Copyright (c) 2015 Pactera. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
* PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache License, Version 2.0 for the specific language
* governing permissions and limitations under the License.
*/
package au.com.pactera.pacterapulse.helper;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by liny1 on 14/05/2015.
*/
public class VoteManager
{
protected static String VOTED_DATE = "VOTED_DATE";
protected static String VOTED_VALUE = "VOTED_VALUE";
protected static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
private Context context;
private SharedPreferences sharedPreferences;
public VoteManager(Context context)
{
this.context = context;
}
/**
* submit the vote with the emotion value
*
* @param emotion the emotion value in integer
*/
public void saveVote(int emotion)
{
Date now = new Date();
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.edit().putString(VOTED_DATE, Preference.getUID(context) + simpleDateFormat.format(now)).apply();
sharedPreferences.edit().putInt(VOTED_VALUE, emotion).apply();
Log.d("info", "saved");
}
/**
* check if the user has voted the emotion today
*
* @return isVoted the boolean value
*/
public boolean hasVotedToday()
{
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String votedDayString = sharedPreferences.getString(VOTED_DATE, "01/01/2000");
return !TextUtils.isEmpty(votedDayString) && votedDayString.equals(Preference.getUID(context) + simpleDateFormat.format(new Date()));
}
}
| apache-2.0 |
dannil/scb-java-client | src/main/java/com/github/dannil/scbjavaclient/client/SCBClient.java | 12887 | /*
* Copyright 2014 Daniel Nilsson
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.github.dannil.scbjavaclient.client;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import com.github.dannil.scbjavaclient.client.agriculture.AgricultureClient;
import com.github.dannil.scbjavaclient.client.businessactivities.BusinessActivitiesClient;
import com.github.dannil.scbjavaclient.client.educationandresearch.EducationAndResearchClient;
import com.github.dannil.scbjavaclient.client.energy.EnergyClient;
import com.github.dannil.scbjavaclient.client.environment.EnvironmentClient;
import com.github.dannil.scbjavaclient.client.financialmarkets.FinancialMarketsClient;
import com.github.dannil.scbjavaclient.client.goodsandservices.GoodsAndServicesClient;
import com.github.dannil.scbjavaclient.client.labourmarket.LabourMarketClient;
import com.github.dannil.scbjavaclient.client.livingconditions.LivingConditionsClient;
import com.github.dannil.scbjavaclient.client.population.PopulationClient;
import com.github.dannil.scbjavaclient.client.pricesandconsumption.PricesAndConsumptionClient;
import com.github.dannil.scbjavaclient.client.publicfinances.PublicFinancesClient;
import com.github.dannil.scbjavaclient.client.transport.TransportClient;
import com.github.dannil.scbjavaclient.communication.URLEndpoint;
import com.github.dannil.scbjavaclient.communication.http.HttpStatusCode;
import com.github.dannil.scbjavaclient.communication.http.requester.AbstractRequester;
import com.github.dannil.scbjavaclient.communication.http.requester.GETRequester;
import com.github.dannil.scbjavaclient.constants.APIConstants;
import com.github.dannil.scbjavaclient.format.json.JsonAPIConfigTableFormat;
import com.github.dannil.scbjavaclient.format.json.JsonAPITableFormat;
import com.github.dannil.scbjavaclient.utility.QueryBuilder;
/**
* <p>Root client for the client hierarchy.</p>
*
* @since 0.0.2
*/
public class SCBClient extends AbstractContainerClient {
/**
* <p>Default constructor. Initializes values and creates sub-clients.</p>
*/
public SCBClient() {
super();
addClient("agriculture", new AgricultureClient());
addClient("businessactivities", new BusinessActivitiesClient());
addClient("educationandresearch", new EducationAndResearchClient());
addClient("energy", new EnergyClient());
addClient("environment", new EnvironmentClient());
addClient("financialmarkets", new FinancialMarketsClient());
addClient("goodsandservices", new GoodsAndServicesClient());
addClient("labourmarket", new LabourMarketClient());
addClient("livingconditions", new LivingConditionsClient());
addClient("population", new PopulationClient());
addClient("pricesandconsumption", new PricesAndConsumptionClient());
addClient("publicfinances", new PublicFinancesClient());
addClient("transport", new TransportClient());
}
/**
* <p>Overloaded constructor.</p>
*
* @param locale
* the locale for this client
*/
public SCBClient(Locale locale) {
this();
setLocale(locale);
}
/**
* <p>Retrieve the client for interacting with agriculture data.</p>
*
* @return a client for agriculture data
*/
public AgricultureClient agriculture() {
return (AgricultureClient) getClient("agriculture");
}
/**
* <p>Retrieve the client for interacting with business activities data.</p>
*
* @return a client for business activities data
*/
public BusinessActivitiesClient businessActivities() {
return (BusinessActivitiesClient) getClient("businessactivities");
}
/**
* <p>Retrieve the client for interacting with education and research data.</p>
*
* @return a client for education and research data
*/
public EducationAndResearchClient educationAndResearch() {
return (EducationAndResearchClient) getClient("educationandresearch");
}
/**
* <p>Retrieve the client for interacting with energy data.</p>
*
* @return a client for energy data
*/
public EnergyClient energy() {
return (EnergyClient) getClient("energy");
}
/**
* <p>Retrieve the client for interacting with environment data.</p>
*
* @return a client for environment data
*/
public EnvironmentClient environment() {
return (EnvironmentClient) getClient("environment");
}
/**
* <p>Retrieve the client for interacting with financial markets data.</p>
*
* @return a client for financial markets data
*/
public FinancialMarketsClient financialMarkets() {
return (FinancialMarketsClient) getClient("financialmarkets");
}
/**
* <p>Retrieve the client for interacting with goods and services data.</p>
*
* @return a client for goods and services data
*/
public GoodsAndServicesClient goodsAndServices() {
return (GoodsAndServicesClient) getClient("goodsandservices");
}
/**
* <p>Retrieve the client for interacting with labour market data.</p>
*
* @return a client for labour market data
*/
public LabourMarketClient labourMarket() {
return (LabourMarketClient) getClient("labourmarket");
}
/**
* <p>Retrieve the client for interacting with living conditions data.</p>
*
* @return a client for living conditions data
*/
public LivingConditionsClient livingConditions() {
return (LivingConditionsClient) getClient("livingconditions");
}
/**
* <p>Retrieve the client for interacting with population data.</p>
*
* @return a client for population data
*/
public PopulationClient population() {
return (PopulationClient) getClient("population");
}
/**
* <p>Retrieve the client for interacting with prices and consumption data.</p>
*
* @return a client for prices and consumption data
*/
public PricesAndConsumptionClient pricesAndConsumption() {
return (PricesAndConsumptionClient) getClient("pricesandconsumption");
}
/**
* <p>Retrieve the client for interacting with public finances data.</p>
*
* @return a client for public finances data
*/
public PublicFinancesClient publicFinances() {
return (PublicFinancesClient) getClient("publicfinances");
}
/**
* <p>Retrieve the client for interacting with transport data.</p>
*
* @return a client for transport data
*/
public TransportClient transport() {
return (TransportClient) getClient("transport");
}
/**
* <p>Fetches all the inputs for a given table from the API. If the table doesn't
* exist an empty <code>Map</code> will be returned.</p>
*
* @param table
* the table to fetch the inputs from
* @return a collection of all codes and their respective values for the given table
*
* @see com.github.dannil.scbjavaclient.format.json.JsonAPITableFormat#getPairs()
* JsonAPITableFormat#getPairs()
*/
public Map<String, Collection<String>> getInputs(String table) {
String url = getUrl() + table;
String json = doGetRequest(url);
if (json == null) {
return new HashMap<>();
}
return new JsonAPITableFormat(json).getPairs();
}
/**
* <p>Returns the list of the available regions for a given table. If the table
* doesn't exist an empty <code>List</code> will be returned.</p>
*
* @param table
* the table to retrieve the regions from
* @return a list of the available regions for the given table
*/
public List<String> getRegions(String table) {
String url = getUrl() + table;
String json = doGetRequest(url);
if (json == null) {
return new ArrayList<>();
}
JsonAPITableFormat format = new JsonAPITableFormat(json);
return format.getValues(APIConstants.REGION_CODE);
}
/**
* <p>Returns the list of the available times for a given table. If the table doesn't
* exist an empty <code>List</code> will be returned.</p>
*
* @param table
* the table to retrieve the times from
* @return a list of the available times for the given table
*/
public List<String> getTimes(String table) {
String url = getUrl() + table;
String json = doGetRequest(url);
if (json == null) {
return new ArrayList<>();
}
JsonAPITableFormat format = new JsonAPITableFormat(json);
return format.getValues(APIConstants.TIME_CODE);
}
/**
* <p>Fetch the JSON response from the specified table. As opposed to
* {@link #getRawData(String, Map)}, this method fetches all available data and
* therefore doesn't support selecting specific values before calling the API.</p>
*
* <p>Do note: as this method matches all content codes available on the API, the
* response is likely to be several times larger than the response when selecting
* values.</p>
*
* @param table
* the table to fetch data from
* @return a JSON string containing all available data in the specified table
*
* @see com.github.dannil.scbjavaclient.format.json.JsonAPITableFormat#getValues(String)
* JsonAPITableFormat#getValues(String)
*/
public String getRawData(String table) {
Map<String, Collection<?>> inputs = new HashMap<>();
return getRawData(table, inputs);
}
/**
* <p>Fetch the JSON response from the specified table. Useful if you're only
* interested in the raw JSON data.</p>
*
* @param table
* the table to fetch data from
* @param query
* the selected values
* @return a response from the API formatted as JSON
*/
public String getRawData(String table, Map<String, Collection<?>> query) {
return doPostRequest(getUrl() + table, QueryBuilder.build(query));
}
/**
* <p>Fetches the config from the API. Useful if you for example need to know how
* often you're allowed to make calls to the API, or the max size of the response.</p>
*
* @return the config
*/
public Map<String, String> getConfig() {
String url = getUrl() + "?config";
String json = doGetRequest(url);
JsonAPIConfigTableFormat format = new JsonAPIConfigTableFormat(json);
Map<String, String> config = new HashMap<>();
for (Entry<String, Collection<String>> entry : format.getPairs().entrySet()) {
Iterator<String> it = entry.getValue().iterator();
config.put(entry.getKey(), it.next());
}
return config;
}
/**
* <p>Checks if the specified language is supported by the API. See
* {@link #isSupportedLocale(Locale)} for implementation details.</p>
*
* @param language
* the language to check
* @return true if the language is supported, otherwise false
*/
public static boolean isSupportedLanguage(String language) {
Locale locale = new Locale(language);
return isSupportedLocale(locale);
}
/**
* <p>Checks if the specified <code>Locale</code> is supported by the API. The method
* performs a request to the API using the <code>Locale</code>'s language and checks
* if a HTTP resource exists matching the language.</p>
*
* @param locale
* the <code>Locale</code> to check
* @return true if the <code>Locale</code> is supported, otherwise false
*/
public static boolean isSupportedLocale(Locale locale) {
String url = URLEndpoint.getRootUrl(locale).toString();
AbstractRequester get = new GETRequester();
HttpResponse<String> response = get.getResponse(url);
return response.statusCode() == HttpStatusCode.OK.getCode();
}
@Override
public URLEndpoint getUrl() {
return getRootUrl();
}
}
| apache-2.0 |
SmasSive/MarvelSuperHeroComicViewr | app/src/androidTest/java/com/smassive/comicviewr/app/ApplicationTest.java | 358 | package com.smassive.comicviewr.app;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
IHTSDO/snow-owl | snomed/com.b2international.snowowl.snomed.importer/src/com/b2international/snowowl/snomed/importer/net4j/SnomedSubsetImportUtil.java | 10566 | /*
* Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.importer.net4j;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.b2international.commons.VerhoeffCheck;
import com.b2international.snowowl.snomed.importer.net4j.SnomedSubsetImportConfiguration.SubsetEntry;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
/**
* Provides utility methods for dsv imports.
*
*/
public class SnomedSubsetImportUtil {
/**
* Sets the properties (separator char, SNOMED CT concept ID column, line feed character) of the given subset entry.
*
* @param entry the subset entry which contains informations for the process.
* @return <code>true</code> if the file contains concept IDs which can be imported, <code>false</code> otherwise.
*/
public boolean setProperties(SubsetEntry entry) throws InvalidFormatException, IOException {
if ("xls".equals(entry.getExtension()) || "xlsx".equals(entry.getExtension())) {
return processExcelFile(entry);
} else {
return processTextFile(entry);
}
}
/**
* Updates properties where the value of the property is <code>null</code>.
*
* @param entry
*/
public void updateNullProperties(final SubsetEntry entry) {
if (null == entry.getEffectiveTime()) {
entry.setEffectiveTime("");
}
if (null == entry.getNamespace()) {
entry.setNamespace("");
}
if (null == entry.getFieldSeparator()) {
entry.setFieldSeparator("");
}
if (null == entry.getQuoteCharacter()) {
entry.setQuoteCharacter("");
}
if (null == entry.getLineFeedCharacter()) {
entry.setLineFeedCharacter("nl");
}
if (null == entry.getSheetNumber()) {
entry.setSheetNumber(-1);
}
}
/*
* Collects the header, line feed and separator characters and the column where SNOMED CT ID can be found.
*/
private boolean processTextFile(final SubsetEntry entry) throws IOException {
final FileInputStream inputStream = createFileInputStream(entry);
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
int lineNumber = 0;
boolean firstLine = true;
boolean hasConceptId = false;
while (null != (line = reader.readLine())) {
if (firstLine) {
setHeadings(line, entry);
setDefaultLineFeedCharacter(entry);
setDefaultSeparatorCharacter(line, entry);
firstLine = false;
}
if (setSnomedCtColumnId(line, lineNumber, entry)) {
hasConceptId = true;
break;
}
lineNumber++;
}
reader.close();
inputStream.close();
return hasConceptId;
}
// Sets the headings for XLS subset and the column number where the SNOMED CT id can be found
private boolean processExcelFile(final SubsetEntry entry) throws InvalidFormatException, IOException {
final FileInputStream inputStream = createFileInputStream(entry);
final Workbook workbook = WorkbookFactory.create(inputStream);
final List<Integer> list = getSheetAndFirstRowNumber(workbook, workbook.getNumberOfSheets());
if (null != list) {
final int sheetNumber = list.get(0);
final int firstRowNumber = list.get(1);
final Sheet sheet = workbook.getSheetAt(sheetNumber);
final List<String> row = collectRowValues(sheet.getRow(firstRowNumber));
entry.setHeadings(row);
entry.setSheetNumber(sheetNumber);
if (entry.isHasHeader()) {
Optional<String> match = FluentIterable.from(row).firstMatch(new Predicate<String>() {
@Override public boolean apply(String input) {
return input.contains("concept") && (input.contains("id") || input.contains("sctid"));
}
});
entry.setIdColumnNumber(match.isPresent() ? row.indexOf(match.get()) : 0); // default to first?
} else {
for (int i = 0; i < row.size(); i++) {
if (isConceptId(row.get(i).trim())) {
entry.setIdColumnNumber(i);
}
}
}
return true;
} else {
return false;
}
}
// Returns with the right sheet number where SNOMED CT can be found and with the first row number
private List<Integer> getSheetAndFirstRowNumber(final Workbook workbook, final int numberOfSheets) {
for (int i = 0; i < numberOfSheets; i++) {
final Sheet sheet = workbook.getSheetAt(i);
int firstRow = -1;
for (int j = 0; j < sheet.getLastRowNum(); j++) {
final List<String> row = collectRowValues(sheet.getRow(j));
for (final String value : row) {
if (!value.isEmpty() && -1 == firstRow) {
firstRow = j;
}
}
if (containsConceptId(row)) {
return Lists.newArrayList(i, firstRow);
}
}
}
return null;
}
// Checks if the given row contains SNOMED CT id
private boolean containsConceptId(final List<String> collectRowValues) {
for (String rowValue : collectRowValues) {
if (isConceptId(rowValue)) {
return true;
}
}
return false;
}
// Collects the row values
private List<String> collectRowValues(final Row row) {
List<String> list = Lists.newArrayList();
for (int i = 0; i < row.getLastCellNum(); i++) {
list.add(getStringValue(row.getCell(i, Row.CREATE_NULL_AS_BLANK)));
}
return list;
}
// Returns with the textual representation of the cell or empty string if the cell is empty (null)
private String getStringValue(final Cell cell) {
String value = "";
// empty cell
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
value = cell.getDateCellValue().toString();
} else {
value = Integer.toString((int) cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = Boolean.toString(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
value = cell.getCellFormula();
break;
}
return value;
}
// Sets the headers for a non XLS file
private void setHeadings(final String firstRow, final SubsetEntry entry) throws IOException {
final String [] headings;
if (firstRow.contains("\t")) {
headings = firstRow.split("\t");
} else if (firstRow.contains(",")) {
headings = firstRow.split(",");
} else if (firstRow.contains(";")) {
headings = firstRow.split(";");
} else if (firstRow.contains("|")) {
headings = firstRow.split("\\|");
} else {
headings = new String[] {firstRow};
}
if (!entry.getHeadings().isEmpty()) {
entry.getHeadings().clear();
}
if (entry.isHasHeader()) {
for (final String heading : headings) {
entry.getHeadings().add(heading);
}
} else {
for (int i = 0; i < headings.length; i++) {
entry.getHeadings().add(String.format("%d.", i));
}
}
}
// Sets the default separator character
private void setDefaultSeparatorCharacter(final String firstRow, final SubsetEntry entry) throws IOException {
if (firstRow.contains("\t")) {
entry.setFieldSeparator("\t");
} else if (firstRow.contains(",")) {
entry.setFieldSeparator(",");
} else if (firstRow.contains(";")) {
entry.setFieldSeparator(";");
} else if (firstRow.contains("|")) {
entry.setFieldSeparator("\\|");
} else {
entry.setFieldSeparator("");
}
}
// Sets the column number where the SNOMED CT id can be found
private boolean setSnomedCtColumnId(final String line, final int lineNumber, final SubsetEntry entry) {
final List<String> idCandidates;
if (StringUtils.isEmpty(entry.getFieldSeparator())) {
idCandidates = Arrays.asList(new String[] {line});
} else {
idCandidates = Arrays.asList(line.split(entry.getFieldSeparator()));
}
for (final String idCandidate : idCandidates) {
if (isConceptId(idCandidate)) {
entry.setFirstConceptRowNumber(lineNumber);
entry.setIdColumnNumber(idCandidates.indexOf(idCandidate));
return true;
}
}
return false;
}
// Sets the default separator character
private void setDefaultLineFeedCharacter(final SubsetEntry entry) throws IOException {
FileInputStream inputStream = createFileInputStream(entry);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
int i;
boolean isNewLineFound = false;
boolean containsCarriageReturn = false;
while (!isNewLineFound && -1 != (i = reader.read())) {
if (i == 13) {
containsCarriageReturn = true;
isNewLineFound = true;
}
if (i == 10) {
isNewLineFound = true;
}
}
if (containsCarriageReturn) {
entry.setLineFeedCharacter("nlc");
} else {
entry.setLineFeedCharacter("nl");
}
reader.close();
inputStream.close();
}
// Checks whether the given SNOMED CT id is a valid id
private boolean isConceptId(final String sctId) {
if (!Pattern.matches("^\\d*$", sctId) || sctId.length() < 6 || sctId.length() > 18) {
return false;
}
if (!VerhoeffCheck.validateLastChecksumDigit(sctId)) {
return false;
}
final String componentNatureId = sctId.substring(sctId.length()-2, sctId.length()-1);
if ("1".equals(componentNatureId)) {
return false;
}
if ("2".equals(componentNatureId)) {
return false;
}
return true;
}
private FileInputStream createFileInputStream(final SubsetEntry entry) throws FileNotFoundException {
return new FileInputStream(entry.getFileURL().getPath().replace("%20", " "));
}
} | apache-2.0 |
julienledem/redelm | parquet-column/src/main/java/parquet/example/data/simple/BooleanValue.java | 1067 | /**
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package parquet.example.data.simple;
import parquet.io.RecordConsumer;
public class BooleanValue extends Primitive {
private final boolean bool;
public BooleanValue(boolean bool) {
this.bool = bool;
}
@Override
public String toString() {
return String.valueOf(bool);
}
@Override
public boolean getBoolean() {
return bool;
}
@Override
public void writeValue(RecordConsumer recordConsumer) {
recordConsumer.addBoolean(bool);
}
}
| apache-2.0 |
jamalgithub/workdev | in28Minutes-javaInterview/src/main/java/com/in28minutes/java/others/garbagecollection/GarbageCollectionExamples.java | 274 | package com.in28minutes.java.others.garbagecollection;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class GarbageCollectionExamples {
void method() {
Calendar calendar = new GregorianCalendar(2000, 10, 30);
System.out.println(calendar);
}
}
| apache-2.0 |
afiantara/apache-wicket-1.5.7 | src/wicket-core/src/main/java/org/apache/wicket/markup/html/navigation/paging/PagingNavigation.java | 11276 | /*
* 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.wicket.markup.html.navigation.paging;
import java.util.Map;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.list.Loop;
import org.apache.wicket.markup.html.list.LoopItem;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.collections.MicroMap;
/**
* A navigation for a PageableListView that holds links to other pages of the PageableListView.
* <p>
* For each row (one page of the list of pages) a {@link PagingNavigationLink}will be added that
* contains a {@link Label} with the page number of that link (1..n).
*
* <pre>
*
* <td wicket:id="navigation">
* <a wicket:id="pageLink" href="SearchCDPage.html">
* <span wicket:id="pageNumber">1</span>
* </a>
* </td>
*
* </pre>
*
* thus renders like:
*
* <pre>
* 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
* </pre>
*
* </p>
* <p>
* Override method populateItem to customize the rendering of the navigation. For instance:
*
* <pre>
* protected void populateItem(LoopItem loopItem)
* {
* final int page = loopItem.getIteration();
* final PagingNavigationLink link = new PagingNavigationLink("pageLink", pageableListView, page);
* if (page > 0)
* {
* loopItem.add(new Label("separator", "|"));
* }
* else
* {
* loopItem.add(new Label("separator", ""));
* }
* link.add(new Label("pageNumber", String.valueOf(page + 1)));
* link.add(new Label("pageLabel", "page"));
* loopItem.add(link);
* }
* </pre>
*
* With:
*
* <pre>
* <span wicket:id="navigation">
* <span wicket:id="separator"></span>
* <a wicket:id="pageLink" href="#">
* <span wicket:id="pageLabel"></span><span wicket:id="pageNumber"></span>
* </a>
* </span>
* </pre>
*
* renders like:
*
* <pre>
* page1 | page2 | page3 | page4 | page5 | page6 | page7 | page8 | page9
* </pre>
*
* </p>
* Assuming a PageableListView with 1000 entries and not more than 10 lines shall be printed per
* page, the navigation bar would have 100 entries. Because this is not feasible PagingNavigation's
* navigation bar is pageable as well.
* <p>
* The page links displayed are automatically adjusted based on the number of page links to be
* displayed and a margin. The margin makes sure that the page link pointing to the current page is
* not at the left or right end of the page links currently printed and thus providing a better user
* experience.
* <p>
* Use setMargin() and setViewSize() to adjust the navigation's bar view size and margin.
* <p>
* Please
*
* @see PagingNavigator for a ready made component which already includes links to the first,
* previous, next and last page.
*
* @author Jonathan Locke
* @author Eelco Hillenius
* @author Juergen Donnerstag
*/
public class PagingNavigation extends Loop
{
private static final long serialVersionUID = 1L;
/** The PageableListView this navigation is navigating. */
protected IPageable pageable;
/** The label provider for the text that the links should be displaying. */
protected IPagingLabelProvider labelProvider;
/** Offset for the Loop */
private int startIndex;
/**
* Number of links on the left and/or right to keep the current page link somewhere near the
* middle.
*/
private int margin = -1;
/** Default separator between page numbers. Null: no separator. */
private String separator = null;
/**
* The maximum number of page links to show.
*/
private int viewSize = 10;
/**
* Constructor.
*
* @param id
* See Component
* @param pageable
* The underlying pageable component to navigate
*/
public PagingNavigation(final String id, final IPageable pageable)
{
this(id, pageable, null);
}
/**
* Constructor.
*
* @param id
* See Component
* @param pageable
* The underlying pageable component to navigate
* @param labelProvider
* The label provider for the text that the links should be displaying.
*/
public PagingNavigation(final String id, final IPageable pageable,
final IPagingLabelProvider labelProvider)
{
super(id, null);
this.pageable = pageable;
this.labelProvider = labelProvider;
startIndex = 0;
}
/**
* Gets the margin, default value is half the view size, unless explicitly set.
*
* @return the margin
*/
public int getMargin()
{
if (margin == -1 && viewSize != 0)
{
return viewSize / 2;
}
return margin;
}
/**
* Gets the seperator.
*
* @return the seperator
*/
public String getSeparator()
{
return separator;
}
/**
* Gets the view size (is fixed by user).
*
* @return view size
*/
public int getViewSize()
{
return viewSize;
}
/**
* view size of the navigation bar.
*
* @param size
*/
public void setViewSize(final int size)
{
viewSize = size;
}
/**
* Sets the margin.
*
* @param margin
* the margin
*/
public void setMargin(final int margin)
{
this.margin = margin;
}
/**
* Sets the seperator. Null meaning, no separator at all.
*
* @param separator
* the seperator
*/
public void setSeparator(final String separator)
{
this.separator = separator;
}
@Override
protected void onBeforeRender()
{
setDefaultModel(new Model<Integer>(pageable.getPageCount()));
// PagingNavigation itself (as well as the PageableListView)
// may have pages.
// The index of the first page link depends on the PageableListView's
// page currently printed.
setStartIndex();
super.onBeforeRender();
}
/**
* Allow subclasses replacing populateItem to calculate the current page number
*
* @return start index
*/
protected final int getStartIndex()
{
return startIndex;
}
/**
* Populate the current cell with a page link (PagingNavigationLink) enclosing the page number
* the link is pointing to. Subclasses may provide there own implementation adding more
* sophisticated page links.
*
* @see org.apache.wicket.markup.html.list.Loop#populateItem(Loop.LoopItem)
*/
@Override
protected void populateItem(final LoopItem loopItem)
{
// Get the index of page this link shall point to
final int pageIndex = getStartIndex() + loopItem.getIndex();
// Add a page link pointing to the page
final AbstractLink link = newPagingNavigationLink("pageLink", pageable, pageIndex);
link.add(new TitleAppender(pageIndex));
loopItem.add(link);
// Add a page number label to the list which is enclosed by the link
String label = "";
if (labelProvider != null)
{
label = labelProvider.getPageLabel(pageIndex);
}
else
{
label = String.valueOf(pageIndex + 1);
}
link.add(new Label("pageNumber", label));
}
/**
* Factory method for creating page number links.
*
* @param id
* the component id.
* @param pageable
* the pageable for the link
* @param pageIndex
* the page index the link points to
* @return the page navigation link.
*/
protected AbstractLink newPagingNavigationLink(String id, IPageable pageable, int pageIndex)
{
return new PagingNavigationLink<Void>(id, pageable, pageIndex);
}
/**
* Renders the page link. Add the separator if not the last page link
*
* @see Loop#renderItem(Loop.LoopItem)
*/
@Override
protected void renderItem(final LoopItem loopItem)
{
// Call default implementation
super.renderItem(loopItem);
// Add separator if not last page
if (separator != null && (loopItem.getIndex() != getIterations() - 1))
{
getResponse().write(separator);
}
}
/**
* Get the first page link to render. Adjust the first page link based on the current
* PageableListView page displayed.
*/
private void setStartIndex()
{
// Which startIndex are we currently using
int firstListItem = startIndex;
// How many page links shall be displayed
int viewSize = Math.min(getViewSize(), pageable.getPageCount());
int margin = getMargin();
// What is the PageableListView's page index to be displayed
int currentPage = pageable.getCurrentPage();
// Make sure the current page link index is within the current
// window taking the left and right margin into account
if (currentPage < (firstListItem + margin))
{
firstListItem = currentPage - margin;
}
else if ((currentPage >= (firstListItem + viewSize - margin)))
{
firstListItem = (currentPage + margin + 1) - viewSize;
}
// Make sure the first index is >= 0 and the last index is <=
// than the last page link index.
if ((firstListItem + viewSize) >= pageable.getPageCount())
{
firstListItem = pageable.getPageCount() - viewSize;
}
if (firstListItem < 0)
{
firstListItem = 0;
}
if ((viewSize != getIterations()) || (startIndex != firstListItem))
{
modelChanging();
// Tell the ListView what the new start index shall be
addStateChange();
startIndex = firstListItem;
setIterations(Math.min(viewSize, pageable.getPageCount()));
modelChanged();
// force all children to be re-rendered
removeAll();
}
}
/**
* Set the number of iterations.
*
* @param i
* the number of iterations
*/
private void setIterations(int i)
{
setDefaultModelObject(i);
}
/**
* Appends title attribute to navigation links
*
* @author igor.vaynberg
*/
private final class TitleAppender extends Behavior
{
private static final long serialVersionUID = 1L;
/** resource key for the message */
private static final String RES = "PagingNavigation.page";
/** page number */
private final int page;
/**
* Constructor
*
* @param page
* page number to use as the ${page} var
*/
public TitleAppender(int page)
{
this.page = page;
}
/** {@inheritDoc} */
@Override
public void onComponentTag(Component component, ComponentTag tag)
{
Map<String, String> vars = new MicroMap<String, String>("page",
String.valueOf(page + 1));
tag.put("title", PagingNavigation.this.getString(RES, Model.ofMap(vars)));
}
}
} | apache-2.0 |
afiantara/apache-wicket-1.5.7 | src/wicket-util/src/test/java/org/apache/wicket/util/LongEncoderTest.java | 1425 | /*
* 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.wicket.util;
import java.util.HashSet;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests {@link LongEncoder}
*
* @author igor
*/
public class LongEncoderTest
{
/**
* Tests the default alphabet included with the encoder
*/
@Test
public void defaultAlphabet()
{
Set<String> encoded = new HashSet<String>();
for (int i = -10000; i < 10000; i++)
{
String enc = LongEncoder.encode(i);
Assert.assertFalse("uniqueness: " + i, encoded.contains(enc));
encoded.add(enc);
Assert.assertEquals("decoding: " + i, i, LongEncoder.decode(enc));
}
}
}
| apache-2.0 |
RanaAhmedHamdy/Apple-Store | app/src/main/java/com/bigr/applestore/subcategories/SubCategoriesFragment.java | 3627 | package com.bigr.applestore.subcategories;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.bigr.applestore.cart.Cart;
import com.bigr.applestore.productslist.ProductsList;
import com.bigr.applestore.R;
import com.bigr.applestore.adapters.CustomListViewAdapter;
import com.bigr.applestore.models.Subcategory;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.util.ArrayList;
/**
* Created by Rana on 3/21/2016.
*/
public class SubCategoriesFragment extends Fragment {
private String mainCategory;
private ArrayList<Subcategory> subcategories;
private ListView subCategoriesList;
public SubCategoriesFragment() {
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sub_categories, container, false);
subcategories = new ArrayList<>();
mainCategory = getActivity().getIntent().getExtras().get("main_category").toString();
subCategoriesList = (ListView) rootView.findViewById(R.id.subcategories_list);
Firebase ref = new Firebase("https://appleluran.firebaseio.com/subcategories/" + mainCategory + "/");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("There are " + snapshot.getChildrenCount() + " blog posts");
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Subcategory subcategory = postSnapshot.getValue(Subcategory.class);
subcategories.add(subcategory);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(getActivity(),
R.layout.subcategories_list_item, subcategories);
subCategoriesList.setAdapter(adapter);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
subCategoriesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), ProductsList.class);
intent.putExtra("main_category", mainCategory);
intent.putExtra("subcategory", subCategoriesList.getItemAtPosition(position).toString().toLowerCase());
startActivity(intent);
}
});
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_cart, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.basket) {
Intent intent = new Intent(getActivity(), Cart.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
melix/japicmp-gradle-plugin | src/test/test-projects/filtering/field/src/main2/java/A.java | 108 | package me.champeau.gradle.japicmp;
public class A {
public String bad;
public String unchanged;
}
| apache-2.0 |
orika-mapper/orika | core/src/test/java/ma/glasnost/orika/test/community/Issue19TestCase.java | 1877 | /*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011-2013 Orika authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ma.glasnost.orika.test.community;
import org.junit.Assert;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.junit.Test;
/**
* Copying objects works only first time.
* <p>
*
* @see <a href="https://code.google.com/archive/p/orika/issues/19">https://code.google.com/archive/p/orika/</a>
*
*/
public class Issue19TestCase {
@Test
public void test() {
MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
A a = new A();
a.setAttribute("attribute");
B b = new B();
mapperFactory.getMapperFacade().map(a, b);
Assert.assertEquals(a.getAttribute(),b.getAttribute());
B b1 = new B();
mapperFactory.getMapperFacade().map(a, b1);
Assert.assertEquals(a.getAttribute(),b1.getAttribute());
}
static public class A {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
static public class B {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
}
| apache-2.0 |
hopjojo/PublicWidget | pickerview/src/main/java/com/bigkoo/pickerview/view/WheelOptions.java | 12735 | package com.bigkoo.pickerview.view;
import android.graphics.Typeface;
import android.view.View;
import com.bigkoo.pickerview.R;
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.lib.WheelView;
import com.bigkoo.pickerview.listener.OnItemSelectedListener;
import java.util.List;
public class WheelOptions<T> {
private View view;
private WheelView wv_option1;
private WheelView wv_option2;
private WheelView wv_option3;
private List<T> mOptions1Items;
private List<List<T>> mOptions2Items;
private List<T> N_mOptions2Items;
private List<List<List<T>>> mOptions3Items;
private List<T> N_mOptions3Items;
private boolean linkage;
private OnItemSelectedListener wheelListener_option1;
private OnItemSelectedListener wheelListener_option2;
//文字的颜色和分割线的颜色
int textColorOut;
int textColorCenter;
int dividerColor;
private WheelView.DividerType dividerType;
// 条目间距倍数
float lineSpacingMultiplier = 1.6F;
public View getView() {
return view;
}
public void setView(View view) {
this.view = view;
}
public WheelOptions(View view, Boolean linkage) {
super();
this.linkage = linkage;
this.view = view;
wv_option1 = (WheelView) view.findViewById(R.id.options1);// 初始化时显示的数据
wv_option2 = (WheelView) view.findViewById(R.id.options2);
wv_option3 = (WheelView) view.findViewById(R.id.options3);
}
public void setPicker(List<T> options1Items,
List<List<T>> options2Items,
List<List<List<T>>> options3Items) {
this.mOptions1Items = options1Items;
this.mOptions2Items = options2Items;
this.mOptions3Items = options3Items;
int len = ArrayWheelAdapter.DEFAULT_LENGTH;
if (this.mOptions3Items == null)
len = 8;
if (this.mOptions2Items == null)
len = 12;
// 选项1
wv_option1.setAdapter(new ArrayWheelAdapter(mOptions1Items, len));// 设置显示数据
wv_option1.setCurrentItem(0);// 初始化时显示的数据
// 选项2
if (mOptions2Items != null)
wv_option2.setAdapter(new ArrayWheelAdapter(mOptions2Items.get(0)));// 设置显示数据
wv_option2.setCurrentItem(wv_option1.getCurrentItem());// 初始化时显示的数据
// 选项3
if (mOptions3Items != null)
wv_option3.setAdapter(new ArrayWheelAdapter(mOptions3Items.get(0).get(0)));// 设置显示数据
wv_option3.setCurrentItem(wv_option3.getCurrentItem());
wv_option1.setIsOptions(true);
wv_option2.setIsOptions(true);
wv_option3.setIsOptions(true);
if (this.mOptions2Items == null)
wv_option2.setVisibility(View.GONE);
if (this.mOptions3Items == null)
wv_option3.setVisibility(View.GONE);
// 联动监听器
wheelListener_option1 = new OnItemSelectedListener() {
@Override
public void onItemSelected(int index) {
int opt2Select = 0;
if (mOptions2Items != null) {
opt2Select = wv_option2.getCurrentItem();//上一个opt2的选中位置
//新opt2的位置,判断如果旧位置没有超过数据范围,则沿用旧位置,否则选中最后一项
opt2Select = opt2Select >= mOptions2Items.get(index).size() - 1 ? mOptions2Items.get(index).size() - 1 : opt2Select;
wv_option2.setAdapter(new ArrayWheelAdapter(mOptions2Items.get(index)));
wv_option2.setCurrentItem(opt2Select);
}
if (mOptions3Items != null) {
wheelListener_option2.onItemSelected(opt2Select);
}
}
};
wheelListener_option2 = new OnItemSelectedListener() {
@Override
public void onItemSelected(int index) {
if (mOptions3Items != null) {
int opt1Select = wv_option1.getCurrentItem();
opt1Select = opt1Select >= mOptions3Items.size() - 1 ? mOptions3Items.size() - 1 : opt1Select;
index = index >= mOptions2Items.get(opt1Select).size() - 1 ? mOptions2Items.get(opt1Select).size() - 1 : index;
int opt3 = wv_option3.getCurrentItem();//上一个opt3的选中位置
//新opt3的位置,判断如果旧位置没有超过数据范围,则沿用旧位置,否则选中最后一项
opt3 = opt3 >= mOptions3Items.get(opt1Select).get(index).size() - 1 ? mOptions3Items.get(opt1Select).get(index).size() - 1 : opt3;
wv_option3.setAdapter(new ArrayWheelAdapter(mOptions3Items
.get(wv_option1.getCurrentItem()).get(index)));
wv_option3.setCurrentItem(opt3);
}
}
};
// 添加联动监听
if (options2Items != null && linkage)
wv_option1.setOnItemSelectedListener(wheelListener_option1);
if (options3Items != null && linkage)
wv_option2.setOnItemSelectedListener(wheelListener_option2);
}
//不联动情况下
public void setNPicker(List<T> options1Items,
List<T> options2Items,
List<T> options3Items) {
this.mOptions1Items = options1Items;
this.N_mOptions2Items = options2Items;
this.N_mOptions3Items = options3Items;
int len = ArrayWheelAdapter.DEFAULT_LENGTH;
if (this.N_mOptions3Items == null)
len = 8;
if (this.N_mOptions2Items == null)
len = 12;
// 选项1
wv_option1.setAdapter(new ArrayWheelAdapter(mOptions1Items, len));// 设置显示数据
wv_option1.setCurrentItem(0);// 初始化时显示的数据
// 选项2
if (N_mOptions2Items != null)
wv_option2.setAdapter(new ArrayWheelAdapter(N_mOptions2Items));// 设置显示数据
wv_option2.setCurrentItem(wv_option1.getCurrentItem());// 初始化时显示的数据
// 选项3
if (N_mOptions3Items != null)
wv_option3.setAdapter(new ArrayWheelAdapter(N_mOptions3Items));// 设置显示数据
wv_option3.setCurrentItem(wv_option3.getCurrentItem());
wv_option1.setIsOptions(true);
wv_option2.setIsOptions(true);
wv_option3.setIsOptions(true);
if (this.N_mOptions2Items == null)
wv_option2.setVisibility(View.GONE);
if (this.N_mOptions3Items == null)
wv_option3.setVisibility(View.GONE);
}
public void setTextContentSize(int textSize) {
wv_option1.setTextSize(textSize);
wv_option2.setTextSize(textSize);
wv_option3.setTextSize(textSize);
}
private void setTextColorOut() {
wv_option1.setTextColorOut(textColorOut);
wv_option2.setTextColorOut(textColorOut);
wv_option3.setTextColorOut(textColorOut);
}
private void setTextColorCenter() {
wv_option1.setTextColorCenter(textColorCenter);
wv_option2.setTextColorCenter(textColorCenter);
wv_option3.setTextColorCenter(textColorCenter);
}
private void setDividerColor() {
wv_option1.setDividerColor(dividerColor);
wv_option2.setDividerColor(dividerColor);
wv_option3.setDividerColor(dividerColor);
}
private void setDividerType() {
wv_option1.setDividerType(dividerType);
wv_option2.setDividerType(dividerType);
wv_option3.setDividerType(dividerType);
}
private void setLineSpacingMultiplier() {
wv_option1.setLineSpacingMultiplier(lineSpacingMultiplier);
wv_option2.setLineSpacingMultiplier(lineSpacingMultiplier);
wv_option3.setLineSpacingMultiplier(lineSpacingMultiplier);
}
/**
* 设置选项的单位
*
* @param label1 单位
* @param label2 单位
* @param label3 单位
*/
public void setLabels(String label1, String label2, String label3) {
if (label1 != null)
wv_option1.setLabel(label1);
if (label2 != null)
wv_option2.setLabel(label2);
if (label3 != null)
wv_option3.setLabel(label3);
}
/**
* 设置是否循环滚动
*
* @param cyclic 是否循环
*/
public void setCyclic(boolean cyclic) {
wv_option1.setCyclic(cyclic);
wv_option2.setCyclic(cyclic);
wv_option3.setCyclic(cyclic);
}
/**
* 设置字体样式
*
* @param font 系统提供的几种样式
*/
public void setTypeface (Typeface font) {
wv_option1.setTypeface(font);
wv_option2.setTypeface(font);
wv_option3.setTypeface(font);
}
/**
* 分别设置第一二三级是否循环滚动
*
* @param cyclic1,cyclic2,cyclic3 是否循环
*/
public void setCyclic(boolean cyclic1, boolean cyclic2, boolean cyclic3) {
wv_option1.setCyclic(cyclic1);
wv_option2.setCyclic(cyclic2);
wv_option3.setCyclic(cyclic3);
}
/**
* 返回当前选中的结果对应的位置数组 因为支持三级联动效果,分三个级别索引,0,1,2。
* 在快速滑动未停止时,点击确定按钮,会进行判断,如果匹配数据越界,则设为0,防止index出错导致崩溃。
*
* @return 索引数组
*/
public int[] getCurrentItems() {
int[] currentItems = new int[3];
currentItems[0] = wv_option1.getCurrentItem();
if (mOptions2Items!=null&&mOptions2Items.size()>0){//非空判断
currentItems[1] = wv_option2.getCurrentItem()>(mOptions2Items.get(currentItems[0]).size()-1)?0:wv_option2.getCurrentItem();
}else {
currentItems[1] = wv_option2.getCurrentItem();
}
if (mOptions3Items!=null&&mOptions3Items.size()>0){//非空判断
currentItems[2] = wv_option3.getCurrentItem()>(mOptions3Items.get(currentItems[0]).get(currentItems[1]).size()-1)?0:wv_option3.getCurrentItem();
}else {
currentItems[2] = wv_option3.getCurrentItem();
}
return currentItems;
}
public void setCurrentItems(int option1, int option2, int option3) {
if (linkage) {
itemSelected(option1, option2, option3);
}
wv_option1.setCurrentItem(option1);
wv_option2.setCurrentItem(option2);
wv_option3.setCurrentItem(option3);
}
private void itemSelected(int opt1Select, int opt2Select, int opt3Select) {
if (mOptions2Items != null) {
wv_option2.setAdapter(new ArrayWheelAdapter(mOptions2Items
.get(opt1Select)));
wv_option2.setCurrentItem(opt2Select);
}
if (mOptions3Items != null) {
wv_option3.setAdapter(new ArrayWheelAdapter(mOptions3Items
.get(opt1Select).get(
opt2Select)));
wv_option3.setCurrentItem(opt3Select);
}
}
/**
* 设置间距倍数,但是只能在1.2-2.0f之间
*
* @param lineSpacingMultiplier
*/
public void setLineSpacingMultiplier(float lineSpacingMultiplier) {
this.lineSpacingMultiplier = lineSpacingMultiplier;
setLineSpacingMultiplier();
}
/**
* 设置分割线的颜色
*
* @param dividerColor
*/
public void setDividerColor(int dividerColor) {
this.dividerColor = dividerColor;
setDividerColor();
}
/**
* 设置分割线的类型
*
* @param dividerType
*/
public void setDividerType(WheelView.DividerType dividerType) {
this.dividerType = dividerType;
setDividerType();
}
/**
* 设置分割线之间的文字的颜色
*
* @param textColorCenter
*/
public void setTextColorCenter(int textColorCenter) {
this.textColorCenter = textColorCenter;
setTextColorCenter();
}
/**
* 设置分割线以外文字的颜色
*
* @param textColorOut
*/
public void setTextColorOut(int textColorOut) {
this.textColorOut = textColorOut;
setTextColorOut();
}
/**
* Label 是否只显示中间选中项的
*
* @param isCenterLabel
*/
public void isCenterLabel(Boolean isCenterLabel) {
wv_option1.isCenterLabel(isCenterLabel);
wv_option2.isCenterLabel(isCenterLabel);
wv_option3.isCenterLabel(isCenterLabel);
}
}
| apache-2.0 |
extremeCrazyCoder/dsworkbench | Core/src/main/java/de/tor/tribes/util/bb/TroopListFormatter.java | 2847 | /*
* Copyright 2015 Torridity.
*
* 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 de.tor.tribes.util.bb;
import de.tor.tribes.util.troops.VillageTroopsHolder;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
/**
* @author Torridity
*/
public class TroopListFormatter extends BasicFormatter<VillageTroopsHolder> {
private static final String[] VARIABLES = new String[] {LIST_START, LIST_END, ELEMENT_COUNT, ELEMENT_ID};
private static final String TEMPLATE_PROPERTY = "troops.list.bbexport.template";
@Override
public String formatElements(List<VillageTroopsHolder> pElements, boolean pExtended) {
StringBuilder b = new StringBuilder();
int cnt = 1;
NumberFormat f = getNumberFormatter(pElements.size());
String beforeList = getHeader();
String listItemTemplate = getLineTemplate();
String afterList = getFooter();
String replacedStart = StringUtils.replaceEach(beforeList, new String[] {ELEMENT_COUNT}, new String[] {f.format(pElements.size())});
VillageTroopsHolder dummyHolder = new VillageTroopsHolder();
//replace unit icons
replacedStart = StringUtils.replaceEach(replacedStart, dummyHolder.getBBVariables(), dummyHolder.getReplacements(pExtended));
b.append(replacedStart).append("\n");
formatElementsCore(b, pElements, pExtended, listItemTemplate, f);
String replacedEnd = StringUtils.replaceEach(afterList, new String[] {ELEMENT_COUNT}, new String[] {f.format(pElements.size())});
b.append(replacedEnd);
return b.toString();
}
@Override
public String getPropertyKey() {
return TEMPLATE_PROPERTY;
}
@Override
public String getStandardTemplate() {
return VillageTroopsHolder.getStandardTemplate();
}
@Override
public String[] getTemplateVariables() {
List<String> vars = new LinkedList<>();
Collections.addAll(vars, VARIABLES);
Collections.addAll(vars, new VillageTroopsHolder().getBBVariables());
return vars.toArray(new String[vars.size()]);
}
@Override
public Class<VillageTroopsHolder> getConvertableType() {
return VillageTroopsHolder.class;
}
}
| apache-2.0 |
priimak/cloudkeeper | cloudkeeper-core/cloudkeeper-model/src/main/java/com/svbio/cloudkeeper/model/beans/element/module/MutableProxyModule.java | 2597 | package com.svbio.cloudkeeper.model.beans.element.module;
import com.svbio.cloudkeeper.model.bare.element.module.BareModuleVisitor;
import com.svbio.cloudkeeper.model.bare.element.module.BareProxyModule;
import com.svbio.cloudkeeper.model.beans.CopyOption;
import com.svbio.cloudkeeper.model.beans.element.MutableQualifiedNamable;
import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;
@XmlRootElement(name = "proxy-module")
public final class MutableProxyModule extends MutableModule<MutableProxyModule> implements BareProxyModule {
private static final long serialVersionUID = 5394012602906125856L;
@Nullable private MutableQualifiedNamable declaration;
public MutableProxyModule() { }
private MutableProxyModule(BareProxyModule original, CopyOption[] copyOptions) {
super(original, copyOptions);
declaration = MutableQualifiedNamable.copyOf(original.getDeclaration(), copyOptions);
}
@Nullable
public static MutableProxyModule copyOfProxyModule(@Nullable BareProxyModule original, CopyOption... copyOptions) {
return original == null
? null
: new MutableProxyModule(original, copyOptions);
}
@Override
public boolean equals(@Nullable Object otherObject) {
if (this == otherObject) {
return true;
} else if (!super.equals(otherObject)) {
return false;
}
return Objects.equals(declaration, ((MutableProxyModule) otherObject).declaration);
}
@Override
public int hashCode() {
return 31 * super.hashCode() + Objects.hashCode(declaration);
}
@Override
public String toString() {
return BareProxyModule.Default.toString(this);
}
@Override
protected MutableProxyModule self() {
return this;
}
@Override
@Nullable
public <T, P> T accept(BareModuleVisitor<T, P> visitor, @Nullable P parameter) {
return visitor.visitLinkedModule(this, parameter);
}
@XmlAttribute(name = "ref")
@Override
@Nullable
public MutableQualifiedNamable getDeclaration() {
return declaration;
}
public MutableProxyModule setDeclaration(@Nullable MutableQualifiedNamable declaration) {
this.declaration = declaration;
return this;
}
public MutableProxyModule setDeclaration(String declarationName) {
return setDeclaration(
new MutableQualifiedNamable().setQualifiedName(declarationName)
);
}
}
| apache-2.0 |
kstenschke/shifter-plugin | src/com/kstenschke/shifter/models/shiftable_types/Css.java | 4628 | /*
* Copyright Kay Stenschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kstenschke.shifter.models.shiftable_types;
import com.kstenschke.shifter.models.comparators.CssAttributesStyleLineComparator;
import com.kstenschke.shifter.utils.UtilsTextual;
import java.util.*;
import java.util.regex.Pattern;
import static org.apache.commons.lang.StringUtils.trim;
/**
* Cascading Stylesheet - sort all attributes in all selectors alphabetically
*/
public class Css {
public static final String ACTION_TEXT = "Shift CSS";
public static String getShifted(String value) {
return value.contains("{") && value.contains("}")
? sortAttributeStyleLinesInsideSelectors(value)
: sortAttributeStyleLines(value);
}
private static String sortAttributeStyleLinesInsideSelectors(String value) {
// Split CSS into groups of attribute-style lines per selector
String[] attributeGroups = value.split("([^\r\n,{}]+)(,(?=[^}]*\\{)|\\s*\\{)");
String[] attributeGroupsSorted = new String[attributeGroups.length];
// 1. Collect groups of attribute-style lines per selector
int indexMatch = 0;
for (String attributeGroup : attributeGroups) {
if (indexMatch > 0) {
List<String> lines = splitAttributesIntoLines(attributeGroup);
prepareAttributeStyleLinesForConcat(lines);
sortAttributeStyles(lines);
attributeGroupsSorted[indexMatch] = UtilsTextual.rtrim(UtilsTextual.joinLines(lines).toString());
value = value.replaceFirst(Pattern.quote(attributeGroup), "###SHIFTERMARKER" + indexMatch + "###");
}
indexMatch++;
}
// 2. Replace attribute-rule groups by their sorted variant
for (int indexMarker = 1; indexMarker < indexMatch; indexMarker++) {
value = value.replaceFirst(
"###SHIFTERMARKER" + indexMarker + "###",
attributeGroupsSorted[indexMarker]);
}
return value;
}
/**
* Sort given lines (each being an attribute-style definition tupel, like: "<attribute>:<style>")
*
* @param value
* @return String
*/
private static String sortAttributeStyleLines(String value) {
List<String> lines = splitAttributesIntoLines(value);
if (doAllButLastLineEndWithSemicolon(lines)) {
lines.set(lines.size() - 1, UtilsTextual.rtrim(lines.get(lines.size() - 1)) + ";");
}
sortAttributeStyles(lines);
return UtilsTextual.rtrim(UtilsTextual.joinLines(lines).toString());
}
private static boolean doAllButLastLineEndWithSemicolon(List<String> lines) {
int amountLines = lines.size();
int index = 0;
for (String line : lines) {
if (index >= amountLines - 1) {
return !trim(line).endsWith(";");
}
if (!trim(line).endsWith(";")) {
return false;
}
index++;
}
return true;
}
private static List<String> splitAttributesIntoLines(String str) {
return Arrays.asList(str.split("\\n"));
}
/**
* Sort CSS lines containing "<attribute>:<style>"
*
* @param list Passed by reference
*/
private static void sortAttributeStyles(List<String> list) {
list.sort(new CssAttributesStyleLineComparator());
}
/**
* Ensure that all attribute lines end w/ ";\n"
*
* @param lines Lists are passed by reference
*/
private static void prepareAttributeStyleLinesForConcat(List<String> lines) {
int index = 0;
for (String line : lines) {
String trimmed = trim(line);
if (!trimmed.isEmpty() && !"}".equals(trimmed)) {
line = UtilsTextual.rtrim(line);
if (!line.endsWith(";")) {
line = line + ";";
}
line = line + "\n";
}
lines.set(index, line);
index++;
}
}
}
| apache-2.0 |
neo4j/neo4j-java-driver | driver/src/main/java/org/neo4j/driver/internal/handlers/pulln/AutoPullResponseHandler.java | 9854 | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.driver.internal.handlers.pulln;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.neo4j.driver.Query;
import org.neo4j.driver.Record;
import org.neo4j.driver.internal.handlers.PullAllResponseHandler;
import org.neo4j.driver.internal.handlers.PullResponseCompletionListener;
import org.neo4j.driver.internal.handlers.RunResponseHandler;
import org.neo4j.driver.internal.spi.Connection;
import org.neo4j.driver.internal.util.Iterables;
import org.neo4j.driver.internal.util.MetadataExtractor;
import org.neo4j.driver.summary.ResultSummary;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.neo4j.driver.internal.handlers.pulln.FetchSizeUtil.UNLIMITED_FETCH_SIZE;
import static org.neo4j.driver.internal.util.Futures.completedWithNull;
import static org.neo4j.driver.internal.util.Futures.failedFuture;
/**
* Built on top of {@link BasicPullResponseHandler} to be able to pull in batches.
* It is exposed as {@link PullAllResponseHandler} as it can automatically pull when running out of records locally.
*/
public class AutoPullResponseHandler extends BasicPullResponseHandler implements PullAllResponseHandler
{
private static final Queue<Record> UNINITIALIZED_RECORDS = Iterables.emptyQueue();
private final long fetchSize;
private final long lowRecordWatermark;
private final long highRecordWatermark;
// initialized lazily when first record arrives
private Queue<Record> records = UNINITIALIZED_RECORDS;
private ResultSummary summary;
private Throwable failure;
private boolean isAutoPullEnabled = true;
private CompletableFuture<Record> recordFuture;
private CompletableFuture<ResultSummary> summaryFuture;
public AutoPullResponseHandler(Query query, RunResponseHandler runResponseHandler, Connection connection, MetadataExtractor metadataExtractor,
PullResponseCompletionListener completionListener, long fetchSize )
{
super(query, runResponseHandler, connection, metadataExtractor, completionListener );
this.fetchSize = fetchSize;
//For pull everything ensure conditions for disabling auto pull are never met
if ( fetchSize == UNLIMITED_FETCH_SIZE )
{
this.highRecordWatermark = Long.MAX_VALUE;
this.lowRecordWatermark = Long.MAX_VALUE;
}
else
{
this.highRecordWatermark = (long) (fetchSize * 0.7);
this.lowRecordWatermark = (long) (fetchSize * 0.3);
}
installRecordAndSummaryConsumers();
}
private void installRecordAndSummaryConsumers()
{
installRecordConsumer( ( record, error ) -> {
if ( record != null )
{
enqueueRecord( record );
completeRecordFuture( record );
}
// if ( error != null ) Handled by summary.error already
if ( record == null && error == null )
{
// complete
completeRecordFuture( null );
}
} );
installSummaryConsumer( ( summary, error ) -> {
if ( error != null )
{
handleFailure( error );
}
if ( summary != null )
{
this.summary = summary;
completeSummaryFuture( summary );
}
if ( error == null && summary == null ) // has_more
{
if ( isAutoPullEnabled )
{
request( fetchSize );
}
}
} );
}
private void handleFailure( Throwable error )
{
// error has not been propagated to the user, remember it
if ( !failRecordFuture( error ) && !failSummaryFuture( error ) )
{
failure = error;
}
}
public synchronized CompletionStage<Record> peekAsync()
{
Record record = records.peek();
if ( record == null )
{
if ( isDone() )
{
return completedWithValueIfNoFailure( null );
}
if ( recordFuture == null )
{
recordFuture = new CompletableFuture<>();
}
return recordFuture;
}
else
{
return completedFuture( record );
}
}
public synchronized CompletionStage<Record> nextAsync()
{
return peekAsync().thenApply( ignore -> dequeueRecord() );
}
public synchronized CompletionStage<ResultSummary> consumeAsync()
{
records.clear();
if ( isDone() )
{
return completedWithValueIfNoFailure( summary );
}
else
{
cancel();
if ( summaryFuture == null )
{
summaryFuture = new CompletableFuture<>();
}
return summaryFuture;
}
}
public synchronized <T> CompletionStage<List<T>> listAsync( Function<Record,T> mapFunction )
{
return pullAllAsync().thenApply( summary -> recordsAsList( mapFunction ) );
}
@Override
public synchronized CompletionStage<Throwable> pullAllFailureAsync()
{
return pullAllAsync().handle( ( ignore, error ) -> error );
}
@Override
public void prePopulateRecords()
{
request( fetchSize );
}
private synchronized CompletionStage<ResultSummary> pullAllAsync()
{
if ( isDone() )
{
return completedWithValueIfNoFailure( summary );
}
else
{
request( UNLIMITED_FETCH_SIZE );
if ( summaryFuture == null )
{
summaryFuture = new CompletableFuture<>();
}
return summaryFuture;
}
}
private void enqueueRecord( Record record )
{
if ( records == UNINITIALIZED_RECORDS )
{
records = new ArrayDeque<>();
}
records.add( record );
// too many records in the queue, pause auto request gathering
if ( records.size() > highRecordWatermark )
{
isAutoPullEnabled = false;
}
}
private Record dequeueRecord()
{
Record record = records.poll();
if ( records.size() <= lowRecordWatermark )
{
//if not in streaming state we need to restart streaming
if ( state() != State.STREAMING_STATE )
{
request( fetchSize );
}
isAutoPullEnabled = true;
}
return record;
}
private <T> List<T> recordsAsList( Function<Record,T> mapFunction )
{
if ( !isDone() )
{
throw new IllegalStateException( "Can't get records as list because SUCCESS or FAILURE did not arrive" );
}
List<T> result = new ArrayList<>( records.size() );
while ( !records.isEmpty() )
{
Record record = records.poll();
result.add( mapFunction.apply( record ) );
}
return result;
}
private Throwable extractFailure()
{
if ( failure == null )
{
throw new IllegalStateException( "Can't extract failure because it does not exist" );
}
Throwable error = failure;
failure = null; // propagate failure only once
return error;
}
private void completeRecordFuture( Record record )
{
if ( recordFuture != null )
{
CompletableFuture<Record> future = recordFuture;
recordFuture = null;
future.complete( record );
}
}
private void completeSummaryFuture( ResultSummary summary )
{
if ( summaryFuture != null )
{
CompletableFuture<ResultSummary> future = summaryFuture;
summaryFuture = null;
future.complete( summary );
}
}
private boolean failRecordFuture( Throwable error )
{
if ( recordFuture != null )
{
CompletableFuture<Record> future = recordFuture;
recordFuture = null;
future.completeExceptionally( error );
return true;
}
return false;
}
private boolean failSummaryFuture( Throwable error )
{
if ( summaryFuture != null )
{
CompletableFuture<ResultSummary> future = summaryFuture;
summaryFuture = null;
future.completeExceptionally( error );
return true;
}
return false;
}
private <T> CompletionStage<T> completedWithValueIfNoFailure( T value )
{
if ( failure != null )
{
return failedFuture( extractFailure() );
}
else if ( value == null )
{
return completedWithNull();
}
else
{
return completedFuture( value );
}
}
}
| apache-2.0 |
CarloAntonio/Game-Of-Flicks | GameOfFlicks/app/src/androidTest/java/com/riskitbiskit/gameofflicks/ExampleInstrumentedTest.java | 762 | package com.riskitbiskit.gameofflicks;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.riskitbiskit.gameofflicks", appContext.getPackageName());
}
}
| apache-2.0 |
murreIsCoding/coolweather | src/com/coolweather/app/util/HttpUtil.java | 1287 | package com.coolweather.app.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
public static void sendHttpRequest(final String address ,final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection = null ;
try {
URL url =new URL(address);
connection =(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response =new StringBuilder();
String line ;
while((line = reader.readLine())!=null){
response.append(line);
}
if(listener != null){
listener.onFinish(response.toString());
}
} catch (Exception e) {
// TODO: handle exception
if(listener != null){
listener.onError(e);
}
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
| apache-2.0 |
lathil/Ptoceti | com.ptoceti.osgi.pi/src/main/java/com/ptoceti/osgi/pi/impl/ConfigReader.java | 6022 | package com.ptoceti.osgi.pi.impl;
/*
* #%L
* **********************************************************************
* ORGANIZATION : ptoceti
* PROJECT : Pi
* FILENAME : ConfigReader.java
*
* This file is part of the Ptoceti project. More information about
* this project can be found here: http://www.ptoceti.com/
* **********************************************************************
* %%
* Copyright (C) 2013 - 2015 ptoceti
* %%
* 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.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.kxml2.io.KXmlParser;
import org.osgi.service.log.LogService;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public class ConfigReader {
public static final String PinsElement = "Pins";
public static final String PinElement = "Pin";
public static final String IdentificationElement = "Identification";
public static final String ScopeElement = "Scope";
public static final String DirectionIn = "DirectionIn";
public static final String Digital = "Digital";
public static final String PinNumber = "PinNumber";
public static final String UnitElement = "Unit";
public static final String ScalingElement = "Scale";
public static final String OffsetElement = "Offset";
/**
* A url to the configFile
*/
URL configUrl = null;
public ConfigReader(URL configFileUrl){
configUrl = configFileUrl;
}
public ConfigReader(String configFilePath) {
if (configFilePath.startsWith("file:")) {
configFilePath = configFilePath.substring("file:".length());
File file = new File(configFilePath);
if (file.exists() && !file.isDirectory()) {
try {
configUrl = file.toURI().toURL();
} catch (MalformedURLException e) {
Activator.log(LogService.LOG_ERROR,"Error creating url for file path: " + configFilePath);
}
} else {
Activator.log( LogService.LOG_ERROR, "Error reading modbusdevice file at: " + file.getAbsolutePath());
}
} else {
configUrl = Activator.getResourceStream(configFilePath);
}
}
public List<PinConfig> initialiseDataFromConfigFile() throws XmlPullParserException, IOException{
List<PinConfig> pins = null;
if (configUrl != null) {
InputStream configFileStream = configUrl.openStream();
pins = parse(configFileStream);
configFileStream.close();
}
return pins;
}
private List<PinConfig> parse(InputStream configFileStream) throws XmlPullParserException, IOException{
List<PinConfig> pins = null;
KXmlParser parser = new KXmlParser();
// We set to null the encoding type. The parser should then dected it from the file stream.
parser.setInput(configFileStream, null);
int eventType = parser.getEventType();
while( eventType != XmlPullParser.END_DOCUMENT) {
if( eventType == XmlPullParser.START_TAG){
if( parser.getName().equals( PinsElement)) {
// We move to the next element inside the Wires element
parser.next();
pins = parsePinsElement(parser);
break;
}
}
eventType = parser.next();
}
return pins;
}
private List<PinConfig> parsePinsElement(KXmlParser parser) throws XmlPullParserException, IOException {
List<PinConfig> pins = new ArrayList<PinConfig>();
int eventType = parser.getEventType();
while( eventType != XmlPullParser.END_TAG) {
if(eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals(PinElement)) {
pins.add(this.parsePinElement(parser));
}
}
eventType = parser.next();
}
return pins;
}
private PinConfig parsePinElement(KXmlParser parser) throws XmlPullParserException, IOException {
PinConfig pin = new PinConfig();
int eventType = parser.getEventType();
while( eventType != XmlPullParser.END_TAG) {
if(eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals(IdentificationElement)) {
pin.setIdentification(parseGetText(parser));
} else if (parser.getName().equals(ScopeElement)) {
pin.setScope(parseGetText(parser));
} else if (parser.getName().equals(UnitElement)) {
pin.setUnit(parseGetText(parser));
} else if (parser.getName().equals(ScalingElement)) {
pin.setScale(Double.valueOf(parseGetText(parser)));
} else if (parser.getName().equals(OffsetElement)) {
pin.setOffset(Double.valueOf(parseGetText(parser)));
} else if (parser.getName().equals(DirectionIn)) {
pin.setDirectionIn(Boolean.valueOf(parseGetText(parser)));
} else if (parser.getName().equals(Digital)) {
pin.setDigital(Boolean.valueOf(parseGetText(parser)));
} else if (parser.getName().equals(PinNumber)) {
pin.setPinNumber(Integer.valueOf(parseGetText(parser)));
}
}
eventType = parser.next();
}
return pin;
}
private String parseGetText(KXmlParser parser) throws XmlPullParserException, IOException {
int eventType = parser.getEventType();
String text = null;
eventType = parser.next();
while( eventType != XmlPullParser.END_TAG) {
if( eventType == XmlPullParser.TEXT) {
text = parser.getText();
if(text.trim().length() == 0) text = null;
} else if( eventType == XmlPullParser.START_TAG) {
// We skip this subtree
parser.skipSubTree();
// SkipSubTree position us on the corresponding end tag
}
eventType = parser.next();
}
return text;
}
}
| apache-2.0 |
patrickweege/SaGUI | sagui-parent/sagui-render-mobile/src/main/java/com/fatuhiva/touch/controller/grid/JextGridAction.java | 516 | package com.fatuhiva.touch.controller.grid;
import com.fatuhiva.model.grid.FatuGrid;
import com.fatuhiva.touch.controller.IJextAction;
public class JextGridAction {
public enum GridEvent {
GETDATA
}
private IJextAction<FatuGrid> webAction;
private GridEvent evt;
public JextGridAction(IJextAction<FatuGrid> webAction) {
this.webAction = webAction;
evt = GridEvent.valueOf((String)webAction.getParameter("EVENT"));
}
public GridEvent getEvent() {
return evt;
}
}
| apache-2.0 |
sht5/Android-tcp-server-and-client | client/AndroidTCPServer/src/com/example/android_tcp_server/EnumsAndStatics.java | 986 | package com.example.android_tcp_server;
import java.util.Arrays;
import java.util.List;
import com.example.android_tcp_server.EnumsAndStatics.MessageTypes;
public class EnumsAndStatics {
public enum MessageTypes{MessageFromServer,MessageFromClient,REGISTRATION_APPROVED}
public static final String MESSAGE_TYPE_FOR_JSON ="messageType";
public static final String MESSAGE_CONTENT_FOR_JSON ="messageContent";
public static final String SERVER_IP_PREF ="pref_ip";
public static final String SERVER_PORT_PREF ="pref_port";
public static MessageTypes getMessageTypeByString(String messageInString)
{
if(messageInString.equals(MessageTypes.MessageFromServer.toString()))
return MessageTypes.MessageFromServer;
if(messageInString.equals(MessageTypes.MessageFromClient.toString()))
return MessageTypes.MessageFromClient;
if(messageInString.equals(MessageTypes.REGISTRATION_APPROVED.toString()))
return MessageTypes.REGISTRATION_APPROVED;
return null;
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-cloudtrail/src/main/java/com/amazonaws/services/cloudtrail/model/transform/InvalidCloudWatchLogsLogGroupArnExceptionUnmarshaller.java | 3122 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.cloudtrail.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.cloudtrail.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* InvalidCloudWatchLogsLogGroupArnException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidCloudWatchLogsLogGroupArnExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private InvalidCloudWatchLogsLogGroupArnExceptionUnmarshaller() {
super(com.amazonaws.services.cloudtrail.model.InvalidCloudWatchLogsLogGroupArnException.class, "InvalidCloudWatchLogsLogGroupArnException");
}
@Override
public com.amazonaws.services.cloudtrail.model.InvalidCloudWatchLogsLogGroupArnException unmarshallFromContext(JsonUnmarshallerContext context)
throws Exception {
com.amazonaws.services.cloudtrail.model.InvalidCloudWatchLogsLogGroupArnException invalidCloudWatchLogsLogGroupArnException = new com.amazonaws.services.cloudtrail.model.InvalidCloudWatchLogsLogGroupArnException(
null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return invalidCloudWatchLogsLogGroupArnException;
}
private static InvalidCloudWatchLogsLogGroupArnExceptionUnmarshaller instance;
public static InvalidCloudWatchLogsLogGroupArnExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new InvalidCloudWatchLogsLogGroupArnExceptionUnmarshaller();
return instance;
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java | 162794 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util.treeView;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.UiActivity;
import com.intellij.ide.UiActivityMonitor;
import com.intellij.ide.util.treeView.TreeRunnable.TreeConsumer;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.ui.LoadingNode;
import com.intellij.ui.treeStructure.AlwaysExpandedTree;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.*;
import com.intellij.util.concurrency.LockToken;
import com.intellij.util.concurrency.QueueProcessor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.*;
import org.jetbrains.concurrency.AsyncPromise;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.concurrency.Promises;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
* @deprecated use {@link com.intellij.ui.tree.AsyncTreeModel} and {@link com.intellij.ui.tree.StructureTreeModel} instead.
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2020.3")
@Deprecated
public class AbstractTreeUi {
private static final Logger LOG = Logger.getInstance(AbstractTreeBuilder.class);
protected JTree myTree;// protected for TestNG
private DefaultTreeModel myTreeModel;
private AbstractTreeStructure myTreeStructure;
private AbstractTreeUpdater myUpdater;
private Comparator<? super NodeDescriptor<?>> myNodeDescriptorComparator;
private final Comparator<TreeNode> myNodeComparator = new Comparator<>() {
@Override
public int compare(TreeNode n1, TreeNode n2) {
if (isLoadingNode(n1) && isLoadingNode(n2)) return 0;
if (isLoadingNode(n1)) return -1;
if (isLoadingNode(n2)) return 1;
NodeDescriptor<?> nodeDescriptor1 = getDescriptorFrom(n1);
NodeDescriptor<?> nodeDescriptor2 = getDescriptorFrom(n2);
if (nodeDescriptor1 == null && nodeDescriptor2 == null) return 0;
if (nodeDescriptor1 == null) return -1;
if (nodeDescriptor2 == null) return 1;
return myNodeDescriptorComparator != null
? myNodeDescriptorComparator.compare(nodeDescriptor1, nodeDescriptor2)
: nodeDescriptor1.getIndex() - nodeDescriptor2.getIndex();
}
};
long myOwnComparatorStamp;
private long myLastComparatorStamp;
private DefaultMutableTreeNode myRootNode;
private final Map<Object, Object> myElementToNodeMap = new HashMap<>();
private final Set<DefaultMutableTreeNode> myUnbuiltNodes = new HashSet<>();
private TreeExpansionListener myExpansionListener;
private MySelectionListener mySelectionListener;
private final QueueProcessor<Runnable> myWorker = new QueueProcessor<>(runnable -> {
runnable.run();
TimeoutUtil.sleep(1);
});
private final Set<Runnable> myActiveWorkerTasks = new HashSet<>();
private ProgressIndicator myProgress;
private AbstractTreeNode<Object> TREE_NODE_WRAPPER;
private boolean myRootNodeWasQueuedToInitialize;
private boolean myRootNodeInitialized;
private final Map<Object, List<NodeAction>> myNodeActions = new HashMap<>();
private boolean myUpdateFromRootRequested;
private boolean myWasEverShown;
private boolean myUpdateIfInactive;
private final Map<Object, UpdateInfo> myLoadedInBackground = new HashMap<>();
private final Map<Object, List<NodeAction>> myNodeChildrenActions = new HashMap<>();
private long myClearOnHideDelay = -1;
private volatile long ourUi2Countdown;
private final Set<Runnable> myDeferredSelections = new HashSet<>();
private final Set<Runnable> myDeferredExpansions = new HashSet<>();
private boolean myCanProcessDeferredSelections;
private UpdaterTreeState myUpdaterState;
private AbstractTreeBuilder myBuilder;
private final Set<DefaultMutableTreeNode> myUpdatingChildren = new HashSet<>();
private boolean myCanYield;
private final List<TreeUpdatePass> myYieldingPasses = new ArrayList<>();
private boolean myYieldingNow;
private final Set<DefaultMutableTreeNode> myPendingNodeActions = new HashSet<>();
private final Set<Runnable> myYieldingDoneRunnables = new HashSet<>();
private final Alarm myBusyAlarm = new Alarm();
private final Runnable myWaiterForReady = new TreeRunnable("AbstractTreeUi.myWaiterForReady") {
@Override
public void perform() {
maybeSetBusyAndScheduleWaiterForReady(false, null);
}
};
private final RegistryValue myYieldingUpdate = Registry.get("ide.tree.yieldingUiUpdate");
private final RegistryValue myShowBusyIndicator = Registry.get("ide.tree.showBusyIndicator");
private final RegistryValue myWaitForReadyTime = Registry.get("ide.tree.waitForReadyTimeout");
private boolean myWasEverIndexNotReady;
private boolean myShowing;
private final FocusAdapter myFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
maybeReady();
}
};
private final Set<DefaultMutableTreeNode> myNotForSmartExpand = new HashSet<>();
private TreePath myRequestedExpand;
private TreePath mySilentExpand;
private TreePath mySilentSelect;
private final ActionCallback myInitialized = new ActionCallback();
private final BusyObject.Impl myBusyObject = new BusyObject.Impl() {
@Override
public boolean isReady() {
return AbstractTreeUi.this.isReady(true);
}
@Override
protected void onReadyWasSent() {
removeActivity();
}
};
private boolean myPassThroughMode;
private final Set<Object> myAutoExpandRoots = new HashSet<>();
private final RegistryValue myAutoExpandDepth = Registry.get("ide.tree.autoExpandMaxDepth");
private final Set<DefaultMutableTreeNode> myWillBeExpanded = new HashSet<>();
private SimpleTimerTask myCleanupTask;
private final AtomicBoolean myCancelRequest = new AtomicBoolean();
private final ReentrantLock myStateLock = new ReentrantLock();
private final AtomicBoolean myResettingToReadyNow = new AtomicBoolean();
private final Map<Progressive, ProgressIndicator> myBatchIndicators = new HashMap<>();
private final Map<Progressive, ActionCallback> myBatchCallbacks = new HashMap<>();
private final Map<DefaultMutableTreeNode, DefaultMutableTreeNode> myCancelledBuild = new WeakHashMap<>();
private boolean mySelectionIsAdjusted;
private boolean myReleaseRequested;
private boolean mySelectionIsBeingAdjusted;
private final Set<Object> myRevalidatedObjects = new HashSet<>();
private final Set<Runnable> myUserRunnables = new HashSet<>();
private UiActivityMonitor myActivityMonitor;
@NonNls private UiActivity myActivityId;
@Override
public String toString() {
return "AbstractTreeUi: builder = " + myBuilder;
}
protected void init(@NotNull AbstractTreeBuilder builder,
@NotNull JTree tree,
@NotNull DefaultTreeModel treeModel,
AbstractTreeStructure treeStructure,
@Nullable Comparator<? super NodeDescriptor<?>> comparator,
boolean updateIfInactive) {
myBuilder = builder;
myTree = tree;
myTreeModel = treeModel;
myActivityMonitor = UiActivityMonitor.getInstance();
myActivityId = new UiActivity.AsyncBgOperation("TreeUi " + this);
addModelListenerToDiagnoseAccessOutsideEdt();
TREE_NODE_WRAPPER = AbstractTreeBuilder.createSearchingTreeNodeWrapper();
myTree.setModel(myTreeModel);
setRootNode((DefaultMutableTreeNode)treeModel.getRoot());
myTreeStructure = treeStructure;
myNodeDescriptorComparator = comparator;
myUpdateIfInactive = updateIfInactive;
UIUtil.invokeLaterIfNeeded(new TreeRunnable("AbstractTreeUi.init") {
@Override
public void perform() {
if (!wasRootNodeInitialized()) {
if (myRootNode.getChildCount() == 0) {
insertLoadingNode(myRootNode, true);
}
}
}
});
myExpansionListener = new MyExpansionListener();
myTree.addTreeExpansionListener(myExpansionListener);
mySelectionListener = new MySelectionListener();
myTree.addTreeSelectionListener(mySelectionListener);
setUpdater(getBuilder().createUpdater());
myProgress = getBuilder().createProgressIndicator();
Disposer.register(getBuilder(), getUpdater());
if (myProgress != null) {
Disposer.register(getBuilder(), () -> myProgress.cancel());
}
final UiNotifyConnector uiNotify = new UiNotifyConnector(tree, new Activatable() {
@Override
public void showNotify() {
myShowing = true;
myWasEverShown = true;
if (canInitiateNewActivity()) {
activate(true);
}
}
@Override
public void hideNotify() {
myShowing = false;
if (canInitiateNewActivity()) {
deactivate();
}
}
});
Disposer.register(getBuilder(), uiNotify);
myTree.addFocusListener(myFocusListener);
}
private boolean isNodeActionsPending() {
return !myNodeActions.isEmpty() || !myNodeChildrenActions.isEmpty();
}
private void clearNodeActions() {
myNodeActions.clear();
myNodeChildrenActions.clear();
}
private void maybeSetBusyAndScheduleWaiterForReady(boolean forcedBusy, @Nullable Object element) {
if (!myShowBusyIndicator.asBoolean()) return;
boolean canUpdateBusyState = false;
if (forcedBusy) {
if (canYield() || isToBuildChildrenInBackground(element)) {
canUpdateBusyState = true;
}
} else {
canUpdateBusyState = true;
}
if (!canUpdateBusyState) return;
if (myTree instanceof Tree) {
final Tree tree = (Tree)myTree;
final boolean isBusy = !isReady(true) || forcedBusy;
if (isBusy && tree.isShowing()) {
tree.setPaintBusy(true);
myBusyAlarm.cancelAllRequests();
myBusyAlarm.addRequest(myWaiterForReady, myWaitForReadyTime.asInteger());
}
else {
tree.setPaintBusy(false);
}
}
}
private void setHoldSize(boolean holdSize) {
if (myTree instanceof Tree) {
final Tree tree = (Tree)myTree;
tree.setHoldSize(holdSize);
}
}
private void cleanUpAll() {
final long now = System.currentTimeMillis();
final long timeToCleanup = ourUi2Countdown;
if (timeToCleanup != 0 && now >= timeToCleanup) {
ourUi2Countdown = 0;
Runnable runnable = new TreeRunnable("AbstractTreeUi.cleanUpAll") {
@Override
public void perform() {
if (!canInitiateNewActivity()) return;
myCleanupTask = null;
getBuilder().cleanUp();
}
};
if (isPassthroughMode()) {
runnable.run();
}
else {
invokeLaterIfNeeded(false, runnable);
}
}
}
void doCleanUp() {
Runnable cleanup = new TreeRunnable("AbstractTreeUi.doCleanUp") {
@Override
public void perform() {
if (canInitiateNewActivity()) {
cleanUpNow();
}
}
};
if (isPassthroughMode()) {
cleanup.run();
}
else {
invokeLaterIfNeeded(false, cleanup);
}
}
void invokeLaterIfNeeded(boolean forceEdt, @NotNull final Runnable runnable) {
Runnable actual = new TreeRunnable("AbstractTreeUi.invokeLaterIfNeeded") {
@Override
public void perform() {
if (!isReleased()) {
runnable.run();
}
}
};
if (isPassthroughMode() || !forceEdt && !isEdt() && !isTreeShowing() && !myWasEverShown) {
actual.run();
}
else {
UIUtil.invokeLaterIfNeeded(actual);
}
}
public void activate(boolean byShowing) {
cancelCurrentCleanupTask();
myCanProcessDeferredSelections = true;
ourUi2Countdown = 0;
if (!myWasEverShown || myUpdateFromRootRequested || myUpdateIfInactive) {
getBuilder().updateFromRoot();
}
getUpdater().showNotify();
myWasEverShown |= byShowing;
}
private void cancelCurrentCleanupTask() {
if (myCleanupTask != null) {
myCleanupTask.cancel();
myCleanupTask = null;
}
}
void deactivate() {
getUpdater().hideNotify();
myBusyAlarm.cancelAllRequests();
if (!myWasEverShown) return;
// ask for termination of background children calculation
if (myProgress != null && myProgress.isRunning()) myProgress.cancel();
if (!isReady()) {
cancelUpdate();
myUpdateFromRootRequested = true;
}
if (getClearOnHideDelay() >= 0) {
ourUi2Countdown = System.currentTimeMillis() + getClearOnHideDelay();
scheduleCleanUpAll();
}
}
private void scheduleCleanUpAll() {
cancelCurrentCleanupTask();
myCleanupTask = SimpleTimer.getInstance().setUp(new TreeRunnable("AbstractTreeUi.scheduleCleanUpAll") {
@Override
public void perform() {
cleanUpAll();
}
}, getClearOnHideDelay());
}
void requestRelease() {
myReleaseRequested = true;
cancelUpdate().doWhenDone(new TreeRunnable("AbstractTreeUi.requestRelease: on done") {
@Override
public void perform() {
releaseNow();
}
});
}
public ProgressIndicator getProgress() {
return myProgress;
}
private void releaseNow() {
try (LockToken ignored = acquireLock()) {
myTree.removeTreeExpansionListener(myExpansionListener);
myTree.removeTreeSelectionListener(mySelectionListener);
myTree.removeFocusListener(myFocusListener);
disposeNode(getRootNode());
myElementToNodeMap.clear();
getUpdater().cancelAllRequests();
myWorker.clear();
clearWorkerTasks();
TREE_NODE_WRAPPER.setValue(null);
if (myProgress != null) {
myProgress.cancel();
}
cancelCurrentCleanupTask();
myTree = null;
setUpdater(null);
myTreeStructure = null;
myBuilder.releaseUi();
myBuilder = null;
clearNodeActions();
myDeferredSelections.clear();
myDeferredExpansions.clear();
myYieldingDoneRunnables.clear();
}
}
public boolean isReleased() {
return myBuilder == null;
}
void doExpandNodeChildren(@NotNull final DefaultMutableTreeNode node) {
if (!myUnbuiltNodes.contains(node)) return;
if (isLoadedInBackground(getElementFor(node))) return;
AbstractTreeStructure structure = getTreeStructure();
structure.asyncCommit().doWhenDone(new TreeRunnable("AbstractTreeUi.doExpandNodeChildren") {
@Override
public void perform() {
addSubtreeToUpdate(node);
// at this point some tree updates may already have been run as a result of
// in tests these updates may lead to the instance disposal, so getUpdater() at the next line may return null
final AbstractTreeUpdater updater = getUpdater();
if (updater != null) {
updater.performUpdate();
}
}
});
//if (structure.hasSomethingToCommit()) structure.commit();
}
public final AbstractTreeStructure getTreeStructure() {
return myTreeStructure;
}
public final JTree getTree() {
return myTree;
}
@Nullable
private static NodeDescriptor getDescriptorFrom(Object node) {
if (node instanceof DefaultMutableTreeNode) {
Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
if (userObject instanceof NodeDescriptor) {
return (NodeDescriptor)userObject;
}
}
return null;
}
@Nullable
public final DefaultMutableTreeNode getNodeForElement(@NotNull Object element, final boolean validateAgainstStructure) {
DefaultMutableTreeNode result = null;
if (validateAgainstStructure) {
int index = 0;
while (true) {
final DefaultMutableTreeNode node = findNode(element, index);
if (node == null) break;
if (isNodeValidForElement(element, node)) {
result = node;
break;
}
index++;
}
}
else {
result = getFirstNode(element);
}
if (result != null && !isNodeInStructure(result)) {
disposeNode(result);
result = null;
}
return result;
}
private boolean isNodeInStructure(@NotNull DefaultMutableTreeNode node) {
return TreeUtil.isAncestor(getRootNode(), node) && getRootNode() == myTreeModel.getRoot();
}
private boolean isNodeValidForElement(@NotNull final Object element, @NotNull final DefaultMutableTreeNode node) {
return isSameHierarchy(element, node) || isValidChildOfParent(element, node);
}
private boolean isValidChildOfParent(@NotNull final Object element, @NotNull final DefaultMutableTreeNode node) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
final Object parentElement = getElementFor(parent);
if (!isInStructure(parentElement)) return false;
if (parent instanceof ElementNode) {
return ((ElementNode)parent).isValidChild(element);
}
for (int i = 0; i < parent.getChildCount(); i++) {
final TreeNode child = parent.getChildAt(i);
final Object eachElement = getElementFor(child);
if (element.equals(eachElement)) return true;
}
return false;
}
private boolean isSameHierarchy(@NotNull Object element, @NotNull DefaultMutableTreeNode node) {
Object eachParent = element;
DefaultMutableTreeNode eachParentNode = node;
boolean valid;
while (true) {
if (eachParent == null) {
valid = eachParentNode == null;
break;
}
if (!eachParent.equals(getElementFor(eachParentNode))) {
valid = false;
break;
}
eachParent = getTreeStructure().getParentElement(eachParent);
eachParentNode = (DefaultMutableTreeNode)eachParentNode.getParent();
}
return valid;
}
@Nullable
public final DefaultMutableTreeNode getNodeForPath(Object @NotNull [] path) {
DefaultMutableTreeNode node = null;
for (final Object pathElement : path) {
node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement);
if (node == null) {
break;
}
}
return node;
}
final void buildNodeForElement(@NotNull Object element) {
getUpdater().performUpdate();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null) {
final List<Object> elements = new ArrayList<>();
while (true) {
element = getTreeStructure().getParentElement(element);
if (element == null) {
break;
}
elements.add(0, element);
}
for (final Object element1 : elements) {
node = getNodeForElement(element1, false);
if (node != null) {
expand(node, true);
}
}
}
}
public final void buildNodeForPath(Object @NotNull [] path) {
getUpdater().performUpdate();
DefaultMutableTreeNode node = null;
for (final Object pathElement : path) {
node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement);
if (node != null && node != path[path.length - 1]) {
expand(node, true);
}
}
}
public final void setNodeDescriptorComparator(Comparator<? super NodeDescriptor<?>> nodeDescriptorComparator) {
myNodeDescriptorComparator = nodeDescriptorComparator;
myLastComparatorStamp = -1;
getBuilder().queueUpdateFrom(getTreeStructure().getRootElement(), true);
}
@NotNull
protected AbstractTreeBuilder getBuilder() {
return myBuilder;
}
protected final void initRootNode() {
if (myUpdateIfInactive) {
activate(false);
}
else {
myUpdateFromRootRequested = true;
}
}
private boolean initRootNodeNowIfNeeded(@NotNull final TreeUpdatePass pass) {
boolean wasCleanedUp = false;
if (myRootNodeWasQueuedToInitialize) {
Object root = getTreeStructure().getRootElement();
Object currentRoot = getElementFor(myRootNode);
if (Comparing.equal(root, currentRoot)) return false;
Object rootAgain = getTreeStructure().getRootElement();
if (root != rootAgain && !root.equals(rootAgain)) {
assert false : "getRootElement() if called twice must return either root1 == root2 or root1.equals(root2)";
}
cleanUpNow();
wasCleanedUp = true;
}
if (myRootNodeWasQueuedToInitialize) return true;
myRootNodeWasQueuedToInitialize = true;
final Object rootElement = getTreeStructure().getRootElement();
addNodeAction(rootElement, false, node -> processDeferredActions());
final Ref<NodeDescriptor> rootDescriptor = new Ref<>(null);
final boolean bgLoading = isToBuildChildrenInBackground(rootElement);
Runnable build = new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: build") {
@Override
public void perform() {
rootDescriptor.set(getTreeStructure().createDescriptor(rootElement, null));
getRootNode().setUserObject(rootDescriptor.get());
update(rootDescriptor.get(), true);
pass.addToUpdated(rootDescriptor.get());
}
};
Runnable update = new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: update") {
@Override
public void perform() {
Object fromDescriptor = getElementFromDescriptor(rootDescriptor.get());
if (!isNodeNull(fromDescriptor)) {
createMapping(fromDescriptor, getRootNode());
}
insertLoadingNode(getRootNode(), true);
boolean willUpdate = false;
if (!rootDescriptor.isNull() && isAutoExpand(rootDescriptor.get())) {
willUpdate = myUnbuiltNodes.contains(getRootNode());
expand(getRootNode(), true);
}
ActionCallback callback;
if (willUpdate) {
callback = ActionCallback.DONE;
}
else {
callback = updateNodeChildren(getRootNode(), pass, null, false, false, false, true, true);
}
callback.doWhenDone(new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: on done updateNodeChildren") {
@Override
public void perform() {
if (getRootNode().getChildCount() == 0) {
myTreeModel.nodeChanged(getRootNode());
}
}
});
}
};
if (bgLoading) {
queueToBackground(build, update)
.onSuccess(new TreeConsumer<>("AbstractTreeUi.initRootNodeNowIfNeeded: on processed queueToBackground") {
@Override
public void perform() {
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.initRootNodeNowIfNeeded: on processed queueToBackground later") {
@Override
public void perform() {
myRootNodeInitialized = true;
processNodeActionsIfReady(myRootNode);
}
});
}
});
}
else {
build.run();
update.run();
myRootNodeInitialized = true;
processNodeActionsIfReady(myRootNode);
}
return wasCleanedUp;
}
private boolean isAutoExpand(@NotNull NodeDescriptor descriptor) {
return isAutoExpand(descriptor, true);
}
private boolean isAutoExpand(@NotNull NodeDescriptor descriptor, boolean validate) {
if (isAlwaysExpandedTree()) return false;
boolean autoExpand = getBuilder().isAutoExpandNode(descriptor);
Object element = getElementFromDescriptor(descriptor);
if (validate && element != null) {
autoExpand = validateAutoExpand(autoExpand, element);
}
if (!autoExpand && !myTree.isRootVisible()) {
if (element != null && element.equals(getTreeStructure().getRootElement())) return true;
}
return autoExpand;
}
private boolean validateAutoExpand(boolean autoExpand, @NotNull Object element) {
if (autoExpand) {
int distance = getDistanceToAutoExpandRoot(element);
if (distance < 0) {
myAutoExpandRoots.add(element);
}
else {
if (distance >= myAutoExpandDepth.asInteger() - 1) {
autoExpand = false;
}
}
if (autoExpand) {
DefaultMutableTreeNode node = getNodeForElement(element, false);
autoExpand = node != null && isInVisibleAutoExpandChain(node);
}
}
return autoExpand;
}
private boolean isInVisibleAutoExpandChain(@NotNull DefaultMutableTreeNode child) {
TreeNode eachParent = child;
while (eachParent != null) {
if (myRootNode == eachParent) return true;
NodeDescriptor eachDescriptor = getDescriptorFrom(eachParent);
if (eachDescriptor == null || !isAutoExpand(eachDescriptor, false)) {
TreePath path = getPathFor(eachParent);
return myWillBeExpanded.contains(path.getLastPathComponent()) || myTree.isExpanded(path) && myTree.isVisible(path);
}
eachParent = eachParent.getParent();
}
return false;
}
private int getDistanceToAutoExpandRoot(@NotNull Object element) {
int distance = 0;
Object eachParent = element;
while (eachParent != null) {
if (myAutoExpandRoots.contains(eachParent)) break;
eachParent = getTreeStructure().getParentElement(eachParent);
distance++;
}
return eachParent != null ? distance : -1;
}
private boolean isAutoExpand(@NotNull DefaultMutableTreeNode node) {
NodeDescriptor descriptor = getDescriptorFrom(node);
return descriptor != null && isAutoExpand(descriptor);
}
private boolean isAlwaysExpandedTree() {
return myTree instanceof AlwaysExpandedTree && ((AlwaysExpandedTree)myTree).isAlwaysExpanded();
}
@NotNull
private Promise<Boolean> update(@NotNull final NodeDescriptor nodeDescriptor, boolean now) {
Promise<Boolean> promise;
if (now || isPassthroughMode()) {
promise = Promises.resolvedPromise(update(nodeDescriptor));
}
else {
final AsyncPromise<Boolean> result = new AsyncPromise<>();
promise = result;
boolean bgLoading = isToBuildInBackground(nodeDescriptor);
boolean edt = isEdt();
if (bgLoading) {
if (edt) {
final AtomicBoolean changes = new AtomicBoolean();
queueToBackground(new TreeRunnable("AbstractTreeUi.update: build") {
@Override
public void perform() {
changes.set(update(nodeDescriptor));
}
}, new TreeRunnable("AbstractTreeUi.update: post") {
@Override
public void perform() {
result.setResult(changes.get());
}
}
);
}
else {
result.setResult(update(nodeDescriptor));
}
}
else {
if (edt || !myWasEverShown) {
result.setResult(update(nodeDescriptor));
}
else {
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.update: later") {
@Override
public void perform() {
execute(new TreeRunnable("AbstractTreeUi.update: later execute") {
@Override
public void perform() {
result.setResult(update(nodeDescriptor));
}
});
}
});
}
}
}
promise.onSuccess(changes -> {
if (!changes) {
return;
}
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.update: on done result") {
@Override
public void perform() {
Object element = nodeDescriptor.getElement();
DefaultMutableTreeNode node = element == null ? null : getNodeForElement(element, false);
if (node != null) {
TreePath path = getPathFor(node);
if (myTree.isVisible(path)) {
updateNodeImageAndPosition(node);
}
}
}
});
});
return promise;
}
private boolean update(@NotNull final NodeDescriptor nodeDescriptor) {
while(true) {
try (LockToken ignored = attemptLock()) {
if (ignored == null) { // async children calculation is in progress under lock
if (myProgress != null && myProgress.isRunning()) myProgress.cancel();
continue;
}
final AtomicBoolean update = new AtomicBoolean();
execute(new TreeRunnable("AbstractTreeUi.update") {
@Override
public void perform() {
nodeDescriptor.setUpdateCount(nodeDescriptor.getUpdateCount() + 1);
update.set(getBuilder().updateNodeDescriptor(nodeDescriptor));
}
});
return update.get();
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady(e);
return false;
}
catch (InterruptedException e) {
LOG.info(e);
return false;
}
}
}
public void assertIsDispatchThread() {
if (isPassthroughMode()) return;
if ((isTreeShowing() || myWasEverShown) && !isEdt()) {
LOG.error("Must be in event-dispatch thread");
}
}
private static boolean isEdt() {
return SwingUtilities.isEventDispatchThread();
}
private boolean isTreeShowing() {
return myShowing;
}
private void assertNotDispatchThread() {
if (isPassthroughMode()) return;
if (isEdt()) {
LOG.error("Must not be in event-dispatch thread");
}
}
private void processDeferredActions() {
processDeferredActions(myDeferredSelections);
processDeferredActions(myDeferredExpansions);
}
private static void processDeferredActions(@NotNull Set<Runnable> actions) {
final Runnable[] runnables = actions.toArray(new Runnable[0]);
actions.clear();
for (Runnable runnable : runnables) {
runnable.run();
}
}
//todo: to make real callback
@NotNull
public ActionCallback queueUpdate(Object element) {
return queueUpdate(element, true);
}
@NotNull
public ActionCallback queueUpdate(final Object fromElement, boolean updateStructure) {
assertIsDispatchThread();
try {
if (getUpdater() == null) {
return ActionCallback.REJECTED;
}
final ActionCallback result = new ActionCallback();
DefaultMutableTreeNode nodeToUpdate = null;
boolean updateElementStructure = updateStructure;
for (Object element = fromElement; element != null; element = getTreeStructure().getParentElement(element)) {
final DefaultMutableTreeNode node = getFirstNode(element);
if (node != null) {
nodeToUpdate = node;
break;
}
updateElementStructure = true; // always update children if element does not exist
}
addSubtreeToUpdate(nodeToUpdate != null? nodeToUpdate : getRootNode(), new TreeRunnable("AbstractTreeUi.queueUpdate") {
@Override
public void perform() {
result.setDone();
}
}, updateElementStructure);
return result;
}
catch (ProcessCanceledException e) {
return ActionCallback.REJECTED;
}
}
public void doUpdateFromRoot() {
updateSubtree(getRootNode(), false);
}
public final void updateSubtree(@NotNull DefaultMutableTreeNode node, boolean canSmartExpand) {
updateSubtree(new TreeUpdatePass(node), canSmartExpand);
}
private void updateSubtree(@NotNull TreeUpdatePass pass, boolean canSmartExpand) {
final AbstractTreeUpdater updater = getUpdater();
if (updater != null) {
updater.addSubtreeToUpdate(pass);
}
else {
updateSubtreeNow(pass, canSmartExpand);
}
}
final void updateSubtreeNow(@NotNull TreeUpdatePass pass, boolean canSmartExpand) {
maybeSetBusyAndScheduleWaiterForReady(true, getElementFor(pass.getNode()));
setHoldSize(true);
boolean consumed = initRootNodeNowIfNeeded(pass);
if (consumed) return;
final DefaultMutableTreeNode node = pass.getNode();
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
if (pass.isUpdateStructure()) {
setUpdaterState(new UpdaterTreeState(this)).beforeSubtreeUpdate();
boolean forceUpdate = true;
TreePath path = getPathFor(node);
boolean invisible = !myTree.isExpanded(path) && (path.getParentPath() == null || !myTree.isExpanded(path.getParentPath()));
if (invisible && myUnbuiltNodes.contains(node)) {
forceUpdate = false;
}
updateNodeChildren(node, pass, null, false, canSmartExpand, forceUpdate, false, pass.isUpdateChildren());
}
else {
updateRow(0, pass);
}
}
private void updateRow(final int row, @NotNull final TreeUpdatePass pass) {
LOG.debug("updateRow: ", row, " - ", pass);
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.updateRow") {
@Override
public void perform() {
if (row >= getTree().getRowCount()) return;
TreePath path = getTree().getPathForRow(row);
if (path != null) {
final NodeDescriptor descriptor = getDescriptorFrom(path.getLastPathComponent());
if (descriptor != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
maybeYield(() -> update(descriptor, false)
.onSuccess(new TreeConsumer<>("AbstractTreeUi.updateRow: inner") {
@Override
public void perform() {
updateRow(row + 1, pass);
}
}), pass, node);
}
}
}
});
}
boolean isToBuildChildrenInBackground(Object element) {
AbstractTreeStructure structure = getTreeStructure();
return element != null && structure.isToBuildChildrenInBackground(element);
}
private boolean isToBuildInBackground(NodeDescriptor descriptor) {
return isToBuildChildrenInBackground(getElementFromDescriptor(descriptor));
}
@NotNull
private UpdaterTreeState setUpdaterState(@NotNull UpdaterTreeState state) {
if (state.equals(myUpdaterState)) return state;
final UpdaterTreeState oldState = myUpdaterState;
if (oldState == null) {
myUpdaterState = state;
return state;
}
else {
oldState.addAll(state);
return oldState;
}
}
void doUpdateNode(@NotNull final DefaultMutableTreeNode node) {
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
final Object prevElement = getElementFromDescriptor(descriptor);
if (prevElement == null) return;
update(descriptor, false)
.onSuccess(changes -> {
if (!isValid(descriptor)) {
if (isInStructure(prevElement)) {
Object toUpdate = ObjectUtils.notNull(getTreeStructure().getParentElement(prevElement), getTreeStructure().getRootElement());
getUpdater().addSubtreeToUpdateByElement(toUpdate);
return;
}
}
if (changes) {
updateNodeImageAndPosition(node);
}
});
}
public Object getElementFromDescriptor(NodeDescriptor descriptor) {
return getBuilder().getTreeStructureElement(descriptor);
}
@NotNull
private ActionCallback updateNodeChildren(@NotNull final DefaultMutableTreeNode node,
@NotNull final TreeUpdatePass pass,
@Nullable final LoadedChildren loadedChildren,
final boolean forcedNow,
final boolean toSmartExpand,
final boolean forceUpdate,
final boolean descriptorIsUpToDate,
final boolean updateChildren) {
AbstractTreeStructure treeStructure = getTreeStructure();
ActionCallback result = treeStructure.asyncCommit();
result.doWhenDone(new TreeRunnable("AbstractTreeUi.updateNodeChildren: on done") {
@Override
public void perform() {
try {
removeFromCancelled(node);
execute(new TreeRunnable("AbstractTreeUi.updateNodeChildren: execute") {
@Override
public void perform() {
doUpdateChildren(node, pass, loadedChildren, forcedNow, toSmartExpand, forceUpdate, descriptorIsUpToDate, updateChildren);
}
});
}
catch (ProcessCanceledException e) {
addToCancelled(node);
throw e;
}
}
});
return result;
}
private void doUpdateChildren(@NotNull final DefaultMutableTreeNode node,
@NotNull final TreeUpdatePass pass,
@Nullable final LoadedChildren loadedChildren,
boolean forcedNow,
final boolean toSmartExpand,
boolean forceUpdate,
boolean descriptorIsUpToDate,
final boolean updateChildren) {
try {
final NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) {
removeFromUnbuilt(node);
removeLoading(node, true);
return;
}
boolean descriptorIsReady = descriptorIsUpToDate || pass.isUpdated(descriptor);
final boolean wasExpanded = myTree.isExpanded(new TreePath(node.getPath())) || isAutoExpand(node);
final boolean wasLeaf = node.getChildCount() == 0;
boolean bgBuild = isToBuildInBackground(descriptor);
boolean requiredToUpdateChildren = forcedNow || wasExpanded;
if (!requiredToUpdateChildren && forceUpdate) {
boolean alwaysPlus = getBuilder().isAlwaysShowPlus(descriptor);
if (alwaysPlus && wasLeaf) {
requiredToUpdateChildren = true;
}
else {
requiredToUpdateChildren = !alwaysPlus;
if (!requiredToUpdateChildren && !myUnbuiltNodes.contains(node)) {
removeChildren(node);
}
}
}
final AtomicReference<LoadedChildren> preloaded = new AtomicReference<>(loadedChildren);
if (!requiredToUpdateChildren) {
if (myUnbuiltNodes.contains(node) && node.getChildCount() == 0) {
insertLoadingNode(node, true);
}
if (!descriptorIsReady) {
update(descriptor, false);
}
return;
}
if (!forcedNow && !bgBuild && myUnbuiltNodes.contains(node)) {
if (!descriptorIsReady) {
update(descriptor, true);
descriptorIsReady = true;
}
if (processAlwaysLeaf(node) || !updateChildren) {
return;
}
Pair<Boolean, LoadedChildren> unbuilt = processUnbuilt(node, descriptor, pass, wasExpanded, null);
if (unbuilt.getFirst()) {
return;
}
preloaded.set(unbuilt.getSecond());
}
final boolean childForceUpdate = isChildNodeForceUpdate(node, forceUpdate, wasExpanded);
if (!forcedNow && isToBuildInBackground(descriptor)) {
boolean alwaysLeaf = processAlwaysLeaf(node);
queueBackgroundUpdate(
new UpdateInfo(descriptor, pass, canSmartExpand(node, toSmartExpand), wasExpanded, childForceUpdate, descriptorIsReady,
!alwaysLeaf && updateChildren), node);
}
else {
if (!descriptorIsReady) {
update(descriptor, false)
.onSuccess(new TreeConsumer<>("AbstractTreeUi.doUpdateChildren") {
@Override
public void perform() {
if (processAlwaysLeaf(node) || !updateChildren) return;
updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, childForceUpdate);
}
});
}
else {
if (processAlwaysLeaf(node) || !updateChildren) return;
updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, childForceUpdate);
}
}
}
finally {
if (!isReleased()) {
processNodeActionsIfReady(node);
}
}
}
private boolean processAlwaysLeaf(@NotNull DefaultMutableTreeNode node) {
Object element = getElementFor(node);
NodeDescriptor desc = getDescriptorFrom(node);
if (desc == null) return false;
if (element != null && getTreeStructure().isAlwaysLeaf(element)) {
removeFromUnbuilt(node);
removeLoading(node, true);
if (node.getChildCount() > 0) {
final TreeNode[] children = new TreeNode[node.getChildCount()];
for (int i = 0; i < node.getChildCount(); i++) {
children[i] = node.getChildAt(i);
}
if (isSelectionInside(node)) {
addSelectionPath(getPathFor(node), true, Conditions.alwaysTrue(), null);
}
processInnerChange(new TreeRunnable("AbstractTreeUi.processAlwaysLeaf") {
@Override
public void perform() {
for (TreeNode each : children) {
removeNodeFromParent((MutableTreeNode)each, true);
disposeNode((DefaultMutableTreeNode)each);
}
}
});
}
removeFromUnbuilt(node);
desc.setWasDeclaredAlwaysLeaf(true);
processNodeActionsIfReady(node);
return true;
}
else {
boolean wasLeaf = desc.isWasDeclaredAlwaysLeaf();
desc.setWasDeclaredAlwaysLeaf(false);
if (wasLeaf) {
insertLoadingNode(node, true);
}
return false;
}
}
private boolean isChildNodeForceUpdate(@NotNull DefaultMutableTreeNode node, boolean parentForceUpdate, boolean parentExpanded) {
TreePath path = getPathFor(node);
return parentForceUpdate && (parentExpanded || myTree.isExpanded(path));
}
private void updateNodeChildrenNow(@NotNull final DefaultMutableTreeNode node,
@NotNull final TreeUpdatePass pass,
@Nullable final LoadedChildren preloadedChildren,
final boolean toSmartExpand,
final boolean wasExpanded,
final boolean forceUpdate) {
if (isUpdatingChildrenNow(node)) return;
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
final NodeDescriptor descriptor = getDescriptorFrom(node);
final MutualMap<Object, Integer> elementToIndexMap = loadElementsFromStructure(descriptor, preloadedChildren);
final LoadedChildren loadedChildren =
preloadedChildren != null ? preloadedChildren : new LoadedChildren(elementToIndexMap.getKeys().toArray());
addToUpdatingChildren(node);
pass.setCurrentNode(node);
final boolean canSmartExpand = canSmartExpand(node, toSmartExpand);
removeFromUnbuilt(node);
//noinspection unchecked
processExistingNodes(node, elementToIndexMap, pass, canSmartExpand(node, toSmartExpand), forceUpdate, wasExpanded, preloadedChildren)
.onSuccess(new TreeConsumer("AbstractTreeUi.updateNodeChildrenNow: on done processExistingNodes") {
@Override
public void perform() {
if (isDisposed(node)) {
removeFromUpdatingChildren(node);
return;
}
removeLoading(node, false);
final boolean expanded = isExpanded(node, wasExpanded);
if (expanded) {
myWillBeExpanded.add(node);
}
else {
myWillBeExpanded.remove(node);
}
collectNodesToInsert(descriptor, elementToIndexMap, node, expanded, loadedChildren)
.doWhenDone((Consumer<List<TreeNode>>)nodesToInsert -> {
insertNodesInto(nodesToInsert, node);
ActionCallback callback = updateNodesToInsert(nodesToInsert, pass, canSmartExpand, isChildNodeForceUpdate(node, forceUpdate, expanded));
callback.doWhenDone(new TreeRunnable("AbstractTreeUi.updateNodeChildrenNow: on done updateNodesToInsert") {
@Override
public void perform() {
removeLoading(node, false);
removeFromUpdatingChildren(node);
if (node.getChildCount() > 0) {
if (expanded) {
expand(node, canSmartExpand);
}
}
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
final Object element = getElementFor(node);
addNodeAction(element, false, node1 -> removeLoading(node1, false));
processNodeActionsIfReady(node);
}
});
}).doWhenProcessed(new TreeRunnable("AbstractTreeUi.updateNodeChildrenNow: on processed collectNodesToInsert") {
@Override
public void perform() {
myWillBeExpanded.remove(node);
removeFromUpdatingChildren(node);
processNodeActionsIfReady(node);
}
});
}
})
.onError(new TreeConsumer<>("AbstractTreeUi.updateNodeChildrenNow: on reject processExistingNodes") {
@Override
public void perform() {
removeFromUpdatingChildren(node);
processNodeActionsIfReady(node);
}
});
}
private boolean isDisposed(@NotNull DefaultMutableTreeNode node) {
return !node.isNodeAncestor((DefaultMutableTreeNode)myTree.getModel().getRoot());
}
private void expandSilently(TreePath path) {
assertIsDispatchThread();
try {
mySilentExpand = path;
getTree().expandPath(path);
}
finally {
mySilentExpand = null;
}
}
private void addSelectionSilently(TreePath path) {
assertIsDispatchThread();
try {
mySilentSelect = path;
getTree().getSelectionModel().addSelectionPath(path);
}
finally {
mySilentSelect = null;
}
}
private void expand(@NotNull DefaultMutableTreeNode node, boolean canSmartExpand) {
expand(new TreePath(node.getPath()), canSmartExpand);
}
private void expand(@NotNull final TreePath path, boolean canSmartExpand) {
final Object last = path.getLastPathComponent();
boolean isLeaf = myTree.getModel().isLeaf(path.getLastPathComponent());
final boolean isRoot = last == myTree.getModel().getRoot();
final TreePath parent = path.getParentPath();
if (isRoot && !myTree.isExpanded(path)) {
if (myTree.isRootVisible() || myUnbuiltNodes.contains(last)) {
insertLoadingNode((DefaultMutableTreeNode)last, false);
}
expandPath(path, canSmartExpand);
}
else if (myTree.isExpanded(path) ||
isLeaf && parent != null && myTree.isExpanded(parent) && !myUnbuiltNodes.contains(last) && !isCancelled(last)) {
if (last instanceof DefaultMutableTreeNode) {
processNodeActionsIfReady((DefaultMutableTreeNode)last);
}
}
else {
if (isLeaf && (myUnbuiltNodes.contains(last) || isCancelled(last))) {
insertLoadingNode((DefaultMutableTreeNode)last, true);
expandPath(path, canSmartExpand);
}
else if (isLeaf && parent != null) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent.getLastPathComponent();
if (parentNode != null) {
addToUnbuilt(parentNode);
}
expandPath(parent, canSmartExpand);
}
else {
expandPath(path, canSmartExpand);
}
}
}
private void addToUnbuilt(DefaultMutableTreeNode node) {
myUnbuiltNodes.add(node);
}
private void removeFromUnbuilt(DefaultMutableTreeNode node) {
myUnbuiltNodes.remove(node);
}
private Pair<Boolean, LoadedChildren> processUnbuilt(@NotNull final DefaultMutableTreeNode node,
final NodeDescriptor descriptor,
@NotNull final TreeUpdatePass pass,
final boolean isExpanded,
@Nullable final LoadedChildren loadedChildren) {
final Ref<Pair<Boolean, LoadedChildren>> result = new Ref<>();
execute(new TreeRunnable("AbstractTreeUi.processUnbuilt") {
@Override
public void perform() {
if (!isExpanded && getBuilder().isAlwaysShowPlus(descriptor)) {
result.set(new Pair<>(true, null));
return;
}
final Object element = getElementFor(node);
if (element == null) {
trace("null element for node " + node);
result.set(new Pair<>(true, null));
return;
}
addToUpdatingChildren(node);
try {
final LoadedChildren children = loadedChildren != null ? loadedChildren : new LoadedChildren(getChildrenFor(element));
boolean processed;
if (children.getElements().isEmpty()) {
removeFromUnbuilt(node);
removeLoading(node, true);
processed = true;
}
else {
if (isAutoExpand(node)) {
addNodeAction(getElementFor(node), false, node1 -> {
final TreePath path = new TreePath(node1.getPath());
if (getTree().isExpanded(path) || children.getElements().isEmpty()) {
removeLoading(node1, false);
}
else {
maybeYield(() -> {
expand(element, null);
return Promises.resolvedPromise();
}, pass, node1);
}
});
}
processed = false;
}
removeFromUpdatingChildren(node);
processNodeActionsIfReady(node);
result.set(new Pair<>(processed, children));
}
finally {
removeFromUpdatingChildren(node);
}
}
});
return result.get();
}
private boolean removeIfLoading(@NotNull TreeNode node) {
if (isLoadingNode(node)) {
moveSelectionToParentIfNeeded(node);
removeNodeFromParent((MutableTreeNode)node, false);
return true;
}
return false;
}
private void moveSelectionToParentIfNeeded(@NotNull TreeNode node) {
TreePath path = getPathFor(node);
if (myTree.getSelectionModel().isPathSelected(path)) {
TreePath parentPath = path.getParentPath();
myTree.getSelectionModel().removeSelectionPath(path);
if (parentPath != null) {
myTree.getSelectionModel().addSelectionPath(parentPath);
}
}
}
//todo [kirillk] temporary consistency check
private Object[] getChildrenFor(final Object element) {
final Ref<Object[]> passOne = new Ref<>();
try (LockToken ignored = acquireLock()) {
execute(new TreeRunnable("AbstractTreeUi.getChildrenFor") {
@Override
public void perform() {
passOne.set(getTreeStructure().getChildElements(element));
}
});
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady(e);
return ArrayUtilRt.EMPTY_OBJECT_ARRAY;
}
if (!Registry.is("ide.tree.checkStructure")) return passOne.get();
final Object[] passTwo = getTreeStructure().getChildElements(element);
Set<Object> two = ContainerUtil.set(passTwo);
if (passOne.get().length != passTwo.length) {
LOG.error(
"AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" +
element);
}
else {
for (Object eachInOne : passOne.get()) {
if (!two.contains(eachInOne)) {
LOG.error(
"AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" +
element);
break;
}
}
}
return passOne.get();
}
private void warnOnIndexNotReady(IndexNotReadyException e) {
if (!myWasEverIndexNotReady) {
myWasEverIndexNotReady = true;
LOG.error("Tree is not dumb-mode-aware; treeBuilder=" + getBuilder() + " treeStructure=" + getTreeStructure(), e);
}
}
@NotNull
private ActionCallback updateNodesToInsert(@NotNull final List<? extends TreeNode> nodesToInsert,
@NotNull TreeUpdatePass pass,
boolean canSmartExpand,
boolean forceUpdate) {
ActionCallback.Chunk chunk = new ActionCallback.Chunk();
for (TreeNode node : nodesToInsert) {
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)node;
ActionCallback callback = updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true, true);
if (!callback.isDone()) {
chunk.add(callback);
}
}
return chunk.getWhenProcessed();
}
@NotNull
private Promise<?> processExistingNodes(@NotNull final DefaultMutableTreeNode node,
@NotNull final MutualMap<Object, Integer> elementToIndexMap,
@NotNull final TreeUpdatePass pass,
final boolean canSmartExpand,
final boolean forceUpdate,
final boolean wasExpanded,
@Nullable final LoadedChildren preloaded) {
final List<TreeNode> childNodes = TreeUtil.listChildren(node);
return maybeYield(() -> {
if (pass.isExpired()) return Promises.<Void>rejectedPromise();
if (childNodes.isEmpty()) return Promises.resolvedPromise();
List<Promise<?>> promises = new SmartList<>();
for (TreeNode each : childNodes) {
final DefaultMutableTreeNode eachChild = (DefaultMutableTreeNode)each;
if (isLoadingNode(eachChild)) {
continue;
}
final boolean childForceUpdate = isChildNodeForceUpdate(eachChild, forceUpdate, wasExpanded);
promises.add(maybeYield(() -> {
NodeDescriptor descriptor = preloaded != null ? preloaded.getDescriptor(getElementFor(eachChild)) : null;
NodeDescriptor descriptorFromNode = getDescriptorFrom(eachChild);
if (isValid(descriptor)) {
eachChild.setUserObject(descriptor);
if (descriptorFromNode != null) {
descriptor.setChildrenSortingStamp(descriptorFromNode.getChildrenSortingStamp());
}
}
else {
descriptor = descriptorFromNode;
}
return processExistingNode(eachChild, descriptor, node, elementToIndexMap, pass, canSmartExpand,
childForceUpdate, preloaded);
}, pass, node));
for (Promise<?> promise : promises) {
if (promise.getState() == Promise.State.REJECTED) {
return Promises.<Void>rejectedPromise();
}
}
}
return Promises.all(promises);
}, pass, node);
}
private boolean isRerunNeeded(@NotNull TreeUpdatePass pass) {
if (pass.isExpired() || !canInitiateNewActivity()) return false;
final boolean rerunBecauseTreeIsHidden = !pass.isExpired() && !isTreeShowing() && getUpdater().isInPostponeMode();
return rerunBecauseTreeIsHidden || getUpdater().isRerunNeededFor(pass);
}
public static <T> T calculateYieldingToWriteAction(@NotNull Supplier<? extends T> producer) throws ProcessCanceledException {
if (!Registry.is("ide.abstractTreeUi.BuildChildrenInBackgroundYieldingToWriteAction") ||
ApplicationManager.getApplication().isDispatchThread()) {
return producer.get();
}
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null && indicator.isRunning()) {
return producer.get();
}
Ref<T> result = new Ref<>();
boolean succeeded = ProgressManager.getInstance().runInReadActionWithWriteActionPriority(
() -> result.set(producer.get()),
indicator
);
if (!succeeded || indicator != null && indicator.isCanceled()) {
throw new ProcessCanceledException();
}
return result.get();
}
@FunctionalInterface
private interface AsyncRunnable {
@NotNull
Promise<?> run();
}
@NotNull
private Promise<?> maybeYield(@NotNull final AsyncRunnable processRunnable, @NotNull final TreeUpdatePass pass, final DefaultMutableTreeNode node) {
if (isRerunNeeded(pass)) {
getUpdater().requeue(pass);
return Promises.<Void>rejectedPromise();
}
if (canYield()) {
final AsyncPromise<?> result = new AsyncPromise<Void>();
pass.setCurrentNode(node);
boolean wasRun = yieldAndRun(new TreeRunnable("AbstractTreeUi.maybeYeild") {
@Override
public void perform() {
if (pass.isExpired()) {
result.setError("expired");
return;
}
if (isRerunNeeded(pass)) {
runDone(new TreeRunnable("AbstractTreeUi.maybeYeild: rerun") {
@Override
public void perform() {
if (!pass.isExpired()) {
queueUpdate(getElementFor(node));
}
}
});
result.setError("requeue");
}
else {
try {
//noinspection unchecked
execute(processRunnable).processed((Promise)result);
}
catch (ProcessCanceledException e) {
pass.expire();
cancelUpdate();
result.setError("rejected");
}
}
}
}, pass);
if (!wasRun) {
result.setError("rejected");
}
return result;
}
else {
try {
return execute(processRunnable);
}
catch (ProcessCanceledException e) {
pass.expire();
cancelUpdate();
return Promises.<Void>rejectedPromise();
}
}
}
@NotNull
private Promise<?> execute(@NotNull AsyncRunnable runnable) throws ProcessCanceledException {
try {
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
Promise<?> promise = runnable.run();
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
return promise;
}
catch (ProcessCanceledException e) {
if (!isReleased()) {
setCancelRequested(true);
resetToReady();
}
throw e;
}
}
private void execute(@NotNull Runnable runnable) throws ProcessCanceledException {
try {
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
runnable.run();
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
}
catch (ProcessCanceledException e) {
if (!isReleased()) {
setCancelRequested(true);
resetToReady();
}
throw e;
}
}
private boolean canInitiateNewActivity() {
return !isCancelProcessed() && !myReleaseRequested && !isReleased();
}
private void resetToReady() {
if (isReady()) {
return;
}
if (myResettingToReadyNow.get()) {
_getReady();
return;
}
myResettingToReadyNow.set(true);
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.resetToReady: later") {
@Override
public void perform() {
if (!myResettingToReadyNow.get()) {
return;
}
Progressive[] progressives = myBatchIndicators.keySet().toArray(new Progressive[0]);
for (Progressive each : progressives) {
myBatchIndicators.remove(each).cancel();
myBatchCallbacks.remove(each).setRejected();
}
resetToReadyNow();
}
});
}
@NotNull
private ActionCallback resetToReadyNow() {
if (isReleased()) return ActionCallback.REJECTED;
assertIsDispatchThread();
DefaultMutableTreeNode[] uc;
synchronized (myUpdatingChildren) {
uc = myUpdatingChildren.toArray(new DefaultMutableTreeNode[0]);
}
for (DefaultMutableTreeNode each : uc) {
resetIncompleteNode(each);
}
Object[] bg = ArrayUtil.toObjectArray(myLoadedInBackground.keySet());
for (Object each : bg) {
final DefaultMutableTreeNode node = getNodeForElement(each, false);
if (node != null) {
resetIncompleteNode(node);
}
}
myUpdaterState = null;
getUpdater().reset();
myYieldingNow = false;
myYieldingPasses.clear();
myYieldingDoneRunnables.clear();
myNodeActions.clear();
myNodeChildrenActions.clear();
synchronized (myUpdatingChildren) {
myUpdatingChildren.clear();
}
myLoadedInBackground.clear();
myDeferredExpansions.clear();
myDeferredSelections.clear();
ActionCallback result = _getReady();
result.doWhenDone(new TreeRunnable("AbstractTreeUi.resetToReadyNow: on done") {
@Override
public void perform() {
myResettingToReadyNow.set(false);
setCancelRequested(false);
}
});
maybeReady();
return result;
}
void addToCancelled(@NotNull DefaultMutableTreeNode node) {
myCancelledBuild.put(node, node);
}
private void removeFromCancelled(@NotNull DefaultMutableTreeNode node) {
myCancelledBuild.remove(node);
}
public boolean isCancelled(@NotNull Object node) {
return node instanceof DefaultMutableTreeNode && myCancelledBuild.containsKey(node);
}
private void resetIncompleteNode(@NotNull DefaultMutableTreeNode node) {
if (myReleaseRequested) return;
addToCancelled(node);
if (!isExpanded(node, false)) {
node.removeAllChildren();
Object element = getElementFor(node);
if (element != null && !getTreeStructure().isAlwaysLeaf(element)) {
insertLoadingNode(node, true);
}
}
else {
removeFromUnbuilt(node);
removeLoading(node, true);
}
}
private boolean yieldAndRun(@NotNull final Runnable runnable, @NotNull final TreeUpdatePass pass) {
myYieldingPasses.add(pass);
myYieldingNow = true;
yieldToEDT(new TreeRunnable("AbstractTreeUi.yieldAndRun") {
@Override
public void perform() {
if (isReleased()) return;
runOnYieldingDone(new TreeRunnable("AbstractTreeUi.yieldAndRun: inner") {
@Override
public void perform() {
if (isReleased()) return;
executeYieldingRequest(runnable, pass);
}
});
}
});
return true;
}
private boolean isYeildingNow() {
return myYieldingNow;
}
private boolean hasScheduledUpdates() {
return getUpdater().hasNodesToUpdate();
}
public boolean isReady() {
return isReady(false);
}
boolean isCancelledReady() {
return isReady(false) && !myCancelledBuild.isEmpty();
}
public boolean isReady(boolean attempt) {
if (attempt && myStateLock.isLocked()) return false;
Boolean ready = checkValue(() -> isIdle() && !hasPendingWork() && !isNodeActionsPending(), attempt);
return ready != null && ready.booleanValue();
}
@Nullable
private Boolean checkValue(@NotNull Computable<Boolean> computable, boolean attempt) {
try (LockToken ignored = attempt ? attemptLock() : acquireLock()) {
return computable.compute();
}
catch (InterruptedException e) {
LOG.info(e);
return null;
}
}
@NotNull
@NonNls
public String getStatus() {
return "isReady=" + isReady() + "\n" +
" isIdle=" + isIdle() + "\n" +
" isYeildingNow=" + isYeildingNow() + "\n" +
" isWorkerBusy=" + isWorkerBusy() + "\n" +
" hasUpdatingChildrenNow=" + hasUpdatingChildrenNow() + "\n" +
" isLoadingInBackgroundNow=" + isLoadingInBackgroundNow() + "\n" +
" hasPendingWork=" + hasPendingWork() + "\n" +
" hasNodesToUpdate=" + hasNodesToUpdate() + "\n" +
" updaterState=" + myUpdaterState + "\n" +
" hasScheduledUpdates=" + hasScheduledUpdates() + "\n" +
" isPostponedMode=" + getUpdater().isInPostponeMode() + "\n" +
" nodeActions=" + myNodeActions.keySet() + "\n" +
" nodeChildrenActions=" + myNodeChildrenActions.keySet() + "\n" +
"isReleased=" + isReleased() + "\n" +
" isReleaseRequested=" + isReleaseRequested() + "\n" +
"isCancelProcessed=" + isCancelProcessed() + "\n" +
" isCancelRequested=" + myCancelRequest + "\n" +
" isResettingToReadyNow=" + myResettingToReadyNow + "\n" +
"canInitiateNewActivity=" + canInitiateNewActivity() + "\n" +
"batchIndicators=" + myBatchIndicators;
}
public boolean hasPendingWork() {
return hasNodesToUpdate() ||
myUpdaterState != null && myUpdaterState.isProcessingNow() ||
hasScheduledUpdates() && !getUpdater().isInPostponeMode();
}
public boolean isIdle() {
return !isYeildingNow() && !isWorkerBusy() && !hasUpdatingChildrenNow() && !isLoadingInBackgroundNow();
}
private void executeYieldingRequest(@NotNull Runnable runnable, @NotNull TreeUpdatePass pass) {
try {
try {
myYieldingPasses.remove(pass);
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
runnable.run();
}
finally {
if (!isReleased()) {
maybeYieldingFinished();
}
}
}
catch (ProcessCanceledException e) {
resetToReady();
}
}
private void maybeYieldingFinished() {
if (myYieldingPasses.isEmpty()) {
myYieldingNow = false;
flushPendingNodeActions();
}
}
void maybeReady() {
assertIsDispatchThread();
if (isReleased()) return;
boolean ready = isReady(true);
if (!ready) return;
myRevalidatedObjects.clear();
setCancelRequested(false);
myResettingToReadyNow.set(false);
myInitialized.setDone();
if (canInitiateNewActivity()) {
if (myUpdaterState != null && !myUpdaterState.isProcessingNow()) {
UpdaterTreeState oldState = myUpdaterState;
if (!myUpdaterState.restore(null)) {
setUpdaterState(oldState);
}
if (!isReady(true)) return;
}
}
setHoldSize(false);
if (myTree.isShowing()) {
if (getBuilder().isToEnsureSelectionOnFocusGained() && Registry.is("ide.tree.ensureSelectionOnFocusGained")) {
TreeUtil.ensureSelection(myTree);
}
}
if (myInitialized.isDone()) {
if (isReleaseRequested() || isCancelProcessed()) {
myBusyObject.onReady(this);
} else {
myBusyObject.onReady();
}
}
if (canInitiateNewActivity()) {
TreePath[] selection = getTree().getSelectionPaths();
Rectangle visible = getTree().getVisibleRect();
if (selection != null) {
for (TreePath each : selection) {
Rectangle bounds = getTree().getPathBounds(each);
if (bounds != null && (visible.contains(bounds) || visible.intersects(bounds))) {
getTree().repaint(bounds);
}
}
}
}
}
private void flushPendingNodeActions() {
final DefaultMutableTreeNode[] nodes = myPendingNodeActions.toArray(new DefaultMutableTreeNode[0]);
myPendingNodeActions.clear();
for (DefaultMutableTreeNode each : nodes) {
processNodeActionsIfReady(each);
}
final Runnable[] actions = myYieldingDoneRunnables.toArray(new Runnable[0]);
for (Runnable each : actions) {
if (!isYeildingNow()) {
myYieldingDoneRunnables.remove(each);
each.run();
}
}
maybeReady();
}
protected void runOnYieldingDone(@NotNull Runnable onDone) {
getBuilder().runOnYieldingDone(onDone);
}
protected void yieldToEDT(@NotNull Runnable runnable) {
getBuilder().yieldToEDT(runnable);
}
@NotNull
private MutualMap<Object, Integer> loadElementsFromStructure(final NodeDescriptor descriptor,
@Nullable LoadedChildren preloadedChildren) {
MutualMap<Object, Integer> elementToIndexMap = new MutualMap<>(true);
final Object element = getElementFromDescriptor(descriptor);
if (!isValid(element)) return elementToIndexMap;
List<Object> children = preloadedChildren != null
? preloadedChildren.getElements()
: Arrays.asList(getChildrenFor(element));
int index = 0;
for (Object child : children) {
if (!isValid(child)) continue;
elementToIndexMap.put(child, index);
index++;
}
return elementToIndexMap;
}
public static boolean isLoadingNode(final Object node) {
return node instanceof LoadingNode;
}
@NotNull
private AsyncResult<List<TreeNode>> collectNodesToInsert(final NodeDescriptor descriptor,
@NotNull final MutualMap<Object, Integer> elementToIndexMap,
final DefaultMutableTreeNode parent,
final boolean addLoadingNode,
@NotNull final LoadedChildren loadedChildren) {
final AsyncResult<List<TreeNode>> result = new AsyncResult<>();
final List<TreeNode> nodesToInsert = new ArrayList<>();
Collection<Object> allElements = elementToIndexMap.getKeys();
ActionCallback processingDone = allElements.isEmpty() ? ActionCallback.DONE : new ActionCallback(allElements.size());
for (final Object child : allElements) {
Integer index = elementToIndexMap.getValue(child);
boolean needToUpdate = false;
NodeDescriptor loadedDesc = loadedChildren.getDescriptor(child);
final NodeDescriptor childDescr;
if (!isValid(loadedDesc, descriptor)) {
childDescr = getTreeStructure().createDescriptor(child, descriptor);
needToUpdate = true;
}
else {
childDescr = loadedDesc;
}
if (index == null) {
index = Integer.MAX_VALUE;
needToUpdate = true;
}
childDescr.setIndex(index.intValue());
final ActionCallback update = new ActionCallback();
if (needToUpdate) {
update(childDescr, false)
.onSuccess(changes -> {
loadedChildren.putDescriptor(child, childDescr, changes);
update.setDone();
});
}
else {
update.setDone();
}
update.doWhenDone(new TreeRunnable("AbstractTreeUi.collectNodesToInsert: on done update") {
@Override
public void perform() {
Object element = getElementFromDescriptor(childDescr);
if (!isNodeNull(element)) {
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null || node.getParent() != parent) {
final DefaultMutableTreeNode childNode = createChildNode(childDescr);
if (addLoadingNode || getBuilder().isAlwaysShowPlus(childDescr)) {
insertLoadingNode(childNode, true);
}
else {
addToUnbuilt(childNode);
}
nodesToInsert.add(childNode);
createMapping(element, childNode);
}
}
processingDone.setDone();
}
});
}
processingDone.doWhenDone(new TreeRunnable("AbstractTreeUi.collectNodesToInsert: on done processing") {
@Override
public void perform() {
result.setDone(nodesToInsert);
}
});
return result;
}
@NotNull
protected DefaultMutableTreeNode createChildNode(final NodeDescriptor descriptor) {
return new ElementNode(this, descriptor);
}
protected boolean canYield() {
return myCanYield && myYieldingUpdate.asBoolean();
}
private long getClearOnHideDelay() {
return myClearOnHideDelay;
}
@NotNull
public ActionCallback getInitialized() {
return myInitialized;
}
public ActionCallback getReady(@NotNull Object requestor) {
return myBusyObject.getReady(requestor);
}
private ActionCallback _getReady() {
return getReady(this);
}
private void addToUpdatingChildren(@NotNull DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
myUpdatingChildren.add(node);
}
}
private void removeFromUpdatingChildren(@NotNull DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
myUpdatingChildren.remove(node);
}
}
boolean isUpdatingChildrenNow(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
return myUpdatingChildren.contains(node);
}
}
boolean isParentUpdatingChildrenNow(@NotNull DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
DefaultMutableTreeNode eachParent = (DefaultMutableTreeNode)node.getParent();
while (eachParent != null) {
if (myUpdatingChildren.contains(eachParent)) return true;
eachParent = (DefaultMutableTreeNode)eachParent.getParent();
}
return false;
}
}
private boolean hasUpdatingChildrenNow() {
synchronized (myUpdatingChildren) {
return !myUpdatingChildren.isEmpty();
}
}
@NotNull
Map<Object, List<NodeAction>> getNodeActions() {
return myNodeActions;
}
@NotNull
List<Object> getLoadedChildrenFor(@NotNull Object element) {
List<Object> result = new ArrayList<>();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
for (int i = 0; i < node.getChildCount(); i++) {
TreeNode each = node.getChildAt(i);
if (isLoadingNode(each)) continue;
result.add(getElementFor(each));
}
}
return result;
}
boolean hasNodesToUpdate() {
return getUpdater().hasNodesToUpdate();
}
@NotNull
public List<Object> getExpandedElements() {
final List<Object> result = new ArrayList<>();
if (isReleased()) return result;
final Enumeration<TreePath> enumeration = myTree.getExpandedDescendants(getPathFor(getRootNode()));
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
TreePath each = enumeration.nextElement();
Object eachElement = getElementFor(each.getLastPathComponent());
if (eachElement != null) {
result.add(eachElement);
}
}
}
return result;
}
@NotNull
public ActionCallback cancelUpdate() {
if (isReleased()) return ActionCallback.REJECTED;
setCancelRequested(true);
final ActionCallback done = new ActionCallback();
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.cancelUpdate") {
@Override
public void perform() {
if (isReleased()) {
done.setRejected();
return;
}
if (myResettingToReadyNow.get()) {
_getReady().notify(done);
} else if (isReady()) {
resetToReadyNow();
done.setDone();
} else {
if (isIdle() && hasPendingWork()) {
resetToReadyNow();
done.setDone();
} else {
_getReady().notify(done);
}
}
maybeReady();
}
});
if (isEdt() || isPassthroughMode()) {
maybeReady();
}
return done;
}
private void setCancelRequested(boolean requested) {
try (LockToken ignored = isUnitTestingMode() ? acquireLock() : attemptLock()) {
myCancelRequest.set(requested);
}
catch (InterruptedException ignored) {
}
}
@Nullable
private LockToken attemptLock() throws InterruptedException {
return LockToken.attemptLock(myStateLock, Registry.intValue("ide.tree.uiLockAttempt"));
}
@NotNull
private LockToken acquireLock() {
return LockToken.acquireLock(myStateLock);
}
@NotNull
public ActionCallback batch(@NotNull final Progressive progressive) {
assertIsDispatchThread();
EmptyProgressIndicator indicator = new EmptyProgressIndicator();
final ActionCallback callback = new ActionCallback();
myBatchIndicators.put(progressive, indicator);
myBatchCallbacks.put(progressive, callback);
try {
progressive.run(indicator);
}
catch (ProcessCanceledException e) {
resetToReadyNow().doWhenProcessed(new TreeRunnable("AbstractTreeUi.batch: catch") {
@Override
public void perform() {
callback.setRejected();
}
});
return callback;
}
finally {
if (isReleased()) return ActionCallback.REJECTED;
_getReady().doWhenDone(new TreeRunnable("AbstractTreeUi.batch: finally") {
@Override
public void perform() {
if (myBatchIndicators.containsKey(progressive)) {
ProgressIndicator indicator = myBatchIndicators.remove(progressive);
myBatchCallbacks.remove(progressive);
if (indicator.isCanceled()) {
callback.setRejected();
} else {
callback.setDone();
}
} else {
callback.setRejected();
}
}
});
maybeReady();
}
return callback;
}
boolean isCancelProcessed() {
return myCancelRequest.get() || myResettingToReadyNow.get();
}
boolean isToPaintSelection() {
return isReady(true) || !mySelectionIsAdjusted;
}
boolean isReleaseRequested() {
return myReleaseRequested;
}
public void executeUserRunnable(@NotNull Runnable runnable) {
try {
myUserRunnables.add(runnable);
runnable.run();
}
finally {
myUserRunnables.remove(runnable);
}
}
static class ElementNode extends DefaultMutableTreeNode {
Set<Object> myElements = new HashSet<>();
AbstractTreeUi myUi;
ElementNode(AbstractTreeUi ui, NodeDescriptor descriptor) {
super(descriptor);
myUi = ui;
}
@Override
public void insert(final MutableTreeNode newChild, final int childIndex) {
super.insert(newChild, childIndex);
final Object element = myUi.getElementFor(newChild);
if (element != null) {
myElements.add(element);
}
}
@Override
public void remove(final int childIndex) {
final TreeNode node = getChildAt(childIndex);
super.remove(childIndex);
final Object element = myUi.getElementFor(node);
if (element != null) {
myElements.remove(element);
}
}
boolean isValidChild(Object childElement) {
return myElements.contains(childElement);
}
@Override
public String toString() {
return String.valueOf(getUserObject());
}
}
private boolean isUpdatingParent(DefaultMutableTreeNode kid) {
return getUpdatingParent(kid) != null;
}
@Nullable
private DefaultMutableTreeNode getUpdatingParent(DefaultMutableTreeNode kid) {
DefaultMutableTreeNode eachParent = kid;
while (eachParent != null) {
if (isUpdatingChildrenNow(eachParent)) return eachParent;
eachParent = (DefaultMutableTreeNode)eachParent.getParent();
}
return null;
}
private boolean isLoadedInBackground(Object element) {
return getLoadedInBackground(element) != null;
}
private UpdateInfo getLoadedInBackground(Object element) {
synchronized (myLoadedInBackground) {
return isNodeNull(element) ? null : myLoadedInBackground.get(element);
}
}
private void addToLoadedInBackground(Object element, UpdateInfo info) {
if (isNodeNull(element)) return;
synchronized (myLoadedInBackground) {
warnMap("put into myLoadedInBackground: ", myLoadedInBackground);
myLoadedInBackground.put(element, info);
}
}
private void removeFromLoadedInBackground(final Object element) {
if (isNodeNull(element)) return;
synchronized (myLoadedInBackground) {
warnMap("remove from myLoadedInBackground: ", myLoadedInBackground);
myLoadedInBackground.remove(element);
}
}
private boolean isLoadingInBackgroundNow() {
synchronized (myLoadedInBackground) {
return !myLoadedInBackground.isEmpty();
}
}
private void queueBackgroundUpdate(@NotNull final UpdateInfo updateInfo, @NotNull final DefaultMutableTreeNode node) {
assertIsDispatchThread();
final Object oldElementFromDescriptor = getElementFromDescriptor(updateInfo.getDescriptor());
if (isNodeNull(oldElementFromDescriptor)) return;
UpdateInfo loaded = getLoadedInBackground(oldElementFromDescriptor);
if (loaded != null) {
loaded.apply(updateInfo);
return;
}
addToLoadedInBackground(oldElementFromDescriptor, updateInfo);
maybeSetBusyAndScheduleWaiterForReady(true, oldElementFromDescriptor);
if (!isNodeBeingBuilt(node)) {
LoadingNode loadingNode = new LoadingNode(getLoadingNodeText());
myTreeModel.insertNodeInto(loadingNode, node, node.getChildCount());
}
removeFromUnbuilt(node);
final Ref<LoadedChildren> children = new Ref<>();
final Ref<Object> elementFromDescriptor = new Ref<>();
final DefaultMutableTreeNode[] nodeToProcessActions = new DefaultMutableTreeNode[1];
final TreeConsumer<Void> finalizeRunnable = new TreeConsumer<>("AbstractTreeUi.queueBackgroundUpdate: finalize") {
@Override
public void perform() {
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: finalize later") {
@Override
public void perform() {
if (isReleased()) return;
removeLoading(node, false);
removeFromLoadedInBackground(elementFromDescriptor.get());
removeFromLoadedInBackground(oldElementFromDescriptor);
if (nodeToProcessActions[0] != null) {
processNodeActionsIfReady(nodeToProcessActions[0]);
}
}
});
}
};
Runnable buildRunnable = new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: build") {
@Override
public void perform() {
if (updateInfo.getPass().isExpired()) {
finalizeRunnable.run();
return;
}
if (!updateInfo.isDescriptorIsUpToDate()) {
update(updateInfo.getDescriptor(), true);
}
if (!updateInfo.isUpdateChildren()) {
nodeToProcessActions[0] = node;
return;
}
Object element = getElementFromDescriptor(updateInfo.getDescriptor());
if (element == null) {
removeFromLoadedInBackground(oldElementFromDescriptor);
finalizeRunnable.run();
return;
}
elementFromDescriptor.set(element);
Object[] loadedElements = getChildrenFor(element);
final LoadedChildren loaded = new LoadedChildren(loadedElements);
for (final Object each : loadedElements) {
NodeDescriptor<?> existingDesc = getDescriptorFrom(getNodeForElement(each, true));
NodeDescriptor<?> eachChildDescriptor = isValid(existingDesc, updateInfo.getDescriptor()) ? existingDesc : getTreeStructure().createDescriptor(each, updateInfo.getDescriptor());
execute(new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate") {
@Override
public void perform() {
try {
loaded.putDescriptor(each, eachChildDescriptor, update(eachChildDescriptor, true).blockingGet(0));
}
catch (TimeoutException | ExecutionException e) {
LOG.error(e);
}
}
});
}
children.set(loaded);
}
@NotNull
@NonNls
@Override
public String toString() {
return "runnable=" + oldElementFromDescriptor;
}
};
Runnable updateRunnable = new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: update") {
@Override
public void perform() {
if (updateInfo.getPass().isExpired()) {
finalizeRunnable.run();
return;
}
if (children.get() == null) {
finalizeRunnable.run();
return;
}
if (isRerunNeeded(updateInfo.getPass())) {
removeFromLoadedInBackground(elementFromDescriptor.get());
getUpdater().requeue(updateInfo.getPass());
return;
}
removeFromLoadedInBackground(elementFromDescriptor.get());
if (myUnbuiltNodes.contains(node)) {
Pair<Boolean, LoadedChildren> unbuilt =
processUnbuilt(node, updateInfo.getDescriptor(), updateInfo.getPass(), isExpanded(node, updateInfo.isWasExpanded()),
children.get());
if (unbuilt.getFirst()) {
nodeToProcessActions[0] = node;
return;
}
}
ActionCallback callback = updateNodeChildren(node, updateInfo.getPass(), children.get(),
true, updateInfo.isCanSmartExpand(), updateInfo.isForceUpdate(), true, true);
callback.doWhenDone(new TreeRunnable("AbstractTreeUi.queueBackgroundUpdate: on done updateNodeChildren") {
@Override
public void perform() {
if (isRerunNeeded(updateInfo.getPass())) {
getUpdater().requeue(updateInfo.getPass());
return;
}
Object element = elementFromDescriptor.get();
if (element != null) {
removeLoading(node, false);
nodeToProcessActions[0] = node;
}
}
});
}
};
queueToBackground(buildRunnable, updateRunnable)
.onSuccess(finalizeRunnable)
.onError(new TreeConsumer<>("AbstractTreeUi.queueBackgroundUpdate: on rejected") {
@Override
public void perform() {
updateInfo.getPass().expire();
}
});
}
private boolean isExpanded(@NotNull DefaultMutableTreeNode node, boolean isExpanded) {
return isExpanded || myTree.isExpanded(getPathFor(node));
}
private void removeLoading(@NotNull DefaultMutableTreeNode parent, boolean forced) {
if (!forced && myUnbuiltNodes.contains(parent) && !myCancelledBuild.containsKey(parent)) {
return;
}
boolean reallyRemoved = false;
for (int i = 0; i < parent.getChildCount(); i++) {
TreeNode child = parent.getChildAt(i);
if (removeIfLoading(child)) {
reallyRemoved = true;
i--;
}
}
maybeReady();
if (reallyRemoved) {
nodeStructureChanged(parent);
}
}
private void processNodeActionsIfReady(@NotNull final DefaultMutableTreeNode node) {
assertIsDispatchThread();
if (isNodeBeingBuilt(node)) return;
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
if (isYeildingNow()) {
myPendingNodeActions.add(node);
return;
}
final Object element = getElementFromDescriptor(descriptor);
boolean childrenReady = !isLoadedInBackground(element) && !isUpdatingChildrenNow(node);
processActions(node, element, myNodeActions, childrenReady ? myNodeChildrenActions : null);
if (childrenReady) {
processActions(node, element, myNodeChildrenActions, null);
}
warnMap("myNodeActions: processNodeActionsIfReady: ", myNodeActions);
warnMap("myNodeChildrenActions: processNodeActionsIfReady: ", myNodeChildrenActions);
if (!isUpdatingParent(node) && !isWorkerBusy()) {
final UpdaterTreeState state = myUpdaterState;
if (myNodeActions.isEmpty() && state != null && !state.isProcessingNow()) {
if (canInitiateNewActivity()) {
if (!state.restore(childrenReady ? node : null)) {
setUpdaterState(state);
}
}
}
}
maybeReady();
}
private static void processActions(@NotNull DefaultMutableTreeNode node,
Object element,
@NotNull final Map<Object, List<NodeAction>> nodeActions,
@Nullable final Map<Object, List<NodeAction>> secondaryNodeAction) {
final List<NodeAction> actions = nodeActions.get(element);
if (actions != null) {
nodeActions.remove(element);
List<NodeAction> secondary = secondaryNodeAction != null ? secondaryNodeAction.get(element) : null;
for (NodeAction each : actions) {
if (secondary != null) {
secondary.remove(each);
}
each.onReady(node);
}
}
}
private boolean canSmartExpand(DefaultMutableTreeNode node, boolean canSmartExpand) {
if (!canInitiateNewActivity()) return false;
if (!getBuilder().isSmartExpand()) return false;
boolean smartExpand = canSmartExpand && !myNotForSmartExpand.contains(node);
Object element = getElementFor(node);
return smartExpand && element != null && validateAutoExpand(true, element);
}
private void processSmartExpand(@NotNull final DefaultMutableTreeNode node, final boolean canSmartExpand, boolean forced) {
if (!canInitiateNewActivity()) return;
if (!getBuilder().isSmartExpand()) return;
boolean can = canSmartExpand(node, canSmartExpand);
if (!can && !forced) return;
if (isNodeBeingBuilt(node) && !forced) {
addNodeAction(getElementFor(node), true, node1 -> processSmartExpand(node1, canSmartExpand, true));
}
else {
TreeNode child = getChildForSmartExpand(node);
if (child != null) {
final TreePath childPath = new TreePath(node.getPath()).pathByAddingChild(child);
processInnerChange(new TreeRunnable("AbstractTreeUi.processSmartExpand") {
@Override
public void perform() {
myTree.expandPath(childPath);
}
});
}
}
}
@Nullable
private static TreeNode getChildForSmartExpand(@NotNull DefaultMutableTreeNode node) {
int realChildCount = 0;
TreeNode nodeToExpand = null;
for (int i = 0; i < node.getChildCount(); i++) {
TreeNode eachChild = node.getChildAt(i);
if (!isLoadingNode(eachChild)) {
realChildCount++;
if (nodeToExpand == null) {
nodeToExpand = eachChild;
}
}
if (realChildCount > 1) {
nodeToExpand = null;
break;
}
}
return nodeToExpand;
}
public static boolean isLoadingChildrenFor(final Object nodeObject) {
if (!(nodeObject instanceof DefaultMutableTreeNode)) return false;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject;
int loadingNodes = 0;
for (int i = 0; i < Math.min(node.getChildCount(), 2); i++) {
TreeNode child = node.getChildAt(i);
if (isLoadingNode(child)) {
loadingNodes++;
}
}
return loadingNodes > 0 && loadingNodes == node.getChildCount();
}
boolean isParentLoadingInBackground(@NotNull Object nodeObject) {
return getParentLoadingInBackground(nodeObject) != null;
}
@Nullable
private DefaultMutableTreeNode getParentLoadingInBackground(@NotNull Object nodeObject) {
if (!(nodeObject instanceof DefaultMutableTreeNode)) return null;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject;
TreeNode eachParent = node.getParent();
while (eachParent != null) {
eachParent = eachParent.getParent();
if (eachParent instanceof DefaultMutableTreeNode) {
final Object eachElement = getElementFor(eachParent);
if (isLoadedInBackground(eachElement)) return (DefaultMutableTreeNode)eachParent;
}
}
return null;
}
private static @Nls String getLoadingNodeText() {
return IdeBundle.message("progress.searching");
}
@NotNull
private Promise<?> processExistingNode(@NotNull final DefaultMutableTreeNode childNode,
final NodeDescriptor childDescriptor,
@NotNull final DefaultMutableTreeNode parentNode,
@NotNull final MutualMap<Object, Integer> elementToIndexMap,
@NotNull final TreeUpdatePass pass,
final boolean canSmartExpand,
final boolean forceUpdate,
@Nullable LoadedChildren parentPreloadedChildren) {
if (pass.isExpired()) {
return Promises.<Void>rejectedPromise();
}
if (childDescriptor == null) {
pass.expire();
return Promises.<Void>rejectedPromise();
}
final Object oldElement = getElementFromDescriptor(childDescriptor);
if (isNodeNull(oldElement)) {
// if a tree node with removed element was not properly removed from a tree model
// we must not ignore this situation and should remove a wrong node
removeNodeFromParent(childNode, true);
doUpdateNode(parentNode);
return Promises.<Void>resolvedPromise();
}
Promise<Boolean> update;
if (parentPreloadedChildren != null && parentPreloadedChildren.getDescriptor(oldElement) == childDescriptor) {
update = Promises.resolvedPromise(parentPreloadedChildren.isUpdated(oldElement));
}
else {
update = update(childDescriptor, false);
}
final AsyncPromise<Void> result = new AsyncPromise<>();
final Ref<NodeDescriptor> childDesc = new Ref<>(childDescriptor);
update
.onSuccess(isChanged -> {
final AtomicBoolean changes = new AtomicBoolean(isChanged);
final AtomicBoolean forceRemapping = new AtomicBoolean();
final Ref<Object> newElement = new Ref<>(getElementFromDescriptor(childDesc.get()));
final Integer index = newElement.get() == null ? null : elementToIndexMap.getValue(getElementFromDescriptor(childDesc.get()));
Promise<Boolean> promise;
if (index == null) {
promise = Promises.resolvedPromise(false);
}
else {
final Object elementFromMap = elementToIndexMap.getKey(index);
if (elementFromMap != newElement.get() && elementFromMap.equals(newElement.get())) {
if (isInStructure(elementFromMap) && isInStructure(newElement.get())) {
final AsyncPromise<Boolean> updateIndexDone = new AsyncPromise<>();
promise = updateIndexDone;
NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode);
if (parentDescriptor != null) {
childDesc.set(getTreeStructure().createDescriptor(elementFromMap, parentDescriptor));
NodeDescriptor oldDesc = getDescriptorFrom(childNode);
if (isValid(oldDesc)) {
childDesc.get().applyFrom(oldDesc);
}
childNode.setUserObject(childDesc.get());
newElement.set(elementFromMap);
forceRemapping.set(true);
update(childDesc.get(), false)
.onSuccess(isChanged1 -> {
changes.set(isChanged1);
updateIndexDone.setResult(isChanged1);
});
}
// todo why we don't process promise here?
}
else {
promise = Promises.resolvedPromise(changes.get());
}
}
else {
promise = Promises.resolvedPromise(changes.get());
}
promise
.onSuccess(new TreeConsumer<>("AbstractTreeUi.processExistingNode: on done index updating after update") {
@Override
public void perform() {
if (childDesc.get().getIndex() != index.intValue()) {
changes.set(true);
}
childDesc.get().setIndex(index.intValue());
}
});
}
promise
.onSuccess(new TreeConsumer<>("AbstractTreeUi.processExistingNode: on done index updating") {
@Override
public void perform() {
if (!oldElement.equals(newElement.get()) || forceRemapping.get()) {
removeMapping(oldElement, childNode, newElement.get());
Object newE = newElement.get();
if (!isNodeNull(newE)) {
createMapping(newE, childNode);
}
NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode);
if (parentDescriptor != null) {
parentDescriptor.setChildrenSortingStamp(-1);
}
}
if (index == null) {
int selectedIndex = -1;
if (TreeBuilderUtil.isNodeOrChildSelected(myTree, childNode)) {
selectedIndex = parentNode.getIndex(childNode);
}
if (childNode.getParent() instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)childNode.getParent();
if (myTree.isExpanded(new TreePath(parent.getPath()))) {
if (parent.getChildCount() == 1 && parent.getChildAt(0) == childNode) {
insertLoadingNode(parent, false);
}
}
}
Object disposedElement = getElementFor(childNode);
removeNodeFromParent(childNode, selectedIndex >= 0);
disposeNode(childNode);
adjustSelectionOnChildRemove(parentNode, selectedIndex, disposedElement);
result.setResult(null);
}
else {
elementToIndexMap.remove(getElementFromDescriptor(childDesc.get()));
updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true, true)
.doWhenDone(() -> result.setResult(null));
}
}
});
});
return result;
}
private void adjustSelectionOnChildRemove(@NotNull DefaultMutableTreeNode parentNode, int selectedIndex, Object disposedElement) {
if (selectedIndex >= 0 && !getSelectedElements().isEmpty()) return;
DefaultMutableTreeNode node = disposedElement == null ? null : getNodeForElement(disposedElement, false);
if (node != null && isValidForSelectionAdjusting(node)) {
Object newElement = getElementFor(node);
addSelectionPath(getPathFor(node), true, getExpiredElementCondition(newElement), disposedElement);
return;
}
if (selectedIndex >= 0) {
if (parentNode.getChildCount() > 0) {
if (parentNode.getChildCount() > selectedIndex) {
TreeNode newChildNode = parentNode.getChildAt(selectedIndex);
if (isValidForSelectionAdjusting(newChildNode)) {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChildNode)), true, getExpiredElementCondition(disposedElement),
disposedElement);
}
}
else {
TreeNode newChild = parentNode.getChildAt(parentNode.getChildCount() - 1);
if (isValidForSelectionAdjusting(newChild)) {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChild)), true, getExpiredElementCondition(disposedElement),
disposedElement);
}
}
}
else {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(parentNode)), true, getExpiredElementCondition(disposedElement),
disposedElement);
}
}
}
private boolean isValidForSelectionAdjusting(@NotNull TreeNode node) {
if (!myTree.isRootVisible() && getRootNode() == node) return false;
if (isLoadingNode(node)) return true;
final Object elementInTree = getElementFor(node);
if (elementInTree == null) return false;
final TreeNode parentNode = node.getParent();
final Object parentElementInTree = getElementFor(parentNode);
if (parentElementInTree == null) return false;
final Object parentElement = getTreeStructure().getParentElement(elementInTree);
return parentElementInTree.equals(parentElement);
}
@NotNull
private Condition getExpiredElementCondition(final Object element) {
return o -> isInStructure(element);
}
private void addSelectionPath(@NotNull final TreePath path,
final boolean isAdjustedSelection,
final Condition isExpiredAdjustment,
@Nullable final Object adjustmentCause) {
processInnerChange(new TreeRunnable("AbstractTreeUi.addSelectionPath") {
@Override
public void perform() {
TreePath toSelect = null;
if (isLoadingNode(path.getLastPathComponent())) {
final TreePath parentPath = path.getParentPath();
if (parentPath != null && isValidForSelectionAdjusting((TreeNode)parentPath.getLastPathComponent())) {
toSelect = parentPath;
}
}
else {
toSelect = path;
}
if (toSelect != null) {
mySelectionIsAdjusted = isAdjustedSelection;
myTree.addSelectionPath(toSelect);
if (isAdjustedSelection && myUpdaterState != null) {
final Object toSelectElement = getElementFor(toSelect.getLastPathComponent());
myUpdaterState.addAdjustedSelection(toSelectElement, isExpiredAdjustment, adjustmentCause);
}
}
}
});
}
@NotNull
private static TreePath getPathFor(@NotNull TreeNode node) {
if (node instanceof DefaultMutableTreeNode) {
return new TreePath(((DefaultMutableTreeNode)node).getPath());
}
else {
List<TreeNode> nodes = new ArrayList<>();
TreeNode eachParent = node;
while (eachParent != null) {
nodes.add(eachParent);
eachParent = eachParent.getParent();
}
return new TreePath(ArrayUtil.toObjectArray(nodes));
}
}
private void removeNodeFromParent(@NotNull final MutableTreeNode node, final boolean willAdjustSelection) {
processInnerChange(new TreeRunnable("AbstractTreeUi.removeNodeFromParent") {
@Override
public void perform() {
if (willAdjustSelection) {
final TreePath path = getPathFor(node);
if (myTree.isPathSelected(path)) {
myTree.removeSelectionPath(path);
}
}
if (node.getParent() != null) {
myTreeModel.removeNodeFromParent(node);
}
}
});
}
private void expandPath(@NotNull final TreePath path, final boolean canSmartExpand) {
processInnerChange(new TreeRunnable("AbstractTreeUi.expandPath") {
@Override
public void perform() {
if (path.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getChildCount() > 0 && !myTree.isExpanded(path)) {
if (!canSmartExpand) {
myNotForSmartExpand.add(node);
}
try {
myRequestedExpand = path;
myTree.expandPath(path);
processSmartExpand(node, canSmartExpand, false);
}
finally {
myNotForSmartExpand.remove(node);
myRequestedExpand = null;
}
}
else {
processNodeActionsIfReady(node);
}
}
}
});
}
private void processInnerChange(Runnable runnable) {
if (myUpdaterState == null) {
setUpdaterState(new UpdaterTreeState(this));
}
myUpdaterState.process(runnable);
}
private boolean isInnerChange() {
return myUpdaterState != null && myUpdaterState.isProcessingNow() && myUserRunnables.isEmpty();
}
private void makeLoadingOrLeafIfNoChildren(@NotNull final DefaultMutableTreeNode node) {
TreePath path = getPathFor(node);
insertLoadingNode(node, true);
final NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
descriptor.setChildrenSortingStamp(-1);
if (getBuilder().isAlwaysShowPlus(descriptor)) return;
TreePath parentPath = path.getParentPath();
if (myTree.isVisible(path) || parentPath != null && myTree.isExpanded(parentPath)) {
if (myTree.isExpanded(path)) {
addSubtreeToUpdate(node);
}
else {
insertLoadingNode(node, false);
}
}
}
/**
* Indicates whether the given {@code descriptor} is valid
* and its parent is equal to the specified {@code parent}.
*
* @param descriptor a descriptor to test
* @param parent an expected parent for the testing descriptor
* @return {@code true} if the specified descriptor is valid
*/
private boolean isValid(NodeDescriptor descriptor, NodeDescriptor parent) {
if (descriptor == null) return false;
if (parent != null && parent != descriptor.getParentDescriptor()) return false;
return isValid(getElementFromDescriptor(descriptor));
}
private boolean isValid(@Nullable NodeDescriptor descriptor) {
return descriptor != null && isValid(getElementFromDescriptor(descriptor));
}
private boolean isValid(Object element) {
if (isNodeNull(element)) return false;
if (element instanceof ValidateableNode) {
if (!((ValidateableNode)element).isValid()) return false;
}
return getBuilder().validateNode(element);
}
private void insertLoadingNode(final DefaultMutableTreeNode node, boolean addToUnbuilt) {
if (!isLoadingChildrenFor(node)) {
myTreeModel.insertNodeInto(new LoadingNode(), node, 0);
}
if (addToUnbuilt) {
addToUnbuilt(node);
}
}
@NotNull
private Promise<Void> queueToBackground(@NotNull final Runnable bgBuildAction, @Nullable final Runnable edtPostRunnable) {
if (!canInitiateNewActivity()) return Promises.rejectedPromise();
final AsyncPromise<Void> result = new AsyncPromise<>();
final AtomicReference<ProcessCanceledException> fail = new AtomicReference<>();
final Runnable finalizer = new TreeRunnable("AbstractTreeUi.queueToBackground: finalizer") {
@Override
public void perform() {
ProcessCanceledException exception = fail.get();
if (exception == null) {
result.setResult(null);
}
else {
result.setError(exception);
}
}
};
registerWorkerTask(bgBuildAction);
final Runnable pooledThreadWithProgressRunnable = new TreeRunnable("AbstractTreeUi.queueToBackground: progress") {
@Override
public void perform() {
try {
final AbstractTreeBuilder builder = getBuilder();
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
builder.runBackgroundLoading(new TreeRunnable("AbstractTreeUi.queueToBackground: background") {
@Override
public void perform() {
assertNotDispatchThread();
try {
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
execute(bgBuildAction);
if (edtPostRunnable != null) {
builder.updateAfterLoadedInBackground(new TreeRunnable("AbstractTreeUi.queueToBackground: update after") {
@Override
public void perform() {
try {
assertIsDispatchThread();
if (!canInitiateNewActivity()) {
throw new ProcessCanceledException();
}
execute(edtPostRunnable);
}
catch (ProcessCanceledException e) {
fail.set(e);
cancelUpdate();
}
finally {
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
});
}
else {
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
catch (ProcessCanceledException e) {
fail.set(e);
unregisterWorkerTask(bgBuildAction, finalizer);
cancelUpdate();
}
catch (Throwable t) {
unregisterWorkerTask(bgBuildAction, finalizer);
throw new RuntimeException(t);
}
}
});
}
catch (ProcessCanceledException e) {
unregisterWorkerTask(bgBuildAction, finalizer);
cancelUpdate();
}
}
};
Runnable pooledThreadRunnable = new TreeRunnable("AbstractTreeUi.queueToBackground") {
@Override
public void perform() {
try {
if (myProgress != null && ProgressManager.getGlobalProgressIndicator() != myProgress) {
ProgressManager.getInstance().runProcess(pooledThreadWithProgressRunnable, myProgress);
}
else {
execute(pooledThreadWithProgressRunnable);
}
}
catch (ProcessCanceledException e) {
fail.set(e);
unregisterWorkerTask(bgBuildAction, finalizer);
cancelUpdate();
}
}
};
if (isPassthroughMode()) {
execute(pooledThreadRunnable);
}
else {
myWorker.addFirst(pooledThreadRunnable);
}
return result;
}
private void registerWorkerTask(@NotNull Runnable runnable) {
synchronized (myActiveWorkerTasks) {
myActiveWorkerTasks.add(runnable);
}
}
private void unregisterWorkerTask(@NotNull Runnable runnable, @Nullable Runnable finalizeRunnable) {
boolean wasRemoved;
synchronized (myActiveWorkerTasks) {
wasRemoved = myActiveWorkerTasks.remove(runnable);
}
if (wasRemoved && finalizeRunnable != null) {
finalizeRunnable.run();
}
invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.unregisterWorkerTask") {
@Override
public void perform() {
maybeReady();
}
});
}
private boolean isWorkerBusy() {
synchronized (myActiveWorkerTasks) {
return !myActiveWorkerTasks.isEmpty();
}
}
private void clearWorkerTasks() {
synchronized (myActiveWorkerTasks) {
myActiveWorkerTasks.clear();
}
}
private void updateNodeImageAndPosition(@NotNull final DefaultMutableTreeNode node) {
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
if (getElementFromDescriptor(descriptor) == null) return;
nodeChanged(node);
}
private void nodeChanged(final DefaultMutableTreeNode node) {
invokeLaterIfNeeded(true, new TreeRunnable("AbstractTreeUi.nodeChanged") {
@Override
public void perform() {
myTreeModel.nodeChanged(node);
}
});
}
private void nodeStructureChanged(final DefaultMutableTreeNode node) {
invokeLaterIfNeeded(true, new TreeRunnable("AbstractTreeUi.nodeStructureChanged") {
@Override
public void perform() {
myTreeModel.nodeStructureChanged(node);
}
});
}
public DefaultTreeModel getTreeModel() {
return myTreeModel;
}
private void insertNodesInto(@NotNull final List<? extends TreeNode> toInsert, @NotNull final DefaultMutableTreeNode parentNode) {
sortChildren(parentNode, toInsert, false, true);
final List<TreeNode> all = new ArrayList<>(toInsert.size() + parentNode.getChildCount());
all.addAll(toInsert);
all.addAll(TreeUtil.listChildren(parentNode));
if (!toInsert.isEmpty()) {
sortChildren(parentNode, all, true, true);
int[] newNodeIndices = new int[toInsert.size()];
int eachNewNodeIndex = 0;
TreeMap<Integer, TreeNode> insertSet = new TreeMap<>();
for (int i = 0; i < toInsert.size(); i++) {
TreeNode eachNewNode = toInsert.get(i);
while (all.get(eachNewNodeIndex) != eachNewNode) {
eachNewNodeIndex++;
}
newNodeIndices[i] = eachNewNodeIndex;
insertSet.put(eachNewNodeIndex, eachNewNode);
}
for (Map.Entry<Integer, TreeNode> entry : insertSet.entrySet()) {
TreeNode eachNode = entry.getValue();
Integer index = entry.getKey();
parentNode.insert((MutableTreeNode)eachNode, index);
}
myTreeModel.nodesWereInserted(parentNode, newNodeIndices);
}
else {
List<TreeNode> before = new ArrayList<>(all);
sortChildren(parentNode, all, true, false);
if (!before.equals(all)) {
processInnerChange(new TreeRunnable("AbstractTreeUi.insertNodesInto") {
@Override
public void perform() {
Enumeration<TreePath> expanded = getTree().getExpandedDescendants(getPathFor(parentNode));
TreePath[] selected = getTree().getSelectionModel().getSelectionPaths();
parentNode.removeAllChildren();
for (TreeNode each : all) {
parentNode.add((MutableTreeNode)each);
}
nodeStructureChanged(parentNode);
if (expanded != null) {
while (expanded.hasMoreElements()) {
expandSilently(expanded.nextElement());
}
}
if (selected != null) {
for (TreePath each : selected) {
if (!getTree().getSelectionModel().isPathSelected(each)) {
addSelectionSilently(each);
}
}
}
}
});
}
}
}
private void sortChildren(@NotNull DefaultMutableTreeNode node, @NotNull List<? extends TreeNode> children, boolean updateStamp, boolean forceSort) {
NodeDescriptor descriptor = getDescriptorFrom(node);
assert descriptor != null;
if (descriptor.getChildrenSortingStamp() >= getComparatorStamp() && !forceSort) return;
if (!children.isEmpty()) {
try {
getBuilder().sortChildren(myNodeComparator, node, children);
}
catch (IllegalArgumentException exception) {
StringBuilder sb = new StringBuilder("cannot sort children in ").append(toString());
children.forEach(child -> sb.append('\n').append(child));
throw new IllegalArgumentException(sb.toString(), exception);
}
}
if (updateStamp) {
descriptor.setChildrenSortingStamp(getComparatorStamp());
}
}
private void disposeNode(@NotNull DefaultMutableTreeNode node) {
TreeNode parent = node.getParent();
if (parent instanceof DefaultMutableTreeNode) {
addToUnbuilt((DefaultMutableTreeNode)parent);
}
if (node.getChildCount() > 0) {
for (DefaultMutableTreeNode _node = (DefaultMutableTreeNode)node.getFirstChild(); _node != null; _node = _node.getNextSibling()) {
disposeNode(_node);
}
}
removeFromUpdatingChildren(node);
removeFromUnbuilt(node);
removeFromCancelled(node);
if (isLoadingNode(node)) return;
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
final Object element = getElementFromDescriptor(descriptor);
if (!isNodeNull(element)) {
removeMapping(element, node, null);
}
myAutoExpandRoots.remove(element);
node.setUserObject(null);
node.removeAllChildren();
}
public boolean addSubtreeToUpdate(@NotNull final DefaultMutableTreeNode root) {
return addSubtreeToUpdate(root, true);
}
public boolean addSubtreeToUpdate(@NotNull final DefaultMutableTreeNode root, boolean updateStructure) {
return addSubtreeToUpdate(root, null, updateStructure);
}
public boolean addSubtreeToUpdate(@NotNull final DefaultMutableTreeNode root, final Runnable runAfterUpdate) {
return addSubtreeToUpdate(root, runAfterUpdate, true);
}
public boolean addSubtreeToUpdate(@NotNull final DefaultMutableTreeNode root, @Nullable final Runnable runAfterUpdate, final boolean updateStructure) {
final Object element = getElementFor(root);
final boolean alwaysLeaf = element != null && getTreeStructure().isAlwaysLeaf(element);
final TreeUpdatePass updatePass;
if (alwaysLeaf) {
removeFromUnbuilt(root);
removeLoading(root, true);
updatePass = new TreeUpdatePass(root).setUpdateChildren(false);
}
else {
updatePass = new TreeUpdatePass(root).setUpdateStructure(updateStructure).setUpdateStamp(-1);
}
final AbstractTreeUpdater updater = getUpdater();
updater.runAfterUpdate(runAfterUpdate);
updater.addSubtreeToUpdate(updatePass);
return !alwaysLeaf;
}
boolean wasRootNodeInitialized() {
return myRootNodeWasQueuedToInitialize && myRootNodeInitialized;
}
public void select(final Object @NotNull [] elements, @Nullable final Runnable onDone) {
select(elements, onDone, false);
}
public void select(final Object @NotNull [] elements, @Nullable final Runnable onDone, boolean addToSelection) {
select(elements, onDone, addToSelection, false);
}
public void select(final Object @NotNull [] elements, @Nullable final Runnable onDone, boolean addToSelection, boolean deferred) {
_select(elements, onDone, addToSelection, true, false, true, deferred, false, false);
}
void _select(final Object @NotNull [] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkIfInStructure) {
_select(elements, onDone, addToSelection, true, checkIfInStructure, true, false, false, false);
}
void _select(final Object @NotNull [] elements,
@NotNull Runnable onDone) {
_select(elements, onDone, false, true, true, false, false, false, false);
}
public void userSelect(final Object @NotNull [] elements, final Runnable onDone, final boolean addToSelection, boolean scroll) {
_select(elements, onDone, addToSelection, true, false, scroll, false, true, true);
}
void _select(final Object @NotNull [] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure,
final boolean scrollToVisible,
final boolean deferred,
final boolean canSmartExpand,
final boolean mayQueue) {
assertIsDispatchThread();
AbstractTreeUpdater updater = getUpdater();
if (mayQueue && updater != null) {
updater.queueSelection(
new SelectionRequest(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, deferred,
canSmartExpand));
return;
}
boolean willAffectSelection = elements.length > 0 || addToSelection;
if (!willAffectSelection) {
runDone(onDone);
maybeReady();
return;
}
final boolean oldCanProcessDeferredSelection = myCanProcessDeferredSelections;
if (!deferred && wasRootNodeInitialized()) {
_getReady().doWhenDone(new TreeRunnable("AbstractTreeUi._select: on done getReady") {
@Override
public void perform() {
myCanProcessDeferredSelections = false;
}
});
}
if (!checkDeferred(deferred, onDone)) return;
if (!deferred && oldCanProcessDeferredSelection && !myCanProcessDeferredSelections) {
if (!addToSelection) {
getTree().clearSelection();
}
}
runDone(new TreeRunnable("AbstractTreeUi._select") {
@Override
public void perform() {
try {
if (!checkDeferred(deferred, onDone)) return;
final Set<Object> currentElements = getSelectedElements();
if (checkCurrentSelection && !currentElements.isEmpty() && elements.length == currentElements.size()) {
boolean runSelection = false;
for (Object eachToSelect : elements) {
if (!currentElements.contains(eachToSelect)) {
runSelection = true;
break;
}
}
if (!runSelection) {
selectVisible(elements[0], onDone, false, false, scrollToVisible);
return;
}
}
clearSelection();
Set<Object> toSelect = new HashSet<>();
ContainerUtil.addAllNotNull(toSelect, elements);
if (addToSelection) {
ContainerUtil.addAllNotNull(toSelect, currentElements);
}
if (checkIfInStructure) {
toSelect.removeIf(each -> !isInStructure(each));
}
final Object[] elementsToSelect = ArrayUtil.toObjectArray(toSelect);
if (wasRootNodeInitialized()) {
final int[] originalRows = myTree.getSelectionRows();
if (!addToSelection) {
clearSelection();
}
addNext(elementsToSelect, 0, new TreeRunnable("AbstractTreeUi._select: addNext") {
@Override
public void perform() {
if (getTree().isSelectionEmpty()) {
processInnerChange(new TreeRunnable("AbstractTreeUi._select: addNext: processInnerChange") {
@Override
public void perform() {
restoreSelection(currentElements);
}
});
}
runDone(onDone);
}
}, originalRows, deferred, scrollToVisible, canSmartExpand);
}
else {
addToDeferred(elementsToSelect, onDone, addToSelection);
}
}
finally {
maybeReady();
}
}
});
}
private void clearSelection() {
mySelectionIsBeingAdjusted = true;
try {
myTree.clearSelection();
}
finally {
mySelectionIsBeingAdjusted = false;
}
}
boolean isSelectionBeingAdjusted() {
return mySelectionIsBeingAdjusted;
}
private void restoreSelection(@NotNull Set<Object> selection) {
for (Object each : selection) {
DefaultMutableTreeNode node = getNodeForElement(each, false);
if (node != null && isValidForSelectionAdjusting(node)) {
addSelectionPath(getPathFor(node), false, null, null);
}
}
}
private void addToDeferred(final Object @NotNull [] elementsToSelect, final Runnable onDone, final boolean addToSelection) {
if (!addToSelection) {
myDeferredSelections.clear();
}
myDeferredSelections.add(new TreeRunnable("AbstractTreeUi.addToDeferred") {
@Override
public void perform() {
select(elementsToSelect, onDone, addToSelection, true);
}
});
}
private boolean checkDeferred(boolean isDeferred, @Nullable Runnable onDone) {
if (!isDeferred || myCanProcessDeferredSelections || !wasRootNodeInitialized()) {
return true;
}
else {
runDone(onDone);
return false;
}
}
@NotNull
final Set<Object> getSelectedElements() {
TreePath[] paths = myTree.getSelectionPaths();
Set<Object> result = new LinkedHashSet<>();
if (paths != null) {
for (TreePath eachPath : paths) {
if (eachPath.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode eachNode = (DefaultMutableTreeNode)eachPath.getLastPathComponent();
if (eachNode == myRootNode && !myTree.isRootVisible()) continue;
Object eachElement = getElementFor(eachNode);
if (eachElement != null) {
result.add(eachElement);
}
}
}
}
return result;
}
private void addNext(final Object @NotNull [] elements,
final int i,
@Nullable final Runnable onDone,
final int[] originalRows,
final boolean deferred,
final boolean scrollToVisible,
final boolean canSmartExpand) {
if (i >= elements.length) {
if (myTree.isSelectionEmpty()) {
myTree.setSelectionRows(originalRows);
}
runDone(onDone);
}
else {
if (!checkDeferred(deferred, onDone)) {
return;
}
doSelect(elements[i], new TreeRunnable("AbstractTreeUi.addNext") {
@Override
public void perform() {
if (!checkDeferred(deferred, onDone)) return;
addNext(elements, i + 1, onDone, originalRows, deferred, scrollToVisible, canSmartExpand);
}
}, deferred, i == 0, scrollToVisible, canSmartExpand);
}
}
public void select(@Nullable Object element, @Nullable final Runnable onDone) {
select(element, onDone, false);
}
public void select(@Nullable Object element, @Nullable final Runnable onDone, boolean addToSelection) {
if (element == null) return;
_select(new Object[]{element}, onDone, addToSelection, false);
}
private void doSelect(@NotNull final Object element,
final Runnable onDone,
final boolean deferred,
final boolean canBeCentered,
final boolean scrollToVisible,
final boolean canSmartExpand) {
final Runnable _onDone = new TreeRunnable("AbstractTreeUi.doSelect") {
@Override
public void perform() {
if (!checkDeferred(deferred, onDone)) return;
checkPathAndMaybeRevalidate(element, new TreeRunnable("AbstractTreeUi.doSelect: checkPathAndMaybeRevalidate") {
@Override
public void perform() {
selectVisible(element, onDone, true, canBeCentered, scrollToVisible);
}
}, true, canSmartExpand);
}
};
_expand(element, _onDone, true, false, canSmartExpand);
}
private void checkPathAndMaybeRevalidate(@NotNull Object element,
@NotNull final Runnable onDone,
final boolean parentsOnly,
final boolean canSmartExpand) {
boolean toRevalidate = isValid(element) && !myRevalidatedObjects.contains(element) && getNodeForElement(element, false) == null && isInStructure(element);
if (!toRevalidate) {
runDone(onDone);
return;
}
myRevalidatedObjects.add(element);
getBuilder()
.revalidateElement(element)
.onSuccess(o -> invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.checkPathAndMaybeRevalidate: on done revalidateElement") {
@Override
public void perform() {
_expand(o, onDone, parentsOnly, false, canSmartExpand);
}
}))
.onError(throwable -> wrapDone(onDone, "AbstractTreeUi.checkPathAndMaybeRevalidate: on rejected revalidateElement").run());
}
public void scrollSelectionToVisible(@Nullable final Runnable onDone, final boolean shouldBeCentered) {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new TreeRunnable("AbstractTreeUi.scrollSelectionToVisible") {
@Override
public void perform() {
if (isReleased()) return;
int[] rows = myTree.getSelectionRows();
if (rows == null || rows.length == 0) {
runDone(onDone);
return;
}
Object toSelect = null;
for (int eachRow : rows) {
TreePath path = myTree.getPathForRow(eachRow);
toSelect = getElementFor(path.getLastPathComponent());
if (toSelect != null) break;
}
if (toSelect != null) {
selectVisible(toSelect, onDone, true, shouldBeCentered, true);
}
}
});
}
private void selectVisible(@NotNull Object element, final Runnable onDone, boolean addToSelection, boolean canBeCentered, final boolean scroll) {
DefaultMutableTreeNode toSelect = getNodeToScroll(element);
if (toSelect == null) {
runDone(onDone);
return;
}
if (myUpdaterState != null) {
myUpdaterState.addSelection(element);
}
setHoldSize(false);
runDone(wrapScrollTo(onDone, element, toSelect, addToSelection, canBeCentered, scroll));
}
void userScrollTo(Object element, Runnable onDone) {
DefaultMutableTreeNode node = getNodeToScroll(element);
runDone(node == null ? onDone : wrapScrollTo(onDone, element, node, false, true, true));
}
private DefaultMutableTreeNode getNodeToScroll(Object element) {
if (element == null) return null;
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null) return null;
return myTree.isRootVisible() || node != getRootNode() ? node : null;
}
@NotNull
private Runnable wrapDone(Runnable onDone, @NotNull String name) {
return new TreeRunnable(name) {
@Override
public void perform() {
runDone(onDone);
}
};
}
@NotNull
private Runnable wrapScrollTo(Runnable onDone,
@NotNull Object element,
@NotNull DefaultMutableTreeNode node,
boolean addToSelection,
boolean canBeCentered,
boolean scroll) {
return new TreeRunnable("AbstractTreeUi.wrapScrollTo") {
@Override
public void perform() {
int row = getRowIfUnderSelection(element);
if (row == -1) row = myTree.getRowForPath(new TreePath(node.getPath()));
int top = row - 2;
int bottom = row + 2;
if (canBeCentered && Registry.is("ide.tree.autoscrollToVCenter")) {
int count = TreeUtil.getVisibleRowCount(myTree) - 1;
top = count > 0 ? row - count / 2 : row;
bottom = count > 0 ? top + count : row;
}
TreeUtil.showAndSelect(myTree, top, bottom, row, -1, addToSelection, scroll)
.doWhenDone(wrapDone(onDone, "AbstractTreeUi.wrapScrollTo.onDone"));
}
};
}
private int getRowIfUnderSelection(@NotNull Object element) {
final Set<Object> selection = getSelectedElements();
if (selection.contains(element)) {
final TreePath[] paths = getTree().getSelectionPaths();
for (TreePath each : paths) {
if (element.equals(getElementFor(each.getLastPathComponent()))) {
return getTree().getRowForPath(each);
}
}
return -1;
}
Object anchor = TreeAnchorizer.getService().createAnchor(element);
Object o = isNodeNull(anchor) ? null : myElementToNodeMap.get(anchor);
TreeAnchorizer.getService().freeAnchor(anchor);
if (o instanceof List) {
final TreePath[] paths = getTree().getSelectionPaths();
if (paths != null && paths.length > 0) {
Set<DefaultMutableTreeNode> selectedNodes = new HashSet<>();
for (TreePath eachPAth : paths) {
if (eachPAth.getLastPathComponent() instanceof DefaultMutableTreeNode) {
selectedNodes.add((DefaultMutableTreeNode)eachPAth.getLastPathComponent());
}
}
//noinspection unchecked
for (DefaultMutableTreeNode eachNode : (List<DefaultMutableTreeNode>)o) {
while (eachNode != null) {
if (selectedNodes.contains(eachNode)) {
return getTree().getRowForPath(getPathFor(eachNode));
}
eachNode = (DefaultMutableTreeNode)eachNode.getParent();
}
}
}
}
return -1;
}
public void expandAll(@Nullable final Runnable onDone) {
final JTree tree = getTree();
if (tree.getRowCount() > 0) {
final int expandRecursionDepth = Math.max(2, Registry.intValue("ide.tree.expandRecursionDepth"));
new TreeRunnable("AbstractTreeUi.expandAll") {
private int myCurrentRow;
private int myInvocationCount;
@Override
public void perform() {
if (++myInvocationCount > expandRecursionDepth) {
myInvocationCount = 0;
if (isPassthroughMode()) {
run();
}
else {
// need this to prevent stack overflow if the tree is rather big and is "synchronous"
//noinspection SSBasedInspection
SwingUtilities.invokeLater(this);
}
}
else {
final int row = myCurrentRow++;
if (row < tree.getRowCount()) {
final TreePath path = tree.getPathForRow(row);
final Object last = path.getLastPathComponent();
final Object elem = getElementFor(last);
expand(elem, this);
}
else {
runDone(onDone);
}
}
}
}.run();
}
else {
runDone(onDone);
}
}
public void expand(final Object element, @Nullable final Runnable onDone) {
expand(new Object[]{element}, onDone);
}
public void expand(final Object @NotNull [] element, @Nullable final Runnable onDone) {
expand(element, onDone, false);
}
void expand(final Object @NotNull [] element, @Nullable final Runnable onDone, boolean checkIfInStructure) {
_expand(element, onDone == null ? new EmptyRunnable() : onDone, checkIfInStructure);
}
private void _expand(final Object @NotNull [] elements,
@NotNull final Runnable onDone,
final boolean checkIfInStructure) {
try {
runDone(new TreeRunnable("AbstractTreeUi._expand") {
@Override
public void perform() {
if (elements.length == 0) {
runDone(onDone);
return;
}
if (myUpdaterState != null) {
myUpdaterState.clearExpansion();
}
final ActionCallback done = new ActionCallback(elements.length);
done
.doWhenDone(wrapDone(onDone, "AbstractTreeUi._expand: on done expandNext"))
.doWhenRejected(wrapDone(onDone, "AbstractTreeUi._expand: on rejected expandNext"));
expandNext(elements, 0, false, checkIfInStructure, false, done, 0);
}
});
}
catch (ProcessCanceledException e) {
try {
runDone(onDone);
}
catch (ProcessCanceledException ignored) {
//todo[kirillk] added by Nik to fix IDEA-58475. I'm not sure that it is correct solution
}
}
}
private void expandNext(final Object @NotNull [] elements,
final int index,
final boolean parentsOnly,
final boolean checkIfInStricture,
final boolean canSmartExpand,
@NotNull final ActionCallback done,
final int currentDepth) {
if (elements.length <= 0) {
done.setDone();
return;
}
if (index >= elements.length) {
return;
}
final int[] actualDepth = {currentDepth};
boolean breakCallChain = false;
if (actualDepth[0] > Registry.intValue("ide.tree.expandRecursionDepth")) {
actualDepth[0] = 0;
breakCallChain = true;
}
Runnable expandRunnable = new TreeRunnable("AbstractTreeUi.expandNext") {
@Override
public void perform() {
_expand(elements[index], new TreeRunnable("AbstractTreeUi.expandNext: on done") {
@Override
public void perform() {
done.setDone();
expandNext(elements, index + 1, parentsOnly, checkIfInStricture, canSmartExpand, done, actualDepth[0] + 1);
}
}, parentsOnly, checkIfInStricture, canSmartExpand);
}
};
if (breakCallChain && !isPassthroughMode()) {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(expandRunnable);
}
else {
expandRunnable.run();
}
}
public void collapseChildren(@NotNull final Object element, @Nullable final Runnable onDone) {
runDone(new TreeRunnable("AbstractTreeUi.collapseChildren") {
@Override
public void perform() {
final DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
getTree().collapsePath(new TreePath(node.getPath()));
runDone(onDone);
}
}
});
}
private void runDone(@Nullable Runnable done) {
if (done == null) return;
if (!canInitiateNewActivity()) {
if (done instanceof AbstractTreeBuilder.UserRunnable) {
return;
}
}
if (isYeildingNow()) {
myYieldingDoneRunnables.add(done);
}
else {
try {
execute(done);
}
catch (ProcessCanceledException ignored) {
}
}
}
private void _expand(final Object element,
@NotNull final Runnable onDone,
final boolean parentsOnly,
boolean checkIfInStructure,
boolean canSmartExpand) {
if (checkIfInStructure && !isInStructure(element)) {
runDone(onDone);
return;
}
if (wasRootNodeInitialized()) {
List<Object> kidsToExpand = new ArrayList<>();
Object eachElement = element;
DefaultMutableTreeNode firstVisible = null;
while (true) {
if (eachElement == null || !isValid(eachElement)) break;
final int preselected = getRowIfUnderSelection(eachElement);
if (preselected >= 0) {
firstVisible = (DefaultMutableTreeNode)getTree().getPathForRow(preselected).getLastPathComponent();
}
else {
firstVisible = getNodeForElement(eachElement, true);
}
if (eachElement != element || !parentsOnly) {
kidsToExpand.add(eachElement);
}
if (firstVisible != null) break;
eachElement = getTreeStructure().getParentElement(eachElement);
if (eachElement == null) break;
int i = kidsToExpand.indexOf(eachElement);
if (i != -1) {
try {
Object existing = kidsToExpand.get(i);
LOG.error("Tree path contains equal elements at different levels:\n" +
" element: '" + eachElement + "'; " + eachElement.getClass() + " ("+System.identityHashCode(eachElement)+");\n" +
"existing: '" + existing + "'; " + existing.getClass()+ " ("+System.identityHashCode(existing)+"); " +
"path='" + kidsToExpand + "'; tree structure=" + myTreeStructure);
}
catch (AssertionError ignored) {
}
runDone(onDone);
throw new ProcessCanceledException();
}
}
if (firstVisible == null) {
runDone(onDone);
}
else if (kidsToExpand.isEmpty()) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)firstVisible.getParent();
if (parentNode != null) {
final TreePath parentPath = new TreePath(parentNode.getPath());
if (!myTree.isExpanded(parentPath)) {
expand(parentPath, canSmartExpand);
}
}
runDone(onDone);
}
else {
processExpand(firstVisible, kidsToExpand, kidsToExpand.size() - 1, onDone, canSmartExpand);
}
}
else {
deferExpansion(element, onDone, parentsOnly, canSmartExpand);
}
}
private void deferExpansion(final Object element, @NotNull final Runnable onDone, final boolean parentsOnly, final boolean canSmartExpand) {
myDeferredExpansions.add(new TreeRunnable("AbstractTreeUi.deferExpansion") {
@Override
public void perform() {
_expand(element, onDone, parentsOnly, false, canSmartExpand);
}
});
}
private void processExpand(final DefaultMutableTreeNode toExpand,
@NotNull final List<Object> kidsToExpand,
final int expandIndex,
@NotNull final Runnable onDone,
final boolean canSmartExpand) {
final Object element = getElementFor(toExpand);
if (element == null) {
runDone(onDone);
return;
}
addNodeAction(element, true, node -> {
if (node.getChildCount() > 0 && !myTree.isExpanded(new TreePath(node.getPath()))) {
if (!isAutoExpand(node)) {
expand(node, canSmartExpand);
}
}
if (expandIndex <= 0) {
runDone(onDone);
return;
}
checkPathAndMaybeRevalidate(kidsToExpand.get(expandIndex - 1), new TreeRunnable("AbstractTreeUi.processExpand") {
@Override
public void perform() {
final DefaultMutableTreeNode nextNode = getNodeForElement(kidsToExpand.get(expandIndex - 1), false);
processExpand(nextNode, kidsToExpand, expandIndex - 1, onDone, canSmartExpand);
}
}, false, canSmartExpand);
});
boolean childrenToUpdate = areChildrenToBeUpdated(toExpand);
boolean expanded = myTree.isExpanded(getPathFor(toExpand));
boolean unbuilt = myUnbuiltNodes.contains(toExpand);
if (expanded) {
if (unbuilt || childrenToUpdate) {
addSubtreeToUpdate(toExpand);
}
}
else {
expand(toExpand, canSmartExpand);
}
if (!unbuilt && !childrenToUpdate) {
processNodeActionsIfReady(toExpand);
}
}
private boolean areChildrenToBeUpdated(DefaultMutableTreeNode node) {
return getUpdater().isEnqueuedToUpdate(node) || isUpdatingParent(node) || myCancelledBuild.containsKey(node);
}
@Nullable
public Object getElementFor(Object node) {
NodeDescriptor descriptor = getDescriptorFrom(node);
return descriptor == null ? null : getElementFromDescriptor(descriptor);
}
final boolean isNodeBeingBuilt(@NotNull final TreePath path) {
return isNodeBeingBuilt(path.getLastPathComponent());
}
private boolean isNodeBeingBuilt(@NotNull Object node) {
return getParentBuiltNode(node) != null || myRootNode == node && !wasRootNodeInitialized();
}
@Nullable
private DefaultMutableTreeNode getParentBuiltNode(@NotNull Object node) {
DefaultMutableTreeNode parent = getParentLoadingInBackground(node);
if (parent != null) return parent;
if (isLoadingParentInBackground(node)) return (DefaultMutableTreeNode)node;
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
final boolean childrenAreNoLoadedYet = myUnbuiltNodes.contains(treeNode) || isUpdatingChildrenNow(treeNode);
if (childrenAreNoLoadedYet) {
final TreePath nodePath = new TreePath(treeNode.getPath());
if (!myTree.isExpanded(nodePath)) return null;
return (DefaultMutableTreeNode)node;
}
return null;
}
private boolean isLoadingParentInBackground(Object node) {
return node instanceof DefaultMutableTreeNode && isLoadedInBackground(getElementFor(node));
}
public void setTreeStructure(@NotNull AbstractTreeStructure treeStructure) {
myTreeStructure = treeStructure;
clearUpdaterState();
}
public AbstractTreeUpdater getUpdater() {
return myUpdater;
}
public void setUpdater(@Nullable final AbstractTreeUpdater updater) {
myUpdater = updater;
if (updater != null && myUpdateIfInactive) {
updater.showNotify();
}
if (myUpdater != null) {
myUpdater.setPassThroughMode(myPassThroughMode);
}
}
public DefaultMutableTreeNode getRootNode() {
return myRootNode;
}
public void setRootNode(@NotNull final DefaultMutableTreeNode rootNode) {
myRootNode = rootNode;
}
private void dropUpdaterStateIfExternalChange() {
if (!isInnerChange()) {
clearUpdaterState();
myAutoExpandRoots.clear();
mySelectionIsAdjusted = false;
}
}
void clearUpdaterState() {
myUpdaterState = null;
}
private void createMapping(@NotNull Object element, DefaultMutableTreeNode node) {
element = TreeAnchorizer.getService().createAnchor(element);
warnMap("myElementToNodeMap: createMapping: ", myElementToNodeMap);
if (!myElementToNodeMap.containsKey(element)) {
myElementToNodeMap.put(element, node);
}
else {
final Object value = myElementToNodeMap.get(element);
final List<DefaultMutableTreeNode> nodes;
if (value instanceof DefaultMutableTreeNode) {
nodes = new ArrayList<>();
nodes.add((DefaultMutableTreeNode)value);
myElementToNodeMap.put(element, nodes);
}
else {
nodes = (List<DefaultMutableTreeNode>)value;
}
nodes.add(node);
}
}
private void removeMapping(@NotNull Object element, DefaultMutableTreeNode node, @Nullable Object elementToPutNodeActionsFor) {
element = TreeAnchorizer.getService().createAnchor(element);
warnMap("myElementToNodeMap: removeMapping: ", myElementToNodeMap);
final Object value = myElementToNodeMap.get(element);
if (value != null) {
if (value instanceof DefaultMutableTreeNode) {
if (value.equals(node)) {
myElementToNodeMap.remove(element);
}
}
else {
List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value;
final boolean reallyRemoved = nodes.remove(node);
if (reallyRemoved) {
if (nodes.isEmpty()) {
myElementToNodeMap.remove(element);
}
}
}
}
remapNodeActions(element, elementToPutNodeActionsFor);
TreeAnchorizer.getService().freeAnchor(element);
}
private void remapNodeActions(Object element, Object elementToPutNodeActionsFor) {
_remapNodeActions(element, elementToPutNodeActionsFor, myNodeActions);
_remapNodeActions(element, elementToPutNodeActionsFor, myNodeChildrenActions);
warnMap("myNodeActions: remapNodeActions: ", myNodeActions);
warnMap("myNodeChildrenActions: remapNodeActions: ", myNodeChildrenActions);
}
private static void _remapNodeActions(Object element, @Nullable Object elementToPutNodeActionsFor, @NotNull final Map<Object, List<NodeAction>> nodeActions) {
final List<NodeAction> actions = nodeActions.get(element);
nodeActions.remove(element);
if (elementToPutNodeActionsFor != null && actions != null) {
nodeActions.put(elementToPutNodeActionsFor, actions);
}
}
@Nullable
private DefaultMutableTreeNode getFirstNode(@NotNull Object element) {
return findNode(element, 0);
}
@Nullable
private DefaultMutableTreeNode findNode(@NotNull Object element, int startIndex) {
final Object value = getBuilder().findNodeByElement(element);
if (value == null) {
return null;
}
if (value instanceof DefaultMutableTreeNode) {
return startIndex == 0 ? (DefaultMutableTreeNode)value : null;
}
final List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value;
return startIndex < nodes.size() ? nodes.get(startIndex) : null;
}
Object findNodeByElement(Object element) {
element = TreeAnchorizer.getService().createAnchor(element);
try {
if (isNodeNull(element)) return null;
if (myElementToNodeMap.containsKey(element)) {
return myElementToNodeMap.get(element);
}
TREE_NODE_WRAPPER.setValue(element);
return myElementToNodeMap.get(TREE_NODE_WRAPPER);
}
finally {
TREE_NODE_WRAPPER.setValue(null);
TreeAnchorizer.getService().freeAnchor(element);
}
}
@Nullable
private DefaultMutableTreeNode findNodeForChildElement(@NotNull DefaultMutableTreeNode parentNode, Object element) {
Object anchor = TreeAnchorizer.getService().createAnchor(element);
final Object value = isNodeNull(anchor) ? null : myElementToNodeMap.get(anchor);
TreeAnchorizer.getService().freeAnchor(anchor);
if (value == null) {
return null;
}
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode elementNode = (DefaultMutableTreeNode)value;
return parentNode.equals(elementNode.getParent()) ? elementNode : null;
}
final List<DefaultMutableTreeNode> allNodesForElement = (List<DefaultMutableTreeNode>)value;
for (final DefaultMutableTreeNode elementNode : allNodesForElement) {
if (parentNode.equals(elementNode.getParent())) {
return elementNode;
}
}
return null;
}
private void addNodeAction(Object element, boolean shouldChildrenBeReady, @NotNull NodeAction action) {
_addNodeAction(element, action, myNodeActions);
if (shouldChildrenBeReady) {
_addNodeAction(element, action, myNodeChildrenActions);
}
warnMap("myNodeActions: addNodeAction: ", myNodeActions);
warnMap("myNodeChildrenActions: addNodeAction: ", myNodeChildrenActions);
}
public void addActivity() {
if (myActivityMonitor != null) {
myActivityMonitor.addActivity(myActivityId, getUpdater().getModalityState());
}
}
private void removeActivity() {
if (myActivityMonitor != null) {
myActivityMonitor.removeActivity(myActivityId);
}
}
private void _addNodeAction(Object element, NodeAction action, @NotNull Map<Object, List<NodeAction>> map) {
maybeSetBusyAndScheduleWaiterForReady(true, element);
map.computeIfAbsent(element, k -> new ArrayList<>()).add(action);
addActivity();
}
private void cleanUpNow() {
if (!canInitiateNewActivity()) return;
final UpdaterTreeState state = new UpdaterTreeState(this);
myTree.collapsePath(new TreePath(myTree.getModel().getRoot()));
clearSelection();
getRootNode().removeAllChildren();
TREE_NODE_WRAPPER = AbstractTreeBuilder.createSearchingTreeNodeWrapper();
myRootNodeWasQueuedToInitialize = false;
myRootNodeInitialized = false;
clearNodeActions();
myElementToNodeMap.clear();
myDeferredSelections.clear();
myDeferredExpansions.clear();
myLoadedInBackground.clear();
myUnbuiltNodes.clear();
myUpdateFromRootRequested = true;
myWorker.clear();
myTree.invalidate();
state.restore(null);
}
public void setClearOnHideDelay(final long clearOnHideDelay) {
myClearOnHideDelay = clearOnHideDelay;
}
private class MySelectionListener implements TreeSelectionListener {
@Override
public void valueChanged(@NotNull final TreeSelectionEvent e) {
if (mySilentSelect != null && mySilentSelect.equals(e.getNewLeadSelectionPath())) return;
dropUpdaterStateIfExternalChange();
}
}
private class MyExpansionListener implements TreeExpansionListener {
@Override
public void treeExpanded(@NotNull TreeExpansionEvent event) {
final TreePath path = event.getPath();
if (mySilentExpand != null && mySilentExpand.equals(path)) return;
dropUpdaterStateIfExternalChange();
if (myRequestedExpand != null && !myRequestedExpand.equals(path)) {
_getReady().doWhenDone(new TreeRunnable("AbstractTreeUi.MyExpansionListener.treeExpanded") {
@Override
public void perform() {
Object element = getElementFor(path.getLastPathComponent());
expand(element, null);
}
});
return;
}
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (!myUnbuiltNodes.contains(node)) {
removeLoading(node, false);
Set<DefaultMutableTreeNode> childrenToUpdate = new HashSet<>();
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode each = (DefaultMutableTreeNode)node.getChildAt(i);
if (myUnbuiltNodes.contains(each)) {
makeLoadingOrLeafIfNoChildren(each);
childrenToUpdate.add(each);
}
}
if (!childrenToUpdate.isEmpty()) {
for (DefaultMutableTreeNode each : childrenToUpdate) {
maybeUpdateSubtreeToUpdate(each);
}
}
}
else {
getBuilder().expandNodeChildren(node);
}
processSmartExpand(node, canSmartExpand(node, true), false);
processNodeActionsIfReady(node);
}
@Override
public void treeCollapsed(@NotNull TreeExpansionEvent e) {
dropUpdaterStateIfExternalChange();
final TreePath path = e.getPath();
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
TreePath pathToSelect = null;
if (isSelectionInside(node)) {
pathToSelect = new TreePath(node.getPath());
}
if (getBuilder().isDisposeOnCollapsing(descriptor)) {
runDone(new TreeRunnable("AbstractTreeUi.MyExpansionListener.treeCollapsed") {
@Override
public void perform() {
if (isDisposed(node)) return;
TreePath nodePath = new TreePath(node.getPath());
if (myTree.isExpanded(nodePath)) return;
removeChildren(node);
makeLoadingOrLeafIfNoChildren(node);
}
});
if (node.equals(getRootNode())) {
if (myTree.isRootVisible()) {
//todo kirillk to investigate -- should be done by standard selction move
//addSelectionPath(new TreePath(getRootNode().getPath()), true, Condition.FALSE);
}
}
else {
myTreeModel.reload(node);
}
}
if (pathToSelect != null && myTree.isSelectionEmpty()) {
addSelectionPath(pathToSelect, true, Conditions.alwaysFalse(), null);
}
}
}
private void removeChildren(@NotNull DefaultMutableTreeNode node) {
@SuppressWarnings({"unchecked", "rawtypes"})
Enumeration<DefaultMutableTreeNode> children = (Enumeration)node.children();
for (DefaultMutableTreeNode child : Collections.list(children)) {
disposeNode(child);
}
node.removeAllChildren();
nodeStructureChanged(node);
}
private void maybeUpdateSubtreeToUpdate(@NotNull final DefaultMutableTreeNode subtreeRoot) {
if (!myUnbuiltNodes.contains(subtreeRoot)) return;
TreePath path = getPathFor(subtreeRoot);
if (myTree.getRowForPath(path) == -1) return;
DefaultMutableTreeNode parent = getParentBuiltNode(subtreeRoot);
if (parent == null) {
if (!getBuilder().isAlwaysShowPlus(getDescriptorFrom(subtreeRoot))) {
addSubtreeToUpdate(subtreeRoot);
}
}
else if (parent != subtreeRoot) {
addNodeAction(getElementFor(subtreeRoot), true, parent1 -> maybeUpdateSubtreeToUpdate(subtreeRoot));
}
}
private boolean isSelectionInside(@NotNull DefaultMutableTreeNode parent) {
TreePath path = new TreePath(myTreeModel.getPathToRoot(parent));
TreePath[] paths = myTree.getSelectionPaths();
if (paths == null) return false;
for (TreePath path1 : paths) {
if (path.isDescendant(path1)) return true;
}
return false;
}
boolean isInStructure(@Nullable Object element) {
if (isNodeNull(element)) return false;
final AbstractTreeStructure structure = getTreeStructure();
if (structure == null) return false;
final Object rootElement = structure.getRootElement();
Object eachParent = element;
while (eachParent != null) {
if (Comparing.equal(rootElement, eachParent)) return true;
eachParent = structure.getParentElement(eachParent);
}
return false;
}
@FunctionalInterface
interface NodeAction {
void onReady(@NotNull DefaultMutableTreeNode node);
}
void setCanYield(final boolean canYield) {
myCanYield = canYield;
}
@NotNull
Collection<TreeUpdatePass> getYeildingPasses() {
return myYieldingPasses;
}
private static class LoadedChildren {
@NotNull private final List<Object> myElements;
private final Map<Object, NodeDescriptor> myDescriptors = new HashMap<>();
private final Map<NodeDescriptor, Boolean> myChanges = new HashMap<>();
LoadedChildren(Object @Nullable [] elements) {
myElements = Arrays.asList(elements != null ? elements : ArrayUtilRt.EMPTY_OBJECT_ARRAY);
}
void putDescriptor(Object element, NodeDescriptor descriptor, boolean isChanged) {
if (isUnitTestingMode()) {
assert myElements.contains(element);
}
myDescriptors.put(element, descriptor);
myChanges.put(descriptor, isChanged);
}
@NotNull
List<Object> getElements() {
return myElements;
}
NodeDescriptor getDescriptor(Object element) {
return myDescriptors.get(element);
}
@NotNull
@Override
public String toString() {
return myElements + "->" + myChanges;
}
public boolean isUpdated(Object element) {
NodeDescriptor desc = getDescriptor(element);
return myChanges.get(desc);
}
}
private long getComparatorStamp() {
if (myNodeDescriptorComparator instanceof NodeDescriptor.NodeComparator) {
long currentComparatorStamp = ((NodeDescriptor.NodeComparator)myNodeDescriptorComparator).getStamp();
if (currentComparatorStamp > myLastComparatorStamp) {
myOwnComparatorStamp = Math.max(myOwnComparatorStamp, currentComparatorStamp) + 1;
}
myLastComparatorStamp = currentComparatorStamp;
return Math.max(currentComparatorStamp, myOwnComparatorStamp);
}
else {
return myOwnComparatorStamp;
}
}
void incComparatorStamp() {
myOwnComparatorStamp = getComparatorStamp() + 1;
}
private static class UpdateInfo {
NodeDescriptor myDescriptor;
TreeUpdatePass myPass;
boolean myCanSmartExpand;
boolean myWasExpanded;
boolean myForceUpdate;
boolean myDescriptorIsUpToDate;
boolean myUpdateChildren;
UpdateInfo(NodeDescriptor descriptor,
TreeUpdatePass pass,
boolean canSmartExpand,
boolean wasExpanded,
boolean forceUpdate,
boolean descriptorIsUpToDate,
boolean updateChildren) {
myDescriptor = descriptor;
myPass = pass;
myCanSmartExpand = canSmartExpand;
myWasExpanded = wasExpanded;
myForceUpdate = forceUpdate;
myDescriptorIsUpToDate = descriptorIsUpToDate;
myUpdateChildren = updateChildren;
}
synchronized NodeDescriptor getDescriptor() {
return myDescriptor;
}
synchronized TreeUpdatePass getPass() {
return myPass;
}
synchronized boolean isCanSmartExpand() {
return myCanSmartExpand;
}
synchronized boolean isWasExpanded() {
return myWasExpanded;
}
synchronized boolean isForceUpdate() {
return myForceUpdate;
}
synchronized boolean isDescriptorIsUpToDate() {
return myDescriptorIsUpToDate;
}
public synchronized void apply(@NotNull UpdateInfo updateInfo) {
myDescriptor = updateInfo.myDescriptor;
myPass = updateInfo.myPass;
myCanSmartExpand = updateInfo.myCanSmartExpand;
myWasExpanded = updateInfo.myWasExpanded;
myForceUpdate = updateInfo.myForceUpdate;
myDescriptorIsUpToDate = updateInfo.myDescriptorIsUpToDate;
}
public synchronized boolean isUpdateChildren() {
return myUpdateChildren;
}
@Override
@NotNull
@NonNls
public synchronized String toString() {
return "UpdateInfo: desc=" +
myDescriptor +
" pass=" +
myPass +
" canSmartExpand=" +
myCanSmartExpand +
" wasExpanded=" +
myWasExpanded +
" forceUpdate=" +
myForceUpdate +
" descriptorUpToDate=" +
myDescriptorIsUpToDate;
}
}
void setPassthroughMode(boolean passthrough) {
myPassThroughMode = passthrough;
AbstractTreeUpdater updater = getUpdater();
if (updater != null) {
updater.setPassThroughMode(myPassThroughMode);
}
if (!isUnitTestingMode() && passthrough) {
// TODO: this assertion should be restored back as soon as possible [JamTreeTableView should be rewritten, etc]
//LOG.error("Pass-through mode for TreeUi is allowed only for unit test mode");
}
}
boolean isPassthroughMode() {
return myPassThroughMode;
}
private static boolean isUnitTestingMode() {
Application app = ApplicationManager.getApplication();
return app != null && app.isUnitTestMode();
}
private void addModelListenerToDiagnoseAccessOutsideEdt() {
myTreeModel.addTreeModelListener(new TreeModelListener() {
@Override
public void treeNodesChanged(TreeModelEvent e) {
assertIsDispatchThread();
}
@Override
public void treeNodesInserted(TreeModelEvent e) {
assertIsDispatchThread();
}
@Override
public void treeNodesRemoved(TreeModelEvent e) {
assertIsDispatchThread();
}
@Override
public void treeStructureChanged(TreeModelEvent e) {
assertIsDispatchThread();
}
});
}
private <V> void warnMap(String prefix, Map<Object, V> map) {
if (!LOG.isDebugEnabled()) return;
if (!SwingUtilities.isEventDispatchThread() && !myPassThroughMode) {
LOG.warn(prefix + "modified on wrong thread");
}
long count = map.keySet().stream().filter(AbstractTreeUi::isNodeNull).count();
if (count > 0) LOG.warn(prefix + "null keys: " + count + " / " + map.size());
}
/**
* @param element an element in the tree structure
* @return {@code true} if element is {@code null} or if it contains a {@code null} value
*/
private static boolean isNodeNull(Object element) {
if (element instanceof AbstractTreeNode) {
AbstractTreeNode node = (AbstractTreeNode)element;
element = node.getValue();
}
return element == null;
}
public final boolean isConsistent() {
return myTree != null && myTreeModel != null && myTreeModel == myTree.getModel();
}
}
| apache-2.0 |
slyfoxza/minecraft | nbt-api/src/test/java/net/za/slyfox/minecraft/nbt/stream/BigTestNbtParserTest.java | 9062 | /*
* Copyright 2014 Philip Cronje
*
* 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 net.za.slyfox.minecraft.nbt.stream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import org.junit.Test;
import net.za.slyfox.minecraft.nbt.stream.NbtParser.Event;
public abstract class BigTestNbtParserTest extends AbstractNbtParserTest {
@Test
public void parseNbt() throws IOException {
NbtParser parser = createParser(new GZIPInputStream(
BigTestNbtParserTest.class.getResourceAsStream("/net/za/slyfox/minecraft/nbt/bigtest.nbt")));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.COMPOUND));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("Level"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.LONG));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("longTest"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)9223372036854775807L));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.SHORT));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("shortTest"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)((short)32767)));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.STRING));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("stringTest"));
assertThat(parser.next(), is(Event.VALUE_STRING));
assertThat(parser.getString(), is("HELLO WORLD THIS IS A TEST STRING \u00C5\u00C4\u00D6!"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.FLOAT));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("floatTest"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)0.49823147058486938f));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.INT));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("intTest"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)2147483647));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.COMPOUND));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("nested compound test"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.COMPOUND));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("ham"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.STRING));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("name"));
assertThat(parser.next(), is(Event.VALUE_STRING));
assertThat(parser.getString(), is("Hampus"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.FLOAT));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("value"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)0.75f));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.END));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.COMPOUND));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("egg"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.STRING));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("name"));
assertThat(parser.next(), is(Event.VALUE_STRING));
assertThat(parser.getString(), is("Eggbert"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.FLOAT));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("value"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)0.5f));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.END));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.END));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.LIST));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("listTest (long)"));
assertThat(parser.next(), is(Event.LIST_TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.LONG));
assertThat(parser.next(), is(Event.ARRAY_SIZE));
assertThat(parser.getNumber(), is((Number)5));
for(long i = 11L; i <= 15L; ++i) {
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)i));
}
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.LIST));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("listTest (compound)"));
assertThat(parser.next(), is(Event.LIST_TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.COMPOUND));
assertThat(parser.next(), is(Event.ARRAY_SIZE));
assertThat(parser.getNumber(), is((Number)2));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.STRING));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("name"));
assertThat(parser.next(), is(Event.VALUE_STRING));
assertThat(parser.getString(), is("Compound tag #0"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.LONG));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("created-on"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)1264099775885L));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.END));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.STRING));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("name"));
assertThat(parser.next(), is(Event.VALUE_STRING));
assertThat(parser.getString(), is("Compound tag #1"));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.LONG));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("created-on"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)1264099775885L));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.END));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.BYTE));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("byteTest"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)((byte)127)));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.BYTE_ARRAY));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("byteArrayTest (the first 1000 values of "
+ "(n*n*255+n*7)%100, starting with n=0 (0, 62, 34, 16, 8, ...))"));
assertThat(parser.next(), is(Event.ARRAY_SIZE));
assertThat(parser.getNumber(), is((Number)1000));
for(int i = 0; i < 1000; ++i) {
byte expected = (byte)((i * i * 255 + i * 7) % 100);
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)expected));
}
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.DOUBLE));
assertThat(parser.next(), is(Event.TAG_NAME));
assertThat(parser.getString(), is("doubleTest"));
assertThat(parser.next(), is(Event.VALUE_NUMBER));
assertThat(parser.getNumber(), is((Number)0.49312871321823148));
assertThat(parser.next(), is(Event.TAG_ID));
assertThat(parser.getTagType(), is(NbtTagType.END));
assertThat(parser.hasNext(), is(false));
}
}
| apache-2.0 |
steelkiwi/SketchView | sample/src/com/skd/sketchview/sketch/SketchManager.java | 2013 | /*
* Copyright (C) 2014 Steelkiwi Development, Julia Zudikova
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skd.sketchview.sketch;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.res.Resources;
import android.graphics.Paint;
import android.util.Pair;
import com.skd.sketchview.settings.SkColor;
import com.skd.sketchview.settings.SkSize;
/*
* Helper class to create initial set of available brushes to draw a sketch with.
*/
public class SketchManager {
public static HashMap<Pair<Integer, Integer>, Paint> createBrushes(Resources r) {
HashMap<Pair<Integer, Integer>, Paint> brushes = new HashMap<Pair<Integer, Integer>, Paint>();
ArrayList<SkColor> colors = SkColor.getColors(r);
ArrayList<SkSize> sizes = SkSize.getSizes(r);
for (int i=0, len=sizes.size(); i<len; i++) {
for (int j=0, max=colors.size(); j<max; j++) {
int color = r.getColor(colors.get(j).getColorResourceId());
int size = sizes.get(i).getSize();
Paint paint = createBrush(color, size);
brushes.put(new Pair<Integer, Integer>(color, size), paint);
}
}
return brushes;
}
private static Paint createBrush(int color, float width) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(width);
return paint;
}
}
| apache-2.0 |
fangchi/netty-servlet-bridge | src/main/java/net/javaforge/netty/servlet/bridge/impl/HttpServletResponseImpl.java | 7177 | /*
* Copyright 2013 by Maxim Kalina
*
* 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 net.javaforge.netty.servlet.bridge.impl;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.HttpHeaders.Names;
import net.javaforge.netty.servlet.bridge.ServletBridgeRuntimeException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
import static io.netty.handler.codec.http.HttpHeaders.Names.LOCATION;
import static io.netty.handler.codec.http.HttpHeaders.Names.SET_COOKIE;
public class HttpServletResponseImpl implements HttpServletResponse {
private HttpResponse originalResponse;
private ServletOutputStreamImpl outputStream;
private PrintWriterImpl writer;
private boolean responseCommited = false;
private Locale locale = null;
public HttpServletResponseImpl(FullHttpResponse response) {
this.originalResponse = response;
this.outputStream = new ServletOutputStreamImpl(response);
this.writer = new PrintWriterImpl(this.outputStream);
}
public HttpResponse getOriginalResponse() {
return originalResponse;
}
@Override
public void addCookie(Cookie cookie) {
String result = ServerCookieEncoder.encode(new io.netty.handler.codec.http.DefaultCookie(cookie.getName(), cookie.getValue()));
HttpHeaders.addHeader(this.originalResponse, SET_COOKIE, result);
}
@Override
public void addDateHeader(String name, long date) {
HttpHeaders.addHeader(this.originalResponse, name, date);
}
@Override
public void addHeader(String name, String value) {
HttpHeaders.addHeader(this.originalResponse, name, value);
}
@Override
public void addIntHeader(String name, int value) {
HttpHeaders.addIntHeader(this.originalResponse, name, value);
}
@Override
public boolean containsHeader(String name) {
return this.originalResponse.headers().contains(name);
}
@Override
public void sendError(int sc) throws IOException {
this.originalResponse.setStatus(HttpResponseStatus.valueOf(sc));
}
@Override
public void sendError(int sc, String msg) throws IOException {
//Fix the following exception
/*
java.lang.IllegalArgumentException: reasonPhrase contains one of the following prohibited characters: \r\n: FAILED - Cannot find View Map for null.
at io.netty.handler.codec.http.HttpResponseStatus.<init>(HttpResponseStatus.java:514) ~[netty-all-4.1.0.Beta3.jar:4.1.0.Beta3]
at io.netty.handler.codec.http.HttpResponseStatus.<init>(HttpResponseStatus.java:496) ~[netty-all-4.1.0.Beta3.jar:4.1.0.Beta3]
*/
if (msg != null) {
msg = msg.replace('\r', ' ');
msg = msg.replace('\n', ' ');
}
this.originalResponse.setStatus(new HttpResponseStatus(sc, msg));
}
@Override
public void sendRedirect(String location) throws IOException {
setStatus(SC_FOUND);
setHeader(LOCATION, location);
}
@Override
public void setDateHeader(String name, long date) {
HttpHeaders.setHeader(this.originalResponse, name, date);
}
@Override
public void setHeader(String name, String value) {
HttpHeaders.setHeader(this.originalResponse, name, value);
}
@Override
public void setIntHeader(String name, int value) {
HttpHeaders.setIntHeader(this.originalResponse, name, value);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return this.outputStream;
}
@Override
public PrintWriter getWriter() throws IOException {
return this.writer;
}
@Override
public void setStatus(int sc) {
this.originalResponse.setStatus(HttpResponseStatus.valueOf(sc));
}
@Override
public void setStatus(int sc, String sm) {
this.originalResponse.setStatus(new HttpResponseStatus(sc, sm));
}
@Override
public String getContentType() {
return HttpHeaders.getHeader(this.originalResponse,
HttpHeaders.Names.CONTENT_TYPE);
}
@Override
public void setContentType(String type) {
HttpHeaders.setHeader(this.originalResponse,
HttpHeaders.Names.CONTENT_TYPE, type);
}
@Override
public void setContentLength(int len) {
HttpHeaders.setContentLength(this.originalResponse, len);
}
@Override
public boolean isCommitted() {
return this.responseCommited;
}
@Override
public void reset() {
if (isCommitted())
throw new IllegalStateException("Response already commited!");
this.originalResponse.headers().clear();
this.resetBuffer();
}
@Override
public void resetBuffer() {
if (isCommitted())
throw new IllegalStateException("Response already commited!");
this.outputStream.resetBuffer();
}
@Override
public void flushBuffer() throws IOException {
this.getWriter().flush();
this.responseCommited = true;
}
@Override
public int getBufferSize() {
return this.outputStream.getBufferSize();
}
@Override
public void setBufferSize(int size) {
// we using always dynamic buffer for now
}
@Override
public String encodeRedirectURL(String url) {
return this.encodeURL(url);
}
@Override
public String encodeRedirectUrl(String url) {
return this.encodeURL(url);
}
@Override
public String encodeURL(String url) {
try {
return URLEncoder.encode(url, getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
throw new ServletBridgeRuntimeException("Error encoding url!", e);
}
}
@Override
public String encodeUrl(String url) {
return this.encodeRedirectURL(url);
}
@Override
public String getCharacterEncoding() {
return HttpHeaders.getHeader(this.originalResponse,
Names.CONTENT_ENCODING);
}
@Override
public void setCharacterEncoding(String charset) {
HttpHeaders.setHeader(this.originalResponse,
Names.CONTENT_ENCODING, charset);
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public void setLocale(Locale loc) {
this.locale = loc;
}
} | apache-2.0 |
sibok666/flowable-engine | modules/flowable-bpmn-model/src/main/java/org/flowable/bpmn/model/ServiceTask.java | 4114 | /* 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.flowable.bpmn.model;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tijs Rademakers
*/
public class ServiceTask extends TaskWithFieldExtensions {
public static final String DMN_TASK = "dmn";
public static final String MAIL_TASK = "mail";
protected String implementation;
protected String implementationType;
protected String resultVariableName;
protected String type;
protected String operationRef;
protected String extensionId;
protected List<CustomProperty> customProperties = new ArrayList<CustomProperty>();
protected String skipExpression;
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getResultVariableName() {
return resultVariableName;
}
public void setResultVariableName(String resultVariableName) {
this.resultVariableName = resultVariableName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<CustomProperty> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(List<CustomProperty> customProperties) {
this.customProperties = customProperties;
}
public String getOperationRef() {
return operationRef;
}
public void setOperationRef(String operationRef) {
this.operationRef = operationRef;
}
public String getExtensionId() {
return extensionId;
}
public void setExtensionId(String extensionId) {
this.extensionId = extensionId;
}
public boolean isExtended() {
return extensionId != null && !extensionId.isEmpty();
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<CustomProperty>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
}
| apache-2.0 |
marklogic/data-hub-in-a-box | marklogic-data-hub/src/main/java/com/marklogic/hub/impl/MasteringManagerImpl.java | 5623 | /*
* Copyright 2012-2019 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marklogic.hub.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.extensions.ResourceManager;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.util.RequestParameters;
import com.marklogic.hub.DatabaseKind;
import com.marklogic.hub.HubConfig;
import com.marklogic.hub.HubProject;
import com.marklogic.hub.MasteringManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class MasteringManagerImpl implements MasteringManager {
@Autowired
protected HubConfig hubConfig;
@Autowired
protected HubProject hubProject;
protected DatabaseClient srcClient = null;
protected MergeResource mergeResource = null;
protected MatchResource matchResource = null;
@Override
public JsonNode unmerge(String mergeURI, Boolean retainAuditTrail, Boolean blockFutureMerges) {
return getMergeResource().unmerge(mergeURI, retainAuditTrail, blockFutureMerges);
}
@Override
public JsonNode merge(List<String> mergeURIs, String flowName, String stepNumber, Boolean preview, JsonNode options) {
return getMergeResource().merge(mergeURIs, flowName, stepNumber, preview, options);
}
@Override
public JsonNode match(String matchURI, String flowName, String stepNumber, Boolean includeMatchDetails, JsonNode options) {
return getMatchResource().match(matchURI, flowName, stepNumber, includeMatchDetails, options);
}
private MergeResource getMergeResource() {
if (mergeResource == null) {
mergeResource = new MergeResource(getSrcClient(), hubConfig.getDbName(DatabaseKind.FINAL));
}
return mergeResource;
}
private MatchResource getMatchResource() {
if (matchResource == null) {
matchResource = new MatchResource(getSrcClient(), hubConfig.getDbName(DatabaseKind.FINAL));
}
return matchResource;
}
private DatabaseClient getSrcClient() {
if (srcClient == null) {
srcClient = hubConfig.newStagingClient();
}
return srcClient;
}
static class MergeResource extends ResourceManager {
private String targetDatabase;
public MergeResource(DatabaseClient srcClient, String targetDatabase) {
super();
this.targetDatabase = targetDatabase;
srcClient.init("mlSmMerge" , this);
}
public JsonNode unmerge(String mergeURI, Boolean retainAuditTrail, Boolean blockFutureMerges) {
JsonNode resp;
RequestParameters params = new RequestParameters();
params.add("mergeURI", mergeURI);
params.put("retainAuditTrail", retainAuditTrail.toString());
params.put("blockFutureMerges", blockFutureMerges.toString());
params.put("targetDatabase", targetDatabase);
params.put("sourceDatabase", targetDatabase);
JacksonHandle handle = new JacksonHandle();
resp = this.getServices().delete(params, handle).get();
return resp;
}
public JsonNode merge(List<String> mergeURIs, String flowName, String stepNumber, Boolean preview, JsonNode options) {
JsonNode resp;
RequestParameters params = new RequestParameters();
params.put("uri", mergeURIs);
params.put("preview", preview.toString());
params.put("flowName", flowName);
params.put("step", stepNumber);
params.put("targetDatabase", targetDatabase);
params.put("sourceDatabase", targetDatabase);
JacksonHandle jsonOptions = new JacksonHandle().with(options);
resp = this.getServices().post(params, jsonOptions, new JacksonHandle()).get();
return resp;
}
}
static class MatchResource extends ResourceManager {
private String targetDatabase;
public MatchResource(DatabaseClient srcClient, String targetDatabase) {
super();
this.targetDatabase = targetDatabase;
srcClient.init("mlSmMatch" , this);
}
public JsonNode match(String matchURI, String flowName, String stepNumber, Boolean includeMatchDetails, JsonNode options) {
JsonNode resp;
RequestParameters params = new RequestParameters();
params.put("uri", matchURI);
params.put("includeMatchDetails", includeMatchDetails.toString());
params.put("flowName", flowName);
params.put("step", stepNumber);
params.put("targetDatabase", targetDatabase);
params.put("sourceDatabase", targetDatabase);
JacksonHandle jsonOptions = new JacksonHandle().with(options);
resp = this.getServices().post(params, jsonOptions, new JacksonHandle()).get();
return resp;
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-lakeformation/src/main/java/com/amazonaws/services/lakeformation/model/EntityNotFoundException.java | 1216 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.lakeformation.model;
import javax.annotation.Generated;
/**
* <p>
* A specified entity does not exist
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EntityNotFoundException extends com.amazonaws.services.lakeformation.model.AWSLakeFormationException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new EntityNotFoundException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public EntityNotFoundException(String message) {
super(message);
}
}
| apache-2.0 |
huawei-microservice-demo/sockshop-demo | orders/src/main/java/works/weave/socks/orders/controllers/HealthCheckController.java | 1529 | package works.weave.socks.orders.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import works.weave.socks.orders.entities.HealthCheck;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestSchema(schemaId = "health_status")
@RequestMapping(path = "/orders")
public class HealthCheckController {
@Autowired
private MongoTemplate mongoTemplate;
@ResponseStatus(HttpStatus.OK)
@RequestMapping(method = RequestMethod.GET, path = "/health")
public @ResponseBody Map<String, List<HealthCheck>> getHealth() {
Map<String, List<HealthCheck>> map = new HashMap<String, List<HealthCheck>>();
List<HealthCheck> healthChecks = new ArrayList<HealthCheck>();
Date dateNow = Calendar.getInstance().getTime();
HealthCheck app = new HealthCheck("orders", "OK", dateNow);
HealthCheck database = new HealthCheck("orders-db", "OK", dateNow);
try {
mongoTemplate.executeCommand("{ buildInfo: 1 }");
} catch (Exception e) {
database.setStatus("err");
}
healthChecks.add(app);
healthChecks.add(database);
map.put("health", healthChecks);
return map;
}
}
| apache-2.0 |
justinsb/cloudata | cloudata-server-shared/src/main/java/com/cloudata/objectstore/jclouds/SwiftPath.java | 663 | //package com.cloudata.objectstore.jclouds;
//
//class SwiftPath {
// final String container;
// final String name;
//
// public SwiftPath(String container, String name) {
// this.container = container;
// this.name = name;
// }
//
// static SwiftPath split(String path) {
// while (path.startsWith("/")) {
// path = path.substring(1);
// }
// int firstSlash = path.indexOf('/');
// if (firstSlash == -1) {
// return new SwiftPath(path, "");
// } else {
// return new SwiftPath(path.substring(0, firstSlash), path.substring(firstSlash + 1));
// }
// }
// } | apache-2.0 |
kenpu/2014-01-csci2020u | tutorial-for-assignment1/java/Lookfor.java | 1177 | import java.io.*;
public class Lookfor {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Usage: <filename> <keyword>");
System.exit(0);
}
String filename = args[0];
String keyword = args[1];
InputStream in;
try {
in = new FileInputStream(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
long start = System.currentTimeMillis();
int count = 0;
while(line != null) {
if(line.contains(keyword)) {
System.out.println(line);
count += 1;
}
line = reader.readLine();
}
float dur = (System.currentTimeMillis() - start) / 1000f;
System.out.printf("Found %d instances in %.4f seconds\n",
count,
dur);
reader.close();
} catch(Exception e) {
System.out.printf("Cannot open file \"%s\"\n", filename);
System.exit(0);
}
}
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/AddInstanceGroupsResultJsonUnmarshaller.java | 3282 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT 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.amazonaws.services.elasticmapreduce.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* AddInstanceGroupsResult JSON Unmarshaller
*/
public class AddInstanceGroupsResultJsonUnmarshaller implements
Unmarshaller<AddInstanceGroupsResult, JsonUnmarshallerContext> {
public AddInstanceGroupsResult unmarshall(JsonUnmarshallerContext context)
throws Exception {
AddInstanceGroupsResult addInstanceGroupsResult = new AddInstanceGroupsResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("JobFlowId", targetDepth)) {
context.nextToken();
addInstanceGroupsResult.setJobFlowId(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("InstanceGroupIds", targetDepth)) {
context.nextToken();
addInstanceGroupsResult
.setInstanceGroupIds(new ListUnmarshaller<String>(
StringJsonUnmarshaller.getInstance())
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return addInstanceGroupsResult;
}
private static AddInstanceGroupsResultJsonUnmarshaller instance;
public static AddInstanceGroupsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new AddInstanceGroupsResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
hufsm/PocketHub | app/src/main/java/com/github/pockethub/accounts/StoreCredentials.java | 2133 | /*
* Copyright (c) 2016 PocketHub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pockethub.accounts;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class StoreCredentials {
public static final String KEY_URL = "KEY_URL";
private static final String USER_NAME = StoreCredentials.class.getSimpleName() + ".USER_NAME";
private static final String USER_TOKEN = StoreCredentials.class.getSimpleName() + ".USER_TOKEN";
private final SharedPreferences.Editor editor;
private final SharedPreferences preferences;
public StoreCredentials(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
editor = preferences.edit();
}
public void storeToken(String accessToken) {
editor.putString(USER_TOKEN, accessToken);
editor.apply();
}
public String token() {
return preferences.getString(USER_TOKEN, null);
}
public void clear() {
editor.remove(KEY_URL);
editor.remove(USER_NAME);
editor.remove(USER_TOKEN);
editor.commit();
}
public void storeUsername(String name) {
editor.putString(USER_NAME, name);
editor.apply();
}
public void storeUrl(String url) {
editor.putString(KEY_URL, url);
editor.apply();
}
public String getUserName() {
return preferences.getString(USER_NAME, null);
}
public String getUrl() {
return preferences.getString(KEY_URL, null);
}
}
| apache-2.0 |
erik-wramner/JmsTools | JmsCommon/src/test/java/name/wramner/util/AutoCloserTest.java | 2497 | /*
* Copyright 2016 Erik Wramner.
*
* 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 name.wramner.util;
import static org.junit.Assert.assertTrue;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
/**
* Test the {@link AutoCloser}.
*
* @author Erik Wramner
*/
public class AutoCloserTest {
@Test(expected = IllegalStateException.class)
public void testNoCloseMethod() {
try (AutoCloser a = new AutoCloser(new NoCloseMethodResource())) {
}
}
@Test
public void testClose() {
List<CloseMethodResource> resources = new ArrayList<>();
try (AutoCloser a = new AutoCloser()) {
resources.add(new CloseMethodResource(false));
resources.add(new CloseMethodResource(true));
resources.add(new CloseableResource(false));
resources.add(new CloseableResource(true));
for (CloseMethodResource r : resources) {
a.add(r);
}
}
for (CloseMethodResource r : resources) {
assertTrue(r.isClosed());
}
}
private static class NoCloseMethodResource {
}
private static class CloseMethodResource {
private final boolean _throw;
private boolean _closed;
public CloseMethodResource(boolean shouldThrow) {
_throw = shouldThrow;
}
public void close() throws IOException {
_closed = true;
if (_throw) {
throw new IOException("Failed to close!");
}
}
public boolean isClosed() {
return _closed;
}
}
private static class CloseableResource extends CloseMethodResource implements Closeable {
public CloseableResource(boolean shouldThrow) {
super(shouldThrow);
}
}
}
| apache-2.0 |
appdevzhang/AndroidVolleyDemo | app/src/main/java/appdevzhang/com/androidvolleydemo/net/GsonRequest.java | 1697 | package appdevzhang.com.androidvolleydemo.net;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import java.io.UnsupportedEncodingException;
/**
* @ClassName: JsonRequest
* @Description:
* @author: appdevzhang
* @email: 1160030655@qq.com
* @date: 15/8/28 上午9:31
*/
public class GsonRequest<T> extends Request<T> {
private final Listener<T> mListener;
private Gson mGson;
private Class<T> mClass;
public GsonRequest(int method,String url,Class<T> clazz,Listener<T> listener,ErrorListener errorListener) {
super(method,url,errorListener);
mListener = listener;
mGson = new Gson();
mClass = clazz;
}
public GsonRequest(String url,Class<T> clazz,Listener<T> listener,ErrorListener errorListener){
this(Method.GET,url,clazz,listener,errorListener);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse networkResponse) {
try {
String jsonStirng = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
return Response.success(mGson.fromJson(jsonStirng,mClass),HttpHeaderParser.parseCacheHeaders(networkResponse));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError());
}
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
| apache-2.0 |
eggeral/javafx-examples | src/main/java/baylandtag/ag_dummy_person_table/DatabaseException.java | 276 | package baylandtag.ag_dummy_person_table;
public class DatabaseException extends RuntimeException {
private static final long serialVersionUID = 7974621277508998411L;
public DatabaseException(String message, Throwable cause) {
super(message, cause);
}
}
| apache-2.0 |
alexradzin/Mestor | entity-manager/src/test/java/org/mestor/em/CriteriaBuilderTest.java | 18708 | /******************************************************************************************************/
/* */
/* Infinidat Ltd. - Proprietary and Confidential Material */
/* */
/* Copyright (C) 2013, Infinidat Ltd. - All Rights Reserved */
/* */
/* NOTICE: All information contained herein is, and remains the property of Infinidat Ltd. */
/* All information contained herein is protected by trade secret or copyright law. */
/* The intellectual and technical concepts contained herein are proprietary to Infinidat Ltd., */
/* and may be protected by U.S. and Foreign Patents, or patents in progress. */
/* */
/* Redistribution or use, in source or binary forms, with or without modification, */
/* are strictly forbidden unless prior written permission is obtained from Infinidat Ltd. */
/* */
/* */
/******************************************************************************************************/
package org.mestor.em;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.SingularAttribute;
import org.junit.Assert;
import org.junit.Test;
import org.mestor.entities.annotated.Person;
import org.mestor.metadata.EntityMetadata;
import org.mestor.persistence.query.CommonAbstractCriteriaBase;
import org.mestor.persistence.query.QueryImpl;
import org.mestor.query.ClauseInfo;
import org.mestor.query.ClauseInfo.Operand;
import org.mestor.query.OrderByInfo;
import org.mestor.query.OrderByInfo.Order;
import org.mestor.query.QueryInfo;
import org.mestor.query.QueryInfo.QueryType;
import org.mestor.query.QueryInfoAssert;
import com.google.common.base.Function;
public class CriteriaBuilderTest {
private final String MESTOR_PERSISTOR_CLASS = "org.mestor.persistor.class";
private final String MESTOR_ENTITY_PACKAGE = "org.mestor.managed.package";
private final static Map<String, String> fromPerson = Collections.<String, String> singletonMap("person", "Person");
private final EntityManager em;
public CriteriaBuilderTest() {
em = createEntityManager(DummyPersistor.class.getName());
assertNotNull(em);
}
@Test
public void testGetCriteriaBuilder() {
getCriteriaBuilder();
}
@Test
public void testCreateEmptyQuery() {
testCreateQuery(Person.class, new QueryInfo(QueryType.SELECT, null, Collections.<String, String> emptyMap()), new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> input) {
return null;
}
});
}
@Test
public void testCreateQueryWithFrom() {
testCreateQuery(Person.class, new QueryInfo(QueryType.SELECT, null, fromPerson), new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
criteria.from(Person.class);
return null;
}
});
}
@Test
public void testCreateQueryWithFromAndWhereIdEqConst() {
testCreateQueryWithFromAndWhere1("identifier", Integer.class, Operand.EQ, 123);
}
@Test
public void testCreateQueryWithFromAndWhereIdNotEqConst() {
testCreateQueryWithFromAndWhere1("identifier", Integer.class, Operand.NE, 123);
}
@Test
public void testCreateQueryWithFromAndWhereIdGtConst() {
testCreateQueryWithFromAndWhere1("identifier", Integer.class, Operand.GT, 456);
}
@Test
public void testCreateQueryWithFromAndWhereIdGeConst() {
testCreateQueryWithFromAndWhere1("identifier", Integer.class, Operand.GE, 456);
}
@Test
public void testCreateQueryWithFromAndWhereIdLeConst() {
testCreateQueryWithFromAndWhere1("identifier", Integer.class, Operand.LE, 456);
}
@Test
public void testCreateQueryWithFromAndWhereIdLtConst() {
testCreateQueryWithFromAndWhere1("identifier", Integer.class, Operand.LT, 456);
}
@Test
public void testCreateQueryWithFromAndWhereNameEqConst() {
testCreateQueryWithFromAndWhere1("name", String.class, Operand.EQ, "John");
}
@Test(expected = IllegalArgumentException.class)
public void testCreateQueryWithFromAndWhereNotExistingField() {
testCreateQueryWithFromAndWhere1("doesnotexist", String.class, Operand.EQ, "Foobar");
}
@Test
public void testCreateQueryWithFromAndWhereWith2FieldsByAnd() {
twoFieldsByOperand(Operand.AND);
}
@Test
public void testCreateQueryWithFromAndWhereWith2FieldsByOr() {
twoFieldsByOperand(Operand.OR);
}
@Test
public void testCreateQueryWithFromAndWhereWithLikeNoPercent() {
testCreateQueryWithFromAndWhere1("name", String.class, Operand.LIKE, "John");
}
private void twoFieldsByOperand(final Operand op) {
Assert.assertTrue(op == Operand.AND || op == Operand.OR);
testCreateQuery(Person.class,
new QueryInfo(QueryType.SELECT, null,
fromPerson,
new ClauseInfo(null, op, new ClauseInfo[] {
new ClauseInfo("name", Operand.EQ, "John"),
new ClauseInfo("lastName", Operand.EQ, "Lennon") }
),
null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final SingularAttribute<? super Person, String> personNameAttr = getAttribute(Person.class, "name", String.class);
final SingularAttribute<? super Person, String> personLastNameAttr = getAttribute(Person.class, "lastName", String.class);
final CriteriaBuilder builder = getBuilder(criteria);
final Predicate op1 = builder.equal(root.get(personNameAttr), "John");
final Predicate op2 = builder.equal(root.get(personLastNameAttr), "Lennon");
final Predicate where = op == Operand.AND ? builder.and(op1, op2) : builder.or(op1, op2);
criteria.where(where);
return null;
}
});
}
@Test
public void testCreateQueryWithFromAndWhereWithEmptyConjunction() {
testCreateQuery(Person.class,
new QueryInfo(QueryType.SELECT, null, fromPerson, null, null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
criteria.from(Person.class);
final CriteriaBuilder builder = getBuilder(criteria);
criteria.where(builder.conjunction());
return null;
}
});
}
@Test
public void testCreateQueryWithFromAndWhereWithConjunctionAndField() {
testCreateQuery(Person.class,
new QueryInfo(QueryType.SELECT, null, fromPerson, new ClauseInfo("name", Operand.EQ, "John"), null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final SingularAttribute<? super Person, String> personNameAttr = getAttribute(Person.class, "name", String.class);
final CriteriaBuilder builder = getBuilder(criteria);
criteria.where(builder.and(builder.conjunction(), builder.equal(root.get(personNameAttr), "John")));
return null;
}
});
}
@Test
public void testCreateQueryWithFromAndWhereWithIsNull() {
testCreateQuery(
Person.class,
new QueryInfo(
QueryType.SELECT,
null,
fromPerson,
new ClauseInfo("name", Operand.EQ, null),
null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final CriteriaBuilder builder = getBuilder(criteria);
final SingularAttribute<? super Person, String> name = getAttribute(Person.class, "name", String.class);
criteria.where(builder.isNull(root.get(name)));
return null;
}
});
}
private CriteriaBuilder getBuilder(@Nullable final CriteriaQuery<?> criteria) {
// this is ugly casting but it is good enough for tests.
@SuppressWarnings("rawtypes")
final CriteriaBuilder builder = ((CommonAbstractCriteriaBase) criteria).getCriteriaBuilder();
return builder;
}
private <E, F> SingularAttribute<? super E, F> getAttribute(final Class<E> entityClass, final String attrName, final Class<F> attrClass) {
final EntityType<E> entityType = notNull(em.getMetamodel().entity(entityClass));
final SingularAttribute<? super E, F> singularAttribute = entityType.getSingularAttribute(attrName, attrClass);
return notNull(singularAttribute);
}
@Test
public void testCreateQueryWithFromAndWhereIn() {
testCreateQuery(Person.class, new QueryInfo(QueryType.SELECT, null, fromPerson, new ClauseInfo("name", Operand.IN, new String[] { "John",
"Paul", "George", "Ringo" }), null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final SingularAttribute<? super Person, String> personNameAttr = getAttribute(Person.class, "name", String.class);
criteria.where(root.get(personNameAttr).in(Arrays.asList("John", "Paul", "George", "Ringo")));
return null;
}
});
}
@Test
public void testCreateQueryWithFromAndWhereAgeGEConst() {
testCreateQuery(Person.class, new QueryInfo(QueryType.SELECT, null, fromPerson, new ClauseInfo("age", Operand.GE, new Integer(0)), null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final SingularAttribute<? super Person, Integer> personAgeAttr = getAttribute(Person.class, "age", int.class);
final CriteriaBuilder builder = getBuilder(criteria);
criteria.where(builder.greaterThanOrEqualTo(root.get(personAgeAttr), 0));
return null;
}
});
}
@Test
public void testCreateQueryWithFromAndOrderAgeAsc() {
testOrderBy(Order.ASC);
}
@Test
public void testCreateQueryWithFromAndOrderAgeDesc() {
testOrderBy(Order.DSC);
}
private void testOrderBy(final Order order) {
testCreateQuery(Person.class,
new QueryInfo(QueryType.SELECT, null, fromPerson, null, Collections.<OrderByInfo> singletonList(new OrderByInfo("age", order))),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final SingularAttribute<? super Person, Integer> personAgeAttr = getAttribute(Person.class, "age", int.class);
final CriteriaBuilder builder = getBuilder(criteria);
if (order == Order.ASC) {
criteria.orderBy(builder.asc(root.get(personAgeAttr)));
} else {
criteria.orderBy(builder.desc(root.get(personAgeAttr)));
}
return null;
}
});
}
private abstract class FunctionExpression<T> implements Function<CriteriaQuery<T>, Void>{
@Override
public final Void apply(@Nullable final CriteriaQuery<T> criteria) {
final CriteriaBuilder builder = getBuilder(criteria);
final Root<Person> root = notNull(criteria.from(Person.class));
apply(criteria, root, builder);
return null;
}
protected abstract void apply(final CriteriaQuery<T> criteria, final Root<Person> root, final CriteriaBuilder builder);
}
@Test
public void testCreateQueryWithFromCount() {
testQueryWithFunction(
Long.class,
"count(*)",
"age",
new FunctionExpression<Long>() {
@Override
protected void apply(final CriteriaQuery<Long> criteria, final Root<Person> root, final CriteriaBuilder builder) {
final SingularAttribute<? super Person, Integer> personAgeAttr = getAttribute(Person.class, "age", int.class);
criteria.select(builder.count(root.get(personAgeAttr)));
}
});
}
private <T> void testQueryWithFunction(final Class<T> resultClass, final Object value, final String alias, final FunctionExpression<T> func) {
testCreateQuery(resultClass,
new QueryInfo(
QueryType.SELECT,
Collections.<String, Object> singletonMap(alias, value),
fromPerson,
null,
null),
func);
}
@Test
public void testCreateQueryWithFromLiteral() {
testQueryWithFunction(
Long.class,
1l,
"1",
new FunctionExpression<Long>() {
@Override
protected void apply(final CriteriaQuery<Long> criteria, final Root<Person> root, final CriteriaBuilder builder) {
criteria.select(builder.literal(1L));
}
});
}
@Test
public void testCreateQueryWithFromMax() {
testQueryWithFunction(
Integer.class,
"max(age)",
"age",
new FunctionExpression<Integer>() {
@Override
protected void apply(final CriteriaQuery<Integer> criteria, final Root<Person> root, final CriteriaBuilder builder) {
final SingularAttribute<? super Person, Integer> personAgeAttr = getAttribute(Person.class, "age", int.class);
criteria.select(builder.max(root.get(personAgeAttr)));
}
});
}
@Test
public void testCreateQueryWithFromMin() {
testQueryWithFunction(
Integer.class,
"min(age)",
"age",
new FunctionExpression<Integer>() {
@Override
protected void apply(final CriteriaQuery<Integer> criteria, final Root<Person> root, final CriteriaBuilder builder) {
final SingularAttribute<? super Person, Integer> personAgeAttr = getAttribute(Person.class, "age", int.class);
criteria.select(builder.min(root.get(personAgeAttr)));
}
});
}
@Test
public void testCreateQueryWithFromSum() {
testQueryWithFunction(
Integer.class,
"sum(age)",
"age",
new FunctionExpression<Integer>() {
@Override
protected void apply(final CriteriaQuery<Integer> criteria, final Root<Person> root, final CriteriaBuilder builder) {
final SingularAttribute<? super Person, Integer> personAgeAttr = getAttribute(Person.class, "age", int.class);
criteria.select(builder.sum(root.get(personAgeAttr)));
}
});
}
@Test
public void testCreateQueryWithFromUpper() {
testQueryWithFunction(
String.class,
"upper(name)",
"name",
new FunctionExpression<String>() {
@Override
protected void apply(final CriteriaQuery<String> criteria, final Root<Person> root, final CriteriaBuilder builder) {
final SingularAttribute<? super Person, String> personNameAttr = getAttribute(Person.class, "name", String.class);
criteria.select(builder.upper(root.get(personNameAttr)));
}
});
}
private <T> void testCreateQueryWithFromAndWhere1(final String fieldName, final Class<T> fieldType, final Operand operand, final T fieldValue) {
testCreateQuery(Person.class, new QueryInfo(QueryType.SELECT, null, fromPerson, new ClauseInfo(fieldName, operand, fieldValue), null),
new Function<CriteriaQuery<Person>, Void>() {
@Override
public Void apply(@Nullable final CriteriaQuery<Person> criteria) {
final Root<Person> root = notNull(criteria.from(Person.class));
final SingularAttribute<? super Person, T> personIdAttr = getAttribute(Person.class, fieldName, fieldType);
final CriteriaBuilder builder = getBuilder(criteria);
final Path<T> path = root.get(personIdAttr);
final Predicate predicate;
@SuppressWarnings("unchecked")
final Path<Number> numPath = (Path<Number>) path;
@SuppressWarnings("unchecked")
final Path<String> strPath = (Path<String>) path;
switch (operand) {
case EQ:
predicate = builder.equal(path, fieldValue);
break;
case NE:
predicate = builder.notEqual(path, fieldValue);
break;
case GT:
predicate = builder.gt(numPath, (Number) fieldValue);
break;
case GE:
predicate = builder.ge(numPath, (Number) fieldValue);
break;
case LE:
predicate = builder.le(numPath, (Number) fieldValue);
break;
case LT:
predicate = builder.lt(numPath, (Number) fieldValue);
break;
case LIKE:
predicate = builder.like(strPath, (String) fieldValue);
break;
default:
throw new UnsupportedOperationException(operand.name());
}
criteria.where(predicate);
return null;
}
});
}
private <T> void testCreateQuery(final Class<T> clazz, final QueryInfo expected, final Function<CriteriaQuery<T>, Void> f) {
final CriteriaBuilder builder = getCriteriaBuilder();
final CriteriaQuery<T> criteria = builder.createQuery(clazz);
assertNotNull(criteria);
assertEquals(clazz, criteria.getResultType());
f.apply(criteria);
final TypedQuery<T> query = em.createQuery(criteria);
assertNotNull(query);
assertEquals(QueryImpl.class, query.getClass());
final QueryImpl<T> queryImpl = (QueryImpl<T>) query;
final QueryInfo queryInfo = queryImpl.getQueryInfo();
assertNotNull(queryInfo);
QueryInfoAssert.assertQueryInfo(expected, queryInfo);
}
private EntityManager createEntityManager(final String persistorClassName) {
System.setProperty(MESTOR_PERSISTOR_CLASS, persistorClassName);
System.setProperty(MESTOR_ENTITY_PACKAGE, Person.class.getPackage().getName());
try {
final EntityMetadata<Person> personEmd = new EntityMetadata<Person>(Person.class);
personEmd.setTableName("person");
return Persistence.createEntityManagerFactory("mestortest").createEntityManager();
} finally {
System.getProperties().remove(MESTOR_PERSISTOR_CLASS);
}
}
private CriteriaBuilder getCriteriaBuilder() {
final CriteriaBuilder builder = em.getCriteriaBuilder();
assertNotNull(builder);
return builder;
}
private static <T> T notNull(final T value) {
assertNotNull(value);
return value;
}
} | apache-2.0 |
irblsensitivity/irblsensitivity | techniques/BLIA/test/edu/skku/selab/blp/testsuite/DAOAllTests.java | 638 | package edu.skku.selab.blp.testsuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import edu.skku.selab.blp.db.dao.BugDAOTest;
import edu.skku.selab.blp.db.dao.CommitDAOTest;
import edu.skku.selab.blp.db.dao.ExperimentResultDAOTest;
import edu.skku.selab.blp.db.dao.IntegratedAnalysisDAOTest;
import edu.skku.selab.blp.db.dao.SourceFileDAOTest;
@RunWith(Suite.class)
@SuiteClasses({
BugDAOTest.class,
CommitDAOTest.class,
ExperimentResultDAOTest.class,
IntegratedAnalysisDAOTest.class,
SourceFileDAOTest.class})
public class DAOAllTests {
}
| apache-2.0 |
ow2-chameleon/fuchsia | exporters/json-rpc/src/main/java/org/ow2/chameleon/fuchsia/exporter/jsonrpc/JSONRPCExporter.java | 6699 | package org.ow2.chameleon.fuchsia.exporter.jsonrpc;
/*
* #%L
* OW2 Chameleon - Fuchsia Exporter JSON-RPC
* %%
* Copyright (C) 2009 - 2014 OW2 Chameleon
* %%
* 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.
* #L%
*/
import com.googlecode.jsonrpc4j.JsonRpcServer;
import org.apache.felix.ipojo.annotations.*;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.ow2.chameleon.fuchsia.core.FuchsiaUtils;
import org.ow2.chameleon.fuchsia.core.component.AbstractExporterComponent;
import org.ow2.chameleon.fuchsia.core.component.ExporterService;
import org.ow2.chameleon.fuchsia.core.component.ImporterService;
import org.ow2.chameleon.fuchsia.core.declaration.ExportDeclaration;
import org.ow2.chameleon.fuchsia.core.declaration.ImportDeclaration;
import org.ow2.chameleon.fuchsia.core.exceptions.BinderException;
import org.ow2.chameleon.fuchsia.exporter.jsonrpc.model.JSONRPCExportDeclarationWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import static org.apache.felix.ipojo.Factory.INSTANCE_NAME_PROPERTY;
/**
* Provides an {@link ImporterService} allowing to access a.
* remote endpoint through jsonrpc thanks to the jsonrpc4j implementation.
* <p/>
* A valid {@link ImportDeclaration} for this ImporterService contains has metadata :
* - ID : a unique String which is the id of the JSON-RPC service
* - URL : a String containing the URL of the JSON-RPC service to import into OSGi.
* - SERVICE_CLASS : a String containing the name of the class to use to build the proxy
* <p/>
* TODO : Improves the client management, only one client should be created for a given uri.
*/
@Component
@Provides(specifications = {ExporterService.class})
public class JSONRPCExporter extends AbstractExporterComponent {
private static final Logger LOG = LoggerFactory.getLogger(JSONRPCExporter.class);
@ServiceProperty(name = INSTANCE_NAME_PROPERTY)
private String name;
@ServiceProperty(name = "target", value = "(&(fuchsia.export.jsonrpc.instance=*)(scope=generic))")
private String filter;
@Requires
HttpService web;
private Set<String> registeredServlets = new HashSet<String>();
private final BundleContext context;
private ServiceReference serviceReference;
public JSONRPCExporter(BundleContext pContext) {
context = pContext;
}
@Override
protected void useExportDeclaration(ExportDeclaration exportDeclaration) throws BinderException {
Class<?> klass = null;
JSONRPCExportDeclarationWrapper jp = JSONRPCExportDeclarationWrapper.create(exportDeclaration);
try {
klass = FuchsiaUtils.loadClass(context, jp.getInstanceClass());
} catch (ClassNotFoundException e) {
LOG.warn("Failed to load from the own bundle, loading externally", e);
}
String osgiFilter = String.format("(instance.name=%s)", jp.getInstanceName());
List<ServiceReference> references = null;
try {
references = new ArrayList<ServiceReference>(context.getServiceReferences(klass, osgiFilter));
} catch (InvalidSyntaxException e) {
LOG.error("LDAP filter specified on the linker is not valid, recheck your LDAP filters for the linker and exporter. ", e);
return;
}
Object serviceToBePublished = context.getService(references.iterator().next());
final JsonRpcServer jsonRpcServer = new JsonRpcServer(serviceToBePublished, klass);
final String endpointURL = String.format("%s/%s", jp.getUrlContext(), jp.getInstanceName());
Servlet gs = new RPCServlet(jsonRpcServer);
try {
web.registerServlet(endpointURL, gs, new Hashtable(), null);
exportDeclaration.handle(serviceReference);
registeredServlets.add(endpointURL);
LOG.info("JSONRPC-exporter, publishing object exporter at: {}", endpointURL);
} catch (NamespaceException e) {
LOG.error("Namespace failure", e);
} catch (ServletException e) {
LOG.error("Failed registering the servlet to respond the RPC request.", e);
}
}
@Override
protected void denyExportDeclaration(ExportDeclaration exportDeclaration) throws BinderException {
JSONRPCExportDeclarationWrapper jp = JSONRPCExportDeclarationWrapper.create(exportDeclaration);
final String endpointURL = String.format("%s/%s", jp.getUrlContext(), jp.getInstanceName());
exportDeclaration.unhandle(serviceReference);
registeredServlets.remove(endpointURL);
web.unregister(endpointURL);
}
public String getName() {
return name;
}
@PostRegistration
public void registration(ServiceReference serviceReference) {
this.serviceReference = serviceReference;
}
/*
* (non-Javadoc)
* @see org.ow2.chameleon.rose.AbstractImporterComponent#stop()
*/
@Override
@Invalidate
public void stop() {
unregisterAllServlets();
}
/**
* Unregister all servlets registered by this exporter.
*/
private void unregisterAllServlets() {
for (String endpoint : registeredServlets) {
registeredServlets.remove(endpoint);
web.unregister(endpoint);
LOG.info("endpoint {} unregistered", endpoint);
}
}
static class RPCServlet extends HttpServlet {
private final JsonRpcServer jsonRpcServer;
public RPCServlet(JsonRpcServer jsonRpcServer) {
this.jsonRpcServer = jsonRpcServer;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
jsonRpcServer.handle(req, resp);
}
}
}
| apache-2.0 |
seeburger-ag/commons-vfs | commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileSystemManagerTest.java | 1694 | /*
* 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.commons.vfs2.impl;
import java.nio.file.Paths;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests {@link DefaultFileSystemManager}.
*
* @since 2.5.0
*/
public class DefaultFileSystemManagerTest {
/**
* Tests {@link DefaultFileSystemManager#close()}.
*
* @throws FileSystemException
*/
@Test
public void test_close() throws FileSystemException {
try (FileSystemManager fileSystemManager = new DefaultFileSystemManager()) {
VFS.setManager(fileSystemManager);
VFS.setManager(null);
}
Assert.assertNotNull(VFS.getManager());
Assert.assertFalse(VFS.getManager().resolveFile(Paths.get("DoesNotExist.not").toUri()).exists());
}
}
| apache-2.0 |
roman-kashitsyn/rules-dsl | src/main/java/org/rulesdsl/predicates/StatelessSelectors.java | 1449 | /*
* Copyright 2012 Roman Kashitsyn
*
* 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.rulesdsl.predicates;
import org.rulesdsl.Selector;
/**
* @author Roman Kashitsyn
*/
public enum StatelessSelectors implements Selector<Object> {
Anything {
public boolean matches(Object o) {
return true;
}
@Override public String toString() {
return "anything";
}
},
Null {
public boolean matches(Object o) {
return o == null;
}
@Override public String toString() {
return "null?";
}
},
NotNull {
public boolean matches(Object o) {
return o != null;
}
@Override public String toString() {
return "notNull?";
}
};
public boolean apply(Object o) {
return matches(o);
}
}
| apache-2.0 |
spinnaker/kayenta | kayenta-integration-tests/src/test/java/com/netflix/kayenta/tests/ManagementTest.java | 2159 | /*
* Copyright 2019 Playtika
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.kayenta.tests;
import static com.netflix.kayenta.utils.AwaitilityUtils.awaitThirtySecondsUntil;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
public class ManagementTest extends BaseIntegrationTest {
@Value("${embedded.prometheus.port}")
int prometheusPort;
@Test
public void prometheusTargetsAreAllReportingUp() {
awaitThirtySecondsUntil(
() ->
given()
.port(prometheusPort)
.get("/api/v1/targets")
.prettyPeek()
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("status", is("success"))
.body("data.activeTargets[0].health", is("up")));
}
@Test
public void healthIsUp() {
awaitThirtySecondsUntil(
() ->
given()
.port(managementPort)
.get("/health")
.prettyPeek()
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("status", is("UP"))
.body("components.canaryConfigIndexingAgent.status", is("UP"))
.body("components.prometheus.status", is("UP"))
.body("components.prometheus.details.'prometheus-account'.status", is("UP"))
.body("components.redisHealth.status", is("UP")));
}
}
| apache-2.0 |
VHAINNOVATIONS/ASRCM | srcalc/src/test/java/gov/va/med/srcalc/web/view/admin/CategoryBuilderTest.java | 1758 | package gov.va.med.srcalc.web.view.admin;
import static org.junit.Assert.*;
import gov.va.med.srcalc.domain.model.DiscreteNumericalVariable.Category;
import gov.va.med.srcalc.domain.model.MultiSelectOption;
import org.junit.Test;
/**
* Tests the {@link CategoryBuilder} class.
*/
public class CategoryBuilderTest
{
@Test
public final void testBuild()
{
final CategoryBuilder builder = new CategoryBuilder();
// Test default value.
assertEquals("", builder.getValue());
// Test building with the default range.
final String value = "firstValue";
assertSame(builder, builder.setValue(value)); // note: modifying builder
assertEquals(
new Category(new MultiSelectOption(value), 0f, true),
builder.build());
// Test building with a different range.
final float upperBound = -2.1f;
final boolean upperInclusive = false;
assertSame(builder, builder.setUpperBound(upperBound));
assertEquals(upperBound, builder.getUpperBound(), 0.0f);
assertSame(builder, builder.setUpperInclusive(upperInclusive));
assertEquals(upperInclusive, builder.getUpperInclusive());
assertEquals(
new Category(new MultiSelectOption(value), upperBound, upperInclusive),
builder.build());
}
@Test
public final void testFromPrototype()
{
final Category expectedCategory = new Category(
new MultiSelectOption("theValue"), 1.0f, false);
final CategoryBuilder builder = CategoryBuilder.fromPrototype(expectedCategory);
assertEquals(expectedCategory, builder.build());
}
}
| apache-2.0 |