repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
SciGraph/SciGraph | SciGraph-services/src/main/java/io/scigraph/services/health/Neo4jHealthCheck.java | 1580 | /**
* Copyright (C) 2014 The SciGraph 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 io.scigraph.services.health;
import static com.google.common.collect.Iterables.size;
import javax.inject.Inject;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import ru.vyarus.dropwizard.guice.module.installer.feature.health.NamedHealthCheck;
public class Neo4jHealthCheck extends NamedHealthCheck {
private final GraphDatabaseService graphDb;
@Inject
Neo4jHealthCheck(GraphDatabaseService graphDb) {
this.graphDb = graphDb;
}
@Override
protected Result check() throws Exception {
int count = 0;
try (Transaction tx = graphDb.beginTx()) {
count = size(graphDb.getAllNodes());
tx.success();
}
if (count > 0) {
return Result.healthy();
} else {
return Result.unhealthy("There are no nodes in the graph.");
}
}
@Override
public String getName() {
return "Neo4j Health Check";
}
}
| apache-2.0 |
barnyard/p2p-instancemanager | src/test/java/com/bt/pi/app/instancemanager/handlers/PauseInstanceServiceHelperTest.java | 3200 | package com.bt.pi.app.instancemanager.handlers;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.bt.pi.app.common.entities.Instance;
import com.bt.pi.app.common.entities.InstanceAction;
import com.bt.pi.app.common.id.PiIdBuilder;
import com.bt.pi.app.common.resource.PiQueue;
import com.bt.pi.core.application.MessageContext;
import com.bt.pi.core.application.MessageContextFactory;
import com.bt.pi.core.application.watcher.task.TaskProcessingQueueHelper;
import com.bt.pi.core.entity.EntityMethod;
import com.bt.pi.core.id.PId;
@RunWith(MockitoJUnitRunner.class)
public class PauseInstanceServiceHelperTest {
@InjectMocks
private PauseInstanceServiceHelper pauseInstanceServiceHelper = new PauseInstanceServiceHelper();
@Mock
private Instance instance;
@Mock
private MessageContextFactory messageContextFactory;
@Mock
private MessageContext messageContext;
@Mock
private PId nodePId;
@Mock
private PiIdBuilder piIdBuilder;
private String nodeId = "0123";
@Mock
private TaskProcessingQueueHelper taskProcessingQueueHelper;
private String instanceId = "i-123";
@Mock
private PId queuePId;
private int avzCode = 345;
@Before
public void before() {
when(instance.getNodeId()).thenReturn(nodeId);
when(instance.getInstanceId()).thenReturn(instanceId);
when(instance.getUrl()).thenReturn(Instance.getUrl(instanceId));
when(messageContextFactory.newMessageContext()).thenReturn(messageContext);
when(piIdBuilder.getNodeIdFromNodeId(nodeId)).thenReturn(nodePId);
when(piIdBuilder.getGlobalAvailabilityZoneCodeFromEc2Id(instanceId)).thenReturn(avzCode);
when(piIdBuilder.getPId(PiQueue.PAUSE_INSTANCE.getUrl())).thenReturn(queuePId);
when(queuePId.forGlobalAvailablityZoneCode(avzCode)).thenReturn(queuePId);
}
@Test
public void shouldSendMessageToInstanceManagerApplicationForPause() {
// act
pauseInstanceServiceHelper.pauseInstance(instance);
// assert
verify(instance).setActionRequired(InstanceAction.PAUSE);
verify(messageContext).routePiMessageToApplication(nodePId, EntityMethod.UPDATE, instance, InstanceManagerApplication.APPLICATION_NAME);
}
@Test
public void shouldSendMessageToInstanceManagerApplicationForUnpause() {
// act
pauseInstanceServiceHelper.unPauseInstance(instance);
// assert
verify(instance).setActionRequired(InstanceAction.UNPAUSE);
verify(messageContext).routePiMessageToApplication(nodePId, EntityMethod.UPDATE, instance, InstanceManagerApplication.APPLICATION_NAME);
}
@Test
public void shouldAddItemToQueueForPause() {
// setup
// act
pauseInstanceServiceHelper.pauseInstance(instance);
// assert
verify(taskProcessingQueueHelper).addUrlToQueue(queuePId, Instance.getUrl(instanceId), PauseInstanceServiceHelper.RETRIES);
}
}
| apache-2.0 |
mirkosertic/Bytecoder | classlib/java.xml/src/main/resources/META-INF/modules/java.xml/classes/org/xml/sax/ext/DeclHandler.java | 6574 | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.xml.sax.ext;
import org.xml.sax.SAXException;
/**
* SAX2 extension handler for DTD declaration events.
*
* <p>This is an optional extension handler for SAX2 to provide more
* complete information about DTD declarations in an XML document.
* XML readers are not required to recognize this handler, and it
* is not part of core-only SAX2 distributions.</p>
*
* <p>Note that data-related DTD declarations (unparsed entities and
* notations) are already reported through the {@link
* org.xml.sax.DTDHandler DTDHandler} interface.</p>
*
* <p>If you are using the declaration handler together with a lexical
* handler, all of the events will occur between the
* {@link org.xml.sax.ext.LexicalHandler#startDTD startDTD} and the
* {@link org.xml.sax.ext.LexicalHandler#endDTD endDTD} events.</p>
*
* <p>To set the DeclHandler for an XML reader, use the
* {@link org.xml.sax.XMLReader#setProperty setProperty} method
* with the property name
* <code>http://xml.org/sax/properties/declaration-handler</code>
* and an object implementing this interface (or null) as the value.
* If the reader does not report declaration events, it will throw a
* {@link org.xml.sax.SAXNotRecognizedException SAXNotRecognizedException}
* when you attempt to register the handler.</p>
*
* @since 1.4, SAX 2.0 (extensions 1.0)
* @author David Megginson
*/
public interface DeclHandler
{
/**
* Report an element type declaration.
*
* <p>The content model will consist of the string "EMPTY", the
* string "ANY", or a parenthesised group, optionally followed
* by an occurrence indicator. The model will be normalized so
* that all parameter entities are fully resolved and all whitespace
* is removed,and will include the enclosing parentheses. Other
* normalization (such as removing redundant parentheses or
* simplifying occurrence indicators) is at the discretion of the
* parser.</p>
*
* @param name The element type name.
* @param model The content model as a normalized string.
* @throws SAXException The application may raise an exception.
*/
public abstract void elementDecl (String name, String model)
throws SAXException;
/**
* Report an attribute type declaration.
*
* <p>Only the effective (first) declaration for an attribute will
* be reported. The type will be one of the strings "CDATA",
* "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY",
* "ENTITIES", a parenthesized token group with
* the separator "|" and all whitespace removed, or the word
* "NOTATION" followed by a space followed by a parenthesized
* token group with all whitespace removed.</p>
*
* <p>The value will be the value as reported to applications,
* appropriately normalized and with entity and character
* references expanded. </p>
*
* @param eName The name of the associated element.
* @param aName The name of the attribute.
* @param type A string representing the attribute type.
* @param mode A string representing the attribute defaulting mode
* ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if
* none of these applies.
* @param value A string representing the attribute's default value,
* or null if there is none.
* @throws SAXException The application may raise an exception.
*/
public abstract void attributeDecl (String eName,
String aName,
String type,
String mode,
String value)
throws SAXException;
/**
* Report an internal entity declaration.
*
* <p>Only the effective (first) declaration for each entity
* will be reported. All parameter entities in the value
* will be expanded, but general entities will not.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @param value The replacement text of the entity.
* @throws SAXException The application may raise an exception.
* @see #externalEntityDecl
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public abstract void internalEntityDecl (String name, String value)
throws SAXException;
/**
* Report a parsed external entity declaration.
*
* <p>Only the effective (first) declaration for each entity
* will be reported.</p>
*
* <p>If the system identifier is a URL, the parser must resolve it
* fully before passing it to the application.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @param publicId The entity's public identifier, or null if none
* was given.
* @param systemId The entity's system identifier.
* @throws SAXException The application may raise an exception.
* @see #internalEntityDecl
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public abstract void externalEntityDecl (String name, String publicId,
String systemId)
throws SAXException;
}
// end of DeclHandler.java
| apache-2.0 |
backpaper0/doma2 | src/main/java/org/seasar/doma/jdbc/type/NStringType.java | 1699 | /*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.seasar.doma.jdbc.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
/**
* {@link String} 用の {@link JdbcType} の実装です。
*
* @author taedium
*
*/
public class NStringType extends AbstractJdbcType<String> {
public NStringType() {
super(Types.NVARCHAR);
}
@Override
protected String doGetValue(ResultSet resultSet, int index)
throws SQLException {
return resultSet.getNString(index);
}
@Override
protected void doSetValue(PreparedStatement preparedStatement, int index,
String value) throws SQLException {
preparedStatement.setNString(index, value);
}
@Override
protected String doGetValue(CallableStatement callableStatement, int index)
throws SQLException {
return callableStatement.getNString(index);
}
@Override
protected String doConvertToLogFormat(String value) {
return "'" + value + "'";
}
}
| apache-2.0 |
Fabryprog/camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerJailStartingDirectoryTest.java | 2650 | /*
* 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.camel.component.file.remote;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
public class FtpProducerJailStartingDirectoryTest extends FtpServerTestSupport {
private String getFtpUrl() {
return "ftp://admin@localhost:" + getPort() + "/upload/jail?binary=false&password=admin&tempPrefix=.uploading";
}
@Test
public void testWriteOutsideStartingDirectory() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
try {
template.sendBodyAndHeader("direct:start", "Hello World", Exchange.FILE_NAME, "hello.txt");
fail("Should have thrown exception");
} catch (Exception e) {
IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
assertTrue(iae.getMessage().contains("as the filename is jailed to the starting directory"));
}
assertMockEndpointsSatisfied();
}
@Test
public void testWriteInsideStartingDirectory() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Bye World", Exchange.FILE_NAME, "jail/bye.txt");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.setHeader(Exchange.FILE_NAME, simple("../${file:name}"))
.to(getFtpUrl())
.to("mock:result");
}
};
}
} | apache-2.0 |
gkachru/cordova-plugin-background-geolocation | android/src/main/java/com/marianhello/bgloc/DummyActivity.java | 248 | package com.marianhello.bgloc;
import android.app.Activity;
import android.os.Bundle;
public class DummyActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
finish();
}
}
| apache-2.0 |
marques-work/gocd | plugin-infra/go-plugin-config-repo/src/main/java/com/thoughtworks/go/plugin/configrepo/contract/material/CRConfigMaterial.java | 2075 | /*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.plugin.configrepo.contract.material;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.thoughtworks.go.plugin.configrepo.contract.ErrorCollection;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class CRConfigMaterial extends CRMaterial {
public static final String TYPE_NAME = "configrepo";
@SerializedName("filter")
@Expose
private CRFilter filter;
@SerializedName("destination")
@Expose
private String destination;
public CRConfigMaterial() {
this(null, null, null);
}
public CRConfigMaterial(String name, String destination, CRFilter filter) {
super(TYPE_NAME, name);
this.destination = destination;
this.filter = filter;
}
@Override
public String typeName() {
return TYPE_NAME;
}
@Override
public void getErrors(ErrorCollection errors, String parentLocation) {
String location = getLocation(parentLocation);
if (this.filter != null)
this.filter.getErrors(errors, location);
}
@Override
public String getLocation(String parent) {
String myLocation = getLocation() == null ? parent : getLocation();
String name = getName() == null ? "" : getName();
return String.format("%s; Config material %s", myLocation, name);
}
} | apache-2.0 |
darkforestzero/buck | src/com/facebook/buck/apple/AppleBundleDescription.java | 12476 | /*
* 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.apple;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.LinkerMapMode;
import com.facebook.buck.cxx.StripStyle;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Either;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.HasTests;
import com.facebook.buck.model.ImmutableFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.AbstractDescriptionArg;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.Hint;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.MetadataProvidingDescription;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.versions.Version;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Optional;
public class AppleBundleDescription implements Description<AppleBundleDescription.Arg>,
Flavored,
ImplicitDepsInferringDescription<AppleBundleDescription.Arg>,
MetadataProvidingDescription<AppleBundleDescription.Arg> {
public static final ImmutableSet<Flavor> SUPPORTED_LIBRARY_FLAVORS = ImmutableSet.of(
CxxDescriptionEnhancer.STATIC_FLAVOR,
CxxDescriptionEnhancer.SHARED_FLAVOR);
public static final Flavor WATCH_OS_FLAVOR = ImmutableFlavor.of("watchos-armv7k");
public static final Flavor WATCH_SIMULATOR_FLAVOR = ImmutableFlavor.of("watchsimulator-i386");
private static final Flavor WATCH = ImmutableFlavor.of("watch");
private final AppleBinaryDescription appleBinaryDescription;
private final AppleLibraryDescription appleLibraryDescription;
private final FlavorDomain<CxxPlatform> cxxPlatformFlavorDomain;
private final FlavorDomain<AppleCxxPlatform> appleCxxPlatformsFlavorDomain;
private final CxxPlatform defaultCxxPlatform;
private final CodeSignIdentityStore codeSignIdentityStore;
private final ProvisioningProfileStore provisioningProfileStore;
private final AppleConfig appleConfig;
public AppleBundleDescription(
AppleBinaryDescription appleBinaryDescription,
AppleLibraryDescription appleLibraryDescription,
FlavorDomain<CxxPlatform> cxxPlatformFlavorDomain,
FlavorDomain<AppleCxxPlatform> appleCxxPlatformsFlavorDomain,
CxxPlatform defaultCxxPlatform,
CodeSignIdentityStore codeSignIdentityStore,
ProvisioningProfileStore provisioningProfileStore,
AppleConfig appleConfig) {
this.appleBinaryDescription = appleBinaryDescription;
this.appleLibraryDescription = appleLibraryDescription;
this.cxxPlatformFlavorDomain = cxxPlatformFlavorDomain;
this.appleCxxPlatformsFlavorDomain = appleCxxPlatformsFlavorDomain;
this.defaultCxxPlatform = defaultCxxPlatform;
this.codeSignIdentityStore = codeSignIdentityStore;
this.provisioningProfileStore = provisioningProfileStore;
this.appleConfig = appleConfig;
}
@Override
public Arg createUnpopulatedConstructorArg() {
return new Arg();
}
@Override
public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains() {
ImmutableSet.Builder<FlavorDomain<?>> builder = ImmutableSet.builder();
ImmutableSet<FlavorDomain<?>> localDomains = ImmutableSet.of(
AppleDebugFormat.FLAVOR_DOMAIN,
AppleDescriptions.INCLUDE_FRAMEWORKS
);
builder.addAll(localDomains);
appleLibraryDescription.flavorDomains().ifPresent(domains -> builder.addAll(domains));
appleBinaryDescription.flavorDomains().ifPresent(domains -> builder.addAll(domains));
return Optional.of(builder.build());
}
@Override
public boolean hasFlavors(final ImmutableSet<Flavor> flavors) {
if (appleLibraryDescription.hasFlavors(flavors)) {
return true;
}
ImmutableSet.Builder<Flavor> flavorBuilder = ImmutableSet.builder();
for (Flavor flavor : flavors) {
if (AppleDebugFormat.FLAVOR_DOMAIN.getFlavors().contains(flavor)) {
continue;
}
if (AppleDescriptions.INCLUDE_FRAMEWORKS.getFlavors().contains(flavor)) {
continue;
}
flavorBuilder.add(flavor);
}
return appleBinaryDescription.hasFlavors(flavorBuilder.build());
}
@Override
public <A extends Arg> AppleBundle createBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
A args) throws NoSuchBuildTargetException {
AppleDebugFormat flavoredDebugFormat = AppleDebugFormat.FLAVOR_DOMAIN
.getValue(params.getBuildTarget())
.orElse(appleConfig.getDefaultDebugInfoFormatForBinaries());
if (!params.getBuildTarget().getFlavors().contains(flavoredDebugFormat.getFlavor())) {
return (AppleBundle) resolver.requireRule(
params.getBuildTarget().withAppendedFlavors(flavoredDebugFormat.getFlavor()));
}
if (!AppleDescriptions.INCLUDE_FRAMEWORKS.getValue(params.getBuildTarget()).isPresent()) {
return (AppleBundle) resolver.requireRule(
params.getBuildTarget().withAppendedFlavors(
AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR));
}
return AppleDescriptions.createAppleBundle(
cxxPlatformFlavorDomain,
defaultCxxPlatform,
appleCxxPlatformsFlavorDomain,
targetGraph,
params,
resolver,
codeSignIdentityStore,
provisioningProfileStore,
args.binary,
args.extension,
args.productName,
args.infoPlist,
args.infoPlistSubstitutions,
args.deps,
args.tests,
flavoredDebugFormat,
appleConfig.useDryRunCodeSigning(),
appleConfig.cacheBundlesAndPackages());
}
/**
* Propagate the bundle's platform, debug symbol and strip flavors to its dependents
* which are other bundles (e.g. extensions)
*/
@Override
public ImmutableSet<BuildTarget> findDepsForTargetFromConstructorArgs(
BuildTarget buildTarget,
CellPathResolver cellRoots,
AppleBundleDescription.Arg constructorArg) {
if (!cxxPlatformFlavorDomain.containsAnyOf(buildTarget.getFlavors())) {
buildTarget = BuildTarget.builder(buildTarget).addAllFlavors(
ImmutableSet.of(defaultCxxPlatform.getFlavor())).build();
}
Optional<MultiarchFileInfo> fatBinaryInfo =
MultiarchFileInfos.create(appleCxxPlatformsFlavorDomain, buildTarget);
CxxPlatform cxxPlatform;
if (fatBinaryInfo.isPresent()) {
AppleCxxPlatform appleCxxPlatform = fatBinaryInfo.get().getRepresentativePlatform();
cxxPlatform = appleCxxPlatform.getCxxPlatform();
} else {
cxxPlatform = ApplePlatforms.getCxxPlatformForBuildTarget(
cxxPlatformFlavorDomain,
defaultCxxPlatform,
buildTarget);
}
String platformName = cxxPlatform.getFlavor().getName();
final Flavor actualWatchFlavor;
if (ApplePlatform.isSimulator(platformName)) {
actualWatchFlavor = WATCH_SIMULATOR_FLAVOR;
} else if (platformName.startsWith(ApplePlatform.IPHONEOS.getName()) ||
platformName.startsWith(ApplePlatform.WATCHOS.getName())) {
actualWatchFlavor = WATCH_OS_FLAVOR;
} else {
actualWatchFlavor = ImmutableFlavor.of(platformName);
}
FluentIterable<BuildTarget> depsExcludingBinary = FluentIterable.from(constructorArg.deps)
.filter(Predicates.not(constructorArg.binary::equals));
// Propagate platform flavors. Need special handling for watch to map the pseudo-flavor
// watch to the actual watch platform (simulator or device) so can't use
// BuildTargets.propagateFlavorsInDomainIfNotPresent()
{
FluentIterable<BuildTarget> targetsWithPlatformFlavors = depsExcludingBinary.filter(
BuildTargets.containsFlavors(cxxPlatformFlavorDomain));
FluentIterable<BuildTarget> targetsWithoutPlatformFlavors = depsExcludingBinary.filter(
Predicates.not(BuildTargets.containsFlavors(cxxPlatformFlavorDomain)));
FluentIterable<BuildTarget> watchTargets = targetsWithoutPlatformFlavors
.filter(BuildTargets.containsFlavor(WATCH))
.transform(
input -> BuildTarget.builder(
input.withoutFlavors(WATCH))
.addFlavors(actualWatchFlavor)
.build());
targetsWithoutPlatformFlavors = targetsWithoutPlatformFlavors
.filter(Predicates.not(BuildTargets.containsFlavor(WATCH)));
// Gather all the deps now that we've added platform flavors to everything.
depsExcludingBinary = targetsWithPlatformFlavors
.append(watchTargets)
.append(BuildTargets.propagateFlavorDomains(
buildTarget,
ImmutableSet.of(cxxPlatformFlavorDomain),
targetsWithoutPlatformFlavors));
}
// Propagate some flavors
depsExcludingBinary = BuildTargets.propagateFlavorsInDomainIfNotPresent(
StripStyle.FLAVOR_DOMAIN,
buildTarget,
depsExcludingBinary);
depsExcludingBinary = BuildTargets.propagateFlavorsInDomainIfNotPresent(
AppleDebugFormat.FLAVOR_DOMAIN,
buildTarget,
depsExcludingBinary);
depsExcludingBinary = BuildTargets.propagateFlavorsInDomainIfNotPresent(
LinkerMapMode.FLAVOR_DOMAIN,
buildTarget,
depsExcludingBinary);
if (fatBinaryInfo.isPresent()) {
depsExcludingBinary = depsExcludingBinary.append(
fatBinaryInfo.get().getRepresentativePlatform().getCodesignProvider().getParseTimeDeps());
} else {
depsExcludingBinary = depsExcludingBinary.append(
appleCxxPlatformsFlavorDomain.getValue(buildTarget)
.map(platform -> platform.getCodesignProvider().getParseTimeDeps())
.orElse(ImmutableSet.of()));
}
return ImmutableSet.copyOf(depsExcludingBinary);
}
@Override
public <A extends Arg, U> Optional<U> createMetadata(
BuildTarget buildTarget,
BuildRuleResolver resolver,
A args,
Optional<ImmutableMap<BuildTarget, Version>> selectedVersions,
Class<U> metadataClass) throws NoSuchBuildTargetException {
return resolver.requireMetadata(args.binary, metadataClass);
}
@SuppressFieldNotInitialized
public static class Arg extends AbstractDescriptionArg implements HasAppleBundleFields, HasTests {
public Either<AppleBundleExtension, String> extension;
public BuildTarget binary;
public SourcePath infoPlist;
public ImmutableMap<String, String> infoPlistSubstitutions = ImmutableMap.of();
@Hint(isDep = false) public ImmutableSortedSet<BuildTarget> deps = ImmutableSortedSet.of();
@Hint(isDep = false) public ImmutableSortedSet<BuildTarget> tests = ImmutableSortedSet.of();
public Optional<String> xcodeProductType;
public Optional<String> productName;
@Override
public Either<AppleBundleExtension, String> getExtension() {
return extension;
}
@Override
public SourcePath getInfoPlist() {
return infoPlist;
}
@Override
public ImmutableSortedSet<BuildTarget> getTests() {
return tests;
}
@Override
public Optional<String> getXcodeProductType() {
return xcodeProductType;
}
@Override
public Optional<String> getProductName() {
return productName;
}
}
}
| apache-2.0 |
4treesCH/strolch | li.strolch.model/src/main/java/li/strolch/model/visitor/StrolchRootElementVisitor.java | 4424 | /*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.model.visitor;
import li.strolch.model.ParameterBag;
import li.strolch.model.activity.Action;
import li.strolch.model.parameter.*;
import li.strolch.model.timedstate.*;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface StrolchRootElementVisitor<U> extends StrolchElementVisitor<U> {
@Override
default U visitAction(Action action) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + action.getClass());
}
@Override
default U visitBooleanParam(BooleanParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitDateParam(DateParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitDurationParam(DurationParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitFloatParam(FloatParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitIntegerParam(IntegerParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitLongParam(LongParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitStringParam(StringParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitTextParam(TextParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitStringListParam(StringListParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitIntegerListParam(IntegerListParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitFloatListParam(FloatListParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitLongListParam(LongListParameter param) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + param.getClass());
}
@Override
default U visitBooleanState(BooleanTimedState state) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + state.getClass());
}
@Override
default U visitFloatState(FloatTimedState state) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + state.getClass());
}
@Override
default U visitFloatListState(FloatListTimedState state) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + state.getClass());
}
@Override
default U visitIntegerState(IntegerTimedState state) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + state.getClass());
}
@Override
default U visitLongState(LongTimedState state) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + state.getClass());
}
@Override
default U visitStringState(StringSetTimedState state) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + state.getClass());
}
@Override
default U visitParameterBag(ParameterBag bag) {
throw new UnsupportedOperationException(getClass().getName() + " can not handle " + bag.getClass());
}
}
| apache-2.0 |
pkarmstr/NYBC | solr-4.2.1/lucene/core/src/test/org/apache/lucene/index/Test2BPositions.java | 4031 | package org.apache.lucene.index;
/*
* 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.
*/
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.store.BaseDirectoryWrapper;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TimeUnits;
import org.apache.lucene.util._TestUtil;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.junit.Ignore;
import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;
/**
* Test indexes ~82M docs with 52 positions each, so you get > Integer.MAX_VALUE positions
* @lucene.experimental
*/
@SuppressCodecs({ "SimpleText", "Memory", "Direct" })
@TimeoutSuite(millis = 4 * TimeUnits.HOUR)
public class Test2BPositions extends LuceneTestCase {
// uses lots of space and takes a few minutes
@Ignore("Very slow. Enable manually by removing @Ignore.")
public void test() throws Exception {
BaseDirectoryWrapper dir = newFSDirectory(_TestUtil.getTempDir("2BPositions"));
if (dir instanceof MockDirectoryWrapper) {
((MockDirectoryWrapper)dir).setThrottling(MockDirectoryWrapper.Throttling.NEVER);
}
IndexWriter w = new IndexWriter(dir,
new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))
.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH)
.setRAMBufferSizeMB(256.0)
.setMergeScheduler(new ConcurrentMergeScheduler())
.setMergePolicy(newLogMergePolicy(false, 10))
.setOpenMode(IndexWriterConfig.OpenMode.CREATE));
MergePolicy mp = w.getConfig().getMergePolicy();
if (mp instanceof LogByteSizeMergePolicy) {
// 1 petabyte:
((LogByteSizeMergePolicy) mp).setMaxMergeMB(1024*1024*1024);
}
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.setOmitNorms(true);
Field field = new Field("field", new MyTokenStream(), ft);
doc.add(field);
final int numDocs = (Integer.MAX_VALUE / 26) + 1;
for (int i = 0; i < numDocs; i++) {
w.addDocument(doc);
if (VERBOSE && i % 100000 == 0) {
System.out.println(i + " of " + numDocs + "...");
}
}
w.forceMerge(1);
w.close();
dir.close();
}
public static final class MyTokenStream extends TokenStream {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final PositionIncrementAttribute posIncAtt = addAttribute(PositionIncrementAttribute.class);
int index;
public MyTokenStream() {
termAtt.setLength(1);
termAtt.buffer()[0] = 'a';
}
@Override
public boolean incrementToken() {
if (index < 52) {
posIncAtt.setPositionIncrement(1+index);
index++;
return true;
}
return false;
}
@Override
public void reset() {
index = 0;
}
}
}
| apache-2.0 |
yuriBobrik/HPE-Software-Bamboo-Plugin | Bamboo/hp.application.automation/src/main/java/com/hpe/application/automation/bamboo/tasks/RunFromAlmTaskConfigurator.java | 7551 | /**
© Copyright 2015 Hewlett Packard Enterprise Development LP
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 NON INFRINGEMENT. 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 com.hpe.application.automation.bamboo.tasks;
import com.atlassian.bamboo.build.Job;
import com.atlassian.bamboo.collections.ActionParametersMap;
import com.atlassian.bamboo.plan.artifact.ArtifactDefinitionManager;
import com.atlassian.bamboo.task.TaskDefinition;
import com.atlassian.bamboo.utils.error.ErrorCollection;
import com.atlassian.bamboo.utils.i18n.I18nBean;
import com.atlassian.util.concurrent.NotNull;
import com.atlassian.util.concurrent.Nullable;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class RunFromAlmTaskConfigurator extends AbstractUftTaskConfigurator {
public static final String ALM_SERVER = "almServer";
public static final String USER_NAME = "userName";
public static final String PASSWORD = "password";
public static final String DOMAIN = "domain";
public static final String PROJECT = "projectName";
public static final String TESTS_PATH = "testPathInput";
public static final String TIMEOUT = "timeoutInput";
public static final String RUN_MODE = "runMode";
public static final String RUN_MODE_PARAMETER = "runModeItems";
public static final String TESTING_TOOL_HOST = "testingToolHost";
public static final String DEFAULT_TIMEOUT = "-1";
public static final String RUN_LOCALLY_LBL = "Alm.runLocallyLbl";
public static final String RUN_ON_PLANNED_HOST_LBL = "Alm.runOnPlannedHostLbl";
public static final String RUN_REMOTELY_LBL = "Alm.runRemotelyLbl";
public static final String RUN_LOCALLY_PARAMETER = "1";
public static final String RUN_ON_PLANNED_HOST_PARAMETER = "2";
public static final String RUN_REMOTELY_PARAMETER = "3";
public static final String TASK_NAME_VALUE = "Alm.taskName";
private ArtifactDefinitionManager artifactDefinitionManager;
public void setArtifactDefinitionManager(ArtifactDefinitionManager artifactDefinitionManager){
this.artifactDefinitionManager = artifactDefinitionManager;
}
public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition)
{
final Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition);
config.put(ALM_SERVER, params.getString(ALM_SERVER));
config.put(USER_NAME, params.getString(USER_NAME));
config.put(PASSWORD, params.getString(PASSWORD));
config.put(DOMAIN, params.getString(DOMAIN));
config.put(PROJECT, params.getString(PROJECT));
config.put(TESTS_PATH, params.getString(TESTS_PATH));
config.put(TIMEOUT, params.getString(TIMEOUT));
config.put(RUN_MODE, params.getString(RUN_MODE));
config.put(TESTING_TOOL_HOST, params.getString(TESTING_TOOL_HOST));
config.put(CommonTaskConfigurationProperties.TASK_NAME, getI18nBean().getText(TASK_NAME_VALUE));
return config;
}
private String trimEnd(String s, char ch)
{
if (s == null || s.length() < 1) {
return s;
}
else if (s.length() == 1 && s.charAt(0) == ch)
{
return "";
}
int i = s.length() - 1;
while(s.charAt(i) == ch && i > 0)
{
s = s.substring(0, i);
i--;
}
return s;
}
public void validate(@NotNull final ActionParametersMap params, @NotNull final ErrorCollection errorCollection)
{
super.validate(params, errorCollection);
I18nBean textProvider = getI18nBean();
params.put(ALM_SERVER, trimEnd(params.getString(ALM_SERVER), '/'));
if (StringUtils.isEmpty(params.getString(ALM_SERVER))) {
errorCollection.addError(ALM_SERVER, textProvider.getText("Alm.error.ALMServerIsEmpty"));
}
if (StringUtils.isEmpty(params.getString(USER_NAME))) {
errorCollection.addError(USER_NAME, textProvider.getText("Alm.error.userNameIsEmpty"));
}
if (StringUtils.isEmpty(params.getString(DOMAIN))) {
errorCollection.addError(DOMAIN, textProvider.getText("Alm.error.domainIsEmpty"));
}
if (StringUtils.isEmpty(params.getString(PROJECT))) {
errorCollection.addError(PROJECT, textProvider.getText("Alm.error.projectIsEmpty"));
}
if (StringUtils.isEmpty(params.getString(TESTS_PATH)))
{
errorCollection.addError(TESTS_PATH, textProvider.getText("Alm.error.testsetIsEmpty"));
}
String timeoutParameter = params.getString(TIMEOUT);
if(!StringUtils.isEmpty(timeoutParameter))
{
if (!StringUtils.isNumeric(timeoutParameter) || Integer.parseInt(timeoutParameter) <0 | Integer.parseInt(timeoutParameter) > 30)
{
errorCollection.addError(TIMEOUT, textProvider.getText("Alm.error.timeoutIsNotCorrect"));
}
}
}
@Override
public void populateContextForCreate(@NotNull final Map<String, Object> context)
{
(new HpTasksArtifactRegistrator()).registerCommonArtifact((Job) context.get("plan"), getI18nBean(), this.artifactDefinitionManager);
super.populateContextForCreate(context);
populateContextForLists(context);
//Default run mode value must be run locally
context.put(RUN_MODE, RUN_LOCALLY_PARAMETER);
}
private void populateContextForLists(@NotNull final Map<String, Object> context)
{
context.put(RUN_MODE_PARAMETER, getRunModes());
}
@Override
public void populateContextForEdit(@NotNull final Map<String, Object> context, @NotNull final TaskDefinition taskDefinition)
{
super.populateContextForEdit(context, taskDefinition);
Map<String, String> configuration = taskDefinition.getConfiguration();
context.put(ALM_SERVER, configuration.get(ALM_SERVER));
context.put(USER_NAME, configuration.get(USER_NAME));
context.put(PASSWORD, configuration.get(PASSWORD));
context.put(DOMAIN, configuration.get(DOMAIN));
context.put(PROJECT, configuration.get(PROJECT));
context.put(TESTS_PATH, configuration.get(TESTS_PATH));
context.put(TIMEOUT, configuration.get(TIMEOUT));
context.put(RUN_MODE, configuration.get(RUN_MODE));
context.put(TESTING_TOOL_HOST, configuration.get(TESTING_TOOL_HOST));
populateContextForLists(context);
}
private Map<String, String> getRunModes()
{
Map<String, String> runTypesMap = new HashMap<String, String>();
I18nBean textProvider = getI18nBean();
//Don't change run types adding order. It's used for task creation.
runTypesMap.put(RUN_LOCALLY_PARAMETER, textProvider.getText(RUN_LOCALLY_LBL));
runTypesMap.put(RUN_ON_PLANNED_HOST_PARAMETER, textProvider.getText(RUN_ON_PLANNED_HOST_LBL));
runTypesMap.put(RUN_REMOTELY_PARAMETER, textProvider.getText(RUN_REMOTELY_LBL));
return runTypesMap;
}
}
| apache-2.0 |
Graphity/graphity-processor | src/main/java/com/atomgraph/processor/util/RulePrinter.java | 3668 | /*
* Copyright 2015 Martynas Jusevičius <martynas@atomgraph.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 com.atomgraph.processor.util;
import org.apache.jena.reasoner.TriplePattern;
import org.apache.jena.reasoner.rulesys.ClauseEntry;
import org.apache.jena.reasoner.rulesys.Rule;
import org.apache.jena.util.PrintUtil;
import java.util.List;
/**
*
* @author Martynas Jusevičius {@literal <martynas@atomgraph.com>}
*/
public class RulePrinter
{
public static String print(List<Rule> rules)
{
StringBuilder buff = new StringBuilder();
for (Rule rule : rules)
{
buff.append(print(rule));
}
return buff.toString();
}
public static String print(Rule rule)
{
StringBuilder buff = new StringBuilder();
buff.append("[ ");
if (rule.getName() != null)
{
buff.append(rule.getName());
buff.append(": ");
}
if (rule.isBackward())
{
for ( ClauseEntry aHead : rule.getHead() )
{
buff.append( print( aHead ) );
buff.append( " " );
}
buff.append("<- ");
for ( ClauseEntry aBody : rule.getBody() )
{
buff.append( print( aBody ) );
buff.append( " " );
}
}
else
{
for ( ClauseEntry aBody : rule.getBody() )
{
buff.append( print( aBody ) );
buff.append( " " );
}
buff.append("-> ");
for ( ClauseEntry aHead : rule.getHead() )
{
buff.append( print( aHead ) );
buff.append( " " );
}
}
buff.append("]");
return buff.toString();
}
public static String print(ClauseEntry entry)
{
if (entry instanceof TriplePattern)
{
TriplePattern tp = (TriplePattern)entry;
StringBuilder buff = new StringBuilder();
buff.append("(");
if (tp.getSubject().isURI())
buff.append("<").
append(tp.getSubject().getURI()).
append(">").
toString();
else buff.append(PrintUtil.print(tp.getSubject()));
buff.append(" ");
if (tp.getPredicate().isURI())
buff.append("<").
append(tp.getPredicate().getURI()).
append(">").
toString();
else buff.append(PrintUtil.print(tp.getPredicate()));
buff.append(" ");
if (tp.getObject().isURI())
buff.append("<").
append(tp.getObject().getURI()).
append(">").
toString();
else buff.append(PrintUtil.print(tp.getObject()));
buff.append(")");
return buff.toString();
}
return PrintUtil.print(entry);
}
}
| apache-2.0 |
azureplus/flex-blazeds | modules/proxy/src/flex/messaging/services/http/proxy/RequestFilter.java | 27168 | /*
* 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 flex.messaging.services.http.proxy;
import flex.messaging.FlexContext;
import flex.messaging.FlexSession;
import flex.messaging.io.MessageIOConstants;
import flex.messaging.log.Log;
import flex.messaging.log.Logger;
import flex.messaging.services.HTTPProxyService;
import flex.messaging.services.http.ExternalProxySettings;
import flex.messaging.services.http.httpclient.FlexGetMethod;
import flex.messaging.services.http.httpclient.FlexPostMethod;
import flex.messaging.util.StringUtils;
import flex.messaging.util.URLEncoder;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.OptionsMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.TraceMethod;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* @exclude
* Sends the request to the endpoint, including custom copying of headers and cookies.
*
* @author Brian Deitte
*/
public class RequestFilter extends ProxyFilter
{
private static final int CAUGHT_ERROR = 10706;
private static final int UNKNOWN_HOST = 10707;
private static final int INVALID_METHOD = 10719;
private static final String STRING_JSESSIONID = "jsessionid";
/**
* Invoke the filter.
*
* @param context the context
*/
public void invoke(ProxyContext context)
{
setupRequest(context);
copyCookiesToEndpoint(context);
copyHeadersToEndpoint(context);
addCustomHeaders(context);
recordRequestHeaders(context);
sendRequest(context);
if (next != null)
{
next.invoke(context);
}
}
/**
* Setup the request.
*
* @param context the context
*/
protected void setupRequest(ProxyContext context)
{
// set the proxy to send requests through
ExternalProxySettings externalProxy = context.getExternalProxySettings();
if (externalProxy != null)
{
String proxyServer = externalProxy.getProxyServer();
if (proxyServer != null)
{
context.getTarget().getHostConfig().setProxy(proxyServer, externalProxy.getProxyPort());
if (context.getProxyCredentials() != null)
{
context.getHttpClient().getState().setProxyCredentials(ProxyUtil.getDefaultAuthScope(), context.getProxyCredentials());
}
}
}
String method = context.getMethod();
String encodedPath = context.getTarget().getEncodedPath();
if (MessageIOConstants.METHOD_POST.equals(method))
{
FlexPostMethod postMethod = new FlexPostMethod(encodedPath);
context.setHttpMethod(postMethod);
if (context.hasAuthorization())
{
postMethod.setConnectionForced(true);
}
}
else if (ProxyConstants.METHOD_GET.equals(method))
{
FlexGetMethod getMethod = new FlexGetMethod(context.getTarget().getEncodedPath());
context.setHttpMethod(getMethod);
if (context.hasAuthorization())
{
getMethod.setConnectionForced(true);
}
}
else if (ProxyConstants.METHOD_HEAD.equals(method))
{
HeadMethod headMethod = new HeadMethod(encodedPath);
context.setHttpMethod(headMethod);
}
else if (ProxyConstants.METHOD_PUT.equals(method))
{
PutMethod putMethod = new PutMethod(encodedPath);
context.setHttpMethod(putMethod);
}
else if (ProxyConstants.METHOD_OPTIONS.equals(method))
{
OptionsMethod optionsMethod = new OptionsMethod(encodedPath);
context.setHttpMethod(optionsMethod);
}
else if (ProxyConstants.METHOD_DELETE.equals(method))
{
DeleteMethod deleteMethod = new DeleteMethod(encodedPath);
context.setHttpMethod(deleteMethod);
}
else if (ProxyConstants.METHOD_TRACE.equals(method))
{
TraceMethod traceMethod = new TraceMethod(encodedPath);
context.setHttpMethod(traceMethod);
}
else
{
ProxyException pe = new ProxyException(INVALID_METHOD);
pe.setDetails(INVALID_METHOD, "1", new Object[] { method });
throw pe;
}
HttpMethodBase httpMethod = context.getHttpMethod();
if (httpMethod instanceof EntityEnclosingMethod)
{
((EntityEnclosingMethod)httpMethod).setContentChunked(context.getContentChunked());
}
}
/**
* Before calling the endpoint, set up the cookies found in the request.
* @param context the context
*/
public static void copyCookiesToEndpoint(ProxyContext context)
{
HttpServletRequest clientRequest = FlexContext.getHttpRequest();
context.clearRequestCookies();
if (clientRequest != null)
{
javax.servlet.http.Cookie[] cookies = clientRequest.getCookies();
HttpState initState = context.getHttpClient().getState();
if (cookies != null)
{
// Gather up the cookies keyed on the length of the path.
// This is done so that if we have two cookies with the same name,
// we pass the cookie with the longest path first to the endpoint
TreeMap cookieMap = new TreeMap();
for (javax.servlet.http.Cookie cookie : cookies)
{
CookieInfo origCookie = new CookieInfo(cookie.getName(), cookie.getDomain(), cookie.getName(),
cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), null, cookie.getSecure());
CookieInfo newCookie = RequestUtil.createCookie(origCookie, context, context.getTarget().getUrl().getHost(),
context.getTarget().getUrl().getPath());
if (newCookie != null)
{
Integer pathInt = Integer.valueOf(0 - newCookie.path.length());
ArrayList list = (ArrayList) cookieMap.get(pathInt);
if (list == null)
{
list = new ArrayList();
cookieMap.put(pathInt, list);
}
list.add(newCookie);
}
}
// loop through (in order) the cookies we've gathered
for (Object mapValue : cookieMap.values())
{
ArrayList list = (ArrayList) mapValue;
for (Object aList : list)
{
CookieInfo cookieInfo = (CookieInfo) aList;
if (Log.isInfo())
{
String str = "-- Cookie in request: " + cookieInfo;
Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug(str);
}
Cookie cookie = new Cookie(cookieInfo.domain, cookieInfo.name, cookieInfo.value, cookieInfo.path,
cookieInfo.maxAge, cookieInfo.secure);
// If this is a session cookie and we're dealing with local domain, make sure the session
// cookie has the latest session id. This check is needed when the session was invalidated
// and then recreated in this request; we shouldn't be sending the old session id to the endpoint.
if (context.isLocalDomain() && STRING_JSESSIONID.equalsIgnoreCase(cookieInfo.clientName))
{
FlexSession flexSession = FlexContext.getFlexSession();
if (flexSession != null && flexSession.isValid())
{
String sessionId = flexSession.getId();
String cookieValue = cookie.getValue();
if (!cookieValue.contains(sessionId))
{
int colonIndex = cookieValue.indexOf(':');
if (colonIndex != -1)
{
// Websphere changes jsession id to the following format:
// 4 digit cacheId + jsessionId + ":" + cloneId.
ServletContext servletContext = FlexContext.getServletContext();
String serverInfo = servletContext != null ? servletContext.getServerInfo() : null;
boolean isWebSphere = serverInfo != null && serverInfo.contains("WebSphere");
if (isWebSphere)
{
String cacheId = cookieValue.substring(0, 4);
String cloneId = cookieValue.substring(colonIndex);
String wsSessionId = cacheId + sessionId + cloneId;
cookie.setValue(wsSessionId);
}
else
{
cookie.setValue(sessionId);
}
}
else
{
cookie.setValue(sessionId);
}
}
}
}
// finally add the cookie to the current request
initState.addCookie(cookie);
context.addRequestCookie(cookie);
}
}
}
}
}
/**
* Copy HTTP request headers to the endpoint.
* @param context the context
*/
public static void copyHeadersToEndpoint(ProxyContext context)
{
HttpServletRequest clientRequest = FlexContext.getHttpRequest();
if (clientRequest != null)
{
Enumeration headerNames = clientRequest.getHeaderNames();
while (headerNames.hasMoreElements())
{
String headerName = (String)headerNames.nextElement();
if (RequestUtil.ignoreHeader(headerName, context))
{
continue;
}
Enumeration headers = clientRequest.getHeaders(headerName);
while (headers.hasMoreElements())
{
String value = (String)headers.nextElement();
context.getHttpMethod().addRequestHeader(headerName, value);
if (Log.isInfo())
{
Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug("-- Header in request: " + headerName + " : " + value);
}
}
}
}
}
/**
* Add any custom headers.
*
* @param context the context
*/
protected void addCustomHeaders(ProxyContext context)
{
HttpMethodBase httpMethod = context.getHttpMethod();
String contentType = context.getContentType();
if (contentType != null)
{
httpMethod.setRequestHeader(ProxyConstants.HEADER_CONTENT_TYPE, contentType);
}
Map customHeaders = context.getHeaders();
if (customHeaders != null)
{
for (Object entry : customHeaders.entrySet())
{
String name = (String) ((Map.Entry) entry).getKey();
Object value = ((Map.Entry) entry).getValue();
if (value == null)
{
httpMethod.setRequestHeader(name, "");
}
// Single value for the name.
else if (value instanceof String)
{
httpMethod.setRequestHeader(name, (String) value);
}
// Multiple values for the name.
else if (value instanceof List)
{
List valueList = (List) value;
for (Object currentValue : valueList)
{
if (currentValue == null)
{
httpMethod.addRequestHeader(name, "");
}
else
{
httpMethod.addRequestHeader(name, (String) currentValue);
}
}
}
else if (value.getClass().isArray())
{
Object[] valueArray = (Object[]) value;
for (Object currentValue : valueArray)
{
if (currentValue == null)
{
httpMethod.addRequestHeader(name, "");
}
else
{
httpMethod.addRequestHeader(name, (String) currentValue);
}
}
}
}
}
if (context.isSoapRequest())
{
// add the appropriate headers
context.getHttpMethod().setRequestHeader(ProxyConstants.HEADER_CONTENT_TYPE, MessageIOConstants.CONTENT_TYPE_XML);
// get SOAPAction, and if it doesn't exist, create it
String soapAction = null;
Header header = context.getHttpMethod().getRequestHeader(MessageIOConstants.HEADER_SOAP_ACTION);
if (header != null)
{
soapAction = header.getValue();
}
if (soapAction == null)
{
HttpServletRequest clientRequest = FlexContext.getHttpRequest();
if (clientRequest != null)
{
soapAction = clientRequest.getHeader(MessageIOConstants.HEADER_SOAP_ACTION);
}
// SOAPAction has to be quoted per the SOAP 1.1 spec.
if (soapAction != null && !soapAction.startsWith("\"") && !soapAction.endsWith("\""))
{
soapAction = "\"" + soapAction + "\"";
}
// If soapAction happens to still be null at this point, we'll end up not sending
// one, which should generate a fault on the server side which we'll happily convey
// back to the client.
context.getHttpMethod().setRequestHeader(MessageIOConstants.HEADER_SOAP_ACTION, soapAction);
}
}
}
/**
* Record the request headers in the proxy context.
* @param context the context
*/
protected void recordRequestHeaders(ProxyContext context)
{
if (context.getRecordHeaders())
{
Header[] headers = context.getHttpMethod().getRequestHeaders();
if (headers != null)
{
HashMap recordedHeaders = new HashMap();
for (Header header : headers)
{
String headerName = header.getName();
String headerValue = header.getValue();
Object existingHeaderValue = recordedHeaders.get(headerName);
// Value(s) already exist for the header.
if (existingHeaderValue != null)
{
ArrayList headerValues;
// Only a single value exists.
if (existingHeaderValue instanceof String)
{
headerValues = new ArrayList();
headerValues.add(existingHeaderValue);
headerValues.add(headerValue);
recordedHeaders.put(headerName, headerValues);
}
// Multiple values exist.
else if (existingHeaderValue instanceof ArrayList)
{
headerValues = (ArrayList) existingHeaderValue;
headerValues.add(headerValue);
}
}
else
{
recordedHeaders.put(headerName, headerValue);
}
}
context.setRequestHeaders(recordedHeaders);
}
}
}
/**
* Send the request.
*
* @param context the context
*/
protected void sendRequest(ProxyContext context)
{
Target target = context.getTarget();
String method = context.getMethod();
HttpMethod httpMethod = context.getHttpMethod();
final String BEGIN = "-- Begin ";
final String END = "-- End ";
final String REQUEST = " request --";
if (httpMethod instanceof EntityEnclosingMethod)
{
Object data = processBody(context);
Class dataClass = data.getClass();
if (data instanceof String)
{
String requestString = (String)data;
if (Log.isInfo())
{
Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY);
logger.debug(BEGIN + method + REQUEST);
logger.debug(StringUtils.prettifyString(requestString));
logger.debug(END + method + REQUEST);
}
try
{
StringRequestEntity requestEntity = new StringRequestEntity(requestString, null, "UTF-8");
((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity);
}
catch (UnsupportedEncodingException ex)
{
ProxyException pe = new ProxyException(CAUGHT_ERROR);
pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex });
throw pe;
}
}
else if (dataClass.isArray() && Byte.TYPE.equals(dataClass.getComponentType()))
{
byte[] dataBytes = (byte[])data;
ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(dataBytes, context.getContentType());
((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity);
}
else if (data instanceof InputStream)
{
InputStreamRequestEntity requestEntity = new InputStreamRequestEntity((InputStream)data, context.getContentType());
((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity);
}
//TODO: Support multipart post
//else
//{
//FIXME: Throw exception if unhandled data type
//}
}
else if (httpMethod instanceof GetMethod)
{
Object req = processBody(context);
if (req instanceof String)
{
String requestString = (String)req;
if (Log.isInfo())
{
Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY);
logger.debug(BEGIN + method + REQUEST);
logger.debug(StringUtils.prettifyString(requestString));
logger.debug(END + method + REQUEST);
}
if (!"".equals(requestString))
{
String query = context.getHttpMethod().getQueryString();
if (query != null)
{
query += "&" + requestString;
}
else
{
query = requestString;
}
context.getHttpMethod().setQueryString(query);
}
}
}
context.getHttpClient().setHostConfiguration(target.getHostConfig());
try
{
context.getHttpClient().executeMethod(context.getHttpMethod());
}
catch (UnknownHostException uhex)
{
ProxyException pe = new ProxyException();
pe.setMessage(UNKNOWN_HOST, new Object[] { uhex.getMessage() });
pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
throw pe;
}
catch (Exception ex)
{
// FIXME: JRB - could be more specific by looking for timeout and sending 504 in that case.
// rfc2616 10.5.5 504 - could get more specific if we parse the HttpException
ProxyException pe = new ProxyException(CAUGHT_ERROR);
pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex.getMessage() });
pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
throw pe;
}
}
/**
* Process the request body and return its content.
*
* @param context the context
* @return the body content
*/
protected Object processBody(ProxyContext context)
{
//FIXME: Should we also send on URL params that were used to contact the message broker servlet?
Object body = context.getBody();
if (body == null)
{
return "";
}
else if (body instanceof String)
{
return body;
}
else if (body instanceof Map)
{
Map params = (Map)body;
StringBuffer postData = new StringBuffer();
boolean formValues = false;
for (Object entry : params.entrySet())
{
String name = (String) ((Map.Entry)entry).getKey();
if (!formValues)
{
formValues = true;
}
else
{
postData.append('&');
}
Object vals = ((Map.Entry)entry).getValue();
if (vals == null)
{
encodeParam(postData, name, "");
}
else if (vals instanceof String)
{
String val = (String) vals;
encodeParam(postData, name, val);
}
else if (vals instanceof List)
{
List valLists = (List) vals;
for (int i = 0; i < valLists.size(); i++)
{
Object o = valLists.get(i);
String val = "";
if (o != null)
val = o.toString();
if (i > 0)
postData.append('&');
encodeParam(postData, name, val);
}
}
else if (vals.getClass().isArray())
{
for (int i = 0; i < Array.getLength(vals); i++)
{
Object o = Array.get(vals, i);
String val = "";
if (o != null)
val = o.toString();
if (i > 0)
postData.append('&');
encodeParam(postData, name, val);
}
}
}
return postData.toString();
}
else if (body.getClass().isArray())
{
return body;
}
else if (body instanceof InputStream)
{
return body;
}
else
{
return body.toString();
}
}
/**
* Encode name=value in to a string buffer.
*
* @param buf buffer
* @param name name
* @param val value
*/
protected void encodeParam(StringBuffer buf, String name, String val)
{
name = URLEncoder.encode(name);
val = URLEncoder.encode(val);
buf.append(name);
buf.append('=');
buf.append(val);
}
}
| apache-2.0 |
apache/continuum | continuum-webapp-test/src/test/testng/org/apache/continuum/web/test/parent/AbstractSeleniumTest.java | 12091 | package org.apache.continuum.web.test.parent;
/*
* 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.
*/
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import org.apache.commons.io.IOUtils;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
/**
* Based on AbstractSeleniumTestCase of Emmanuel Venisse test.
*
* @author José Morales Martínez
*/
public abstract class AbstractSeleniumTest
{
protected static String baseUrl;
static String browser;
protected static String maxWaitTimeInMs;
private static final ThreadLocal<Selenium> selenium = new ThreadLocal<Selenium>();
private static Properties p;
private final static String PROPERTIES_SEPARATOR = "=";
private static String maxProjectWaitTimeInMs;
/**
* Initialize selenium
*/
void open( String baseUrl, String browser, String seleniumHost, int seleniumPort )
throws Exception
{
InputStream input = this.getClass().getClassLoader().getResourceAsStream( "testng.properties" );
p = new Properties();
p.load( input );
// for running in the IDE
String svnBaseUrl = "file://localhost/" + new File( "target/example-svn" ).getAbsolutePath();
for ( String key : p.stringPropertyNames() )
{
String value = p.getProperty( key );
String newValue = value.replace( "${svn.base.url}", svnBaseUrl );
newValue = newValue.replace( "${maven.home}", System.getProperty( "maven.home", "/usr/share/maven" ) );
p.setProperty( key, newValue );
}
maxWaitTimeInMs = getProperty( "MAX_WAIT_TIME_IN_MS" );
maxProjectWaitTimeInMs = getProperty( "MAX_PROJECT_WAIT_TIME_IN_MS" );
AbstractSeleniumTest.baseUrl = baseUrl;
AbstractSeleniumTest.browser = browser;
if ( getSelenium() == null )
{
DefaultSelenium s = new DefaultSelenium( seleniumHost, seleniumPort, browser, baseUrl );
s.start();
s.setTimeout( maxWaitTimeInMs );
selenium.set( s );
}
}
public static Selenium getSelenium()
{
return selenium == null ? null : selenium.get();
}
protected String getProperty( String key )
{
return p.getProperty( key );
}
// TODO: look into removing this, as the issue should be fixed by upgrading the resources plugin to v2.4+
protected String getEscapeProperty( String key )
{
InputStream input = this.getClass().getClassLoader().getResourceAsStream( "testng.properties" );
String value = null;
List<String> lines;
try
{
lines = IOUtils.readLines( input );
}
catch ( IOException e )
{
lines = new ArrayList<String>();
}
for ( String l : lines )
{
if ( l != null && l.startsWith( key ) )
{
int indexSeparator = l.indexOf( PROPERTIES_SEPARATOR );
value = l.substring( indexSeparator + 1 ).trim();
break;
}
}
return value;
}
/**
* Close selenium session. Called from AfterSuite method of sub-class
*/
@AfterSuite( alwaysRun = true )
public void close()
throws Exception
{
if ( getSelenium() != null )
{
getSelenium().stop();
selenium.set( null );
}
}
// *******************************************************
// Auxiliar methods. This method help us and simplify test.
// *******************************************************
protected void assertFieldValue( String fieldValue, String fieldName )
{
assertElementPresent( fieldName );
Assert.assertEquals( fieldValue, getSelenium().getValue( fieldName ) );
}
protected void assertPage( String title )
{
Assert.assertEquals( getTitle(), title );
}
protected String getTitle()
{
return getSelenium().getTitle();
}
protected void assertTextPresent( String text )
{
Assert.assertTrue( getSelenium().isTextPresent( text ), "'" + text + "' isn't present." );
}
protected void assertTextNotPresent( String text )
{
Assert.assertFalse( getSelenium().isTextPresent( text ), "'" + text + "' is present." );
}
protected void assertElementPresent( String elementLocator )
{
Assert.assertTrue( isElementPresent( elementLocator ), "'" + elementLocator + "' isn't present." );
}
protected void assertElementNotPresent( String elementLocator )
{
Assert.assertFalse( isElementPresent( elementLocator ), "'" + elementLocator + "' is present." );
}
protected void assertLinkPresent( String text )
{
Assert.assertTrue( isElementPresent( "link=" + text ), "The link '" + text + "' isn't present." );
}
protected void assertLinkNotPresent( String text )
{
Assert.assertFalse( isElementPresent( "link=" + text ), "The link '" + text + "' is present." );
}
protected void assertImgWithAlt( String alt )
{
assertElementPresent( "//img[@alt='" + alt + "']" );
}
protected void assertCellValueFromTable( String expected, String tableElement, int row, int column )
{
Assert.assertEquals( expected, getCellValueFromTable( tableElement, row, column ) );
}
protected boolean isTextPresent( String text )
{
return getSelenium().isTextPresent( text );
}
protected boolean isLinkPresent( String text )
{
return isElementPresent( "link=" + text );
}
protected boolean isElementPresent( String locator )
{
return getSelenium().isElementPresent( locator );
}
protected void waitPage()
{
getSelenium().waitForPageToLoad( maxWaitTimeInMs );
}
protected String getFieldValue( String fieldName )
{
return getSelenium().getValue( fieldName );
}
String getCellValueFromTable( String tableElement, int row, int column )
{
return getSelenium().getTable( tableElement + "." + row + "." + column );
}
protected void selectValue( String locator, String value )
{
getSelenium().select( locator, "label=" + value );
}
void assertOptionPresent( String selectField, String[] options )
{
assertElementPresent( selectField );
String[] optionsPresent = getSelenium().getSelectOptions( selectField );
List<String> expected = Arrays.asList( options );
List<String> present = Arrays.asList( optionsPresent );
Assert.assertTrue( present.containsAll( expected ), "Options expected are not included in present options" );
}
protected void submit()
{
submit( true );
}
protected void submit( boolean wait )
{
clickLinkWithXPath( "//input[@type='submit']", wait );
}
protected void assertButtonWithValuePresent( String text )
{
Assert.assertTrue( isButtonWithValuePresent( text ), "'" + text + "' button isn't present" );
}
void assertButtonWithIdPresent( String id )
{
Assert.assertTrue( isButtonWithIdPresent( id ), "'Button with id =" + id + "' isn't present" );
}
boolean isButtonWithValuePresent( String text )
{
return isElementPresent( "//button[@value='" + text + "']" ) || isElementPresent(
"//input[@value='" + text + "']" );
}
boolean isButtonWithIdPresent( String text )
{
return isElementPresent( "//button[@id='" + text + "']" ) || isElementPresent( "//input[@id='" + text + "']" );
}
protected void clickButtonWithValue( String text )
{
clickButtonWithValue( text, true );
}
void clickButtonWithValue( String text, boolean wait )
{
assertButtonWithValuePresent( text );
if ( isElementPresent( "//button[@value='" + text + "']" ) )
{
clickLinkWithXPath( "//button[@value='" + text + "']", wait );
}
else
{
clickLinkWithXPath( "//input[@value='" + text + "']", wait );
}
}
void clickSubmitWithLocator( String locator )
{
clickLinkWithLocator( locator );
}
protected void clickImgWithAlt( String alt )
{
clickLinkWithLocator( "//img[@alt='" + alt + "']" );
}
protected void clickLinkWithText( String text )
{
clickLinkWithLocator( "link=" + text, true );
}
protected void clickLinkWithXPath( String xpath )
{
clickLinkWithXPath( xpath, true );
}
protected void clickLinkWithXPath( String xpath, boolean wait )
{
clickLinkWithLocator( "xpath=" + xpath, wait );
}
protected void clickLinkWithLocator( String locator )
{
clickLinkWithLocator( locator, true );
}
protected void clickLinkWithLocator( String locator, boolean wait )
{
getSelenium().click( locator );
if ( wait )
{
waitPage();
}
}
protected void setFieldValue( String fieldName, String value )
{
getSelenium().type( fieldName, value );
}
protected void checkField( String locator )
{
getSelenium().check( locator );
}
protected void uncheckField( String locator )
{
getSelenium().uncheck( locator );
}
boolean isChecked( String locator )
{
return getSelenium().isChecked( locator );
}
void assertIsChecked( String locator )
{
Assert.assertTrue( isChecked( locator ) );
}
void click( String locator )
{
getSelenium().click( locator );
}
protected void clickAndWait( String locator )
{
getSelenium().click( locator );
getSelenium().waitForPageToLoad( maxWaitTimeInMs );
}
protected void waitForElementPresent( String locator )
{
waitForElementPresent( locator, true );
}
/*
* This will wait for the condition to be met.
* * shouldBePresent - if the locator is expected or not (true or false respectively)
*/
void waitForElementPresent( String locator, boolean shouldBePresent )
{
waitForOneOfElementsPresent( Collections.singletonList( locator ), shouldBePresent );
}
protected void waitForOneOfElementsPresent( List<String> locators, boolean shouldBePresent )
{
int currentIt = 0;
int maxIt = Integer.valueOf( getProperty( "WAIT_TRIES" ) );
String pageLoadTimeInMs = maxWaitTimeInMs;
while ( currentIt < maxIt )
{
for ( String locator : locators )
{
if ( isElementPresent( locator ) == shouldBePresent )
{
return;
}
}
getSelenium().waitForPageToLoad( pageLoadTimeInMs );
currentIt++;
}
}
void assertEnabled()
{
Assert.assertTrue( getSelenium().isEditable( "alwaysBuild" ), "'" + "alwaysBuild" + "' is disabled" );
}
}
| apache-2.0 |
IBM-Bluemix/news-aggregator | src/main/java/net/bluemix/newsaggregator/api/ResponseReadFeedsDTO.java | 1084 | /*
* Copyright IBM Corp. 2014
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.bluemix.newsaggregator.api;
import java.util.List;
import com.wordnik.swagger.annotations.ApiModelProperty;
import net.bluemix.newsaggregator.NewsEntry;
import net.bluemix.newsaggregator.Person;
public class ResponseReadFeedsDTO {
@ApiModelProperty(value = "Message", required=true)
private String message;
public ResponseReadFeedsDTO() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| apache-2.0 |
dbs-leipzig/gradoop | gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/aggregation/functions/AggregateUtil.java | 2502 | /*
* Copyright © 2014 - 2021 Leipzig University (Database Research Group)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.gradoop.flink.model.impl.operators.aggregation.functions;
import org.gradoop.common.model.api.entities.Element;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.api.functions.AggregateDefaultValue;
import org.gradoop.flink.model.api.functions.AggregateFunction;
import java.util.Map;
import java.util.Set;
/**
* Utility functions for the aggregation operator
*/
public class AggregateUtil {
/**
* Increments the aggregate map by the increment of the aggregate functions on the element
*
* @param aggregate aggregate map to be incremented
* @param element element to increment with
* @param aggregateFunctions aggregate functions
* @return incremented aggregate map
*/
static Map<String, PropertyValue> increment(Map<String, PropertyValue> aggregate,
Element element,
Set<AggregateFunction> aggregateFunctions) {
for (AggregateFunction aggFunc : aggregateFunctions) {
PropertyValue increment = aggFunc.getIncrement(element);
if (increment != null) {
aggregate.compute(aggFunc.getAggregatePropertyKey(), (key, agg) -> agg == null ?
increment.copy() : aggFunc.aggregate(agg, increment));
}
}
return aggregate;
}
/**
* Returns the default aggregate value for the given aggregate function
* or {@link PropertyValue#NULL_VALUE}, if it has no default.
*
* @param aggregateFunction aggregate function
* @return aggregate value
*/
public static PropertyValue getDefaultAggregate(AggregateFunction aggregateFunction) {
if (aggregateFunction instanceof AggregateDefaultValue) {
return ((AggregateDefaultValue) aggregateFunction).getDefaultValue();
} else {
return PropertyValue.NULL_VALUE;
}
}
}
| apache-2.0 |
xloye/tddl5 | tddl-optimizer/src/main/java/com/taobao/tddl/optimizer/parse/cobar/visitor/MySqlLoadDataVisitor.java | 634 | package com.taobao.tddl.optimizer.parse.cobar.visitor;
import com.alibaba.cobar.parser.ast.stmt.dml.DMLLoadStatement;
import com.alibaba.cobar.parser.visitor.EmptySQLASTVisitor;
import com.taobao.tddl.optimizer.core.ast.ASTNode;
import com.taobao.tddl.optimizer.core.ast.dml.LoadDataNode;
public class MySqlLoadDataVisitor extends EmptySQLASTVisitor {
private ASTNode node;
@Override
public void visit(DMLLoadStatement loadData) {
String tableName = loadData.getTable().getIdTextUpUnescape();
node = new LoadDataNode(tableName);
}
public ASTNode getNode() {
return this.node;
}
}
| apache-2.0 |
apache/sis | core/sis-referencing/src/main/java/org/apache/sis/geometry/EnvelopeReducer.java | 7234 | /*
* 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.sis.geometry;
import org.opengis.geometry.Envelope;
import org.opengis.metadata.extent.GeographicBoundingBox;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox;
import org.apache.sis.internal.metadata.ReferencingServices;
import org.apache.sis.internal.referencing.Resources;
import org.apache.sis.referencing.CRS;
import org.apache.sis.util.Utilities;
/**
* Applies union or intersection operations on a sequence of envelopes.
* This utility class infers the a common coordinate reference system
* for performing the reduce operation.
*
* @author Martin Desruisseaux (IRD, Geomatys)
* @version 1.0
*
* @see Envelopes#union(Envelope...)
* @see Envelopes#intersect(Envelope...)
*
* @since 1.0
* @module
*/
class EnvelopeReducer {
/**
* A reducer performing the {@linkplain GeneralEnvelope#add(Envelope) union} operation.
*
* @see Envelopes#union(Envelope...)
*/
static final EnvelopeReducer UNION = new EnvelopeReducer("union");
/**
* A reducer performing the {@linkplain GeneralEnvelope#intersect(Envelope) intersection} operation.
*
* @see Envelopes#intersect(Envelope...)
*/
static final EnvelopeReducer INTERSECT = new EnvelopeReducer("intersect") {
@Override void reduce(GeneralEnvelope result, Envelope other) {
result.intersect(other);
}
@Override void reduce(DefaultGeographicBoundingBox result, GeographicBoundingBox other) {
result.intersect(other);
}
};
/**
* The public method from {@link Envelopes} which is using this envelope reducer.
*/
private final String caller;
/**
* Creates a new reducer. We should have a singleton instance for each type of reduce operation.
*/
EnvelopeReducer(final String caller) {
this.caller = caller;
}
/**
* Applies the reduce operation on the given {@code result} envelope.
* The result is modified in-place.
*/
void reduce(GeneralEnvelope result, Envelope other) {
result.add(other);
}
/**
* Applies the reduce operation on the given {@code result} bounding box.
* The result is modified in-place.
*/
void reduce(DefaultGeographicBoundingBox result, GeographicBoundingBox other) {
result.add(other);
}
/**
* Reduces all given envelopes, transforming them to a common CRS if necessary.
* If all envelopes use the same CRS (ignoring metadata) or if the CRS of all envelopes is {@code null},
* then the reduce operation is performed without transforming any envelope. Otherwise all envelopes are
* transformed to a {@linkplain CRS#suggestCommonTarget common CRS} before reduction.
* The CRS of the returned envelope may different than the CRS of all given envelopes.
*
* @param envelopes the envelopes for which to perform the reduce operation. Null elements are ignored.
* @return result of reduce operation, or {@code null} if the given array does not contain non-null elements.
* @throws TransformException if this method can not determine a common CRS, or if a transformation failed.
*/
final GeneralEnvelope reduce(final Envelope[] envelopes) throws TransformException {
/*
* First, compute the unions or intersections of all envelopes having a common CRS
* without performing any reprojection. In the common case where all envelopes use
* the same CRS, this will result in an array having only one non-null element.
*/
final GeneralEnvelope[] reduced = new GeneralEnvelope[envelopes.length];
int count = 0;
merge: for (final Envelope envelope : envelopes) {
if (envelope != null) {
final CoordinateReferenceSystem crs = envelope.getCoordinateReferenceSystem();
for (int i=0; i<count; i++) {
final GeneralEnvelope previous = reduced[i];
if (Utilities.equalsIgnoreMetadata(crs, previous.getCoordinateReferenceSystem())) {
reduce(previous, envelope);
continue merge;
}
}
reduced[count++] = new GeneralEnvelope(envelope);
}
}
switch (count) {
case 0: return null;
case 1: return reduced[0];
}
/*
* Compute the geographic bounding box of all remaining elements to reduce. This will be used for
* choosing a common CRS. Note that if a warning is logged, ReferencingServices.setBounds(…) will
* pretend that warning come from Envelopes.<caller>. This is related to Envelopes.findOperation(…)
* since the purpose of this bounding box is to find a coordinate operation.
*/
final ReferencingServices converter = ReferencingServices.getInstance();
CoordinateReferenceSystem[] crs = new CoordinateReferenceSystem[count];
DefaultGeographicBoundingBox more = new DefaultGeographicBoundingBox();
DefaultGeographicBoundingBox bbox = null;
for (int i=0; i<count; i++) {
final GeneralEnvelope e = reduced[i];
crs[i] = e.getCoordinateReferenceSystem();
if (converter.setBounds(e, more, caller) != null) { // See above comment about logging.
if (bbox == null) {
bbox = more;
more = new DefaultGeographicBoundingBox();
} else {
reduce(bbox, more);
}
}
}
/*
* Now transform all remaining envelopes, so we can perform final reduction.
*/
final CoordinateReferenceSystem target = CRS.suggestCommonTarget(bbox, crs);
if (target == null) {
throw new TransformException(Resources.format(Resources.Keys.CanNotFindCommonCRS));
}
GeneralEnvelope result = null;
for (int i=0; i<count; i++) {
final Envelope other = Envelopes.transform(reduced[i], target);
if (result == null) {
result = GeneralEnvelope.castOrCopy(other);
} else {
reduce(result, other);
}
}
return result;
}
}
| apache-2.0 |
herval/zeppelin | zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/lifecycle/TimeoutLifecycleManagerTest.java | 5262 | /*
* 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.zeppelin.interpreter.lifecycle;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.interpreter.AbstractInterpreterTest;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreter;
import org.apache.zeppelin.scheduler.Job;
import org.junit.Test;
import java.io.IOException;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TimeoutLifecycleManagerTest extends AbstractInterpreterTest {
@Override
public void setUp() throws Exception {
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_LIFECYCLE_MANAGER_CLASS.getVarName(),
TimeoutLifecycleManager.class.getName());
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_LIFECYCLE_MANAGER_TIMEOUT_CHECK_INTERVAL.getVarName(), "1000");
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_LIFECYCLE_MANAGER_TIMEOUT_THRESHOLD.getVarName(), "10000");
super.setUp();
}
@Test
public void testTimeout_1() throws InterpreterException, InterruptedException, IOException {
interpreterSettingManager.setInterpreterBinding("user1", "note1", interpreterSettingManager.getSettingIds());
assertTrue(interpreterFactory.getInterpreter("user1", "note1", "test.echo") instanceof RemoteInterpreter);
RemoteInterpreter remoteInterpreter = (RemoteInterpreter) interpreterFactory.getInterpreter("user1", "note1", "test.echo");
assertFalse(remoteInterpreter.isOpened());
InterpreterSetting interpreterSetting = interpreterSettingManager.getInterpreterSettingByName("test");
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
Thread.sleep(15*1000);
// InterpreterGroup is not removed after 15 seconds, as TimeoutLifecycleManager only manage it after it is started
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
InterpreterContext context = InterpreterContext.builder()
.setNoteId("noteId")
.setParagraphId("paragraphId")
.build();
remoteInterpreter.interpret("hello world", context);
assertTrue(remoteInterpreter.isOpened());
Thread.sleep(15 * 1000);
// interpreterGroup is timeout, so is removed.
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
assertFalse(remoteInterpreter.isOpened());
}
@Test
public void testTimeout_2() throws InterpreterException, InterruptedException, IOException {
interpreterSettingManager.setInterpreterBinding("user1", "note1", interpreterSettingManager.getSettingIds());
assertTrue(interpreterFactory.getInterpreter("user1", "note1", "test.sleep") instanceof RemoteInterpreter);
final RemoteInterpreter remoteInterpreter = (RemoteInterpreter) interpreterFactory.getInterpreter("user1", "note1", "test.sleep");
// simulate how zeppelin submit paragraph
remoteInterpreter.getScheduler().submit(new Job("test-job", null) {
@Override
public Object getReturn() {
return null;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
InterpreterContext context = InterpreterContext.builder()
.setNoteId("noteId")
.setParagraphId("paragraphId")
.build();
return remoteInterpreter.interpret("100000", context);
}
@Override
protected boolean jobAbort() {
return false;
}
@Override
public void setResult(Object results) {
}
});
while(!remoteInterpreter.isOpened()) {
Thread.sleep(1000);
LOGGER.info("Wait for interpreter to be started");
}
InterpreterSetting interpreterSetting = interpreterSettingManager.getInterpreterSettingByName("test");
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
Thread.sleep(15 * 1000);
// interpreterGroup is not timeout because getStatus is called periodically.
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertTrue(remoteInterpreter.isOpened());
}
}
| apache-2.0 |
parthmehta209/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRAndroidResource.java | 21715 | /* Copyright 2015 Samsung Electronics Co., 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.gearvrf;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.util.TypedValue;
import org.gearvrf.asynchronous.CompressedTexture;
import org.gearvrf.asynchronous.GVRCompressedTextureLoader;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.MarkingFileInputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* A class to minimize overload fan-out.
*
* APIs that load resources can take a {@link GVRAndroidResource} instead of
* having overloads for {@code assets} files, {@code res/drawable} and
* {@code res/raw} files, and plain old files.
*
* See the discussion of asset-relative filenames <i>vs.</i> {@code R.raw}
* resource ids in the <a href="package-summary.html#assets">package
* description</a>.
*
* @since 1.6.1
*/
public class GVRAndroidResource {
private static final String TAG = Log.tag(GVRAndroidResource.class);
private enum StreamStates {
NEW, OPEN, CLOSED
}
private enum ResourceType {
ANDROID_ASSETS, ANDROID_RESOURCE, LINUX_FILESYSTEM, NETWORK, INPUT_STREAM
}
/*
* Instance members
*/
private InputStream stream = null;
private StreamStates streamState;
// Save parameters, for hashCode() and equals()
private final String filePath;
private final int resourceId;
private final String assetPath;
// For hint to Assimp
private String resourceFilePath;
private final URL url;
private boolean enableUrlLocalCache = false;
private Context context = null;
private ResourceType resourceType;
private String inputStreamName;
/**
* Open any file you have permission to read.
*
* @param path
* A Linux file path
*
* @throws FileNotFoundException
* File doesn't exist, or can't be read.
*/
public GVRAndroidResource(String path) throws FileNotFoundException {
streamState = StreamStates.NEW;
filePath = path;
resourceId = 0; // No R.whatever field will ever be 0
assetPath = null;
resourceFilePath = null;
url = null;
resourceType = ResourceType.LINUX_FILESYSTEM;
}
/**
* Open any file you have permission to read.
*
* @param file
* A Java {@link File} object
*
* @throws FileNotFoundException
* File doesn't exist, or can't be read.
*/
public GVRAndroidResource(File file) throws FileNotFoundException {
this(file.getAbsolutePath());
}
/**
* Open a {@code res/raw} or {@code res/drawable} bitmap file.
*
* @param gvrContext
* The GVR Context
* @param resourceId
* A {@code R.raw} or {@code R.drawable} id
*/
public GVRAndroidResource(GVRContext gvrContext, int resourceId) {
this(gvrContext.getContext(), resourceId);
}
/**
* Open a {@code res/raw} or {@code res/drawable} bitmap file.
*
* @param context
* An Android Context
* @param resourceId
* A {@code R.raw} or {@code R.drawable} id
*/
public GVRAndroidResource(Context context, int resourceId) {
this.context = context;
Resources resources = context.getResources();
streamState = StreamStates.NEW;
filePath = null;
this.resourceId = resourceId;
assetPath = null;
url = null;
TypedValue value = new TypedValue();
resources.getValue(resourceId, value, true);
resourceFilePath = value.string.toString();
resourceType = ResourceType.ANDROID_RESOURCE;
}
/**
* Open an {@code assets} file
*
* @param gvrContext
* The GVR Context
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
* @throws IOException
* File does not exist or cannot be read
*/
public GVRAndroidResource(GVRContext gvrContext,
String assetRelativeFilename) throws IOException {
this(gvrContext.getContext(), assetRelativeFilename);
}
/**
* Open an {@code assets} file
*
* @param context
* An Android Context
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
* @throws IOException
* File does not exist or cannot be read
*/
public GVRAndroidResource(Context context, String assetRelativeFilename)
throws IOException {
this.context = context;
streamState = StreamStates.NEW;
filePath = null;
resourceId = 0; // No R.whatever field will ever be 0
assetPath = assetRelativeFilename;
resourceFilePath = null;
url = null;
resourceType = ResourceType.ANDROID_ASSETS;
}
/**
* Open resource from a URL.
*
* @param url
* A Java {@link URL} object
* @throws IOException
*/
public GVRAndroidResource(GVRContext context, URL url) throws IOException {
this(context, url, false);
}
/**
* Create a resource from an {@link InputStream}.
*
* Note that this constructor is package private and is only used by the {@link ZipLoader}
* (for now).
*
* @param name a String for uniquely identifying this resource
* @param inputStream an already open {@link InputStream} for this resource
*/
GVRAndroidResource(String name, InputStream inputStream) {
inputStreamName = name;
stream = inputStream;
streamState = StreamStates.NEW;
filePath = null;
resourceId = 0; // No R.whatever field will ever be 0
assetPath = null;
resourceFilePath = null;
url = null;
resourceType = ResourceType.INPUT_STREAM;
}
/*
* A {@link URLBufferedInputStream} that supports {@link
* InputStream#mark(int)} and {@link InputStream#reset()}
*/
static class URLBufferedInputStream extends InputStream {
private URL url;
private BufferedInputStream in;
public URLBufferedInputStream(URL url) throws IOException {
this.url = url;
in = new BufferedInputStream(url.openStream());
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void reset() throws IOException {
// Since the bufferInputStream resets the offset within the internal
// buffer while may not resets the url's stream correctly
// it could easily causes OOM error when decoding it after some
// initial read and reset.
// Here we tackle it by opening a new connection to the url and
// restart from beginning
in = new BufferedInputStream(url.openStream());
}
@Override
public int read() throws IOException {
return in.read();
}
@Override
public int read(byte[] buffer, int byteOffset, int byteCount)
throws IOException {
return in.read(buffer, byteOffset, byteCount);
}
}
/**
* Download resource from a URL and open it as a regular file.
*
* @param context
* An Android Context
* @param url
* A Java {@link URL} object
* @throws IOException
*/
public GVRAndroidResource(GVRContext context, URL url,
boolean enableUrlLocalCache) throws IOException {
this.enableUrlLocalCache = enableUrlLocalCache;
streamState = StreamStates.NEW;
filePath = null;
resourceId = 0;
assetPath = null;
resourceFilePath = null;
this.url = url;
resourceType = ResourceType.NETWORK;
}
/**
* Get the open stream.
*
* Changes the debug state (visible <i>via</i> {@link #toString()}) to
* {@linkplain GVRAndroidResource.StreamStates#READING READING}.
*
* @return An open {@link InputStream}.
* @throws IOException
*/
public synchronized final InputStream getStream() {
if (streamState != StreamStates.OPEN) {
openStream();
}
return stream;
}
/*
* TODO Should we somehow expose the CLOSED state? Return null or throw an
* exception from getStream()? Or is it enough for the calling code to fail,
* reading a closed stream?
*/
/**
* Close the open stream.
*
* Close the stream if it was opened before
*
*/
public synchronized final void closeStream() {
try {
if (streamState == StreamStates.OPEN) {
stream.close();
stream = null;
}
streamState = StreamStates.CLOSED;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* Open the input stream for resource decoding
*
*
*/
public synchronized void openStream() {
try {
switch (resourceType) {
case ANDROID_ASSETS:
stream = context.getResources().getAssets().open(assetPath);
streamState = StreamStates.OPEN;
break;
case ANDROID_RESOURCE:
stream = context.getResources().openRawResource(resourceId);
streamState = StreamStates.OPEN;
break;
case LINUX_FILESYSTEM:
stream = new MarkingFileInputStream(filePath);
streamState = StreamStates.OPEN;
break;
case NETWORK:
if (!enableUrlLocalCache) {
Log.d(TAG,
"Do not allow local caching, use streaming to get the resource");
stream = new URLBufferedInputStream(url);
streamState = StreamStates.OPEN;
} else {
Log.d(TAG,
"Allow local caching, download the resource to local cache");
File file = GVRAssetLoader.downloadFile(context,
url.toString());
stream = new MarkingFileInputStream(file);
streamState = StreamStates.OPEN;
}
break;
case INPUT_STREAM:
//input stream is already open
streamState = StreamStates.OPEN;
break;
default:
stream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Save the stream position, for later use with {@link #reset()}.
*
* All {@link GVRAndroidResource} streams support
* {@link InputStream#mark(int) mark()} and {@link InputStream#reset()
* reset().} Calling {@link #mark()} right after construction will allow you
* to read the header then {@linkplain #reset() rewind the stream} if you
* can't handle the file format.
* @throws IOException
*
* @since 1.6.7
*/
private void mark() throws IOException {
if (streamState == StreamStates.OPEN) {
if (stream.markSupported()) {
stream.mark(Integer.MAX_VALUE);
} else {
// In case a inputStream (e.g., fileInputStream) doesn't support
// mark, throw a exception
throw new IOException("Input stream doesn't support mark");
}
}
}
/**
* Restore the stream position, to the point set by a previous
* {@link #mark() mark().}
*
* Please note that calling {@link #reset()} generally 'consumes' the
* {@link #mark()} - <em>do not</em> call
*
* <pre>
* mark();
* reset();
* reset();
* </pre>
* @throws IOException
*
* @since 1.6.7
*/
private void reset() throws IOException {
if (streamState == StreamStates.OPEN) {
if (stream.markSupported()) {
stream.reset();
} else {
// In case a inputStream (e.g., fileInputStream) doesn't support
// mark, throw a exception
throw new IOException("Input stream doesn't support mark");
}
}
}
/**
* Returns the filename of the resource with extension.
*
* @return Filename of the GVRAndroidResource. May return null if the
* resource is not associated with any file
*/
public String getResourceFilename() {
switch (resourceType) {
case ANDROID_ASSETS:
return assetPath
.substring(assetPath.lastIndexOf(File.separator) + 1);
case ANDROID_RESOURCE:
return resourceFilePath.substring(
resourceFilePath.lastIndexOf(File.separator) + 1);
case LINUX_FILESYSTEM:
return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
case NETWORK:
return url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
case INPUT_STREAM:
return inputStreamName;
default:
return null;
}
}
/*
* Auto-generated hashCode() and equals(), for container support &c.
*
* These check only the private 'parameter capture' fields - not the
* InputStream.
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((assetPath == null) ? 0 : assetPath.hashCode());
result = prime * result
+ ((filePath == null) ? 0 : filePath.hashCode());
result = prime * result
+ ((url == null) ? 0 : url.hashCode());
result = prime * result
+ ((inputStreamName == null) ? 0 : inputStreamName.hashCode());
result = prime * result + resourceId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GVRAndroidResource other = (GVRAndroidResource) obj;
switch (resourceType) {
case ANDROID_ASSETS:
return assetPath.equals(other.assetPath);
case ANDROID_RESOURCE:
return resourceId == other.resourceId;
case LINUX_FILESYSTEM:
return filePath.equals(other.filePath);
case NETWORK:
return url.equals(other.url);
case INPUT_STREAM:
return inputStreamName.equals(other.inputStreamName);
default:
return false;
}
}
/*
* toString(), for debugging.
*/
/**
* For debugging: shows which file the instance describes, and shows the
* OPEN / READING / CLOSED state of the input stream.
*/
@Override
public String toString() {
return String.format("%s{filePath=%s; resourceId=%x; assetPath=%s, url=%s, " +
"inputStreamName=%s}",streamState, filePath, resourceId, assetPath, url,
inputStreamName);
}
/*
* Generic callback interfaces, for asynchronous APIs that take a {@link
* GVRAndroidResource} parameter
*/
/**
* Callback interface for asynchronous resource loading.
*
* None of the asynchronous resource [textures, and meshes] loading methods
* that take a {@link GVRAndroidResource} parameter return a value. You must
* supply a copy of this interface to get results.
*
* <p>
* While you will often create a callback for each load request, the APIs do
* each include the {@link GVRAndroidResource} that you are loading. This
* lets you use the same callback implementation with multiple resources.
*/
public interface Callback<T extends GVRHybridObject> {
/**
* Resource load succeeded.
*
* @param resource
* A new GVRF resource
* @param androidResource
* The description of the resource that was loaded
* successfully
*/
void loaded(T resource, GVRAndroidResource androidResource);
/**
* Resource load failed.
*
* @param t
* Error information
* @param androidResource
* The description of the resource that could not be loaded
*/
void failed(Throwable t, GVRAndroidResource androidResource);
}
/**
* Callback interface for cancelable resource loading.
*
* Loading uncompressed textures (Android {@linkplain Bitmap bitmaps}) can
* take hundreds of milliseconds and megabytes of memory; loading even
* moderately complex meshes can be even slower. GVRF uses a throttling
* system to manage system load, and an priority system to give you some
* control over the throttling. This means that slow resource loads can take
* enough time that you don't actually need the resource by the time the
* system gets to it. The {@link #stillWanted(GVRAndroidResource)} method
* lets you cancel unneeded loads.
*/
public interface CancelableCallback<T extends GVRHybridObject> extends
Callback<T> {
/**
* Do you still want this resource?
*
* If the throttler has a thread available, your request will be run
* right away; this method will not be called. If not, it is enqueued;
* this method will be called (at least once) before starting to load
* the resource. If you no longer need it, returning {@code false} can
* save non-trivial amounts of time and memory.
*
* @param androidResource
* The description of the resource that is about to be loaded
*
* @return {@code true} to continue loading; {@code false} to abort.
* (Returning {@code false} will not call
* {@link #failed(Throwable, GVRAndroidResource) failed().})
*/
boolean stillWanted(GVRAndroidResource androidResource);
}
/*
* Specialized callback interfaces, to make use a bit smaller and clearer.
*/
/**
* Callback for asynchronous compressed-texture loads.
*
* Compressed textures load very quickly, so they're not subject to
* throttling and don't support
* {@link BitmapTextureCallback#stillWanted(GVRAndroidResource)}
*/
public interface CompressedTextureCallback extends Callback<GVRTexture> {
}
/** Callback for asynchronous bitmap-texture loads. */
public interface BitmapTextureCallback extends
CancelableCallback<GVRTexture> {
}
/**
* Callback for asynchronous texture loads.
*
* Both compressed and bitmapped textures, using the
* {@link GVRContext#loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource)}
* APIs.
*
* @since 1.6.7
*/
public interface TextureCallback extends CancelableCallback<GVRTexture> {
}
/** Callback for asynchronous mesh loads */
public interface MeshCallback extends CancelableCallback<GVRMesh> {
}
private GVRCompressedTextureLoader compressedLoader = null;
private boolean isCompressedTextureSniffed = false;
public synchronized GVRCompressedTextureLoader getCompressedLoader() {
if (!isCompressedTextureSniffed) {
try {
Log.d(TAG, "Looking for compressed header");
openStream();
mark();
try {
compressedLoader = CompressedTexture.sniff(getStream());
} catch (IOException e) {
e.printStackTrace();
} finally {
reset();
//don't close for this type
if (resourceType != ResourceType.INPUT_STREAM) {
closeStream();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
isCompressedTextureSniffed = true;
}
}
return compressedLoader;
}
}
| apache-2.0 |
magnet/bnd | biz.aQute.bndlib/src/aQute/bnd/osgi/ClassDataCollectors.java | 7364 | package aQute.bnd.osgi;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import aQute.bnd.osgi.Clazz.FieldDef;
import aQute.bnd.osgi.Clazz.MethodDef;
import aQute.bnd.osgi.Descriptors.TypeRef;
import aQute.service.reporter.Reporter;
/**
* This class dispatches class data collectors. Over time more and more code was
* looking for annotations and other stuff. In the early days, the parser tried
* to not do full parsing to minimize the cost but basically we are now parsing
* more than necessary because different places began parsing on their own.
*/
class ClassDataCollectors implements Closeable {
final List<ClassDataCollector> delegates = new ArrayList<ClassDataCollector>();
final List<ClassDataCollector> shortlist = new ArrayList<ClassDataCollector>();
final Reporter reporter;
ClassDataCollectors(Reporter reporter) {
this.reporter = reporter;
}
void add(ClassDataCollector cd) {
delegates.add(cd);
}
void parse(Clazz clazz) throws Exception {
clazz.parseClassFileWithCollector(new Collectors(clazz));
}
void with(Clazz clazz, ClassDataCollector cd) throws Exception {
delegates.add(cd);
try {
parse(clazz);
} finally {
delegates.remove(cd);
}
}
public void close() {
for (ClassDataCollector cd : delegates)
try {
if (cd instanceof Closeable)
((Closeable) cd).close();
} catch (Exception e) {
reporter.exception(e, "Failure on call close[%s]", cd);
}
delegates.clear();
shortlist.clear();
}
private class Collectors extends ClassDataCollector {
private final Clazz clazz;
Collectors(Clazz clazz) {
this.clazz = clazz;
}
@Override
public void classBegin(int access, TypeRef name) {
for (ClassDataCollector cd : delegates)
try {
cd.classBegin(access, name);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call classBegin[%s] for %s", clazz, cd);
}
}
@Override
public boolean classStart(int access, TypeRef className) {
boolean start = false;
for (ClassDataCollector cd : delegates)
try {
if (cd.classStart(access, className)) {
shortlist.add(cd);
start = true;
}
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call classStart[%s]", clazz, cd);
}
return start;
}
@Override
public boolean classStart(Clazz clazz) {
boolean start = false;
for (ClassDataCollector cd : delegates)
try {
if (cd.classStart(clazz)) {
shortlist.add(cd);
start = true;
}
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call classStart[%s]", clazz, cd);
}
return start;
}
@Override
public void extendsClass(TypeRef zuper) throws Exception {
for (ClassDataCollector cd : shortlist)
try {
cd.extendsClass(zuper);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call extendsClass[%s]", clazz, cd);
}
}
@Override
public void implementsInterfaces(TypeRef[] interfaces) throws Exception {
for (ClassDataCollector cd : shortlist)
try {
cd.implementsInterfaces(interfaces);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call implementsInterfaces[%s]", clazz, cd);
}
}
@Override
public void addReference(TypeRef ref) {
for (ClassDataCollector cd : shortlist)
try {
cd.addReference(ref);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call addReference[%s]", clazz, cd);
}
}
@Override
public void annotation(Annotation annotation) {
for (ClassDataCollector cd : shortlist)
try {
cd.annotation(annotation);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call annotation[%s]", clazz, cd);
}
}
@Override
public void parameter(int p) {
for (ClassDataCollector cd : shortlist)
try {
cd.parameter(p);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call parameter[%s]", clazz, cd);
}
}
@Override
public void method(MethodDef defined) {
for (ClassDataCollector cd : shortlist)
try {
cd.method(defined);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call method[%s]", clazz, cd);
}
}
@Override
public void field(FieldDef defined) {
for (ClassDataCollector cd : shortlist)
try {
cd.field(defined);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call field[%s]", clazz, cd);
}
}
@Override
public void classEnd() throws Exception {
for (ClassDataCollector cd : shortlist)
try {
cd.classEnd();
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call classEnd[%s]", clazz, cd);
}
shortlist.clear();
}
@Override
public void deprecated() throws Exception {
for (ClassDataCollector cd : shortlist)
try {
cd.deprecated();
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call deprecated[%s]", clazz, cd);
}
}
@Override
public void enclosingMethod(TypeRef cName, String mName, String mDescriptor) {
for (ClassDataCollector cd : shortlist)
try {
cd.enclosingMethod(cName, mName, mDescriptor);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call enclosingMethod[%s]", clazz, cd);
}
}
@Override
public void innerClass(TypeRef innerClass, TypeRef outerClass, String innerName, int innerClassAccessFlags)
throws Exception {
for (ClassDataCollector cd : shortlist)
try {
cd.innerClass(innerClass, outerClass, innerName, innerClassAccessFlags);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call innerClass[%s]", clazz, cd);
}
}
@Override
public void signature(String signature) {
for (ClassDataCollector cd : shortlist)
try {
cd.signature(signature);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call signature[%s]", clazz, cd);
}
}
@Override
public void constant(Object object) {
for (ClassDataCollector cd : shortlist)
try {
cd.constant(object);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call constant[%s]", clazz, cd);
}
}
@Override
public void memberEnd() {
for (ClassDataCollector cd : shortlist)
try {
cd.memberEnd();
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call memberEnd[%s]", clazz, cd);
}
}
@Override
public void version(int minor, int major) {
for (ClassDataCollector cd : shortlist)
try {
cd.version(minor, major);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call version[%s]", clazz, cd);
}
}
@Override
public void referenceMethod(int access, TypeRef className, String method, String descriptor) {
for (ClassDataCollector cd : shortlist)
try {
cd.referenceMethod(access, className, method, descriptor);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call referenceMethod[%s]", clazz, cd);
}
}
@Override
public void referTo(TypeRef typeRef, int modifiers) {
for (ClassDataCollector cd : shortlist)
try {
cd.referTo(typeRef, modifiers);
} catch (Exception e) {
reporter.exception(e, "Failure for %s on call referTo[%s]", clazz, cd);
}
}
}
}
| apache-2.0 |
vivantech/kc_fixes | src/main/java/org/kuali/kra/irb/protocol/reference/ProtocolReferenceRule.java | 991 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.kuali.kra.irb.protocol.reference;
import org.kuali.kra.protocol.protocol.reference.ProtocolReferenceRuleBase;
/**
* This class is implementation of <code>AddProtocolReferenceRule</code> interface. Impl makes sure necessary rules are satisfied
* before object can be used.
*/
public class ProtocolReferenceRule extends ProtocolReferenceRuleBase {
}
| apache-2.0 |
hugosato/apache-axis | test/properties/PackageTests.java | 461 | package test.properties;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test package for property tests
*/
public class PackageTests extends TestCase {
public PackageTests(String name) {
super(name);
}
public static Test suite() throws Exception {
TestSuite suite = new TestSuite();
suite.addTestSuite(TestScopedProperties.class);
return suite;
}
}
| apache-2.0 |
betfair/cougar | cougar-framework/net-util/src/main/java/com/betfair/cougar/netutil/nio/HeapDelta.java | 4425 | /*
* Copyright 2014, The Sporting Exchange Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.betfair.cougar.netutil.nio;
import com.betfair.cougar.core.api.transcription.*;
import com.betfair.platform.virtualheap.HeapListener;
import com.betfair.cougar.netutil.nio.connected.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
*/
public class HeapDelta extends AbstractHeapTranscribable {
private long heapId;
private long updateId;
private List<Update> updates = new ArrayList<Update>();
// used in transcription, change the ordering at your peril!
// add new fields at the end!
private Parameter[] parameters = new Parameter[] {
new Parameter("heapId", ParameterType.create(long.class), true),
new Parameter("updateId", ParameterType.create(long.class), true),
new Parameter("updates", ParameterType.create(ArrayList.class, Update.class), true)
};
public HeapDelta() {
}
public HeapDelta(long heapId, long updateId, List<Update> updates) {
this.heapId = heapId;
this.updateId = updateId;
this.updates = updates;
}
@Override
public void transcribe(TranscriptionOutput out, Set<TranscribableParams> params, boolean client) throws Exception {
out.writeObject(heapId, parameters[0], client);
out.writeObject(updateId, parameters[1], client);
out.writeObject(updates, parameters[2], client);
// NOTE: add new fields at the end
}
@Override
public void transcribe(TranscriptionInput in, Set<TranscribableParams> params, boolean client) throws Exception {
heapId = (Long) in.readObject(parameters[0], client);
updateId = (Long) in.readObject(parameters[1], client);
updates = (List<Update>) in.readObject(parameters[2], client);
// NOTE: add new fields at the end
}
@Override
public Parameter[] getParameters() {
return parameters;
}
public long getHeapId() {
return heapId;
}
public void setHeapId(long heapId) {
this.heapId = heapId;
}
public List<Update> getUpdates() {
return updates;
}
public void setUpdates(List<Update> updates) {
this.updates = updates;
}
public void applyTo(HeapListener listener) {
for (Update u : updates) {
u.apply(listener);
}
}
public void add(Update u) {
updates.add(u);
}
public void setUpdateId(long updateId) {
this.updateId = updateId;
}
public long getUpdateId() {
return updateId;
}
public boolean containsFirstUpdate() {
// initial update must be the first..
if (!updates.isEmpty()) {
if (updates.get(0) instanceof InitialUpdate) {
return true;
}
}
return false;
}
public boolean containsHeapTermination() {
if (!updates.isEmpty()) {
Update last = updates.get(updates.size()-1);
return (last.getActions().contains(TerminateHeap.INSTANCE));
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HeapDelta heapDelta = (HeapDelta) o;
if (heapId != heapDelta.heapId) return false;
if (updateId != heapDelta.updateId) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (heapId ^ (heapId >>> 32));
result = 31 * result + (int) (updateId ^ (updateId >>> 32));
return result;
}
@Override
public String toString() {
return "HeapDelta{" +
"heapId=" + heapId +
", updateId=" + updateId +
", updates=" + updates +
'}';
}
}
| apache-2.0 |
apache/cocoon | blocks/cocoon-asciiart/cocoon-asciiart-impl/src/main/java/org/apache/cocoon/generation/asciiart/AsciiArtPad.java | 23632 | /*
* 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.cocoon.generation.asciiart;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
/**
* A drawing ascii art pad.
*
* @since 18. Dezember 2002
* @version $Id$
*/
public class AsciiArtPad {
private int width;
private int height;
/**
* List of AsciiArt elements
*/
private List pad;
private double xGrid;
private double yGrid;
/**
*Constructor for the AsciiArtPad object
*/
public AsciiArtPad() {
pad = new ArrayList();
}
/**
*Constructor for the AsciiArtPad object
*
*@param w Description of the Parameter
*@param h Description of the Parameter
*/
public AsciiArtPad(int w, int h) {
width = w;
height = h;
pad = new ArrayList();
}
/**
* Sets the width attribute of the AsciiArtPad object
*
*@param width The new width value
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Sets the height attribute of the AsciiArtPad object
*
*@param height The new height value
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Sets the xGrid attribute of the AsciiArtPad object
*
*@param xGrid The new xGrid value
*/
public void setXGrid(double xGrid) {
this.xGrid = xGrid;
}
/**
* Sets the yGrid attribute of the AsciiArtPad object
*
*@param yGrid The new yGrid value
*/
public void setYGrid(double yGrid) {
this.yGrid = yGrid;
}
/**
* Gets the width attribute of the AsciiArtPad object
*
*@return The width value
*/
public int getWidth() {
return width;
}
/**
* Gets the height attribute of the AsciiArtPad object
*
*@return The height value
*/
public int getHeight() {
return height;
}
/**
* Gets the xGrid attribute of the AsciiArtPad object
*
*@return The xGrid value
*/
public double getXGrid() {
return xGrid;
}
/**
* Gets the yGrid attribute of the AsciiArtPad object
*
*@return The yGrid value
*/
public double getYGrid() {
return yGrid;
}
/**
* Add a AsciiArtElement
*
*@param o the AsciiArtElement object
*/
public void add(Object o) {
pad.add(o);
}
/**
* Iterator of AsciiArtPad
*
*@return Iterator iterating over all AsciiArtElements
*/
public Iterator iterator() {
return pad.iterator();
}
/**
* An AsciiArtElement describing a line.
*
*/
public static class AsciiArtLine implements AsciiArtElement {
double xStart;
double yStart;
double xEnd;
double yEnd;
/**
*Constructor for the AsciiArtLine object
*
*@param start Description of the Parameter
*@param end Description of the Parameter
*/
public AsciiArtLine(AsciiArtCoordinate start, AsciiArtCoordinate end) {
xStart = start.getXDouble();
yStart = start.getYDouble();
xEnd = end.getXDouble();
yEnd = end.getYDouble();
}
/**
* Sets the xStart attribute of the AsciiArtLine object
*
*@param xStart The new xStart value
*/
public void setXStart(double xStart) {
this.xStart = xStart;
}
/**
* Sets the yStart attribute of the AsciiArtLine object
*
*@param yStart The new yStart value
*/
public void setYStart(double yStart) {
this.yStart = yStart;
}
/**
* Sets the xEnd attribute of the AsciiArtLine object
*
*@param xEnd The new xEnd value
*/
public void setXEnd(double xEnd) {
this.xEnd = xEnd;
}
/**
* Sets the yEnd attribute of the AsciiArtLine object
*
*@param yEnd The new yEnd value
*/
public void setYEnd(double yEnd) {
this.yEnd = yEnd;
}
/**
* Gets the xStart attribute of the AsciiArtLine object
*
*@return The xStart value
*/
public double getXStart() {
return xStart;
}
/**
* Gets the yStart attribute of the AsciiArtLine object
*
*@return The yStart value
*/
public double getYStart() {
return yStart;
}
/**
* Gets the xEnd attribute of the AsciiArtLine object
*
*@return The xEnd value
*/
public double getXEnd() {
return xEnd;
}
/**
* Gets the yEnd attribute of the AsciiArtLine object
*
*@return The yEnd value
*/
public double getYEnd() {
return yEnd;
}
/**
* Descriptive string
*
*@return String
*/
public String toString() {
String s =
"[xStart:" + String.valueOf(xStart) + "]" +
"[yStart:" + String.valueOf(yStart) + "]" +
"[xEnd:" + String.valueOf(xEnd) + "]" +
"[yEnd:" + String.valueOf(yEnd) + "]";
return s;
}
}
/**
* An AsciiArtElement describing a rectangle.
*
*/
public static class AsciiArtRect implements AsciiArtElement {
double xUpperLeft;
double yUpperLeft;
double xLowerRight;
double yLowerRight;
/**
*Constructor for the AsciiArtRect object
*
*@param upperLeft Description of the Parameter
*@param lowerRight Description of the Parameter
*/
public AsciiArtRect(AsciiArtCoordinate upperLeft, AsciiArtCoordinate lowerRight) {
xUpperLeft = upperLeft.getXDouble();
yUpperLeft = upperLeft.getYDouble();
xLowerRight = lowerRight.getXDouble();
yLowerRight = lowerRight.getYDouble();
}
/**
* Sets the xUpperLeft attribute of the AsciiArtRect object
*
*@param xUpperLeft The new xUpperLeft value
*/
public void setXUpperLeft(double xUpperLeft) {
this.xUpperLeft = xUpperLeft;
}
/**
* Sets the yUpperLeft attribute of the AsciiArtRect object
*
*@param yUpperLeft The new yUpperLeft value
*/
public void setYUpperLeft(double yUpperLeft) {
this.yUpperLeft = yUpperLeft;
}
/**
* Sets the xLowerRight attribute of the AsciiArtRect object
*
*@param xLowerRight The new xLowerRight value
*/
public void setXLowerRight(double xLowerRight) {
this.xLowerRight = xLowerRight;
}
/**
* Sets the yLowerRight attribute of the AsciiArtRect object
*
*@param yLowerRight The new yLowerRight value
*/
public void setYLowerRight(double yLowerRight) {
this.yLowerRight = yLowerRight;
}
/**
* Gets the xUpperLeft attribute of the AsciiArtRect object
*
*@return The xUpperLeft value
*/
public double getXUpperLeft() {
return xUpperLeft;
}
/**
* Gets the yUpperLeft attribute of the AsciiArtRect object
*
*@return The yUpperLeft value
*/
public double getYUpperLeft() {
return yUpperLeft;
}
/**
* Gets the xLowerRight attribute of the AsciiArtRect object
*
*@return The xLowerRight value
*/
public double getXLowerRight() {
return xLowerRight;
}
/**
* Gets the yLowerRight attribute of the AsciiArtRect object
*
*@return The yLowerRight value
*/
public double getYLowerRight() {
return yLowerRight;
}
/**
* Gets the width attribute of the AsciiArtRect object
*
*@return The width value
*/
public double getWidth() {
return Math.abs(xUpperLeft - xLowerRight);
}
/**
* Gets the height attribute of the AsciiArtRect object
*
*@return The height value
*/
public double getHeight() {
return Math.abs(yUpperLeft - yLowerRight);
}
/**
* Descriptive string
*
*@return String
*/
public String toString() {
String s =
"[xUpperLeft:" + String.valueOf(xUpperLeft) + "]" +
"[yUpperLeft:" + String.valueOf(yUpperLeft) + "]" +
"[xLowerRight:" + String.valueOf(xLowerRight) + "]" +
"[yLowerRight:" + String.valueOf(yLowerRight) + "]";
return s;
}
}
/**
* An AsciiArtElement describing a string of text.
*
*/
public static class AsciiArtString implements AsciiArtElement {
private double x;
private double y;
private String s;
/**
*Constructor for the AsciiArtString object
*
*@param s Description of the Parameter
*@param aac Description of the Parameter
*/
public AsciiArtString(AsciiArtCoordinate aac, String s) {
this.x = aac.getXDouble();
this.y = aac.getYDouble();
this.s = s;
}
/**
* Sets the x attribute of the AsciiArtString object
*
*@param x The new x value
*/
public void setX(double x) {
this.x = x;
}
/**
* Sets the y attribute of the AsciiArtString object
*
*@param y The new y value
*/
public void setY(double y) {
this.y = y;
}
/**
* Sets the s attribute of the AsciiArtString object
*
*@param s The new s value
*/
public void setS(String s) {
this.s = s;
}
/**
* Gets the x attribute of the AsciiArtString object
*
*@return The x value
*/
public double getX() {
return x;
}
/**
* Gets the y attribute of the AsciiArtString object
*
*@return The y value
*/
public double getY() {
return y;
}
/**
* Gets the s attribute of the AsciiArtString object
*
*@return The s value
*/
public String getS() {
return s;
}
/**
* Descriptive string
*
*@return String
*/
public String toString() {
String s =
"[x:" + String.valueOf(x) + "]" +
"[y:" + String.valueOf(y) + "]" +
"[s:" + String.valueOf(this.s) + "]";
return s;
}
}
/**
* Helper class describing a coordinate of AsciiArtPad elements.
*
*/
public static class AsciiArtCoordinate {
int x, y;
AsciiArtPad asciiArtPad;
double tx, ty;
/**
*Constructor for the AsciiArtCoordinate object
*/
public AsciiArtCoordinate() { }
/**
*Constructor for the AsciiArtCoordinate object
*
*@param asciiArtPad Description of the Parameter
*/
public AsciiArtCoordinate(AsciiArtPad asciiArtPad) {
setAsciiArtPad(asciiArtPad);
}
/**
*Constructor for the AsciiArtCoordinate object
*
*@param x Description of the Parameter
*@param y Description of the Parameter
*/
public AsciiArtCoordinate(int x, int y) {
setXY(x, y);
}
/**
* Sets the asciiArtPad attribute of the AsciiArtCoordinate object
*
*@param asciiArtPad The new asciiArtPad value
*/
public void setAsciiArtPad(AsciiArtPad asciiArtPad) {
this.asciiArtPad = asciiArtPad;
}
/**
* Sets the xY attribute of the AsciiArtCoordinate object
*
*@param tx The new transXY value
*@param ty The new transXY value
*/
public void setTransXY(double tx, double ty) {
this.tx = tx;
this.ty = ty;
}
/**
* Sets the xY attribute of the AsciiArtCoordinate object
*
*@param x The new xY value
*@param y The new xY value
*/
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Gets the xDouble attribute of the AsciiArtCoordinate object
*
*@return The xDouble value
*/
public double getXDouble() {
return x * asciiArtPad.getXGrid() + tx;
}
/**
* Gets the yDouble attribute of the AsciiArtCoordinate object
*
*@return The yDouble value
*/
public double getYDouble() {
return y * asciiArtPad.getYGrid() + ty;
}
}
/**
* Helper class containing the ascii text data,
* acting as input of an AsciiArtPad
*
*/
public static class AsciiArt {
private String[] s;
private int w;
private int h;
/**
*Constructor for the AsciiArt object
*
*@param s Description of the Parameter
*/
public AsciiArt(String[] s) {
this.s = s;
int length = s.length;
h = length;
w = 0;
for (int i = 0; i < length; i++) {
String line = s[i];
if (line != null && line.length() > w) {
w = line.length();
}
}
}
/**
* Gets the w attribute of the AsciiArt object
*
*@return The w value
*/
public int getW() {
return w;
}
/**
* Gets the h attribute of the AsciiArt object
*
*@return The h value
*/
public int getH() {
return h;
}
/**
* Gets the row attribute of the AsciiArt object
*
*@param r Description of the Parameter
*@return The row value
*/
public String getRow(int r) {
String row = this.s[r];
return row;
}
/**
* Gets the column attribute of the AsciiArt object
*
*@param c Description of the Parameter
*@return The column value
*/
public String getColumn(int c) {
StringBuffer column = new StringBuffer();
final String EMPTY_CHAR = " ";
for (int i = 0; i < s.length; i++) {
if (s[i] != null && c < s[i].length()) {
column.append(s[i].charAt(c));
} else {
column.append(EMPTY_CHAR);
}
}
return column.toString();
}
}
/**
* Builder of AsciiArtElements from an AsciiArt input.
*
*/
public static class AsciiArtPadBuilder {
private AsciiArtPad asciiArtPad;
private AsciiArt aa;
final String EDGE_GROUP = "[+\\\\/]";
final String HLINE_GROUP = "[\\-~=+]";
final String VLINE_GROUP = "[|+]";
final String STRING_SUFFIX_GROUP = "[^\\-|~=\\/+ \\\\]";
//final String STRING_PREFIX_GROUP = "[a-zA-Z0-9_\\*;\\.#]";
final String STRING_PREFIX_GROUP = STRING_SUFFIX_GROUP;
/**
*Constructor for the AsciiArtPadBuilder object
*
*@param asciiArtPad Description of the Parameter
*/
public AsciiArtPadBuilder(AsciiArtPad asciiArtPad) {
this.asciiArtPad = asciiArtPad;
}
/**
* Build AsciiArtElement from an asciiArt
*
*@param asciiArt Description of the Parameter
*/
public void build(String[] asciiArt) {
aa = new AsciiArt(asciiArt);
asciiArtPad.setWidth(aa.getW());
asciiArtPad.setHeight(aa.getH());
// find asciiArt patterns
findRectPattern();
findCornerPattern();
findLinePattern();
findStringPattern();
}
/**
* Find rectangles in the AsciiArt.
* not implemented yet.
*/
protected void findRectPattern() {
}
/**
* Find corners in the AsciiArt
*/
protected void findCornerPattern() {
AsciiArtCoordinate aacStart = new AsciiArtCoordinate(this.asciiArtPad);
aacStart.setTransXY(0, asciiArtPad.getYGrid() / 2);
AsciiArtCoordinate aacEnd = new AsciiArtCoordinate(this.asciiArtPad);
aacEnd.setTransXY(0, asciiArtPad.getYGrid() / 2);
// hor line
try {
final RE reCorner = new RE(EDGE_GROUP);
for (int r = 0; r < aa.getH(); r++) {
String row = aa.getRow(r);
int startIndex = 0;
while (reCorner.match(row, startIndex)) {
String s = reCorner.getParen(0);
int mStart = reCorner.getParenStart(0);
int mEnd = reCorner.getParenEnd(0);
if (s.equals("\\")) {
aacStart.setXY(mStart, r - 1);
aacEnd.setXY(mStart + 1, r);
} else if (s.equals("/")) {
aacStart.setXY(mStart + 1, r - 1);
aacEnd.setXY(mStart, r);
} else {
aacStart.setXY(mStart, r);
aacEnd.setXY(mStart, r);
}
AsciiArtLine aal = new AsciiArtLine(aacStart, aacEnd);
this.asciiArtPad.add(aal);
if (startIndex >= mEnd) {
break;
}
startIndex = mEnd;
}
}
} catch (RESyntaxException rese) {
rese.printStackTrace();
}
}
/**
* Find lines in the AsciiArt
*/
protected void findLinePattern() {
AsciiArtCoordinate aacStart = new AsciiArtCoordinate(this.asciiArtPad);
aacStart.setTransXY(0, asciiArtPad.getYGrid() / 2);
AsciiArtCoordinate aacEnd = new AsciiArtCoordinate(this.asciiArtPad);
aacEnd.setTransXY(0, asciiArtPad.getYGrid() / 2);
// hor line
try {
final RE reHorLine = new RE(HLINE_GROUP + "+");
for (int r = 0; r < aa.getH(); r++) {
String row = aa.getRow(r);
int startIndex = 0;
while (reHorLine.match(row, startIndex)) {
int mStart = reHorLine.getParenStart(0);
int mEnd = reHorLine.getParenEnd(0);
aacStart.setXY(mStart, r);
aacEnd.setXY(mEnd - 1, r);
AsciiArtLine aal = new AsciiArtLine(aacStart, aacEnd);
this.asciiArtPad.add(aal);
if (startIndex >= mEnd) {
break;
}
startIndex = mEnd;
}
}
} catch (RESyntaxException rese) {
rese.printStackTrace();
}
// ver line
try {
RE reVerLine = new RE(VLINE_GROUP + "+");
for (int c = 0; c < aa.getW(); c++) {
String col = aa.getColumn(c);
int startIndex = 0;
while (reVerLine.match(col, startIndex)) {
int mStart = reVerLine.getParenStart(0);
int mEnd = reVerLine.getParenEnd(0);
aacStart.setXY(c, mStart);
aacEnd.setXY(c, mEnd - 1);
AsciiArtLine aal = new AsciiArtLine(aacStart, aacEnd);
this.asciiArtPad.add(aal);
if (startIndex >= mEnd) {
break;
}
startIndex = mEnd;
}
}
} catch (RESyntaxException rese) {
rese.printStackTrace();
}
}
/**
* Find string text in the AsciiArt.
*/
protected void findStringPattern() {
AsciiArtCoordinate aacStart = new AsciiArtCoordinate(this.asciiArtPad);
aacStart.setTransXY(0, 3 * asciiArtPad.getYGrid() / 4);
// string
try {
final RE reString = new RE(STRING_PREFIX_GROUP + STRING_SUFFIX_GROUP + "*");
for (int r = 0; r < aa.getH(); r++) {
String row = aa.getRow(r);
int startIndex = 0;
while (reString.match(row, startIndex)) {
String s = reString.getParen(0);
int mStart = reString.getParenStart(0);
int mEnd = reString.getParenEnd(0);
aacStart.setXY(mStart, r);
AsciiArtString aas = new AsciiArtString(aacStart, s);
this.asciiArtPad.add(aas);
if (startIndex >= mEnd) {
break;
}
startIndex = mEnd;
}
}
} catch (RESyntaxException rese) {
rese.printStackTrace();
}
}
}
/**
* Marker interface of objects addable to the AsciiArtPad
*
*/
public static interface AsciiArtElement {
}
}
| apache-2.0 |
zhangminglei/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/legacy/ClusterConfigHandler.java | 3220 | /*
* 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.flink.runtime.rest.handler.legacy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.runtime.jobmaster.JobManagerGateway;
import org.apache.flink.runtime.rest.messages.ClusterConfigurationInfoEntry;
import org.apache.flink.runtime.rest.messages.ClusterConfigurationInfoHeaders;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonGenerator;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
/**
* Returns the Job Manager's configuration.
*/
public class ClusterConfigHandler extends AbstractJsonRequestHandler {
private final String clusterConfigJson;
public ClusterConfigHandler(Executor executor, Configuration config) {
super(executor);
Preconditions.checkNotNull(config);
this.clusterConfigJson = createConfigJson(config);
}
@Override
public String[] getPaths() {
return new String[]{ClusterConfigurationInfoHeaders.CLUSTER_CONFIG_REST_PATH};
}
@Override
public CompletableFuture<String> handleJsonRequest(
Map<String, String> pathParams,
Map<String, String> queryParams,
JobManagerGateway jobManagerGateway) {
return CompletableFuture.completedFuture(clusterConfigJson);
}
private static String createConfigJson(Configuration config) {
try {
StringWriter writer = new StringWriter();
JsonGenerator gen = JsonFactory.JACKSON_FACTORY.createGenerator(writer);
gen.writeStartArray();
for (String key : config.keySet()) {
gen.writeStartObject();
gen.writeStringField(ClusterConfigurationInfoEntry.FIELD_NAME_CONFIG_KEY, key);
String value = config.getString(key, null);
// Mask key values which contain sensitive information
if (value != null && GlobalConfiguration.isSensitive(key)) {
value = GlobalConfiguration.HIDDEN_CONTENT;
}
gen.writeStringField(ClusterConfigurationInfoEntry.FIELD_NAME_CONFIG_VALUE, value);
gen.writeEndObject();
}
gen.writeEndArray();
gen.close();
return writer.toString();
} catch (IOException e) {
throw new CompletionException(new FlinkException("Could not write configuration.", e));
}
}
}
| apache-2.0 |
racker/omnibus | source/db-5.0.26.NC/java/src/com/sleepycat/persist/impl/ReadOnlyCatalog.java | 2344 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2010 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
package com.sleepycat.persist.impl;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import com.sleepycat.persist.raw.RawObject;
/**
* Read-only catalog operations used when initializing new formats. This
* catalog is used temprarily when the main catalog has not been updated yet,
* but the new formats need to do catalog lookups.
*
* @see PersistCatalog#addNewFormat
*
* @author Mark Hayes
*/
class ReadOnlyCatalog implements Catalog {
private List<Format> formatList;
private Map<String,Format> formatMap;
ReadOnlyCatalog(List<Format> formatList, Map<String,Format> formatMap) {
this.formatList = formatList;
this.formatMap = formatMap;
}
public int getInitVersion(Format format, boolean forReader) {
return Catalog.CURRENT_VERSION;
}
public Format getFormat(int formatId) {
try {
Format format = formatList.get(formatId);
if (format == null) {
throw new IllegalStateException
("Format does not exist: " + formatId);
}
return format;
} catch (NoSuchElementException e) {
throw new IllegalStateException
("Format does not exist: " + formatId);
}
}
public Format getFormat(Class cls, boolean checkEntitySubclassIndexes) {
Format format = formatMap.get(cls.getName());
if (format == null) {
throw new IllegalArgumentException
("Class is not persistent: " + cls.getName());
}
return format;
}
public Format getFormat(String className) {
return formatMap.get(className);
}
public Format createFormat(String clsName, Map<String,Format> newFormats) {
throw new IllegalStateException();
}
public Format createFormat(Class type, Map<String,Format> newFormats) {
throw new IllegalStateException();
}
public boolean isRawAccess() {
return false;
}
public Object convertRawObject(RawObject o, IdentityHashMap converted) {
throw new IllegalStateException();
}
}
| apache-2.0 |
vipinraj/Spark | core/src/main/java/org/jivesoftware/spark/ui/StringTransferHandler.java | 2437 | /**
* Copyright (C) 2004-2011 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.spark.ui;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
/**
* Used for String Drag and Drop functionality.
*/
public abstract class StringTransferHandler extends TransferHandler {
private static final long serialVersionUID = 4783002180033288533L;
protected abstract String exportString(JComponent c);
protected abstract void importString(JComponent c, String str);
protected abstract void cleanup(JComponent c, boolean remove);
protected Transferable createTransferable(JComponent c) {
return new StringSelection(exportString(c));
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean importData(JComponent c, Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
try {
String str = (String)t.getTransferData(DataFlavor.stringFlavor);
importString(c, str);
return true;
}
catch (UnsupportedFlavorException ufe) {
// Nothing to do
}
catch (IOException ioe) {
// Nothing to do
}
}
return false;
}
protected void exportDone(JComponent c, Transferable data, int action) {
cleanup(c, action == MOVE);
}
public boolean canImport(JComponent c, DataFlavor[] flavors) {
for (DataFlavor flavor : flavors) {
if (DataFlavor.stringFlavor.equals(flavor)) {
return true;
}
}
return false;
}
} | apache-2.0 |
CodelightStudios/Android-Smart-Login | smartloginlibrary/src/main/java/studios/codelight/smartloginlibrary/SmartLogin.java | 526 | package studios.codelight.smartloginlibrary;
import android.content.Context;
import android.content.Intent;
/**
* Copyright (c) 2017 Codelight Studios
* Created by kalyandechiraju on 22/04/17.
*/
public abstract class SmartLogin {
public abstract void login(SmartLoginConfig config);
public abstract void signup(SmartLoginConfig config);
public abstract boolean logout(Context context);
public abstract void onActivityResult(int requestCode, int resultCode, Intent data, SmartLoginConfig config);
}
| apache-2.0 |
mattrjacobs/RxJava | rxjava-core/src/main/java/rx/internal/operators/OperatorMerge.java | 32152 | /**
* Copyright 2014 Netflix, 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 rx.internal.operators;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import rx.Observable;
import rx.Observable.Operator;
import rx.Producer;
import rx.Subscriber;
import rx.exceptions.CompositeException;
import rx.exceptions.MissingBackpressureException;
import rx.exceptions.OnErrorThrowable;
import rx.functions.Func1;
import rx.internal.util.RxRingBuffer;
import rx.internal.util.ScalarSynchronousObservable;
import rx.internal.util.SubscriptionIndexedRingBuffer;
/**
* Flattens a list of {@link Observable}s into one {@code Observable}, without any transformation.
* <p>
* <img width="640" height="380" src="https://raw.githubusercontent.com/wiki/Netflix/RxJava/images/rx-operators/merge.png" alt="">
* <p>
* You can combine the items emitted by multiple {@code Observable}s so that they act like a single {@code Observable}, by using the merge operation.
*
* @param <T>
* the type of the items emitted by both the source and merged {@code Observable}s
*/
public class OperatorMerge<T> implements Operator<T, Observable<? extends T>> {
/*
* benjchristensen => This class is complex and I'm not a fan of it despite writing it. I want to give some background
* as to why for anyone who wants to try and help improve it.
*
* One of my first implementations that added backpressure support (Producer.request) was fairly elegant and used a simple
* queue draining approach. It was simple to understand as all onNext were added to their queues, then a single winner
* would drain the queues, similar to observeOn. It killed the Netflix API when I canaried it. There were two problems:
* (1) performance and (2) object allocation overhead causing massive GC pressure. Remember that merge is one of the most
* used operators (mostly due to flatmap) and is therefore critical to and a limiter of performance in any application.
*
* All subsequent work on this class and the various fast-paths and branches within it have been to achieve the needed functionality
* while reducing or eliminating object allocation and keeping performance acceptable.
*
* This has meant adopting strategies such as:
*
* - ring buffers instead of growable queues
* - object pooling
* - skipping request logic when downstream does not need backpressure
* - ScalarValueQueue for optimizing synchronous single-value Observables
* - adopting data structures that use Unsafe (and gating them based on environment so non-Oracle JVMs still work)
*
* It has definitely increased the complexity and maintenance cost of this class, but the performance gains have been significant.
*
* The biggest cost of the increased complexity is concurrency bugs and reasoning through what's going on.
*
* I'd love to have contributions that improve this class, but keep in mind the performance and GC pressure.
* The benchmarks I use are in the JMH OperatorMergePerf class. GC memory pressure is tested using Java Flight Recorder
* to track object allocation.
*
* TODO There is still a known concurrency bug somewhere either in this class, in SubscriptionIndexedRingBuffer or their relationship.
* See https://github.com/Netflix/RxJava/issues/1420 for more information on this.
*/
public OperatorMerge() {
this.delayErrors = false;
}
public OperatorMerge(boolean delayErrors) {
this.delayErrors = delayErrors;
}
private final boolean delayErrors;
@Override
public Subscriber<Observable<? extends T>> call(final Subscriber<? super T> child) {
return new MergeSubscriber<T>(child, delayErrors);
}
private static final class MergeSubscriber<T> extends Subscriber<Observable<? extends T>> {
final NotificationLite<T> on = NotificationLite.instance();
final Subscriber<? super T> actual;
private final MergeProducer<T> mergeProducer;
private int wip;
private boolean completed;
private final boolean delayErrors;
private ConcurrentLinkedQueue<Throwable> exceptions;
private volatile SubscriptionIndexedRingBuffer<InnerSubscriber<T>> childrenSubscribers;
private RxRingBuffer scalarValueQueue = null;
/* protected by lock on MergeSubscriber instance */
private int missedEmitting = 0;
private boolean emitLock = false;
/**
* Using synchronized(this) for `emitLock` instead of ReentrantLock or AtomicInteger is faster when there is no contention.
*
* <pre> {@code
* Using ReentrantLock:
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 44185.294 1295.565 ops/s
*
* Using synchronized(this):
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 79715.981 3704.486 ops/s
*
* Still slower though than allowing concurrency:
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 149331.046 4851.290 ops/s
* } </pre>
*/
public MergeSubscriber(Subscriber<? super T> actual, boolean delayErrors) {
super(actual);
this.actual = actual;
this.mergeProducer = new MergeProducer<T>(this);
this.delayErrors = delayErrors;
// decoupled the subscription chain because we need to decouple and control backpressure
actual.add(this);
actual.setProducer(mergeProducer);
}
@Override
public void onStart() {
// we request backpressure so we can handle long-running Observables that are enqueueing, such as flatMap use cases
// we decouple the Producer chain while keeping the Subscription chain together (perf benefit) via super(actual)
request(RxRingBuffer.SIZE);
}
/*
* This is expected to be executed sequentially as per the Rx contract or it will not work.
*/
@Override
public void onNext(Observable<? extends T> t) {
if (t instanceof ScalarSynchronousObservable) {
handleScalarSynchronousObservable((ScalarSynchronousObservable)t);
} else {
if (t == null || isUnsubscribed()) {
return;
}
synchronized (this) {
// synchronized here because `wip` can be concurrently changed by children Observables
wip++;
}
handleNewSource(t);
}
}
private void handleNewSource(Observable<? extends T> t) {
if (childrenSubscribers == null) {
// lazily create this only if we receive Observables we need to subscribe to
childrenSubscribers = new SubscriptionIndexedRingBuffer<InnerSubscriber<T>>();
add(childrenSubscribers);
}
MergeProducer<T> producerIfNeeded = null;
// if we have received a request then we need to respect it, otherwise we fast-path
if (mergeProducer.requested != Long.MAX_VALUE) {
/**
* <pre> {@code
* With this optimization:
*
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 57100.080 4686.331 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 60.875 1.622 ops/s
*
* Without this optimization:
*
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 29863.945 1858.002 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 30.516 1.087 ops/s
* } </pre>
*/
producerIfNeeded = mergeProducer;
}
InnerSubscriber<T> i = new InnerSubscriber<T>(this, producerIfNeeded);
i.sindex = childrenSubscribers.add(i);
t.unsafeSubscribe(i);
request(1);
}
private void handleScalarSynchronousObservable(ScalarSynchronousObservable<? extends T> t) {
// fast-path for scalar, synchronous values such as Observable.from(int)
/**
* Without this optimization:
*
* <pre> {@code
* Benchmark (size) Mode Samples Score Score error Units
* r.o.OperatorMergePerf.oneStreamOfNthatMergesIn1 1 thrpt 5 2,418,452.409 130572.665 ops/s
* r.o.OperatorMergePerf.oneStreamOfNthatMergesIn1 1000 thrpt 5 5,690.456 94.958 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 takes too long
*
* With this optimization:
*
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1 thrpt 5 5,475,300.198 156741.334 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 68,932.278 1311.023 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 64.405 0.611 ops/s
* } </pre>
*
*/
if (mergeProducer.requested == Long.MAX_VALUE) {
handleScalarSynchronousObservableWithoutRequestLimits(t);
} else {
handleScalarSynchronousObservableWithRequestLimits(t);
}
}
private void handleScalarSynchronousObservableWithoutRequestLimits(ScalarSynchronousObservable<? extends T> t) {
T value = t.get();
if (getEmitLock()) {
try {
actual.onNext(value);
return;
} finally {
if (releaseEmitLock()) {
drainQueuesIfNeeded();
}
request(1);
}
} else {
initScalarValueQueueIfNeeded();
try {
scalarValueQueue.onNext(value);
} catch (MissingBackpressureException e) {
onError(e);
}
return;
}
}
private void handleScalarSynchronousObservableWithRequestLimits(ScalarSynchronousObservable<? extends T> t) {
if (getEmitLock()) {
boolean emitted = false;
try {
long r = mergeProducer.requested;
if (r > 0) {
emitted = true;
actual.onNext(t.get());
MergeProducer.REQUESTED.decrementAndGet(mergeProducer);
// we handle this Observable without ever incrementing the wip or touching other machinery so just return here
return;
}
} finally {
if (releaseEmitLock()) {
drainQueuesIfNeeded();
}
if (emitted) {
request(1);
}
}
}
// if we didn't return above we need to enqueue
// enqueue the values for later delivery
initScalarValueQueueIfNeeded();
try {
scalarValueQueue.onNext(t.get());
} catch (MissingBackpressureException e) {
onError(e);
}
}
private void initScalarValueQueueIfNeeded() {
if (scalarValueQueue == null) {
scalarValueQueue = RxRingBuffer.getSpmcInstance();
add(scalarValueQueue);
}
}
private synchronized boolean releaseEmitLock() {
emitLock = false;
if (missedEmitting == 0) {
return false;
} else {
return true;
}
}
private synchronized boolean getEmitLock() {
if (emitLock) {
missedEmitting++;
return false;
} else {
emitLock = true;
missedEmitting = 0;
return true;
}
}
private boolean drainQueuesIfNeeded() {
while (true) {
if (getEmitLock()) {
int emitted = 0;
try {
emitted = drainScalarValueQueue();
drainChildrenQueues();
} finally {
boolean moreToDrain = releaseEmitLock();
// request outside of lock
request(emitted);
if (!moreToDrain) {
return true;
}
// otherwise we'll loop and get whatever was added
}
} else {
return false;
}
}
}
int lastDrainedIndex = 0;
/**
* ONLY call when holding the EmitLock.
*/
private void drainChildrenQueues() {
if (childrenSubscribers != null) {
lastDrainedIndex = childrenSubscribers.forEach(DRAIN_ACTION, lastDrainedIndex);
}
}
/**
* ONLY call when holding the EmitLock.
*/
private int drainScalarValueQueue() {
if (scalarValueQueue != null) {
long r = mergeProducer.requested;
int emittedWhileDraining = 0;
if (r < 0) {
// drain it all
Object o = null;
while ((o = scalarValueQueue.poll()) != null) {
on.accept(actual, o);
emittedWhileDraining++;
}
} else if (r > 0) {
// drain what was requested
long toEmit = r;
for (int i = 0; i < toEmit; i++) {
Object o = scalarValueQueue.poll();
if (o == null) {
break;
} else {
on.accept(actual, o);
emittedWhileDraining++;
}
}
// decrement the number we emitted from outstanding requests
MergeProducer.REQUESTED.getAndAdd(mergeProducer, -emittedWhileDraining);
}
return emittedWhileDraining;
}
return 0;
}
final Func1<InnerSubscriber<T>, Boolean> DRAIN_ACTION = new Func1<InnerSubscriber<T>, Boolean>() {
@Override
public Boolean call(InnerSubscriber<T> s) {
if (s.q != null) {
long r = mergeProducer.requested;
int emitted = 0;
emitted += s.drainQueue();
if (emitted > 0) {
/*
* `s.emitted` is not volatile (because of performance impact of making it so shown by JMH tests)
* but `emitted` can ONLY be touched by the thread holding the `emitLock` which we're currently inside.
*
* Entering and leaving the emitLock flushes all values so this is visible to us.
*/
emitted += s.emitted;
// TODO we may want to store this in s.emitted and only request if above batch
// reset this since we have requested them all
s.emitted = 0;
s.requestMore(emitted);
}
if (emitted == r) {
// we emitted as many as were requested so stop the forEach loop
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
};
@Override
public void onError(Throwable e) {
if (delayErrors) {
synchronized (this) {
if (exceptions == null) {
exceptions = new ConcurrentLinkedQueue<Throwable>();
}
}
exceptions.add(e);
boolean sendOnComplete = false;
synchronized (this) {
wip--;
if (wip == 0 && completed) {
sendOnComplete = true;
}
}
if (sendOnComplete) {
drainAndComplete();
}
} else {
actual.onError(e);
}
}
@Override
public void onCompleted() {
boolean c = false;
synchronized (this) {
completed = true;
if (wip == 0) {
c = true;
}
}
if (c) {
// complete outside of lock
drainAndComplete();
}
}
void completeInner(InnerSubscriber<T> s) {
boolean sendOnComplete = false;
synchronized (this) {
wip--;
if (wip == 0 && completed) {
sendOnComplete = true;
}
}
childrenSubscribers.remove(s.sindex);
if (sendOnComplete) {
drainAndComplete();
}
}
private void drainAndComplete() {
drainQueuesIfNeeded(); // TODO need to confirm whether this is needed or not
if (delayErrors) {
Queue<Throwable> es = null;
synchronized (this) {
es = exceptions;
}
if (es != null) {
if (es.isEmpty()) {
actual.onCompleted();
} else if (es.size() == 1) {
actual.onError(es.poll());
} else {
actual.onError(new CompositeException(es));
}
} else {
actual.onCompleted();
}
} else {
actual.onCompleted();
}
}
}
private static final class MergeProducer<T> implements Producer {
private final MergeSubscriber<T> ms;
public MergeProducer(MergeSubscriber<T> ms) {
this.ms = ms;
}
private volatile long requested = 0;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<MergeProducer> REQUESTED = AtomicLongFieldUpdater.newUpdater(MergeProducer.class, "requested");
@Override
public void request(long n) {
if (requested == Long.MAX_VALUE) {
return;
}
if (n == Long.MAX_VALUE) {
requested = Long.MAX_VALUE;
} else {
REQUESTED.getAndAdd(this, n);
ms.drainQueuesIfNeeded();
}
}
}
private static final class InnerSubscriber<T> extends Subscriber<T> {
public int sindex;
final MergeSubscriber<T> parentSubscriber;
final MergeProducer<T> producer;
/** Make sure the inner termination events are delivered only once. */
volatile int terminated;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<InnerSubscriber> ONCE_TERMINATED = AtomicIntegerFieldUpdater.newUpdater(InnerSubscriber.class, "terminated");
private final RxRingBuffer q = RxRingBuffer.getSpmcInstance();
/* protected by emitLock */
int emitted = 0;
final int THRESHOLD = (int) (q.capacity() * 0.7);
public InnerSubscriber(MergeSubscriber<T> parent, MergeProducer<T> producer) {
this.parentSubscriber = parent;
this.producer = producer;
add(q);
request(q.capacity());
}
@Override
public void onNext(T t) {
emit(t, false);
}
@Override
public void onError(Throwable e) {
// it doesn't go through queues, it immediately onErrors and tears everything down
if (ONCE_TERMINATED.compareAndSet(this, 0, 1)) {
parentSubscriber.onError(e);
}
}
@Override
public void onCompleted() {
if (ONCE_TERMINATED.compareAndSet(this, 0, 1)) {
emit(null, true);
}
}
public void requestMore(long n) {
request(n);
}
private void emit(T t, boolean complete) {
boolean drain = false;
boolean enqueue = true;
/**
* This optimization to skip the queue is messy ... but it makes a big difference in performance when merging a single stream
* with many values, or many intermittent streams without contention. It doesn't make much of a difference if there is contention.
*
* Below are some of the relevant benchmarks to show the difference.
*
* <pre> {@code
* With this fast-path:
*
* Benchmark (size) Mode Samples Score Score error Units
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1 thrpt 5 5344143.680 393484.592 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 83582.662 4293.755 ops/s +++
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 73.889 4.477 ops/s +++
*
* r.o.OperatorMergePerf.mergeNSyncStreamsOfN 1 thrpt 5 5799265.333 199205.296 ops/s +
* r.o.OperatorMergePerf.mergeNSyncStreamsOfN 1000 thrpt 5 62.655 2.521 ops/s +++
*
* r.o.OperatorMergePerf.mergeTwoAsyncStreamsOfN 1 thrpt 5 76925.616 4909.174 ops/s
* r.o.OperatorMergePerf.mergeTwoAsyncStreamsOfN 1000 thrpt 5 3634.977 242.469 ops/s
*
* Without:
*
* Benchmark (size) Mode Samples Score Score error Units
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1 thrpt 5 5099295.678 159539.842 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 18196.671 10053.298 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 19.184 1.028 ops/s
*
* r.o.OperatorMergePerf.mergeNSyncStreamsOfN 1 thrpt 5 5591612.719 591821.763 ops/s
* r.o.OperatorMergePerf.mergeNSyncStreamsOfN 1000 thrpt 5 21.018 3.251 ops/s
*
* r.o.OperatorMergePerf.mergeTwoAsyncStreamsOfN 1 thrpt 5 72692.073 18395.031 ops/s
* r.o.OperatorMergePerf.mergeTwoAsyncStreamsOfN 1000 thrpt 5 4379.093 386.368 ops/s
* } </pre>
*
* It looks like it may cause a slowdown in highly contended cases (like 'mergeTwoAsyncStreamsOfN' above) as instead of just
* putting in the queue, it attempts to get the lock. We are optimizing for the non-contended case.
*/
if (parentSubscriber.getEmitLock()) {
enqueue = false;
try {
// drain the queue if there is anything in it before emitting the current value
emitted += drainQueue();
// }
if (producer == null) {
// no backpressure requested
if (complete) {
parentSubscriber.completeInner(this);
} else {
try {
parentSubscriber.actual.onNext(t);
} catch (Throwable e) {
// special error handling due to complexity of merge
onError(OnErrorThrowable.addValueAsLastCause(e, t));
}
emitted++;
}
} else {
// this needs to check q.count() as draining above may not have drained the full queue
// perf tests show this to be okay, though different queue implementations could perform poorly with this
if (producer.requested > 0 && q.count() == 0) {
if (complete) {
parentSubscriber.completeInner(this);
} else {
try {
parentSubscriber.actual.onNext(t);
} catch (Throwable e) {
// special error handling due to complexity of merge
onError(OnErrorThrowable.addValueAsLastCause(e, t));
}
emitted++;
MergeProducer.REQUESTED.decrementAndGet(producer);
}
} else {
// no requests available, so enqueue it
enqueue = true;
}
}
} finally {
drain = parentSubscriber.releaseEmitLock();
}
if (emitted > THRESHOLD) {
// this is for batching requests when we're in a use case that isn't queueing, always fast-pathing the onNext
/**
* <pre> {@code
* Without this batching:
*
* Benchmark (size) Mode Samples Score Score error Units
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1 thrpt 5 5060743.715 100445.513 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 36606.582 1610.582 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 38.476 0.973 ops/s
*
* With this batching:
*
* Benchmark (size) Mode Samples Score Score error Units
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1 thrpt 5 5367945.738 262740.137 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000 thrpt 5 62703.930 8496.036 ops/s
* r.o.OperatorMergePerf.merge1SyncStreamOfN 1000000 thrpt 5 72.711 3.746 ops/s
*} </pre>
*/
request(emitted);
// we are modifying this outside of the emit lock ... but this can be considered a "lazySet"
// and it will be flushed before anything else touches it because the emitLock will be obtained
// before any other usage of it
emitted = 0;
}
}
if (enqueue) {
enqueue(t, complete);
drain = true;
}
if (drain) {
/**
* This extra check for whether to call drain is ugly, but it helps:
* <pre> {@code
* Without:
* r.o.OperatorMergePerf.mergeNSyncStreamsOfN 1000 thrpt 5 61.812 1.455 ops/s
*
* With:
* r.o.OperatorMergePerf.mergeNSyncStreamsOfN 1000 thrpt 5 78.795 1.766 ops/s
* } </pre>
*/
parentSubscriber.drainQueuesIfNeeded();
}
}
private void enqueue(T t, boolean complete) {
try {
if (complete) {
q.onCompleted();
} else {
q.onNext(t);
}
} catch (MissingBackpressureException e) {
onError(e);
}
}
private int drainRequested() {
int emitted = 0;
// drain what was requested
long toEmit = producer.requested;
Object o;
for (int i = 0; i < toEmit; i++) {
o = q.poll();
if (o == null) {
// no more items
break;
} else if (q.isCompleted(o)) {
parentSubscriber.completeInner(this);
} else {
try {
if (!q.accept(o, parentSubscriber.actual)) {
emitted++;
}
} catch (Throwable e) {
// special error handling due to complexity of merge
onError(OnErrorThrowable.addValueAsLastCause(e, o));
}
}
}
// decrement the number we emitted from outstanding requests
MergeProducer.REQUESTED.getAndAdd(producer, -emitted);
return emitted;
}
private int drainAll() {
int emitted = 0;
// drain it all
Object o;
while ((o = q.poll()) != null) {
if (q.isCompleted(o)) {
parentSubscriber.completeInner(this);
} else {
try {
if (!q.accept(o, parentSubscriber.actual)) {
emitted++;
}
} catch (Throwable e) {
// special error handling due to complexity of merge
onError(OnErrorThrowable.addValueAsLastCause(e, o));
}
}
}
return emitted;
}
private int drainQueue() {
if (producer != null) {
return drainRequested();
} else {
return drainAll();
}
}
}
}
| apache-2.0 |
ezsimple/java | springboot/GMybatis/src/main/java/kr/grid/GMybatisApplication.java | 303 | package kr.grid;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(GMybatisApplication.class, args);
}
}
| apache-2.0 |
apioo/psx-api | tests/Generator/Client/resource/java_collection/EntryCollection.java | 280 | /**
* EntryCollection generated on 0000-00-00
* @see https://sdkgen.app
*/
public class EntryCollection {
private Entry[] entry;
public void setEntry(Entry[] entry) {
this.entry = entry;
}
public Entry[] getEntry() {
return this.entry;
}
}
| apache-2.0 |
B2M-Software/project-drahtlos-smg20 | analyzer.impl/src/main/java/org/fortiss/smg/analyzer/impl/calculations/dispersion/Minimum.java | 1040 | package org.fortiss.smg.analyzer.impl.calculations.dispersion;
import java.util.List;
import org.fortiss.smg.analyzer.impl.calculations.centralTendency.CalculationMethods;
import org.fortiss.smg.informationbroker.api.DoublePoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Ann Katrin Gibtner (annkatrin.gibtner@tum.de)
*
*/
public class Minimum extends CalculationMethods {
private final static Logger logger = LoggerFactory.getLogger(Minimum.class);
/**
* Returns the element of the list with the smallest value
*
* @param list
* all elements
* @return the smallest value
* @throws IllegalArgumentException
* if {@code list} is null or empty
*/
@Override
public Double calculate(List<DoublePoint> list)
throws IllegalArgumentException {
CalculationMethods.sort(list);
if (list == null || list.isEmpty()) {
logger.warn("no points available");
throw new IllegalArgumentException("list is null or empty");
}
return list.get(0).getValue();
}
}
| apache-2.0 |
tlkzzz/xpjfx | src/main/java/com/tlkzzz/jeesite/common/utils/EhCacheUtils.java | 2032 | /**
* Copyright © 2012-2016 <a href="https://github.com/tlkzzz/jeesite">JeeSite</a> All rights reserved.
*/
package com.tlkzzz.jeesite.common.utils;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* Cache工具类
* @author tlkzzz
* @version 2013-5-29
*/
public class EhCacheUtils {
private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));
private static final String SYS_CACHE = "sysCache";
/**
* 获取SYS_CACHE缓存
* @param key
* @return
*/
public static Object get(String key) {
return get(SYS_CACHE, key);
}
/**
* 写入SYS_CACHE缓存
* @param key
* @return
*/
public static void put(String key, Object value) {
put(SYS_CACHE, key, value);
}
/**
* 从SYS_CACHE缓存中移除
* @param key
* @return
*/
public static void remove(String key) {
remove(SYS_CACHE, key);
}
/**
* 获取缓存
* @param cacheName
* @param key
* @return
*/
public static Object get(String cacheName, String key) {
Element element = getCache(cacheName).get(key);
return element==null?null:element.getObjectValue();
}
/**
* 写入缓存
* @param cacheName
* @param key
* @param value
*/
public static void put(String cacheName, String key, Object value) {
Element element = new Element(key, value);
getCache(cacheName).put(element);
}
/**
* 从缓存中移除
* @param cacheName
* @param key
*/
public static void remove(String cacheName, String key) {
getCache(cacheName).remove(key);
}
/**
* 获得一个Cache,没有则创建一个。
* @param cacheName
* @return
*/
private static Cache getCache(String cacheName){
Cache cache = cacheManager.getCache(cacheName);
if (cache == null){
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
cache.getCacheConfiguration().setEternal(true);
}
return cache;
}
public static CacheManager getCacheManager() {
return cacheManager;
}
}
| apache-2.0 |
cuba-platform/cuba | modules/global/src/com/haulmont/cuba/security/auth/LocalizedCredentials.java | 1018 | /*
* Copyright (c) 2008-2017 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.haulmont.cuba.security.auth;
import java.util.Locale;
public interface LocalizedCredentials extends Credentials {
/**
* If passed locale should be used instead of locale of User.
*
* @return true if session should be created with passed locale.
*/
boolean isOverrideLocale();
/**
* Credentials locale
*
* @return locale
*/
Locale getLocale();
} | apache-2.0 |
codeaudit/graphene | graphene-parent/graphene-dao-es/src/main/java/graphene/dao/es/ESRestAPIConnectionImpl.java | 6681 | package graphene.dao.es;
import graphene.model.idl.G_SymbolConstants;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.Search.Builder;
import io.searchbox.core.SearchResult;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.slf4j.Logger;
public class ESRestAPIConnectionImpl implements ESRestAPIConnection {
public static final float DEFAULT_MIN_SCORE = 0.5f;
@Inject
private Logger logger;
@Inject
private JestClient client;
@Inject
@Symbol(JestModule.ES_SEARCH_INDEX)
private String indexName;
@Inject
@Symbol(JestModule.ES_DEFAULT_TIMEOUT)
private String defaultESTimeout;
@Inject
@Symbol(G_SymbolConstants.DEFAULT_MAX_SEARCH_RESULTS)
private Long maxSearchResults;
// private String createCleanUrl(@Nullable final String basicAuth, final
// String baseUrl) {
// if (basicAuth != null) {
// logger.debug("Auth information provided, using auth info.");
// final String cleanAuth = basicAuth.replaceAll("@", "%40");
// final String cleanURL = baseUrl.replace("http://", "http://" + cleanAuth
// + "@");
// return cleanURL;
// }
// logger.debug("No auth information provided, using without auth info.");
// return baseUrl;
// }
@Override
public void createIndex(final String indexName, final int shards, final int replicas) {
try {
if ((shards > 0) && (replicas > 0)) {
logger.debug("Creating index " + indexName + " with " + shards + "shard(s) and " + replicas
+ " replica(s).");
final ImmutableSettings.Builder sb = ImmutableSettings.settingsBuilder();
sb.put("number_of_shards", shards);
sb.put("number_of_replicas", replicas);
client.execute(new CreateIndex.Builder(indexName).settings(sb.build().getAsMap())
.setParameter("timeout", defaultESTimeout).build());
} else {
logger.debug("Creating index " + indexName + " with default settings");
client.execute(new CreateIndex.Builder(indexName).setParameter("timeout", defaultESTimeout).build());
}
} catch (final Exception e) {
logger.error("createIndex " + e.getMessage());
}
}
@Override
public void createIndex(final String indexName, final String settings) {
try {
if (settings != null) {
logger.debug("Creating index " + indexName + " with settings " + settings);
client.execute(new CreateIndex.Builder(indexName).settings(
ImmutableSettings.builder().loadFromSource(settings)).build());
} else {
logger.debug("Creating index " + indexName + " with default settings");
client.execute(new CreateIndex.Builder(indexName).build());
}
} catch (final Exception e) {
logger.error("createIndex " + e.getMessage());
}
}
@Override
public void deleteIndex(final String indexName) throws Exception {
final DeleteIndex deleteIndex = new DeleteIndex.Builder(indexName).setParameter("timeout", defaultESTimeout)
.build();
client.execute(deleteIndex);
}
private String executeAction(final Builder sb) {
final Search action = sb.setParameter("timeout", defaultESTimeout).build();
logger.debug("Action:\n" + action.toString());
SearchResult result;
String resultString = null;
try {
result = client.execute(action);
if (result != null) {
resultString = result.getJsonString();
} else {
logger.error("Result string was null for action " + action.toString());
}
} catch (final Exception e) {
logger.error("executeAction " + e.getMessage());
}
return resultString;
}
/**
* @return the client
*/
@Override
public final JestClient getClient() {
return client;
}
@Override
public String getIndexName() {
return indexName;
}
// @Override
// public long performCount(@Nullable final String basicAuth, final String
// baseUrl, final String index,
// final String type, final String fieldName, final String term) throws
// DataAccessException {
// try {
// final io.searchbox.core.Count.Builder action = new Count.Builder()
// .setParameter("timeout", defaultESTimeout);
// if (ValidationUtils.isValid(term)) {
// final SearchSourceBuilder searchSourceBuilder = new
// SearchSourceBuilder();
//
// QueryBuilder qb;
// if (ValidationUtils.isValid(fieldName)) {
// qb = QueryBuilders.matchPhraseQuery(fieldName, term);
// } else {
// qb = QueryBuilders.matchPhraseQuery("_all", term);
// }
// final SearchSourceBuilder query = searchSourceBuilder.query(qb);
// action.query(query.toString());
// logger.debug(query.toString());
// }
// if (ValidationUtils.isValid(index)) {
// action.addIndex(index);
// logger.debug("index: " + index);
// }
// if (ValidationUtils.isValid(type)) {
// action.addType(type);
// logger.debug("type: " + type);
// }
//
// final CountResult result = client.execute(action.build());
// final long longCount = result.getCount().longValue();
// logger.debug("Found a count of: " + longCount);
// return longCount;
// } catch (final Exception e) {
// logger.error("performCount " + e.getMessage());
// throw new DataAccessException(
// "Could not connect to one of the external resources needed for your request: "
// + e.getMessage());
// }
// }
// @Override
// public String performQuery(final String basicAuth, final String baseurl,
// final G_EntityQuery q)
// throws DataAccessException {
//
// final String retval = null;
//
// return retval;
// }
//
// @Override
// public String performQuery(@Nullable final String basicAuth, final String
// baseurl, final String index,
// final String type, final String fieldName, final String term, final long
// from, final long size)
// throws DataAccessException {
// try {
// final SearchSourceBuilder = new SearchSourceBuilder();
// final QueryBuilder qb = QueryBuilders.matchQuery(fieldName, term);
// searchSourceBuilder.query(qb);
// final Builder sb = new
// Search.Builder(searchSourceBuilder.toString()).addIndex(index)
// .setParameter("timeout", defaultESTimeout).setParameter("from",
// from).setParameter("size", size);
// return executeAction(sb);
// } catch (final Exception e) {
// logger.error("performQuery " + e.getMessage());
// throw new DataAccessException(
// "Could not connect to one of the external resources needed for your request: "
// + e.getMessage());
// }
// }
/**
* @param client
* the client to set
*/
public final void setClient(final JestClient client) {
this.client = client;
}
@Override
public void setIndexName(final String indexName) {
this.indexName = indexName;
}
}
| apache-2.0 |
MOHAMED-OKASHA/bari3 | Arduino-master-Customized/app/src/processing/app/syntax/TextAreaPainter.java | 22813 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* TextAreaPainter.java - Paints the text area
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
package processing.app.syntax;
import processing.app.*;
import processing.app.syntax.im.CompositionTextPainter;
import javax.swing.ToolTipManager;
import javax.swing.text.*;
import javax.swing.JComponent;
import java.awt.event.MouseEvent;
import java.awt.*;
import java.awt.print.*;
/**
* The text area repaint manager. It performs double buffering and paints
* lines of text.
* @author Slava Pestov
*/
public class TextAreaPainter extends JComponent
implements TabExpander, Printable
{
/** True if inside printing, will handle disabling the highlight */
boolean printing;
/** Current setting for editor.antialias preference */
boolean antialias;
/** A specific painter composed by the InputMethod.*/
protected CompositionTextPainter compositionTextPainter;
/**
* Creates a new repaint manager. This should be not be called
* directly.
*/
public TextAreaPainter(JEditTextArea textArea, TextAreaDefaults defaults)
{
this.textArea = textArea;
setAutoscrolls(true);
setDoubleBuffered(true);
setOpaque(true);
ToolTipManager.sharedInstance().registerComponent(this);
currentLine = new Segment();
currentLineIndex = -1;
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
setFont(defaults.font);
setForeground(defaults.fgcolor);
setBackground(defaults.bgcolor);
antialias = Preferences.getBoolean("editor.antialias");
blockCaret = defaults.blockCaret;
styles = defaults.styles;
cols = defaults.cols;
rows = defaults.rows;
caretColor = defaults.caretColor;
selectionColor = defaults.selectionColor;
lineHighlightColor = defaults.lineHighlightColor;
lineHighlight = defaults.lineHighlight;
bracketHighlightColor = defaults.bracketHighlightColor;
bracketHighlight = defaults.bracketHighlight;
paintInvalid = defaults.paintInvalid;
eolMarkerColor = defaults.eolMarkerColor;
eolMarkers = defaults.eolMarkers;
}
/**
* Get CompositionTextPainter. if CompositionTextPainter is not created, create it.
*/
public CompositionTextPainter getCompositionTextpainter(){
if(compositionTextPainter == null){
compositionTextPainter = new CompositionTextPainter(textArea);
}
return compositionTextPainter;
}
/**
* Returns if this component can be traversed by pressing the
* Tab key. This returns false.
*/
// public final boolean isManagingFocus()
// {
// return false;
// }
/**
* Returns the syntax styles used to paint colorized text. Entry <i>n</i>
* will be used to paint tokens with id = <i>n</i>.
* @see processing.app.syntax.Token
*/
public final SyntaxStyle[] getStyles()
{
return styles;
}
/**
* Sets the syntax styles used to paint colorized text. Entry <i>n</i>
* will be used to paint tokens with id = <i>n</i>.
* @param styles The syntax styles
* @see processing.app.syntax.Token
*/
public final void setStyles(SyntaxStyle[] styles)
{
this.styles = styles;
repaint();
}
/**
* Returns the caret color.
*/
public final Color getCaretColor()
{
return caretColor;
}
/**
* Sets the caret color.
* @param caretColor The caret color
*/
public final void setCaretColor(Color caretColor)
{
this.caretColor = caretColor;
invalidateSelectedLines();
}
/**
* Returns the selection color.
*/
public final Color getSelectionColor()
{
return selectionColor;
}
/**
* Sets the selection color.
* @param selectionColor The selection color
*/
public final void setSelectionColor(Color selectionColor)
{
this.selectionColor = selectionColor;
invalidateSelectedLines();
}
/**
* Returns the line highlight color.
*/
public final Color getLineHighlightColor()
{
return lineHighlightColor;
}
/**
* Sets the line highlight color.
* @param lineHighlightColor The line highlight color
*/
public final void setLineHighlightColor(Color lineHighlightColor)
{
this.lineHighlightColor = lineHighlightColor;
invalidateSelectedLines();
}
/**
* Returns true if line highlight is enabled, false otherwise.
*/
public final boolean isLineHighlightEnabled()
{
return lineHighlight;
}
/**
* Enables or disables current line highlighting.
* @param lineHighlight True if current line highlight
* should be enabled, false otherwise
*/
public final void setLineHighlightEnabled(boolean lineHighlight)
{
this.lineHighlight = lineHighlight;
invalidateSelectedLines();
}
/**
* Returns the bracket highlight color.
*/
public final Color getBracketHighlightColor()
{
return bracketHighlightColor;
}
/**
* Sets the bracket highlight color.
* @param bracketHighlightColor The bracket highlight color
*/
public final void setBracketHighlightColor(Color bracketHighlightColor)
{
this.bracketHighlightColor = bracketHighlightColor;
invalidateLine(textArea.getBracketLine());
}
/**
* Returns true if bracket highlighting is enabled, false otherwise.
* When bracket highlighting is enabled, the bracket matching the
* one before the caret (if any) is highlighted.
*/
public final boolean isBracketHighlightEnabled()
{
return bracketHighlight;
}
/**
* Enables or disables bracket highlighting.
* When bracket highlighting is enabled, the bracket matching the
* one before the caret (if any) is highlighted.
* @param bracketHighlight True if bracket highlighting should be
* enabled, false otherwise
*/
public final void setBracketHighlightEnabled(boolean bracketHighlight)
{
this.bracketHighlight = bracketHighlight;
invalidateLine(textArea.getBracketLine());
}
/**
* Returns true if the caret should be drawn as a block, false otherwise.
*/
public final boolean isBlockCaretEnabled()
{
return blockCaret;
}
/**
* Sets if the caret should be drawn as a block, false otherwise.
* @param blockCaret True if the caret should be drawn as a block,
* false otherwise.
*/
public final void setBlockCaretEnabled(boolean blockCaret)
{
this.blockCaret = blockCaret;
invalidateSelectedLines();
}
/**
* Returns the EOL marker color.
*/
public final Color getEOLMarkerColor()
{
return eolMarkerColor;
}
/**
* Sets the EOL marker color.
* @param eolMarkerColor The EOL marker color
*/
public final void setEOLMarkerColor(Color eolMarkerColor)
{
this.eolMarkerColor = eolMarkerColor;
repaint();
}
/**
* Returns true if EOL markers are drawn, false otherwise.
*/
public final boolean getEOLMarkersPainted()
{
return eolMarkers;
}
/**
* Sets if EOL markers are to be drawn.
* @param eolMarkers True if EOL markers should be drawn, false otherwise
*/
public final void setEOLMarkersPainted(boolean eolMarkers)
{
this.eolMarkers = eolMarkers;
repaint();
}
/**
* Returns true if invalid lines are painted as red tildes (~),
* false otherwise.
*/
public boolean getInvalidLinesPainted()
{
return paintInvalid;
}
/**
* Sets if invalid lines are to be painted as red tildes.
* @param paintInvalid True if invalid lines should be drawn, false otherwise
*/
public void setInvalidLinesPainted(boolean paintInvalid)
{
this.paintInvalid = paintInvalid;
}
/**
* Adds a custom highlight painter.
* @param highlight The highlight
*/
public void addCustomHighlight(Highlight highlight)
{
highlight.init(textArea,highlights);
highlights = highlight;
}
/**
* Highlight interface.
*/
public interface Highlight
{
/**
* Called after the highlight painter has been added.
* @param textArea The text area
* @param next The painter this one should delegate to
*/
void init(JEditTextArea textArea, Highlight next);
/**
* This should paint the highlight and delgate to the
* next highlight painter.
* @param gfx The graphics context
* @param line The line number
* @param y The y co-ordinate of the line
*/
void paintHighlight(Graphics gfx, int line, int y);
/**
* Returns the tool tip to display at the specified
* location. If this highlighter doesn't know what to
* display, it should delegate to the next highlight
* painter.
* @param evt The mouse event
*/
String getToolTipText(MouseEvent evt);
}
/**
* Returns the tool tip to display at the specified location.
* @param evt The mouse event
*/
public String getToolTipText(MouseEvent evt)
{
if(highlights != null)
return highlights.getToolTipText(evt);
else
return null;
}
/**
* Returns the font metrics used by this component.
*/
public FontMetrics getFontMetrics()
{
return fm;
}
/**
* Sets the font for this component. This is overridden to update the
* cached font metrics and to recalculate which lines are visible.
* @param font The font
*/
public void setFont(Font font)
{
super.setFont(font);
fm = super.getFontMetrics(font);
textArea.recalculateVisibleLines();
}
/**
* Repaints the text.
* @param gfx The graphics context
*/
public void paint(Graphics gfx)
{
Graphics2D g2 = (Graphics2D) gfx;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
antialias ?
RenderingHints.VALUE_TEXT_ANTIALIAS_ON :
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
tabSize = fm.charWidth(' ') * ((Integer)textArea.getDocument().getProperty(PlainDocument.tabSizeAttribute)).intValue();
Rectangle clipRect = gfx.getClipBounds();
gfx.setColor(Color.pink);
gfx.fillRect(clipRect.x,clipRect.y,clipRect.width,clipRect.height);
// We don't use yToLine() here because that method doesn't
// return lines past the end of the document
int height = fm.getHeight();
int firstLine = textArea.getFirstLine();
int firstInvalid = firstLine + clipRect.y / height;
// Because the clipRect's height is usually an even multiple
// of the font height, we subtract 1 from it, otherwise one
// too many lines will always be painted.
int lastInvalid = firstLine + (clipRect.y + clipRect.height - 1) / height;
try {
TokenMarker tokenMarker = textArea.getDocument().getTokenMarker();
int x = textArea.getHorizontalOffset();
for (int line = firstInvalid; line <= lastInvalid; line++) {
paintLine(gfx,tokenMarker,line,textArea.getWidth()-textArea.getLineLength(line)*fm.charWidth(' '));
}
if (tokenMarker != null && tokenMarker.isNextLineRequested()) {
int h = clipRect.y + clipRect.height;
repaint(0,h,getWidth(),getHeight() - h);
}
} catch (Exception e) {
System.err.println("Error repainting line"
+ " range {" + firstInvalid + ","
+ lastInvalid + "}:");
e.printStackTrace();
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
int lineHeight = fm.getHeight();
int linesPerPage = (int) (pageFormat.getImageableHeight() / lineHeight);
int lineCount = textArea.getLineCount();
int lastPage = lineCount / linesPerPage;
if (pageIndex > lastPage) {
return NO_SUCH_PAGE;
} else {
Graphics2D g2d = (Graphics2D)g;
TokenMarker tokenMarker = textArea.getDocument().getTokenMarker();
int firstLine = pageIndex*linesPerPage;
g2d.translate(Math.max(54, pageFormat.getImageableX()),
pageFormat.getImageableY() - firstLine*lineHeight);
printing = true;
for (int line = firstLine; line < firstLine + linesPerPage; line++) {
paintLine(g2d, tokenMarker, line, 0);
}
printing = false;
return PAGE_EXISTS;
}
}
/**
* Marks a line as needing a repaint.
* @param line The line to invalidate
*/
public final void invalidateLine(int line)
{
repaint(0,textArea.lineToY(line) + fm.getMaxDescent() + fm.getLeading(),
getWidth(),fm.getHeight());
}
/**
* Marks a range of lines as needing a repaint.
* @param firstLine The first line to invalidate
* @param lastLine The last line to invalidate
*/
public final void invalidateLineRange(int firstLine, int lastLine)
{
repaint(0,textArea.lineToY(firstLine) +
fm.getMaxDescent() + fm.getLeading(),
getWidth(),(lastLine - firstLine + 1) * fm.getHeight());
}
/**
* Repaints the lines containing the selection.
*/
public final void invalidateSelectedLines()
{
invalidateLineRange(textArea.getSelectionStartLine(),
textArea.getSelectionStopLine());
}
/**
* Implementation of TabExpander interface. Returns next tab stop after
* a specified point.
* @param x The x co-ordinate
* @param tabOffset Ignored
* @return The next tab stop after <i>x</i>
*/
public float nextTabStop(float x, int tabOffset)
{
int offset = textArea.getHorizontalOffset();
int ntabs = ((int)x - offset) / tabSize;
return (ntabs + 1) * tabSize + offset;
}
/**
* Returns the painter's preferred size.
*/
public Dimension getPreferredSize()
{
Dimension dim = new Dimension();
dim.width = fm.charWidth('w') * cols;
dim.height = fm.getHeight() * rows;
return dim;
}
/**
* Returns the painter's minimum size.
*/
public Dimension getMinimumSize()
{
Dimension dim = new Dimension();
dim.width = fm.charWidth('w') * 10;
dim.height = fm.getHeight() * 4;
return dim;
}
// package-private members
int currentLineIndex;
Token currentLineTokens;
Segment currentLine;
/**
* Accessor used by tools that want to hook in and grab the formatting.
*/
public int getCurrentLineIndex() {
return currentLineIndex;
}
/**
* Accessor used by tools that want to hook in and grab the formatting.
*/
public void setCurrentLineIndex(int what) {
currentLineIndex = what;
}
/**
* Accessor used by tools that want to hook in and grab the formatting.
*/
public Token getCurrentLineTokens() {
return currentLineTokens;
}
/**
* Accessor used by tools that want to hook in and grab the formatting.
*/
public void setCurrentLineTokens(Token tokens) {
currentLineTokens = tokens;
}
/**
* Accessor used by tools that want to hook in and grab the formatting.
*/
public Segment getCurrentLine() {
return currentLine;
}
// protected members
protected JEditTextArea textArea;
protected SyntaxStyle[] styles;
protected Color caretColor;
protected Color selectionColor;
protected Color lineHighlightColor;
protected Color bracketHighlightColor;
protected Color eolMarkerColor;
protected boolean blockCaret;
protected boolean lineHighlight;
protected boolean bracketHighlight;
protected boolean paintInvalid;
protected boolean eolMarkers;
protected int cols;
protected int rows;
protected int tabSize;
protected FontMetrics fm;
protected Highlight highlights;
protected void paintLine(Graphics gfx, TokenMarker tokenMarker,
int line, int x)
{
Font defaultFont = getFont();
Color defaultColor = getForeground();
currentLineIndex = line;
int y = textArea.lineToY(line);
if (line < 0 || line >= textArea.getLineCount()) {
if (paintInvalid) {
paintHighlight(gfx,line,y);
styles[Token.INVALID].setGraphicsFlags(gfx,defaultFont);
gfx.drawString("~",0,y + fm.getHeight());
}
} else if(tokenMarker == null) {
paintPlainLine(gfx,line,defaultFont,defaultColor,x,y);
} else {
paintSyntaxLine(gfx,tokenMarker,line,defaultFont,
defaultColor,x,y);
}
}
protected void paintPlainLine(Graphics gfx, int line, Font defaultFont,
Color defaultColor, int x, int y)
{
paintHighlight(gfx,line,y);
textArea.getLineText(line,currentLine);
gfx.setFont(defaultFont);
gfx.setColor(defaultColor);
y += fm.getHeight();
x = Utilities.drawTabbedText(currentLine,x,y,gfx,this,0);
/*
* Draw characters via input method.
*/
if (compositionTextPainter != null && compositionTextPainter.hasComposedTextLayout()) {
compositionTextPainter.draw(gfx, lineHighlightColor);
}
if (eolMarkers) {
gfx.setColor(eolMarkerColor);
gfx.drawString(".",x,y);
}
}
protected void paintSyntaxLine(Graphics gfx, TokenMarker tokenMarker,
int line, Font defaultFont,
Color defaultColor, int x, int y)
{
textArea.getLineText(currentLineIndex,currentLine);
currentLineTokens = tokenMarker.markTokens(currentLine,
currentLineIndex);
paintHighlight(gfx,line,y);
gfx.setFont(defaultFont);
gfx.setColor(defaultColor);
y += fm.getHeight();
x = SyntaxUtilities.paintSyntaxLine(currentLine,
currentLineTokens,
styles, this, gfx, x, y);
/*
* Draw characters via input method.
*/
if (compositionTextPainter != null && compositionTextPainter.hasComposedTextLayout()) {
compositionTextPainter.draw(gfx, lineHighlightColor);
}
if (eolMarkers) {
gfx.setColor(eolMarkerColor);
gfx.drawString(".",x,y);
}
}
protected void paintHighlight(Graphics gfx, int line, int y)
{
if (!printing) {
if (line >= textArea.getSelectionStartLine()
&& line <= textArea.getSelectionStopLine())
paintLineHighlight(gfx,line,y);
if (highlights != null)
highlights.paintHighlight(gfx,line,y);
if (bracketHighlight && line == textArea.getBracketLine())
paintBracketHighlight(gfx,line,y);
if (line == textArea.getCaretLine())
paintCaret(gfx,line,y);
}
}
protected void paintLineHighlight(Graphics gfx, int line, int y)
{
int height = fm.getHeight();
y += fm.getLeading() + fm.getMaxDescent();
int selectionStart = textArea.getSelectionStart();
int selectionEnd = textArea.getSelectionStop();
if (selectionStart == selectionEnd) {
if (lineHighlight) {
gfx.setColor(lineHighlightColor);
gfx.fillRect(0,y,getWidth(),height);
}
} else {
gfx.setColor(selectionColor);
int selectionStartLine = textArea.getSelectionStartLine();
int selectionEndLine = textArea.getSelectionStopLine();
int lineStart = textArea.getLineStartOffset(line);
int x1, x2;
if (textArea.isSelectionRectangular()) {
int lineLen = textArea.getLineLength(line);
x1 = textArea._offsetToX(line,Math.min(lineLen, selectionStart - textArea.getLineStartOffset(selectionStartLine)));
x2 = textArea._offsetToX(line,Math.min(lineLen, selectionEnd - textArea.getLineStartOffset(selectionEndLine)));
if (x1 == x2)
x2++;
} else if(selectionStartLine == selectionEndLine) {
x1 = textArea._offsetToX(line, selectionStart - lineStart);
x2 = textArea._offsetToX(line, selectionEnd - lineStart);
} else if(line == selectionStartLine) {
x1 = textArea._offsetToX(line, selectionStart - lineStart);
x2 = getWidth();
} else if(line == selectionEndLine) {
//x1 = 0;
// hack from stendahl to avoid doing weird side selection thing
x1 = textArea._offsetToX(line, 0);
// attempt at getting the gutter too, but doesn't seem to work
//x1 = textArea._offsetToX(line, -textArea.getHorizontalOffset());
x2 = textArea._offsetToX(line, selectionEnd - lineStart);
} else {
//x1 = 0;
// hack from stendahl to avoid doing weird side selection thing
x1 = textArea._offsetToX(line, 0);
// attempt at getting the gutter too, but doesn't seem to work
//x1 = textArea._offsetToX(line, -textArea.getHorizontalOffset());
x2 = getWidth();
}
// "inlined" min/max()
gfx.fillRect(x1 > x2 ? x2 : x1,y,x1 > x2 ?
(x1 - x2) : (x2 - x1),height);
}
}
protected void paintBracketHighlight(Graphics gfx, int line, int y)
{
int position = textArea.getBracketPosition();
if(position == -1)
return;
y += fm.getLeading() + fm.getMaxDescent();
int x = textArea._offsetToX(line,position);
gfx.setColor(bracketHighlightColor);
// Hack!!! Since there is no fast way to get the character
// from the bracket matching routine, we use ( since all
// brackets probably have the same width anyway
gfx.drawRect(x,y,fm.charWidth('(') - 1,
fm.getHeight() - 1);
}
protected void paintCaret(Graphics gfx, int line, int y)
{
//System.out.println("painting caret " + line + " " + y);
if (textArea.isCaretVisible()) {
//System.out.println("caret is visible");
int offset = textArea.getCaretPosition() - textArea.getLineStartOffset(line);
int shift = textArea.getWidth()-textArea.getLineLength(line)*fm.charWidth('w');
int caretX = textArea._offsetToX(line, offset);
// if (caretX-shift/2 <=0)
//caretX=textArea.getWidth()-caretX-shift/2;
int caretWidth = ((blockCaret ||
textArea.isOverwriteEnabled()) ?
fm.charWidth('w') : 1);
y += fm.getLeading() + fm.getMaxDescent();
int height = fm.getHeight();
//System.out.println("caretX, width = " + caretX + " " + caretWidth);
gfx.setColor(caretColor);
if (textArea.isOverwriteEnabled()) {
gfx.fillRect(caretX,y + height - 1, caretWidth,1);
} else {
// some machines don't like the drawRect for the single
// pixel caret.. this caused a lot of hell because on that
// minority of machines, the caret wouldn't show up past
// the first column. the fix is to use drawLine() in
// those cases, as a workaround.
if (caretWidth == 1) {
gfx.drawLine(caretX, y, caretX, y + height - 1);
} else {
gfx.drawRect(caretX, y, caretWidth - 1, height - 1);
}
//gfx.drawRect(caretX, y, caretWidth, height - 1);
}
}
}
}
| apache-2.0 |
4treesCH/strolch | li.strolch.agent/src/main/java/li/strolch/persistence/api/UpdateResourceCommand.java | 2155 | /*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.api;
import java.text.MessageFormat;
import li.strolch.agent.api.ResourceMap;
import li.strolch.exception.StrolchException;
import li.strolch.model.Resource;
import li.strolch.service.api.Command;
import li.strolch.utils.dbc.DBC;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class UpdateResourceCommand extends Command {
private Resource resource;
private Resource replaced;
private boolean updated;
/**
* @param tx
*/
public UpdateResourceCommand(StrolchTransaction tx) {
super(tx);
}
/**
* @param resource
* the resource to set
*/
public void setResource(Resource resource) {
this.resource = resource;
}
@Override
public void validate() {
DBC.PRE.assertNotNull("Resource may not be null!", this.resource);
}
@Override
public void doCommand() {
tx().lock(this.resource);
ResourceMap resourceMap = tx().getResourceMap();
this.replaced = resourceMap.getBy(tx(), this.resource.getType(), this.resource.getId());
if (this.replaced == null) {
String msg = "The Resource {0} can not be updated as it does not exist!!";
msg = MessageFormat.format(msg, this.resource.getLocator());
throw new StrolchException(msg);
}
resourceMap.update(tx(), this.resource);
this.updated = true;
}
@Override
public void undo() {
if (this.updated && tx().isRollingBack()) {
if (tx().isVersioningEnabled())
tx().getResourceMap().undoVersion(tx(), this.resource);
else
tx().getResourceMap().update(tx(), this.replaced);
}
}
}
| apache-2.0 |
zhou-jg/tefler | person.zhoujg.feature/src-gen/person/zhoujg/feature/Feature.java | 5879 | /**
*/
package person.zhoujg.feature;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Feature</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link person.zhoujg.feature.Feature#getName <em>Name</em>}</li>
* <li>{@link person.zhoujg.feature.Feature#getInCard <em>In Card</em>}</li>
* <li>{@link person.zhoujg.feature.Feature#getBody <em>Body</em>}</li>
* <li>{@link person.zhoujg.feature.Feature#getOutCard <em>Out Card</em>}</li>
* <li>{@link person.zhoujg.feature.Feature#getRef <em>Ref</em>}</li>
* <li>{@link person.zhoujg.feature.Feature#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @see person.zhoujg.feature.FeaturePackage#getFeature()
* @model
* @generated
*/
public interface Feature extends EObject
{
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see person.zhoujg.feature.FeaturePackage#getFeature_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link person.zhoujg.feature.Feature#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>In Card</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>In Card</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>In Card</em>' attribute.
* @see #setInCard(String)
* @see person.zhoujg.feature.FeaturePackage#getFeature_InCard()
* @model
* @generated
*/
String getInCard();
/**
* Sets the value of the '{@link person.zhoujg.feature.Feature#getInCard <em>In Card</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>In Card</em>' attribute.
* @see #getInCard()
* @generated
*/
void setInCard(String value);
/**
* Returns the value of the '<em><b>Body</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Body</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Body</em>' containment reference.
* @see #setBody(FeatureBody)
* @see person.zhoujg.feature.FeaturePackage#getFeature_Body()
* @model containment="true"
* @generated
*/
FeatureBody getBody();
/**
* Sets the value of the '{@link person.zhoujg.feature.Feature#getBody <em>Body</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Body</em>' containment reference.
* @see #getBody()
* @generated
*/
void setBody(FeatureBody value);
/**
* Returns the value of the '<em><b>Out Card</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Out Card</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Out Card</em>' attribute.
* @see #setOutCard(String)
* @see person.zhoujg.feature.FeaturePackage#getFeature_OutCard()
* @model
* @generated
*/
String getOutCard();
/**
* Sets the value of the '{@link person.zhoujg.feature.Feature#getOutCard <em>Out Card</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Out Card</em>' attribute.
* @see #getOutCard()
* @generated
*/
void setOutCard(String value);
/**
* Returns the value of the '<em><b>Ref</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Ref</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Ref</em>' reference.
* @see #setRef(Feature)
* @see person.zhoujg.feature.FeaturePackage#getFeature_Ref()
* @model
* @generated
*/
Feature getRef();
/**
* Sets the value of the '{@link person.zhoujg.feature.Feature#getRef <em>Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Ref</em>' reference.
* @see #getRef()
* @generated
*/
void setRef(Feature value);
/**
* Returns the value of the '<em><b>Type</b></em>' attribute.
* The literals are from the enumeration {@link person.zhoujg.feature.AttributeType}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute.
* @see person.zhoujg.feature.AttributeType
* @see #setType(AttributeType)
* @see person.zhoujg.feature.FeaturePackage#getFeature_Type()
* @model
* @generated
*/
AttributeType getType();
/**
* Sets the value of the '{@link person.zhoujg.feature.Feature#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' attribute.
* @see person.zhoujg.feature.AttributeType
* @see #getType()
* @generated
*/
void setType(AttributeType value);
} // Feature
| apache-2.0 |
monetate/closure-compiler | src/com/google/javascript/jscomp/TypeTransformation.java | 30586 | /*
* Copyright 2014 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.jscomp.parsing.TypeTransformationParser;
import com.google.javascript.jscomp.parsing.TypeTransformationParser.Keywords;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.StaticTypedScope;
import com.google.javascript.rhino.jstype.StaticTypedSlot;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A class for processing type transformation expressions
*/
class TypeTransformation {
private static final String VIRTUAL_FILE = "<TypeTransformation.java>";
static final DiagnosticType UNKNOWN_TYPEVAR =
DiagnosticType.warning("TYPEVAR_UNDEFINED",
"Reference to an unknown type variable {0}");
static final DiagnosticType UNKNOWN_STRVAR =
DiagnosticType.warning("UNKNOWN_STRVAR",
"Reference to an unknown string variable {0}");
static final DiagnosticType UNKNOWN_TYPENAME =
DiagnosticType.warning("TYPENAME_UNDEFINED",
"Reference to an unknown type name {0}");
static final DiagnosticType BASETYPE_INVALID =
DiagnosticType.warning("BASETYPE_INVALID",
"The type {0} cannot be templatized");
static final DiagnosticType TEMPTYPE_INVALID =
DiagnosticType.warning("TEMPTYPE_INVALID",
"Expected templatized type in {0} found {1}");
static final DiagnosticType INDEX_OUTOFBOUNDS =
DiagnosticType.warning("INDEX_OUTOFBOUNDS",
"Index out of bounds in templateTypeOf: expected a number less than {0}, found {1}");
static final DiagnosticType DUPLICATE_VARIABLE =
DiagnosticType.warning("DUPLICATE_VARIABLE",
"The variable {0} is already defined");
// This warning is never exercised.
static final DiagnosticType UNKNOWN_NAMEVAR =
DiagnosticType.warning("UNKNOWN_NAMEVAR",
"Reference to an unknown name variable {0}");
static final DiagnosticType RECTYPE_INVALID =
DiagnosticType.warning("RECTYPE_INVALID",
"The first parameter of a maprecord must be a record type, "
+ "found {0}");
static final DiagnosticType MAPRECORD_BODY_INVALID =
DiagnosticType.warning("MAPRECORD_BODY_INVALID",
"The body of a maprecord function must evaluate to a record type or "
+ "a no type, found {0}");
static final DiagnosticType VAR_UNDEFINED =
DiagnosticType.warning("VAR_UNDEFINED",
"Variable {0} is undefined in the scope");
static final DiagnosticType INVALID_CTOR =
DiagnosticType.warning("INVALID_CTOR",
"Expected a constructor type, found {0}");
static final DiagnosticType RECPARAM_INVALID =
DiagnosticType.warning("RECPARAM_INVALID",
"Expected a record type, found {0}");
static final DiagnosticType PROPTYPE_INVALID =
DiagnosticType.warning("PROPTYPE_INVALID",
"Expected object type, found {0}");
private final AbstractCompiler compiler;
private final JSTypeRegistry registry;
private final StaticTypedScope typeEnv;
/**
* A helper class for holding the information about the type variables
* and the name variables in maprecord expressions
*/
private static class NameResolver {
final ImmutableMap<String, JSType> typeVars;
final ImmutableMap<String, String> nameVars;
NameResolver(ImmutableMap<String, JSType> typeVars, ImmutableMap<String, String> nameVars) {
this.typeVars = typeVars;
this.nameVars = nameVars;
}
}
@SuppressWarnings("unchecked")
TypeTransformation(AbstractCompiler compiler, StaticTypedScope typeEnv) {
this.compiler = compiler;
this.registry = compiler.getTypeRegistry();
this.typeEnv = typeEnv;
}
private boolean isTypeVar(Node n) {
return n.isName();
}
private boolean isTypeName(Node n) {
return n.isStringLit();
}
private boolean isBooleanOperation(Node n) {
return n.isAnd() || n.isOr() || n.isNot();
}
private Keywords nameToKeyword(String s) {
return TypeTransformationParser.Keywords.valueOf(Ascii.toUpperCase(s));
}
private JSType getType(String typeName) {
JSType type = registry.getType(typeEnv, typeName);
if (type != null) {
return type;
}
StaticTypedSlot slot = typeEnv.getSlot(typeName);
type = slot != null ? slot.getType() : null;
if (type != null) {
if (type.isConstructor() || type.isInterface()) {
return type.toMaybeFunctionType().getInstanceType().getRawType();
}
if (type.isEnumElementType()) {
return type.getEnumeratedTypeOfEnumElement();
}
return type;
}
JSDocInfo jsdoc = slot == null ? null : slot.getJSDocInfo();
if (jsdoc != null && jsdoc.hasTypedefType()) {
return this.registry.evaluateTypeExpression(jsdoc.getTypedefType(), typeEnv);
}
return null;
}
private JSType getUnknownType() {
return registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE);
}
private JSType getNoType() {
return registry.getNativeObjectType(JSTypeNative.NO_TYPE);
}
private JSType getAllType() {
return registry.getNativeType(JSTypeNative.ALL_TYPE);
}
private JSType getObjectType() {
return registry.getNativeType(JSTypeNative.OBJECT_TYPE);
}
private JSType createUnionType(JSType[] variants) {
return registry.createUnionType(variants);
}
private JSType createRecordType(ImmutableMap<String, JSType> props) {
return this.registry.createRecordType(props);
}
private void reportWarning(Node n, DiagnosticType msg, String... param) {
compiler.report(JSError.make(n, msg, param));
}
private <T> ImmutableMap<String, T> addNewEntry(
ImmutableMap<String, T> map, String name, T type) {
return new ImmutableMap.Builder<String, T>().putAll(map).put(name, type).buildOrThrow();
}
private String getFunctionParameter(Node n, int i) {
Preconditions.checkArgument(n.isFunction(), "Expected a function node, found %s", n);
return n.getSecondChild().getChildAtIndex(i).getString();
}
private String getCallName(Node n) {
Preconditions.checkArgument(n.isCall(), "Expected a call node, found %s", n);
return n.getFirstChild().getString();
}
private Node getCallArgument(Node n, int i) {
Preconditions.checkArgument(n.isCall(), "Expected a call node, found %s", n);
return n.getChildAtIndex(i + 1);
}
private int getCallParamCount(Node n) {
Preconditions.checkArgument(n.isCall(), "Expected a call node, found %s", n);
return n.getChildCount() - 1;
}
// TODO(dimvar): rewrite the uses of this method to use siblings() and delete it.
// Copying is unnecessarily inefficient.
private ImmutableList<Node> getCallParams(Node n) {
Preconditions.checkArgument(n.isCall(), "Expected a call node, found %s", n);
ImmutableList.Builder<Node> builder = new ImmutableList.Builder<>();
for (int i = 0; i < getCallParamCount(n); i++) {
builder.add(getCallArgument(n, i));
}
return builder.build();
}
private Node getComputedPropValue(Node n) {
Preconditions.checkArgument(
n.isComputedProp(), "Expected a computed property node, found %s", n);
return n.getSecondChild();
}
private String getComputedPropName(Node n) {
Preconditions.checkArgument(
n.isComputedProp(), "Expected a computed property node, found %s", n);
return n.getFirstChild().getString();
}
/** Evaluates the type transformation expression and returns the resulting type.
*
* @param ttlAst The node representing the type transformation expression
* @param typeVars The environment containing the information about the type variables
* @return JSType The resulting type after the transformation
*/
JSType eval(Node ttlAst, ImmutableMap<String, JSType> typeVars) {
return eval(ttlAst, typeVars, ImmutableMap.of());
}
/** Evaluates the type transformation expression and returns the resulting type.
*
* @param ttlAst The node representing the type transformation expression
* @param typeVars The environment containing the information about the type variables
* @param nameVars The environment containing the information about the name variables
* @return JSType The resulting type after the transformation
*/
@SuppressWarnings("unchecked")
@VisibleForTesting
JSType eval(Node ttlAst, ImmutableMap<String, JSType> typeVars,
ImmutableMap<String, String> nameVars) {
JSType result = evalInternal(ttlAst, new NameResolver(typeVars, nameVars));
return result.isEmptyType() ? getUnknownType() : result;
}
private JSType evalInternal(Node ttlAst, NameResolver nameResolver) {
if (isTypeName(ttlAst)) {
return evalTypeName(ttlAst);
}
if (isTypeVar(ttlAst)) {
return evalTypeVar(ttlAst, nameResolver);
}
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
switch (keyword.kind) {
case TYPE_CONSTRUCTOR:
return evalTypeExpression(ttlAst, nameResolver);
case OPERATION:
return evalOperationExpression(ttlAst, nameResolver);
default:
throw new IllegalStateException(
"Could not evaluate the type transformation expression");
}
}
private JSType evalOperationExpression(Node ttlAst, NameResolver nameResolver) {
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
switch (keyword) {
case COND:
return evalConditional(ttlAst, nameResolver);
case MAPUNION:
return evalMapunion(ttlAst, nameResolver);
case MAPRECORD:
return evalMaprecord(ttlAst, nameResolver);
case TYPEOFVAR:
return evalTypeOfVar(ttlAst);
case INSTANCEOF:
return evalInstanceOf(ttlAst, nameResolver);
case PRINTTYPE:
return evalPrintType(ttlAst, nameResolver);
case PROPTYPE:
return evalPropType(ttlAst, nameResolver);
default:
throw new IllegalStateException("Invalid type transformation operation");
}
}
private JSType evalTypeExpression(Node ttlAst, NameResolver nameResolver) {
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
switch (keyword) {
case TYPE:
return evalTemplatizedType(ttlAst, nameResolver);
case UNION:
return evalUnionType(ttlAst, nameResolver);
case NONE:
return getNoType();
case ALL:
return getAllType();
case UNKNOWN:
return getUnknownType();
case RAWTYPEOF:
return evalRawTypeOf(ttlAst, nameResolver);
case TEMPLATETYPEOF:
return evalTemplateTypeOf(ttlAst, nameResolver);
case RECORD:
return evalRecordType(ttlAst, nameResolver);
case TYPEEXPR:
return evalNativeTypeExpr(ttlAst);
default:
throw new IllegalStateException("Invalid type expression");
}
}
private JSType evalTypeName(Node ttlAst) {
String typeName = ttlAst.getString();
JSType resultingType = getType(typeName);
// If the type name is not defined then return UNKNOWN and report a warning
if (resultingType == null) {
reportWarning(ttlAst, UNKNOWN_TYPENAME, typeName);
return getUnknownType();
}
return resultingType;
}
private JSType evalTemplatizedType(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
JSType firstParam = evalInternal(params.get(0), nameResolver);
if (!firstParam.isRawTypeOfTemplatizedType()) {
reportWarning(ttlAst, BASETYPE_INVALID, firstParam.toString());
return getUnknownType();
}
// TODO(lpino): Check that the number of parameters correspond with the
// number of template types that the base type can take when creating
// a templatized type. For instance, if the base type is Array then there
// must be just one parameter.
JSType[] templatizedTypes = new JSType[params.size() - 1];
Arrays.setAll(templatizedTypes, i -> evalInternal(params.get(i + 1), nameResolver));
ObjectType baseType = firstParam.toMaybeObjectType();
return registry.createTemplatizedType(baseType, templatizedTypes);
}
private JSType evalTypeVar(Node ttlAst, NameResolver nameResolver) {
String typeVar = ttlAst.getString();
JSType resultingType = nameResolver.typeVars.get(typeVar);
// If the type variable is not defined then return UNKNOWN and report a warning
if (resultingType == null) {
reportWarning(ttlAst, UNKNOWN_TYPEVAR, typeVar);
return getUnknownType();
}
return resultingType;
}
private JSType evalUnionType(Node ttlAst, NameResolver nameResolver) {
// Get the parameters of the union
ImmutableList<Node> params = getCallParams(ttlAst);
int paramCount = params.size();
// Create an array of types after evaluating each parameter
JSType[] basicTypes = new JSType[paramCount];
for (int i = 0; i < paramCount; i++) {
basicTypes[i] = evalInternal(params.get(i), nameResolver);
}
return createUnionType(basicTypes);
}
private JSType[] evalTypeParams(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
int paramCount = params.size();
JSType[] result = new JSType[paramCount];
for (int i = 0; i < paramCount; i++) {
result[i] = evalInternal(params.get(i), nameResolver);
}
return result;
}
private String evalString(Node ttlAst, NameResolver nameResolver) {
if (ttlAst.isName()) {
// Return the empty string if the name variable cannot be resolved
if (!nameResolver.nameVars.containsKey(ttlAst.getString())) {
reportWarning(ttlAst, UNKNOWN_STRVAR, ttlAst.getString());
return "";
}
return nameResolver.nameVars.get(ttlAst.getString());
}
return ttlAst.getString();
}
private String[] evalStringParams(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
int paramCount = params.size();
String[] result = new String[paramCount];
for (int i = 0; i < paramCount; i++) {
result[i] = evalString(params.get(i), nameResolver);
}
return result;
}
private boolean evalTypePredicate(Node ttlAst, NameResolver nameResolver) {
JSType[] params = evalTypeParams(ttlAst, nameResolver);
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
JSType type = params[0];
switch (keyword) {
case EQ:
return type.equals(params[1]);
case SUB:
return type.isSubtypeOf(params[1]);
case ISCTOR:
return type.isConstructor();
case ISTEMPLATIZED:
return type.isTemplatizedType();
case ISRECORD:
return type.isRecordType();
case ISUNKNOWN:
return type.isUnknownType();
default:
throw new IllegalStateException(
"Invalid type predicate in the type transformation");
}
}
private boolean evalStringPredicate(Node ttlAst,
NameResolver nameResolver) {
String[] params = evalStringParams(ttlAst, nameResolver);
// If any of the parameters evaluates to the empty string then they were
// not resolved by the name resolver. In this case we always return false.
for (int i = 0; i < params.length; i++) {
if (params[i].isEmpty()) {
return false;
}
}
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
switch (keyword) {
case STREQ:
return params[0].equals(params[1]);
default:
throw new IllegalStateException(
"Invalid string predicate in the type transformation");
}
}
private boolean evalTypevarPredicate(Node ttlAst, NameResolver nameResolver) {
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
switch (keyword) {
case ISDEFINED:
return nameResolver.typeVars.containsKey(getCallArgument(ttlAst, 0).getString());
default:
throw new IllegalStateException(
"Invalid typevar predicate in the type transformation");
}
}
private boolean evalBooleanOperation(Node ttlAst, NameResolver nameResolver) {
boolean param0 = evalBoolean(ttlAst.getFirstChild(), nameResolver);
if (ttlAst.isNot()) {
return !param0;
}
if (ttlAst.isAnd()) {
return param0 && evalBoolean(ttlAst.getLastChild(), nameResolver);
}
if (ttlAst.isOr()) {
return param0 || evalBoolean(ttlAst.getLastChild(), nameResolver);
}
throw new IllegalStateException(
"Invalid boolean predicate in the type transformation");
}
private boolean evalBoolean(Node ttlAst, NameResolver nameResolver) {
if (isBooleanOperation(ttlAst)) {
return evalBooleanOperation(ttlAst, nameResolver);
}
String name = getCallName(ttlAst);
Keywords keyword = nameToKeyword(name);
switch (keyword.kind) {
case STRING_PREDICATE:
return evalStringPredicate(ttlAst, nameResolver);
case TYPE_PREDICATE:
return evalTypePredicate(ttlAst, nameResolver);
case TYPEVAR_PREDICATE:
return evalTypevarPredicate(ttlAst, nameResolver);
default:
throw new IllegalStateException(
"Invalid boolean predicate in the type transformation");
}
}
private JSType evalConditional(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
if (evalBoolean(params.get(0), nameResolver)) {
return evalInternal(params.get(1), nameResolver);
} else {
return evalInternal(params.get(2), nameResolver);
}
}
private JSType evalMapunion(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
Node unionParam = params.get(0);
Node mapFunction = params.get(1);
String paramName = getFunctionParameter(mapFunction, 0);
// The mapunion variable must not be defined in the environment
if (nameResolver.typeVars.containsKey(paramName)) {
reportWarning(ttlAst, DUPLICATE_VARIABLE, paramName);
return getUnknownType();
}
Node mapFunctionBody = NodeUtil.getFunctionBody(mapFunction);
JSType unionType = evalInternal(unionParam, nameResolver);
// If the first parameter does not correspond to a union type then
// consider it as a union with a single type and evaluate
if (!unionType.isUnionType()) {
NameResolver newNameResolver = new NameResolver(
addNewEntry(nameResolver.typeVars, paramName, unionType),
nameResolver.nameVars);
return evalInternal(mapFunctionBody, newNameResolver);
}
// Otherwise obtain the elements in the union type. Note that the block
// above guarantees the casting to be safe
Collection<JSType> unionElms = ImmutableList.copyOf(unionType.getUnionMembers());
// Evaluate the map function body using each element in the union type
int unionSize = unionElms.size();
JSType[] newUnionElms = new JSType[unionSize];
int i = 0;
for (JSType elm : unionElms) {
NameResolver newNameResolver = new NameResolver(
addNewEntry(nameResolver.typeVars, paramName, elm),
nameResolver.nameVars);
newUnionElms[i] = evalInternal(mapFunctionBody, newNameResolver);
i++;
}
return createUnionType(newUnionElms);
}
private JSType evalRawTypeOf(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
JSType type = evalInternal(params.get(0), nameResolver);
if (!type.isTemplatizedType()) {
reportWarning(ttlAst, TEMPTYPE_INVALID, "rawTypeOf", type.toString());
return getUnknownType();
}
return type.toMaybeObjectType().getRawType();
}
private JSType evalTemplateTypeOf(Node ttlAst, NameResolver nameResolver) {
ImmutableList<Node> params = getCallParams(ttlAst);
JSType type = evalInternal(params.get(0), nameResolver);
if (!type.isTemplatizedType()) {
reportWarning(ttlAst, TEMPTYPE_INVALID, "templateTypeOf", type.toString());
return getUnknownType();
}
int index = (int) params.get(1).getDouble();
ImmutableList<? extends JSType> templateTypes = type.toMaybeObjectType().getTemplateTypes();
if (index >= templateTypes.size()) {
reportWarning(ttlAst, INDEX_OUTOFBOUNDS,
Integer.toString(templateTypes.size()), Integer.toString(index));
return getUnknownType();
}
return templateTypes.get(index);
}
private JSType evalRecord(Node record, NameResolver nameResolver) {
Map<String, JSType> props = new LinkedHashMap<>();
for (Node propNode = record.getFirstChild(); propNode != null; propNode = propNode.getNext()) {
// If it is a computed property then find the property name using the resolver
if (propNode.isComputedProp()) {
String compPropName = getComputedPropName(propNode);
// If the name does not exist then report a warning
if (!nameResolver.nameVars.containsKey(compPropName)) {
reportWarning(record, UNKNOWN_NAMEVAR, compPropName);
return getUnknownType();
}
// Otherwise add the property
Node propValue = getComputedPropValue(propNode);
String resolvedName = nameResolver.nameVars.get(compPropName);
JSType resultingType = evalInternal(propValue, nameResolver);
props.put(resolvedName, resultingType);
} else {
String propName = propNode.getString();
JSType resultingType = evalInternal(propNode.getFirstChild(),
nameResolver);
props.put(propName, resultingType);
}
}
return this.registry.createRecordType(props);
}
private JSType evalRecordParam(Node ttlAst, NameResolver nameResolver) {
if (ttlAst.isObjectLit()) {
return evalRecord(ttlAst, nameResolver);
}
// The parameter of record can be a type transformation expression
return evalInternal(ttlAst, nameResolver);
}
private JSType evalRecordType(Node ttlAst, NameResolver nameResolver) {
int paramCount = getCallParamCount(ttlAst);
ImmutableList.Builder<ObjectType> recTypesBuilder = new ImmutableList.Builder<>();
for (int i = 0; i < paramCount; i++) {
JSType type = evalRecordParam(getCallArgument(ttlAst, i), nameResolver);
// Check that each parameter evaluates to an object
ObjectType objType = type.toMaybeObjectType();
if (objType == null || objType.isUnknownType()) {
reportWarning(ttlAst, RECPARAM_INVALID, type.toString());
return getUnknownType();
}
JSType recType = this.registry.buildRecordTypeFromObject(objType);
if (!recType.equals(getObjectType())) {
recTypesBuilder.add(recType.toMaybeObjectType());
}
}
return joinRecordTypes(recTypesBuilder.build());
}
private void putNewPropInPropertyMap(Map<String, JSType> props,
String newPropName, JSType newPropValue) {
// TODO(lpino): Decide if the best strategy is to collapse the properties
// to a union type or not. So far, new values replace the old ones except
// if they are two record types in which case the properties are joined
// together
// Three cases:
// (i) If the key does not exist then add it to the map with the new value
// (ii) If the key to be added already exists in the map and the new value
// is not a record type then the current value is replaced with the new one
// (iii) If the new value is a record type and the current is not then
// the current value is replaced with the new one
if (!props.containsKey(newPropName)
|| !newPropValue.isRecordType()
|| !props.get(newPropName).isRecordType()) {
props.put(newPropName, newPropValue);
return;
}
// Otherwise join the current value with the new one since both are records
props.put(newPropName,
joinRecordTypes(ImmutableList.of(
(ObjectType) props.get(newPropName),
(ObjectType) newPropValue)));
}
/**
* Merges a list of record types.
* Example
* {r:{s:string, n:number}} and {a:boolean}
* is transformed into {r:{s:string, n:number}, a:boolean}
*/
private JSType joinRecordTypes(ImmutableList<ObjectType> recTypes) {
Map<String, JSType> props = new LinkedHashMap<>();
for (ObjectType recType : recTypes) {
for (String newPropName : recType.getOwnPropertyNames()) {
JSType newPropValue = recType.getPropertyType(newPropName);
// Put the new property depending if it already exists in the map
putNewPropInPropertyMap(props, newPropName, newPropValue);
}
}
return createRecordType(ImmutableMap.copyOf(props));
}
private JSType evalMaprecord(Node ttlAst, NameResolver nameResolver) {
Node recordNode = ttlAst.getSecondChild();
Node mapFunction = ttlAst.getChildAtIndex(2);
JSType type = evalInternal(recordNode, nameResolver);
// If it is an empty record type (Object) then return
if (type.equals(getObjectType())) {
return getObjectType();
}
// The parameter must be a valid record type
if (!type.isRecordType()) {
// TODO(lpino): Decide how to handle non-record types
reportWarning(recordNode, RECTYPE_INVALID, type.toString());
return getUnknownType();
}
ObjectType objtype = type.toMaybeObjectType();
// Fetch the information of the map function
String paramKey = getFunctionParameter(mapFunction, 0);
String paramValue = getFunctionParameter(mapFunction, 1);
// The maprecord variables must not be defined in the environment
if (nameResolver.nameVars.containsKey(paramKey)) {
reportWarning(ttlAst, DUPLICATE_VARIABLE, paramKey);
return getUnknownType();
}
if (nameResolver.typeVars.containsKey(paramValue)) {
reportWarning(ttlAst, DUPLICATE_VARIABLE, paramValue);
return getUnknownType();
}
// Compute the new properties using the map function
Node mapFnBody = NodeUtil.getFunctionBody(mapFunction);
Map<String, JSType> newProps = new LinkedHashMap<>();
for (String propName : objtype.getOwnPropertyNames()) {
// The value of the current property
JSType propValue = objtype.getPropertyType(propName);
// Evaluate the map function body with paramValue and paramKey replaced
// by the values of the current property
NameResolver newNameResolver = new NameResolver(
addNewEntry(nameResolver.typeVars, paramValue, propValue),
addNewEntry(nameResolver.nameVars, paramKey, propName));
JSType body = evalInternal(mapFnBody, newNameResolver);
// If the body returns unknown then the whole expression returns unknown
if (body.isUnknownType()) {
return getUnknownType();
}
// Skip the property when the body evaluates to NO_TYPE
// or the empty record (Object)
if (body.isEmptyType() || body.equals(getObjectType())) {
continue;
}
// Otherwise the body must evaluate to a record type
if (!body.isRecordType()) {
reportWarning(ttlAst, MAPRECORD_BODY_INVALID, body.toString());
return getUnknownType();
}
// Add the properties of the resulting record type to the original one
ObjectType bodyAsObj = body.toMaybeObjectType();
for (String newPropName : bodyAsObj.getOwnPropertyNames()) {
JSType newPropValue = bodyAsObj.getPropertyType(newPropName);
// If the key already exists then we have to mix it with the current property value
putNewPropInPropertyMap(newProps, newPropName, newPropValue);
}
}
return createRecordType(ImmutableMap.copyOf(newProps));
}
private JSType evalTypeOfVar(Node ttlAst) {
String name = getCallArgument(ttlAst, 0).getString();
StaticTypedSlot slot = typeEnv.getSlot(name);
JSType type = slot != null ? slot.getType() : null;
if (type == null) {
reportWarning(ttlAst, VAR_UNDEFINED, name);
return getUnknownType();
}
return type;
}
private JSType evalInstanceOf(Node ttlAst, NameResolver nameResolver) {
JSType type = evalInternal(getCallArgument(ttlAst, 0), nameResolver);
if (type.isUnknownType() || !type.isConstructor()) {
reportWarning(ttlAst, INVALID_CTOR, type.getDisplayName());
return getUnknownType();
}
return type.toMaybeFunctionType().getInstanceType();
}
private JSType evalNativeTypeExpr(Node ttlAst) {
JSTypeExpression expr = new JSTypeExpression(getCallArgument(ttlAst, 0), VIRTUAL_FILE);
return this.registry.evaluateTypeExpression(expr, this.typeEnv);
}
private JSType evalPrintType(Node ttlAst, NameResolver nameResolver) {
JSType type = evalInternal(getCallArgument(ttlAst, 1), nameResolver);
String msg = getCallArgument(ttlAst, 0).getString() + type;
System.out.println(msg);
return type;
}
private JSType evalPropType(Node ttlAst, NameResolver nameResolver) {
JSType type = evalInternal(getCallArgument(ttlAst, 1), nameResolver);
ObjectType objType = type.toMaybeObjectType();
if (objType == null) {
reportWarning(ttlAst, PROPTYPE_INVALID, type.toString());
return getUnknownType();
}
JSType propType = objType.getPropertyType(getCallArgument(ttlAst, 0).getString());
return firstNonNull(propType, getUnknownType());
}
}
| apache-2.0 |
Niranjan-K/andes | modules/andes-core/broker/src/main/java/org/wso2/andes/store/cassandra/CassandraConstants.java | 5142 | /*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.andes.store.cassandra;
import me.prettyprint.cassandra.serializers.ByteBufferSerializer;
import me.prettyprint.cassandra.serializers.BytesArraySerializer;
import me.prettyprint.cassandra.serializers.IntegerSerializer;
import me.prettyprint.cassandra.serializers.LongSerializer;
import me.prettyprint.cassandra.serializers.StringSerializer;
/**
* Constants used by Cassandra Stores related classes
*/
public class CassandraConstants {
// connection properties
/**
* Connection property to get the jndi lookup name (value) of the data source
*/
protected static final String PROP_JNDI_LOOKUP_NAME = "dataSource";
/**
* Cassandra cluster objects replication factor for key space.
*/
protected static final String PROP_REPLICATION_FACTOR = "replicationFactor";
/**
* GC grace seconds for Cassandra. ( Specifies the time to wait before garbage collecting
* tombstones in Cassandra )
*/
protected static final String PROP_GC_GRACE_SECONDS = "GCGraceSeconds";
/**
* Read Consistency level. From How many replicas to be read before satisfying the read request
*/
protected static final String PROP_READ_CONSISTENCY = "readConsistencyLevel";
/**
* Write consistency level. How many replicas to be successfully written before acknowledging
*/
protected static final String PROP_WRITE_CONSISTENCY = "writeConsistencyLevel";
/**
* Replication placement strategy (algorithm) to be used is defined in this class
*/
protected static final String PROP_STRATEGY_CLASS = "strategyClass";
/**
* Keysapce to be used by MB
*/
public final static String KEYSPACE = "QpidKeySpace";
/**
* Long data type for Cassandra
*/
public final static String LONG_TYPE = "LongType";
/**
* Integer Data type for Cassandra
*/
public final static String INTEGER_TYPE = "IntegerType";
/**
* String data type for Cassandra
*/
public final static String STRING_TYPE = "StringType";
public static StringSerializer stringSerializer = StringSerializer.get();
public static LongSerializer longSerializer = LongSerializer.get();
public static BytesArraySerializer bytesArraySerializer = BytesArraySerializer.get();
public static IntegerSerializer integerSerializer = IntegerSerializer.get();
public static ByteBufferSerializer byteBufferSerializer = ByteBufferSerializer.get();
//column family to keep track of loaded exchanges
public final static String EXCHANGE_COLUMN_FAMILY = "ExchangeColumnFamily";
public final static String EXCHANGE_ROW = "ExchangesRow";
//column family to keep track of queues created
public final static String QUEUE_COLUMN_FAMILY = "QueueColumnFamily";
public final static String QUEUE_ROW = "QueuesRow";
//column family to keep track of bindings
public final static String BINDING_COLUMN_FAMILY = "BindingColumnFamily";
//column family to add and remove message content with their <messageID,offset> values
public final static String MESSAGE_CONTENT_COLUMN_FAMILY = "MessageContent";
//column family to keep messages for node queues (<nodequeue,messageID>)
public final static String NODE_QUEUES_COLUMN_FAMILY = "NodeQueues";
//column family to keep messages for global queues (<global-queue,messageID>)
public final static String GLOBAL_QUEUES_COLUMN_FAMILY = "GlobalQueue";
//column family to keep message metadata for queues
public final static String META_DATA_COLUMN_FAMILY = "MetaData";
//column family to keep track of message IDs for topics <nodeQueueName,MessageID>
public final static String PUB_SUB_MESSAGE_IDS_COLUMN_FAMILY = "pubSubMessages";
public final static String SUBSCRIPTIONS_COLUMN_FAMILY = "Subscriptions";
//column family to keep track of nodes and their syncing info (i.e bind IP Address) under NODE_DETAIL_ROW.
public final static String NODE_DETAIL_COLUMN_FAMILY = "CusterNodeDetails";
public final static String NODE_DETAIL_ROW = "NodeDetailsRow";
//column family to keep track of message properties (count) under MESSAGE_COUNTERS_RAW_NAME
public final static String MESSAGE_COUNTERS_COLUMN_FAMILY = "MessageCountDetails";
public final static String MESSAGE_COUNTERS_RAW_NAME = "QueueMessageCountRow";
public final static String MESSAGES_FOR_EXPIRY_COLUMN_FAMILY="MessagesForExpiration";
}
| apache-2.0 |
Hope6537/hope6537-utils | hope-share-module/hope-custom-datastruct/src/main/java/org.hope6537.datastruct/graph/Topological.java | 1040 | package org.hope6537.datastruct.graph;
/**
* Created by Hope6537 on 2015/3/28.
*/
public class Topological {
private Iterable<Integer> order;
public Topological(DirectedGraph graph) {
this(graph, "reverse");
}
public Topological(DirectedGraph graph, String type) {
DirectedCycle cycleFinder = new DirectedCycle(graph);
if (!cycleFinder.hasCycle()) {
DepthFirstOrder search = new DepthFirstOrder(graph);
switch (type) {
case "pre":
order = search.pre();
break;
case "post":
order = search.post();
break;
case "reverse":
order = search.reversePost();
break;
default:
order = search.reversePost();
}
}
}
public Iterable<Integer> getOrder() {
return order;
}
public boolean isDAG() {
return order != null;
}
}
| apache-2.0 |
DennisKirch/GitlabJavaAPI | src/main/java/org/gitlab/api/models/GitlabGroupMember.java | 96 | package org.gitlab.api.models;
public class GitlabGroupMember extends GitlabAbstractMember {
}
| apache-2.0 |
xiaob/-abase-reader | reader/reader/org/geometerplus/zlibrary/text/view/style/ZLTextExplicitlyDecoratedStyle.java | 4350 | /*
* Copyright (C) 2007-2013 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.text.view.style;
import org.geometerplus.zlibrary.core.util.ZLBoolean3;
import org.geometerplus.zlibrary.text.model.*;
import org.geometerplus.zlibrary.text.view.ZLTextStyle;
public class ZLTextExplicitlyDecoratedStyle extends ZLTextDecoratedStyle implements ZLTextStyleEntry.Feature, ZLTextStyleEntry.FontModifier {
private final ZLTextStyleEntry myEntry;
public ZLTextExplicitlyDecoratedStyle(ZLTextStyle parent, ZLTextStyleEntry entry) {
super(parent, parent.Hyperlink);
myEntry = entry;
}
@Override
protected String getFontFamilyInternal() {
if (myEntry.isFeatureSupported(FONT_FAMILY)) {
// TODO: implement
}
return Parent.getFontFamily();
}
@Override
protected int getFontSizeInternal(ZLTextMetrics metrics) {
if (myEntry instanceof ZLTextCSSStyleEntry && !BaseStyle.UseCSSFontSizeOption.getValue()) {
return Parent.getFontSize(metrics);
}
if (myEntry.isFeatureSupported(FONT_STYLE_MODIFIER)) {
if (myEntry.getFontModifier(FONT_MODIFIER_INHERIT) == ZLBoolean3.B3_TRUE) {
return Parent.Parent.getFontSize(metrics);
}
if (myEntry.getFontModifier(FONT_MODIFIER_LARGER) == ZLBoolean3.B3_TRUE) {
return Parent.Parent.getFontSize(metrics) * 120 / 100;
}
if (myEntry.getFontModifier(FONT_MODIFIER_SMALLER) == ZLBoolean3.B3_TRUE) {
return Parent.Parent.getFontSize(metrics) * 100 / 120;
}
}
if (myEntry.isFeatureSupported(LENGTH_FONT_SIZE)) {
return myEntry.getLength(LENGTH_FONT_SIZE, metrics);
}
return Parent.getFontSize(metrics);
}
@Override
protected boolean isBoldInternal() {
switch (myEntry.getFontModifier(FONT_MODIFIER_BOLD)) {
case B3_TRUE:
return true;
case B3_FALSE:
return false;
default:
return Parent.isBold();
}
}
@Override
protected boolean isItalicInternal() {
switch (myEntry.getFontModifier(FONT_MODIFIER_ITALIC)) {
case B3_TRUE:
return true;
case B3_FALSE:
return false;
default:
return Parent.isItalic();
}
}
@Override
protected boolean isUnderlineInternal() {
switch (myEntry.getFontModifier(FONT_MODIFIER_UNDERLINED)) {
case B3_TRUE:
return true;
case B3_FALSE:
return false;
default:
return Parent.isUnderline();
}
}
@Override
protected boolean isStrikeThroughInternal() {
switch (myEntry.getFontModifier(FONT_MODIFIER_STRIKEDTHROUGH)) {
case B3_TRUE:
return true;
case B3_FALSE:
return false;
default:
return Parent.isStrikeThrough();
}
}
public int getLeftIndent() {
// TODO: implement
return Parent.getLeftIndent();
}
public int getRightIndent() {
// TODO: implement
return Parent.getRightIndent();
}
public int getFirstLineIndentDelta() {
// TODO: implement
return Parent.getFirstLineIndentDelta();
}
public int getLineSpacePercent() {
// TODO: implement
return Parent.getLineSpacePercent();
}
@Override
protected int getVerticalShiftInternal() {
// TODO: implement
return Parent.getVerticalShift();
}
public int getSpaceBefore() {
// TODO: implement
return Parent.getSpaceBefore();
}
public int getSpaceAfter() {
// TODO: implement
return Parent.getSpaceAfter();
}
public byte getAlignment() {
if (myEntry instanceof ZLTextCSSStyleEntry && !BaseStyle.UseCSSTextAlignmentOption.getValue()) {
return Parent.getAlignment();
}
return
myEntry.isFeatureSupported(ALIGNMENT_TYPE)
? myEntry.getAlignmentType()
: Parent.getAlignment();
}
public boolean allowHyphenations() {
// TODO: implement
return Parent.allowHyphenations();
}
}
| apache-2.0 |
michal-lipski/assertj-core | src/test/java/org/assertj/core/error/future/ShouldNotBeCancelled_create_Test.java | 1439 | /**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* Copyright 2012-2015 the original author or authors.
*/
package org.assertj.core.error.future;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.future.ShouldNotBeCancelled.shouldNotBeCancelled;
import java.util.concurrent.CompletableFuture;
import org.assertj.core.internal.TestDescription;
import org.junit.Test;
public class ShouldNotBeCancelled_create_Test {
@Test
public void should_create_error_message() throws Exception {
CompletableFuture<Object> future = new CompletableFuture<Object>();
future.cancel(true);
String error = shouldNotBeCancelled(future).create(new TestDescription("TEST"));
assertThat(error).isEqualTo("[TEST] \n" +
"Expecting\n" +
" <CompletableFuture[Cancelled]>\n" +
"not to be cancelled");
}
}
| apache-2.0 |
pecko/cft | org.eclipse.cft.server.ui/src/org/eclipse/cft/server/ui/DefaultApplicationWizardDelegate.java | 3207 | /*******************************************************************************
* Copyright (c) 2013, 2015 Pivotal Software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* and the Apache License v2.0 is available at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
********************************************************************************/
package org.eclipse.cft.server.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cft.server.core.internal.ApplicationUrlLookupService;
import org.eclipse.cft.server.core.internal.CloudFoundryServer;
import org.eclipse.cft.server.core.internal.client.CloudFoundryApplicationModule;
import org.eclipse.cft.server.ui.internal.wizards.ApplicationWizardDelegate;
import org.eclipse.cft.server.ui.internal.wizards.ApplicationWizardDescriptor;
import org.eclipse.cft.server.ui.internal.wizards.CloudFoundryApplicationEnvVarWizardPage;
import org.eclipse.cft.server.ui.internal.wizards.CloudFoundryApplicationServicesWizardPage;
import org.eclipse.cft.server.ui.internal.wizards.CloudFoundryApplicationWizardPage;
import org.eclipse.cft.server.ui.internal.wizards.CloudFoundryDeploymentWizardPage;
import org.eclipse.jface.wizard.IWizardPage;
/**
* Default delegate for any application that uses standard Java web deployment
* properties for Cloud Foundry. For example, default Java web applications
* require at least one mapped application URL, therefore the wizard delegate
* will provide wizard pages that require that at least one mapped application
* URL is set by the user in the UI.
*
*/
public class DefaultApplicationWizardDelegate extends ApplicationWizardDelegate {
public List<IWizardPage> getWizardPages(ApplicationWizardDescriptor applicationDescriptor,
CloudFoundryServer cloudServer, CloudFoundryApplicationModule applicationModule) {
List<IWizardPage> defaultPages = new ArrayList<IWizardPage>();
ApplicationUrlLookupService urllookup = ApplicationUrlLookupService.getCurrentLookup(cloudServer);
CloudFoundryDeploymentWizardPage deploymentPage = new CloudFoundryDeploymentWizardPage(cloudServer,
applicationModule, applicationDescriptor, urllookup, this);
CloudFoundryApplicationWizardPage applicationNamePage = new CloudFoundryApplicationWizardPage(cloudServer,
applicationModule, applicationDescriptor);
defaultPages.add(applicationNamePage);
defaultPages.add(deploymentPage);
CloudFoundryApplicationServicesWizardPage servicesPage = new CloudFoundryApplicationServicesWizardPage(
cloudServer, applicationModule, applicationDescriptor);
defaultPages.add(servicesPage);
defaultPages.add(new CloudFoundryApplicationEnvVarWizardPage(cloudServer, applicationDescriptor
.getDeploymentInfo()));
return defaultPages;
}
}
| apache-2.0 |
betfair/cougar | cougar-test/cougar-normal-code-tests/src/test/java/com/betfair/cougar/tests/updatedcomponenttests/standardtesting/rpc/RPCPostRequestTypesDateTimeSetTest.java | 4805 | /*
* Copyright 2013, The Sporting Exchange Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Originally from UpdatedComponentTests/StandardTesting/RPC/RPC_Post_RequestTypes_DateTimeSet.xls;
package com.betfair.cougar.tests.updatedcomponenttests.standardtesting.rpc;
import com.betfair.testing.utils.cougar.assertions.AssertionUtils;
import com.betfair.testing.utils.cougar.beans.HttpCallBean;
import com.betfair.testing.utils.cougar.beans.HttpResponseBean;
import com.betfair.testing.utils.cougar.helpers.CougarHelpers;
import com.betfair.testing.utils.cougar.manager.AccessLogRequirement;
import com.betfair.testing.utils.cougar.manager.CougarManager;
import com.betfair.testing.utils.cougar.manager.RequestLogRequirement;
import org.testng.annotations.Test;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
/**
* Ensure that Cougar can handle the dateTimeSet data type in the post body of an RPC request
*/
public class RPCPostRequestTypesDateTimeSetTest {
@Test
public void doTest() throws Exception {
// Set up the Http Call Bean to make the request
CougarManager cougarManager1 = CougarManager.getInstance();
HttpCallBean callBean = cougarManager1.getNewHttpCallBean("87.248.113.14");
CougarManager cougarManager = cougarManager1;
cougarManager.setCougarFaultControllerJMXMBeanAttrbiute("DetailedFaults", "false");
// Set the call bean to use JSON batching
callBean.setJSONRPC(true);
// Set the list of requests to make a batched call to
Map[] mapArray2 = new Map[2];
mapArray2[0] = new HashMap();
mapArray2[0].put("method","dateTimeSetOperation");
mapArray2[0].put("params","[{\"dateTimeSet\":[\"2009-06-01T13:50:00.0Z\",\"2009-06-01T14:50:00.0Z\"]}]");
mapArray2[0].put("id","\"DateTimeSet\"");
mapArray2[1] = new HashMap();
mapArray2[1].put("method","dateTimeSetOperation");
mapArray2[1].put("params","[{\"dateTimeSet\":[\"2012-02-29T13:50:00.0Z\",\"2012-02-29T14:50:00.0Z\"]}]");
mapArray2[1].put("id","\"DateTimeSetLeapYear\"");
callBean.setBatchedRequests(mapArray2);
// Get current time for getting log entries later
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
// Make JSON call to the operation requesting a JSON response
cougarManager.makeRestCougarHTTPCall(callBean, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.JSON);
// Get the response to the batched query (store the response for further comparison as order of batched responses cannot be relied on)
HttpResponseBean actualResponseJSON = callBean.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONJSON);
// Convert the returned json object to a map for comparison
CougarHelpers cougarHelpers4 = new CougarHelpers();
Map<String, Object> map5 = cougarHelpers4.convertBatchedResponseToMap(actualResponseJSON);
AssertionUtils.multiAssertEquals("{\"id\":\"DateTimeSet\",\"result\":{\"responseSet\":[\"2009-06-01T13:50:00.000Z\",\"2009-06-01T14:50:00.000Z\"]},\"jsonrpc\":\"2.0\"}", map5.get("responseDateTimeSet"));
AssertionUtils.multiAssertEquals("{\"id\":\"DateTimeSetLeapYear\",\"result\":{\"responseSet\":[\"2012-02-29T13:50:00.000Z\",\"2012-02-29T14:50:00.000Z\"]},\"jsonrpc\":\"2.0\"}", map5.get("responseDateTimeSetLeapYear"));
AssertionUtils.multiAssertEquals(200, map5.get("httpStatusCode"));
AssertionUtils.multiAssertEquals("OK", map5.get("httpStatusText"));
// Pause the test to allow the logs to be filled
// generalHelpers.pauseTest(500L);
// Check the log entries are as expected
cougarManager.verifyRequestLogEntriesAfterDate(timeStamp, new RequestLogRequirement("2.8", "dateTimeSetOperation"),new RequestLogRequirement("2.8", "dateTimeSetOperation") );
CougarManager cougarManager9 = CougarManager.getInstance();
cougarManager9.verifyAccessLogEntriesAfterDate(timeStamp, new AccessLogRequirement("87.248.113.14", "/json-rpc", "Ok") );
}
}
| apache-2.0 |
achak1987/Incognito | src/main/scala/incognito/archive/ObjectSizeFetcher.java | 372 | package incognito.archive;
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
} | apache-2.0 |
ewolff/microservice | microservice-demo/microservice-demo-order/src/main/java/com/ewolff/microservice/order/clients/Item.java | 1242 | package com.ewolff.microservice.order.clients;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.hateoas.RepresentationModel;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Item extends RepresentationModel {
private String name;
private double price;
@JsonProperty("id")
private long itemId;
public Item() {
super();
}
public Item(long id, String name, double price) {
super();
this.itemId = id;
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public long getItemId() {
return itemId;
}
public void setItemId(long id) {
this.itemId = id;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
| apache-2.0 |
sladomic/literacyapp-android | app/src/main/java/org/literacyapp/authentication/thread/AuthenticationThread.java | 6438 | package org.literacyapp.authentication.thread;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.util.Log;
import android.view.Display;
import org.literacyapp.LiteracyApplication;
import org.literacyapp.authentication.AuthenticationActivity;
import org.literacyapp.contentprovider.dao.AuthenticationEventDao;
import org.literacyapp.contentprovider.dao.DaoSession;
import org.literacyapp.contentprovider.dao.StudentImageCollectionEventDao;
import org.literacyapp.contentprovider.model.analytics.AuthenticationEvent;
import org.literacyapp.contentprovider.model.analytics.StudentImageCollectionEvent;
import org.literacyapp.receiver.BootReceiver;
import org.literacyapp.service.synchronization.AuthenticationJobService;
import org.literacyapp.util.RootHelper;
import java.util.Date;
import java.util.List;
/**
* Created by sladomic on 01.01.17.
*/
public class AuthenticationThread extends Thread {
public static final String IS_DEVICE_ROOTED_IDENTIFIER = "IsDeviceRooted";
private Context context;
private AuthenticationJobService authenticationJobService;
public AuthenticationThread(AuthenticationJobService authenticationJobService){
this.authenticationJobService = authenticationJobService;
this.context = authenticationJobService.getApplicationContext();
}
@Override
public void run() {
if (!isScreenTurnedOff()){
if (didTheMinimumTimePassSinceLastExecution()){
Intent authenticationIntent = new Intent(context, AuthenticationActivity.class);
authenticationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Usage of this flag was inactivated in AuthenticationActivity and StudentImageCollectionActivity on 20170129
//authenticationIntent.putExtra(IS_DEVICE_ROOTED_IDENTIFIER, RootHelper.isDeviceRooted());
context.startActivity(authenticationIntent);
Log.i(getClass().getName(), "The Authentication has been started.");
} else {
Log.i(getClass().getName(), "The Authentication was skipped because the minimum time since the last execution did not pass yet.");
}
} else {
Log.i(getClass().getName(), "The Authentication was skipped because the screen was turned off.");
}
authenticationJobService.jobFinished(authenticationJobService.getJobParameters(), false);
}
private boolean isScreenTurnedOff(){
boolean isScreenTurnedOff = false;
DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
for (Display display : displayManager.getDisplays()) {
if (display.getState() != Display.STATE_ON) {
isScreenTurnedOff = true;
}
}
Log.i(getClass().getName(), "isScreenTurnedOff: " + isScreenTurnedOff);
return isScreenTurnedOff;
}
private boolean didTheMinimumTimePassSinceLastAuthentication(AuthenticationEventDao authenticationEventDao, long minimumTimeInMilliseconds){
boolean didTheMinimumTimePassSinceLastAuthentication = true;
// Get only the last AuthenticationEvent
List<AuthenticationEvent> authenticationEvents = authenticationEventDao.queryBuilder().orderDesc(AuthenticationEventDao.Properties.Time).limit(1).list();
if (authenticationEvents.size() > 0){
AuthenticationEvent authenticationEvent = authenticationEvents.get(0);
long lastAuthenticationTime = authenticationEvent.getTime().getTime().getTime();
long currentTime = new Date().getTime();
Log.i(getClass().getName(), "didTheMinimumTimePassSinceLastAuthentication: lastAuthenticationTime: " + new Date(lastAuthenticationTime) + " minimumTimeInMinutes: " + (minimumTimeInMilliseconds / 1000 / 60) + " currentTime: " + new Date(currentTime));
if ((lastAuthenticationTime + minimumTimeInMilliseconds) > currentTime){
didTheMinimumTimePassSinceLastAuthentication = false;
}
}
return didTheMinimumTimePassSinceLastAuthentication;
}
private boolean didTheMinimumTimePassSinceLastCollection(StudentImageCollectionEventDao studentImageCollectionEventDao, long minimumTimeInMilliseconds){
boolean didTheMinimumTimePassSinceLastCollection = true;
// Get only the last StudentImageCollectionEvent
List<StudentImageCollectionEvent> studentImageCollectionEvents = studentImageCollectionEventDao.queryBuilder().orderDesc(StudentImageCollectionEventDao.Properties.Time).limit(1).list();
if (studentImageCollectionEvents.size() > 0){
StudentImageCollectionEvent studentImageCollectionEvent = studentImageCollectionEvents.get(0);
long lastCollectionTime = studentImageCollectionEvent.getTime().getTime().getTime();
long currentTime = new Date().getTime();
Log.i(getClass().getName(), "didTheMinimumTimePassSinceLastCollection: lastCollectionTime: " + new Date(lastCollectionTime) + " minimumTimeInMinutes: " + (minimumTimeInMilliseconds / 1000 / 60) + " currentTime: " + new Date(currentTime));
if ((lastCollectionTime + minimumTimeInMilliseconds) > currentTime){
didTheMinimumTimePassSinceLastCollection = false;
}
}
return didTheMinimumTimePassSinceLastCollection;
}
private boolean didTheMinimumTimePassSinceLastExecution(){
LiteracyApplication literacyApplication = (LiteracyApplication) context;
DaoSession daoSession = literacyApplication.getDaoSession();
AuthenticationEventDao authenticationEventDao = daoSession.getAuthenticationEventDao();
StudentImageCollectionEventDao studentImageCollectionEventDao = daoSession.getStudentImageCollectionEventDao();
long minimumTimeInMilliseconds = BootReceiver.MINUTES_BETWEEN_AUTHENTICATIONS * 60 * 1000;
boolean didTheMinimumTimePassSinceLastAuthentication = didTheMinimumTimePassSinceLastAuthentication(authenticationEventDao, minimumTimeInMilliseconds);
boolean didTheMinimumTimePassSinceLastCollection = didTheMinimumTimePassSinceLastCollection(studentImageCollectionEventDao, minimumTimeInMilliseconds);
return (didTheMinimumTimePassSinceLastAuthentication && didTheMinimumTimePassSinceLastCollection);
}
}
| apache-2.0 |
commoncrawl/nutch | src/java/org/apache/nutch/service/impl/SeedManagerImpl.java | 1669 | /*
* 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.nutch.service.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.nutch.service.SeedManager;
import org.apache.nutch.service.model.request.SeedList;
public class SeedManagerImpl implements SeedManager {
private static Map<String, SeedList> seeds;
public SeedManagerImpl() {
seeds = new HashMap<>();
}
public SeedList getSeedList(String seedName) {
if(seeds.containsKey(seedName)) {
return seeds.get(seedName);
}
else
return null;
}
public void setSeedList(String seedName, SeedList seedList) {
seeds.put(seedName, seedList);
}
public Map<String, SeedList> getSeeds(){
return seeds;
}
public boolean deleteSeedList(String seedName) {
if(seeds.containsKey(seedName)) {
seeds.remove(seedName);
return true;
}
else
return false;
}
}
| apache-2.0 |
MichaelSun/SiXin | Sixin_Newest/src/ui/com/renren/mobile/chat/ui/account/RegisterActivity.java | 18215 | package com.renren.mobile.chat.ui.account;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.common.manager.LoginManager;
import com.common.manager.LoginManager.LoginInfo;
import com.common.mcs.INetReponseAdapter;
import com.common.mcs.INetRequest;
import com.common.mcs.McsServiceProvider;
import com.common.utils.RegexUtil;
import com.core.json.JsonObject;
import com.core.util.CommonUtil;
import com.renren.mobile.account.LoginControlCenter;
import com.renren.mobile.account.LoginfoModel;
import com.renren.mobile.chat.R;
import com.renren.mobile.chat.base.util.SystemUtil;
import com.renren.mobile.chat.ui.BaseActivity;
import com.renren.mobile.chat.ui.guide.WelcomeActivity;
import com.renren.mobile.chat.ui.setting.SettingForwardActivity;
import com.renren.mobile.chat.view.BaseTitleLayout;
/**
* 注册
* @author kaining.yang
*/
public class RegisterActivity extends BaseActivity {
private static final int LOCK_TIME = 9;
public static final String FLAG_TYPE = "flag_type";
public static final int FLAG_FIND_SECRET = 0;
public static final int FLAG_REGISTER = 1;
public static final int FLAG_BIND_EMAIL = 2;
public static final int FLAG_BIND_PHONE = 3;
/**
* @author kaining.yang
* 0:找回密码 验证帐号
* 1:注册私信
* 2:绑定邮箱
* 3:绑定手机号
*/
private int mFlag;
/**是否正常跳转 */
private boolean normal;
private TextView mGuidance;
private TextView mHint;
private EditText mPhoneOrEmail;
private EditText mCaptcha;
private Button mBtnCaptcha;
private Button mBtnSubmit;
private Handler mCountHandler;
private CountThread mCountThread;
private int mCount;
private String strUser;
private String strCaptcha;
private LinearLayout mTitle;
private Dialog mDialog;
private Context mContext;
private BaseTitleLayout mBaseTitleLayout;
private InterceptSMSMessage mReceiver = new InterceptSMSMessage();
public CaptchaHandler mCaptchaHandler = new CaptchaHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.ykn_register);
mContext = this;
initViews();
initCaptchaReceiver();
mCountHandler = new Handler();
mCountThread = new CountThread();
}
public static void show(Context context, int flagtype){
Intent intent =new Intent(context,RegisterActivity.class);
intent.putExtra(FLAG_TYPE, flagtype);
context.startActivity(intent);
}
private void initCaptchaReceiver() {
IntentFilter filter = new IntentFilter();
filter.setPriority(Integer.MAX_VALUE);
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mReceiver, filter);
Log.d("sunnyykn", "receiver registered");
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
Log.d("sunnyykn", "receiver unregistered");
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
jumpBack();
}
return super.onKeyDown(keyCode, event);
}
private void initViews() {
mTitle = (LinearLayout) this.findViewById(R.id.title);
mPhoneOrEmail = (EditText) this.findViewById(R.id.et_phone_or_email);
mCaptcha = (EditText) this.findViewById(R.id.et_captcha);
mBtnCaptcha = (Button) this.findViewById(R.id.btn_get_captcha);
mBtnSubmit = (Button) this.findViewById(R.id.btn_check_in);
mGuidance = (TextView) this.findViewById(R.id.tv_guidance);
mHint = (TextView) this.findViewById(R.id.tv_hint);
mDialog = new Dialog(this, R.style.sendRequestDialog);
mDialog.setContentView(R.layout.ykn_dialog);
mDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
// title
mBaseTitleLayout = new BaseTitleLayout(this);
mTitle.addView(mBaseTitleLayout.getView(),
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT, 1));
// title back
mBaseTitleLayout.getTitleLeft().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
jumpBack();
}
});
mFlag = getIntent().getExtras().getInt(FLAG_TYPE, FLAG_REGISTER);
switch (mFlag) {
case FLAG_FIND_SECRET:
initViewsFindSecret();
break;
case FLAG_REGISTER:
initViewsRegister();
break;
case FLAG_BIND_EMAIL:
initViewsBindEmail();
break;
case FLAG_BIND_PHONE:
initViewsBindPhone();
break;
default:
break;
}
// 获取验证码
mBtnCaptcha.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
strUser = mPhoneOrEmail.getText().toString();
getCaptcha();
}
});
// 验证验证码
mBtnSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
strCaptcha = mCaptcha.getText().toString();
strUser = mPhoneOrEmail.getText().toString();
checkCaptcha();
}
});
}
private void jumpBack() {
switch (mFlag) {
case FLAG_REGISTER:
WelcomeActivity.show(RegisterActivity.this);
RegisterActivity.this.finish();
break;
case FLAG_BIND_PHONE:
break;
case FLAG_BIND_EMAIL:
break;
case FLAG_FIND_SECRET:
break;
}
}
/**
* @author kaining.yang
* 不同页面的业务逻辑在这里,主要为调不同的请求
* 获取验证码
*/
private void getCaptcha() {
// 发送获取验证码请求前要用正则检查 帐号 是否合法(手机号、邮箱)
switch (mFlag) {
case FLAG_FIND_SECRET:
break;
case FLAG_REGISTER:
if (RegexUtil.isMobilePhone(strUser) || RegexUtil.isEmailAddress(strUser)) {
onClickCaptcha();
McsServiceProvider.getProvider().getCaptcha(strUser, "GET", new responseRegisterCaptcha());
break;
} else {
// 注册帐号不合法
CommonUtil.toast("请填写正确格式的手机号或邮箱!");
break;
}
case FLAG_BIND_EMAIL: // 绑定邮箱和手机号接口一致
if (RegexUtil.isEmailAddress(strUser)) {
onClickCaptcha();
McsServiceProvider.getProvider().getCaptchaBinding(strUser, "GET", new responseBindingCaptcha());
break;
} else {
// 注册帐号不合法
CommonUtil.toast("请填写正确格式的邮箱!");
break;
}
case FLAG_BIND_PHONE:
if (RegexUtil.isMobilePhone(strUser)) {
onClickCaptcha();
McsServiceProvider.getProvider().getCaptchaBinding(strUser, "GET", new responseBindingCaptcha());
break;
} else {
// 注册帐号不合法
CommonUtil.toast("请填写正确格式的手机号!");
break;
}
}
}
class responseRegisterCaptcha extends INetReponseAdapter{
public responseRegisterCaptcha() {
}
@Override
public void onSuccess(INetRequest req, JsonObject data) {
SystemUtil.log("sunnyykn", "获取验证码成功:"+data);
CommonUtil.toast("获取验证码成功!");
SystemUtil.log("sunnyykn", "验证码:"+data);
}
@Override
public void onError(INetRequest req, JsonObject data) {
SystemUtil.log("sunnyykn", "获取验证码失败信息:"+data);
CommonUtil.toast("获取验证码失败!");
}
}
class responseBindingCaptcha extends INetReponseAdapter {
@Override
public void onSuccess(INetRequest req, JsonObject data) {
SystemUtil.log("sunnyykn", "获取验证码成功:"+data);
CommonUtil.toast("获取验证码成功!");
SystemUtil.log("sunnyykn", "验证码:"+data);
}
@Override
public void onError(INetRequest req, JsonObject data) {
SystemUtil.log("sunnyykn", "获取验证码失败信息:"+data);
CommonUtil.toast("获取验证码失败!");
}
}
/**
* @author kaining.yang
* 不同页面的业务逻辑在这里,主要为调不同的请求
* 校对验证码
*/
private void checkCaptcha() {
if (!mDialog.isShowing()) {
mDialog.show();
}
switch (mFlag) {
case FLAG_FIND_SECRET:
break;
case FLAG_REGISTER:
McsServiceProvider.getProvider().checkCaptcha(strUser, strCaptcha, new responseRegisterCheck());
break;
case FLAG_BIND_EMAIL:
//McsServiceProvider.getProvider().bindAccount(strUser, strCaptcha, new responseBindingCheck());
break;
case FLAG_BIND_PHONE:
//McsServiceProvider.getProvider().bindAccount(strUser, strCaptcha, new responseBindingCheck());
break;
}
}
class responseRegisterCheck extends INetReponseAdapter {
public responseRegisterCheck() {
}
@Override
public void onSuccess(INetRequest req, JsonObject data) {
SystemUtil.log("sunnyykn", "验证验证码成功:"+data);
CommonUtil.toast("验证验证码成功!");
// 验证成功后跳转到完善资料并注册页面RegisterInfoActivity
Intent intent = new Intent(RegisterActivity.this, RegisterInfoActivity.class);
intent.putExtra("username", strUser);
intent.putExtra("captcha", strCaptcha);
RegisterActivity.this.startActivity(intent);
RegisterActivity.this.finish();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
@Override
public void onError(INetRequest req, JsonObject data) {
SystemUtil.log("sunnyykn", "验证验证码失败信息:"+data);
CommonUtil.toast("验证验证码失败!");
long error_code = data.getNum("error_code");
String error_msg = data.getString("error_msg");
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
class responseBindingCheck extends INetReponseAdapter {
@Override
public void onSuccess(INetRequest req, JsonObject data) {
SystemUtil.logykn("返回数据:" + data.toString());
SystemUtil.logykn("绑定成功");
CommonUtil.toast("绑定成功!");
// 更新LoginInfo 和数据库
updateUserData();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
// 跳转到绑定手机和邮箱页面
SettingForwardActivity.show(RegisterActivity.this, SettingForwardActivity.ForwardScreenType.SELFINFO_SETTING_SCREEN);
RegisterActivity.this.finish();
}
@Override
public void onError(INetRequest req, JsonObject data) {
SystemUtil.logykn("返回数据:" + data.toString());
SystemUtil.logykn("绑定失败");
CommonUtil.toast("绑定失败!");
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
private void updateUserData() {
LoginInfo info = LoginManager.getInstance().getLoginInfo();
LoginfoModel loginfo = new LoginfoModel();
switch (mFlag) {
case FLAG_BIND_PHONE:
info.mBindInfoMobile.mBindId = strUser;
info.mBindInfoMobile.mBindType = "mobile";
info.mBindInfoMobile.mBindName = "";
info.mBindInfoMobile.mBindPage = "";
loginfo.parse(info);
LoginManager.getInstance().setLoginfo(info);
LoginControlCenter.getInstance().updateUserData(loginfo);
break;
case FLAG_BIND_EMAIL:
info.mBindInfoEmail.mBindId = strUser;
info.mBindInfoEmail.mBindType = "email";
info.mBindInfoEmail.mBindName = "";
info.mBindInfoEmail.mBindPage = "";
loginfo.parse(info);
LoginManager.getInstance().setLoginfo(info); // 更新内存
LoginControlCenter.getInstance().updateUserData(loginfo); // 更新数据库
break;
}
}
private void initViewsFindSecret() {
mHint.setVisibility(View.VISIBLE);
mGuidance.setText(R.string.ykn_register_find_secret_guidance);
mPhoneOrEmail.setHint(R.string.ykn_register_edittext);
mBtnSubmit.setText(R.string.ykn_register_submit);
// title
mBaseTitleLayout.setTitleMiddle(getString(R.string.ykn_register_find_secret_title));
}
private void initViewsRegister() {
mHint.setVisibility(View.GONE);
mGuidance.setText(R.string.ykn_register_guidance);
mPhoneOrEmail.setHint(R.string.ykn_register_edittext);
mBtnSubmit.setText(R.string.ykn_register_submit);
// title
mBaseTitleLayout.setTitleMiddle(getString(R.string.ykn_register_title));
}
private void initViewsBindEmail() {
mHint.setVisibility(View.GONE);
mGuidance.setText(R.string.ykn_register_bind_email_guidance);
mPhoneOrEmail.setHint(R.string.ykn_register_bind_email_edittext);
mBtnSubmit.setText(R.string.ykn_register_bind_email_submit);
// title
mBaseTitleLayout.setTitleMiddle(getString(R.string.ykn_register_bind_email_title));
}
private void initViewsBindPhone() {
mHint.setVisibility(View.GONE);
mGuidance.setText(R.string.ykn_register_bind_phone_guidance);
mPhoneOrEmail.setHint(R.string.ykn_register_bind_phone_edittext);
mBtnSubmit.setText(R.string.ykn_register_bind_phone_submit);
// title
mBaseTitleLayout.setTitleMiddle(getString(R.string.ykn_register_bind_phone_title));
}
/**
* 控制”获取验证码“倒计时按钮
*/
private void onClickCaptcha() {
mCount = LOCK_TIME;
mBtnCaptcha.setBackgroundResource(R.drawable.ykn_button_grey);
mBtnCaptcha.setClickable(false);
mPhoneOrEmail.setClickable(false);
mCountThread.run();
}
class CountThread implements Runnable {
@Override
public void run() {
if (mCount > 0) {
mBtnCaptcha.setText(getString(R.string.ykn_register_button_pressed) + "(" + mCount + ")");
mCount --;
mCountHandler.postDelayed(mCountThread, 1000);
} else if (mCount == 0) {
mBtnCaptcha.setText(getString(R.string.ykn_register_button_normal));
mBtnCaptcha.setBackgroundResource(R.drawable.ykn_button_background_green);
mBtnCaptcha.setClickable(true);
mPhoneOrEmail.setClickable(true);
}
}
}
class CaptchaHandler extends Handler {
@Override
public void handleMessage(Message msg) {
String captcha = (String) msg.obj;
if (captcha != null) {
mCaptcha.setText(captcha);
}
super.handleMessage(msg);
}
}
/**
* @author kaining.yang
* 拦截短信验证码 自动提取短信中的验证码填充到表单中
*/
class InterceptSMSMessage extends BroadcastReceiver {
/**
* The defination of the SMSACTION
*/
private final String SMSACTION = "android.provider.Telephony.SMS_RECEIVED";
/**
* 短信内容
*/
StringBuilder mSmsContent = new StringBuilder();
/**
* 短信发件人号码
*/
StringBuilder mSmsNumber = new StringBuilder();
/**
* 截获的验证码
*/
String verifyCode;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMSACTION)) {
// 接收由Intent传来的数据
Bundle bundle = intent.getExtras();
if (bundle != null) {
// pdus为 android内置短信参数 identifier , 通过bundle.get("")返回一包含pdus的对象
Object[] myOBJpdus = (Object[]) bundle.get("pdus");
// 构建短信对象array,并依据收到的对象长度来创建array的大小
SmsMessage[] messages = new SmsMessage[myOBJpdus.length];
for (int i = 0; i < myOBJpdus.length; i++) {
messages[i] = SmsMessage
.createFromPdu((byte[]) myOBJpdus[i]);
}
for (SmsMessage currentMessage : messages) {
mSmsContent.append(currentMessage.getDisplayMessageBody());
mSmsNumber.append(currentMessage
.getDisplayOriginatingAddress());
}
String smsBody = mSmsContent.toString();
String smsNumber = mSmsNumber.toString();
if (smsNumber.contains("+86")) {
smsNumber = smsNumber.substring(3);
}
Log.d("sunnyykn", "手机号:" + smsNumber);
Log.d("sunnyykn", "短信:" + smsBody);
// 确认该短信内容是否满足过滤条件
boolean flags_filter = false;
if (smsNumber.equals("106900867741")) {
// 屏蔽人人发来的短信
flags_filter = true;
// 解析smsBody,获取其中的验证码,赋值给verifyCode
char[] ch = smsBody.toCharArray();
verifyCode = "";
for (int i = 0; i < ch.length; i++) {
if (Character.isDigit(ch[i]))
verifyCode += ch[i];
}
Log.d("sunnyykn", "验证码" + smsBody);
Log.d("sunnyykn", "验证码" + verifyCode);
}
// 第三步:取消
//if (flags_filter) {
if (true) {
this.abortBroadcast();
Message msg = new Message();
msg.obj = verifyCode;
Log.d("sunnyykn", "msg:" + msg.toString());
Log.d("sunnyykn", "obj:" + msg.obj.toString());
mCaptchaHandler.sendMessage(msg);
}
}
}
}
}
}
| apache-2.0 |
ChinmaySKulkarni/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestSerialReplicationChecker.java | 13147 | /**
* 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.hadoop.hbase.replication.regionserver;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.Cell.Type;
import org.apache.hadoop.hbase.CellBuilderFactory;
import org.apache.hadoop.hbase.CellBuilderType;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionInfoBuilder;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.master.RegionState;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationQueueStorage;
import org.apache.hadoop.hbase.replication.ReplicationStorageFactory;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.ReplicationTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.wal.WAL.Entry;
import org.apache.hadoop.hbase.wal.WALKeyImpl;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap;
@Category({ ReplicationTests.class, MediumTests.class })
public class TestSerialReplicationChecker {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestSerialReplicationChecker.class);
private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
private static String PEER_ID = "1";
private static ReplicationQueueStorage QUEUE_STORAGE;
private static String WAL_FILE_NAME = "test.wal";
private Connection conn;
private SerialReplicationChecker checker;
@Rule
public final TestName name = new TestName();
private TableName tableName;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
UTIL.startMiniCluster(1);
QUEUE_STORAGE = ReplicationStorageFactory.getReplicationQueueStorage(UTIL.getZooKeeperWatcher(),
UTIL.getConfiguration());
QUEUE_STORAGE.addWAL(UTIL.getMiniHBaseCluster().getRegionServer(0).getServerName(), PEER_ID,
WAL_FILE_NAME);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
UTIL.shutdownMiniCluster();
}
@Before
public void setUp() throws IOException {
ReplicationSource source = mock(ReplicationSource.class);
when(source.getPeerId()).thenReturn(PEER_ID);
when(source.getQueueStorage()).thenReturn(QUEUE_STORAGE);
conn = mock(Connection.class);
when(conn.isClosed()).thenReturn(false);
doAnswer(new Answer<Table>() {
@Override
public Table answer(InvocationOnMock invocation) throws Throwable {
return UTIL.getConnection().getTable((TableName) invocation.getArgument(0));
}
}).when(conn).getTable(any(TableName.class));
Server server = mock(Server.class);
when(server.getConnection()).thenReturn(conn);
when(source.getServer()).thenReturn(server);
checker = new SerialReplicationChecker(UTIL.getConfiguration(), source);
tableName = TableName.valueOf(name.getMethodName());
}
private Entry createEntry(RegionInfo region, long seqId) {
WALKeyImpl key = mock(WALKeyImpl.class);
when(key.getTableName()).thenReturn(tableName);
when(key.getEncodedRegionName()).thenReturn(region.getEncodedNameAsBytes());
when(key.getSequenceId()).thenReturn(seqId);
Entry entry = mock(Entry.class);
when(entry.getKey()).thenReturn(key);
return entry;
}
private Cell createCell(RegionInfo region) {
return CellBuilderFactory.create(CellBuilderType.DEEP_COPY).setRow(region.getStartKey())
.setType(Type.Put).build();
}
@Test
public void testNoBarrierCanPush() throws IOException {
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).build();
assertTrue(checker.canPush(createEntry(region, 100), createCell(region)));
}
private void addStateAndBarrier(RegionInfo region, RegionState.State state, long... barriers)
throws IOException {
Put put = new Put(region.getRegionName(), EnvironmentEdgeManager.currentTime());
if (state != null) {
put.addColumn(HConstants.CATALOG_FAMILY, HConstants.STATE_QUALIFIER,
Bytes.toBytes(state.name()));
}
for (int i = 0; i < barriers.length; i++) {
put.addColumn(HConstants.REPLICATION_BARRIER_FAMILY, HConstants.SEQNUM_QUALIFIER,
put.getTimestamp() - barriers.length + i, Bytes.toBytes(barriers[i]));
}
try (Table table = UTIL.getConnection().getTable(TableName.META_TABLE_NAME)) {
table.put(put);
}
}
private void setState(RegionInfo region, RegionState.State state) throws IOException {
Put put = new Put(region.getRegionName(), EnvironmentEdgeManager.currentTime());
put.addColumn(HConstants.CATALOG_FAMILY, HConstants.STATE_QUALIFIER,
Bytes.toBytes(state.name()));
try (Table table = UTIL.getConnection().getTable(TableName.META_TABLE_NAME)) {
table.put(put);
}
}
private void updatePushedSeqId(RegionInfo region, long seqId) throws ReplicationException {
QUEUE_STORAGE.setWALPosition(UTIL.getMiniHBaseCluster().getRegionServer(0).getServerName(),
PEER_ID, WAL_FILE_NAME, 10, ImmutableMap.of(region.getEncodedName(), seqId));
}
private void addParents(RegionInfo region, List<RegionInfo> parents) throws IOException {
Put put = new Put(region.getRegionName(), EnvironmentEdgeManager.currentTime());
put.addColumn(HConstants.REPLICATION_BARRIER_FAMILY,
MetaTableAccessor.REPLICATION_PARENT_QUALIFIER, MetaTableAccessor.getParentsBytes(parents));
try (Table table = UTIL.getConnection().getTable(TableName.META_TABLE_NAME)) {
table.put(put);
}
}
@Test
public void testLastRegionAndOpeningCanNotPush() throws IOException, ReplicationException {
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).build();
addStateAndBarrier(region, RegionState.State.OPEN, 10);
Cell cell = createCell(region);
// can push since we are in the first range
assertTrue(checker.canPush(createEntry(region, 100), cell));
setState(region, RegionState.State.OPENING);
// can not push since we are in the last range and the state is OPENING
assertFalse(checker.canPush(createEntry(region, 102), cell));
addStateAndBarrier(region, RegionState.State.OPEN, 50);
// can not push since the previous range has not been finished yet
assertFalse(checker.canPush(createEntry(region, 102), cell));
updatePushedSeqId(region, 49);
// can push since the previous range has been finished
assertTrue(checker.canPush(createEntry(region, 102), cell));
setState(region, RegionState.State.OPENING);
assertFalse(checker.canPush(createEntry(region, 104), cell));
}
@Test
public void testCanPushUnder() throws IOException, ReplicationException {
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).build();
addStateAndBarrier(region, RegionState.State.OPEN, 10, 100);
updatePushedSeqId(region, 9);
Cell cell = createCell(region);
assertTrue(checker.canPush(createEntry(region, 20), cell));
verify(conn, times(1)).getTable(any(TableName.class));
// not continuous
for (int i = 22; i < 100; i += 2) {
assertTrue(checker.canPush(createEntry(region, i), cell));
}
// verify that we do not go to meta table
verify(conn, times(1)).getTable(any(TableName.class));
}
@Test
public void testCanPushIfContinuous() throws IOException, ReplicationException {
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).build();
addStateAndBarrier(region, RegionState.State.OPEN, 10);
updatePushedSeqId(region, 9);
Cell cell = createCell(region);
assertTrue(checker.canPush(createEntry(region, 20), cell));
verify(conn, times(1)).getTable(any(TableName.class));
// continuous
for (int i = 21; i < 100; i++) {
assertTrue(checker.canPush(createEntry(region, i), cell));
}
// verify that we do not go to meta table
verify(conn, times(1)).getTable(any(TableName.class));
}
@Test
public void testCanPushAfterMerge() throws IOException, ReplicationException {
// 0xFF is the escape byte when storing region name so let's make sure it can work.
byte[] endKey = new byte[] { (byte) 0xFF, 0x00, (byte) 0xFF, (byte) 0xFF, 0x01 };
RegionInfo regionA =
RegionInfoBuilder.newBuilder(tableName).setEndKey(endKey).setRegionId(1).build();
RegionInfo regionB =
RegionInfoBuilder.newBuilder(tableName).setStartKey(endKey).setRegionId(2).build();
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).setRegionId(3).build();
addStateAndBarrier(regionA, null, 10, 100);
addStateAndBarrier(regionB, null, 20, 200);
addStateAndBarrier(region, RegionState.State.OPEN, 200);
addParents(region, Arrays.asList(regionA, regionB));
Cell cell = createCell(region);
// can not push since both parents have not been finished yet
assertFalse(checker.canPush(createEntry(region, 300), cell));
updatePushedSeqId(regionB, 199);
// can not push since regionA has not been finished yet
assertFalse(checker.canPush(createEntry(region, 300), cell));
updatePushedSeqId(regionA, 99);
// can push since all parents have been finished
assertTrue(checker.canPush(createEntry(region, 300), cell));
}
@Test
public void testCanPushAfterSplit() throws IOException, ReplicationException {
// 0xFF is the escape byte when storing region name so let's make sure it can work.
byte[] endKey = new byte[] { (byte) 0xFF, 0x00, (byte) 0xFF, (byte) 0xFF, 0x01 };
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).setRegionId(1).build();
RegionInfo regionA =
RegionInfoBuilder.newBuilder(tableName).setEndKey(endKey).setRegionId(2).build();
RegionInfo regionB =
RegionInfoBuilder.newBuilder(tableName).setStartKey(endKey).setRegionId(3).build();
addStateAndBarrier(region, null, 10, 100);
addStateAndBarrier(regionA, RegionState.State.OPEN, 100, 200);
addStateAndBarrier(regionB, RegionState.State.OPEN, 100, 300);
addParents(regionA, Arrays.asList(region));
addParents(regionB, Arrays.asList(region));
Cell cellA = createCell(regionA);
Cell cellB = createCell(regionB);
// can not push since parent has not been finished yet
assertFalse(checker.canPush(createEntry(regionA, 150), cellA));
assertFalse(checker.canPush(createEntry(regionB, 200), cellB));
updatePushedSeqId(region, 99);
// can push since parent has been finished
assertTrue(checker.canPush(createEntry(regionA, 150), cellA));
assertTrue(checker.canPush(createEntry(regionB, 200), cellB));
}
@Test
public void testCanPushEqualsToBarrier() throws IOException, ReplicationException {
// For binary search, equals to an element will result to a positive value, let's test whether
// it works.
RegionInfo region = RegionInfoBuilder.newBuilder(tableName).build();
addStateAndBarrier(region, RegionState.State.OPEN, 10, 100);
Cell cell = createCell(region);
assertTrue(checker.canPush(createEntry(region, 10), cell));
assertFalse(checker.canPush(createEntry(region, 100), cell));
updatePushedSeqId(region, 99);
assertTrue(checker.canPush(createEntry(region, 100), cell));
}
}
| apache-2.0 |
ImpactDevelopment/ClientAPI | src/main/java/clientapi/command/exception/CommandInitException.java | 961 | /*
* Copyright 2018 ImpactDevelopment
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package clientapi.command.exception;
import clientapi.command.Command;
/**
* Thrown when the initialization of a {@link Command} fails.
*
* @author Brady
* @since 5/31/2017
*/
public final class CommandInitException extends CommandException {
public CommandInitException(Command command, String message) {
super(command, message);
}
}
| apache-2.0 |
arenadata/ambari | ambari-server/src/main/java/org/apache/ambari/server/topology/SettingFactory.java | 3216 | /**
* 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.topology;
import com.google.inject.Singleton;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Creates the Setting object from the parsed blueprint. Expects the settings JSON
* that was parsed to follow the schema here:
*
* "settings" : [
* {
* "recovery_settings" : [{
* "recovery_enabled" : "true"
* }
* ]
* },
* {
* "service_settings" : [
* {
* "name" : "HDFS",
* "recovery_enabled" : "false"
* },
* {
* "name" : "TEZ",
* "recovery_enabled" : "false"
* }
* ]
* },
* {
* "component_settings" : [
* {
* "name" : "DATANODE",
* "recovery_enabled" : "true"
* }
* ]
* }
* ]
*/
@Singleton
public class SettingFactory {
/**
* Attempts to build the list of settings in the following format:
* setting_name1-->[propertyName1-->propertyValue1, propertyName2-->propertyValue2]
* @param blueprintSetting
* @return
*/
public static Setting getSetting(Collection<Map<String, Object>> blueprintSetting) {
Map<String, Set<HashMap<String, String>>> properties = new HashMap<>();
Setting setting = new Setting(properties);
if (blueprintSetting != null) {
for (Map<String, Object> settingMap : blueprintSetting) {
for (Map.Entry<String, Object> entry : settingMap.entrySet()) {
final String[] propertyNames = entry.getKey().split("/");
Set<HashMap<String, String>> settingValue;
if (entry.getValue() instanceof Set) {
settingValue = (HashSet<HashMap<String, String>>)entry.getValue();
}
else if (propertyNames.length > 1){
HashMap<String, String> property = new HashMap<>();
property.put(propertyNames[1], String.valueOf(entry.getValue()));
settingValue = properties.get(propertyNames[0]);
if (settingValue == null) {
settingValue = new HashSet<>();
}
settingValue.add(property);
}
else {
throw new IllegalArgumentException("Invalid setting schema: " + String.valueOf(entry.getValue()));
}
properties.put(propertyNames[0], settingValue);
}
}
}
return setting;
}
}
| apache-2.0 |
wenanguo/anguosoft | spring-boot-common/src/main/java/com/anguo/mybatis/db/core/dialect/db/HSQLDialect.java | 1533 | package com.anguo.mybatis.db.core.dialect.db;
import com.anguo.mybatis.db.core.dialect.Dialect;
/**
* Dialect for HSQLDB
*
* @author AndrewWen
*
*/
public class HSQLDialect implements Dialect {
@Override
public boolean supportsLimit() {
return true;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset),
Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
boolean hasOffset = offset > 0;
return
new StringBuffer(sql.length() + 10)
.append(sql)
.insert(sql.toLowerCase().indexOf("select") + 6, hasOffset ? " limit " + offsetPlaceholder + " " + limitPlaceholder : " top " + limitPlaceholder)
.toString();
}
}
| apache-2.0 |
electricalwind/greycat | greycat/src/main/java/greycat/utility/Unsafe.java | 1339 | /**
* Copyright 2017 The GreyCat Authors. All rights reserved.
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package greycat.utility;
import java.lang.reflect.Field;
/**
* @ignore ts
*/
public class Unsafe {
private static sun.misc.Unsafe unsafe_instance = null;
@SuppressWarnings("restriction")
public static sun.misc.Unsafe getUnsafe() {
if (unsafe_instance == null) {
try {
Field theUnsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe_instance = (sun.misc.Unsafe) theUnsafe.get(null);
} catch (Exception e) {
throw new RuntimeException("ERROR: unsafe operations are not available");
}
}
return unsafe_instance;
}
}
| apache-2.0 |
bomgar/async-http-client | client/src/test/java/org/asynchttpclient/ws/CloseCodeReasonMessageTest.java | 6666 | /*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.ws;
import static org.asynchttpclient.Dsl.*;
import static org.testng.Assert.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.asynchttpclient.AsyncHttpClient;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.testng.annotations.Test;
public class CloseCodeReasonMessageTest extends AbstractBasicTest {
@Override
public WebSocketHandler getWebSocketHandler() {
return new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(EchoSocket.class);
}
};
}
@Test(timeOut = 60000)
public void onCloseWithCode() throws Exception {
try (AsyncHttpClient c = asyncHttpClient()) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<String> text = new AtomicReference<>("");
WebSocket websocket = c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new Listener(latch, text)).build()).get();
websocket.close();
latch.await();
assertTrue(text.get().startsWith("1000"));
}
}
@Test(timeOut = 60000)
public void onCloseWithCodeServerClose() throws Exception {
try (AsyncHttpClient c = asyncHttpClient()) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<String> text = new AtomicReference<>("");
c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new Listener(latch, text)).build()).get();
latch.await();
assertEquals(text.get(), "1001-Idle Timeout");
}
}
public final static class Listener implements WebSocketListener, WebSocketCloseCodeReasonListener {
final CountDownLatch latch;
final AtomicReference<String> text;
public Listener(CountDownLatch latch, AtomicReference<String> text) {
this.latch = latch;
this.text = text;
}
@Override
public void onOpen(WebSocket websocket) {
}
@Override
public void onClose(WebSocket websocket) {
latch.countDown();
}
public void onClose(WebSocket websocket, int code, String reason) {
text.set(code + "-" + reason);
latch.countDown();
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
latch.countDown();
}
}
@Test(timeOut = 60000, expectedExceptions = { ExecutionException.class })
public void getWebSocketThrowsException() throws Throwable {
final CountDownLatch latch = new CountDownLatch(1);
try (AsyncHttpClient client = asyncHttpClient()) {
client.prepareGet("http://apache.org").execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
@Override
public void onMessage(String message) {
}
@Override
public void onOpen(WebSocket websocket) {
}
@Override
public void onClose(WebSocket websocket) {
}
@Override
public void onError(Throwable t) {
latch.countDown();
}
}).build()).get();
}
latch.await();
}
@Test(timeOut = 60000, expectedExceptions = { IllegalArgumentException.class })
public void wrongStatusCode() throws Throwable {
try (AsyncHttpClient client = asyncHttpClient()) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> throwable = new AtomicReference<>();
client.prepareGet("http://apache.org").execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
@Override
public void onMessage(String message) {
}
@Override
public void onOpen(org.asynchttpclient.ws.WebSocket websocket) {
}
@Override
public void onClose(org.asynchttpclient.ws.WebSocket websocket) {
}
@Override
public void onError(Throwable t) {
throwable.set(t);
latch.countDown();
}
}).build());
latch.await();
assertNotNull(throwable.get());
throw throwable.get();
}
}
@Test(timeOut = 60000, expectedExceptions = { IllegalStateException.class })
public void wrongProtocolCode() throws Throwable {
try (AsyncHttpClient c = asyncHttpClient()) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> throwable = new AtomicReference<>();
c.prepareGet("ws://www.google.com").execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
@Override
public void onMessage(String message) {
}
@Override
public void onOpen(WebSocket websocket) {
}
@Override
public void onClose(WebSocket websocket) {
}
@Override
public void onError(Throwable t) {
throwable.set(t);
latch.countDown();
}
}).build());
latch.await();
assertNotNull(throwable.get());
throw throwable.get();
}
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/RenderingKDocTestGenerated.java | 1707 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.idea.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TestMetadata;
import org.jetbrains.kotlin.idea.test.TestRoot;
import org.junit.runner.RunWith;
/**
* This class is generated by {@link org.jetbrains.kotlin.testGenerator.generator.TestGenerator}.
* DO NOT MODIFY MANUALLY.
*/
@SuppressWarnings("all")
@TestRoot("idea/tests")
@TestDataPath("$CONTENT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@TestMetadata("testData/codeInsight/renderingKDoc")
public class RenderingKDocTestGenerated extends AbstractRenderingKDocTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
@TestMetadata("classRendering.kt")
public void testClassRendering() throws Exception {
runTest("testData/codeInsight/renderingKDoc/classRendering.kt");
}
@TestMetadata("difficultKDoc.kt")
public void testDifficultKDoc() throws Exception {
runTest("testData/codeInsight/renderingKDoc/difficultKDoc.kt");
}
@TestMetadata("functionRendering.kt")
public void testFunctionRendering() throws Exception {
runTest("testData/codeInsight/renderingKDoc/functionRendering.kt");
}
@TestMetadata("propertyRendering.kt")
public void testPropertyRendering() throws Exception {
runTest("testData/codeInsight/renderingKDoc/propertyRendering.kt");
}
}
| apache-2.0 |
pfichtner/Ardulink | Mqtt/src/com/github/pfichtner/ardulink/compactors/TimeSlicer.java | 820 | /**
Copyright 2013 project Ardulink http://www.ardulink.org/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES 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.pfichtner.ardulink.compactors;
/**
* [ardulinktitle] [ardulinkversion]
* @author Peter Fichtner
*
* [adsense]
*/
public interface TimeSlicer {
void add(SlicedAnalogReadChangeListenerAdapter worker);
}
| apache-2.0 |
JackFan-Z/panoramagl-a | src/com/panoramagl/opengl/GLUconstants.java | 1939 | /*
* PanoramaGL library
* Version 0.2 beta
* Copyright (c) 2010 Javier Baez <javbaezga@gmail.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 com.panoramagl.opengl;
public class GLUconstants
{
/**error code constants*/
public static final int GLU_INVALID_ENUM = 100900;
public static final int GLU_INVALID_VALUE = 100901;
public static final int GLU_OUT_OF_MEMORY = 100902;
public static final int GLU_INCOMPATIBLE_GL_VERSION = 100903;
public static final int GLU_INVALID_OPERATION = 100904;
/**quadric draw style constants*/
public static final int GLU_POINT = 100010;
public static final int GLU_LINE = 100011;
public static final int GLU_FILL = 100012;
public static final int GLU_SILHOUETTE = 100013;
/**quadric callback constants*/
public static final int GLU_ERROR = 100103;
/**quadric normal constants*/
public static final int GLU_SMOOTH = 100000;
public static final int GLU_FLAT = 100001;
public static final int GLU_NONE = 100002;
/**quadric orientation constants*/
public static final int GLU_OUTSIDE = 100020;
public static final int GLU_INSIDE = 100021;
} | apache-2.0 |
beav/netty-ant | src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java | 4129 | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES 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.jboss.netty.handler.codec.http.websocketx;
import java.util.LinkedHashSet;
import java.util.Set;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.handler.codec.http.HttpRequest;
/**
* Base class for server side web socket opening and closing handshakes
*/
public abstract class WebSocketServerHandshaker {
private final String webSocketUrl;
private final String[] subprotocols;
private final WebSocketVersion version;
/**
* Constructor specifying the destination web socket location
*
* @param version
* the protocol version
* @param webSocketUrl
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
* @param subprotocols
* CSV of supported protocols. Null if sub protocols not supported.
*/
protected WebSocketServerHandshaker(
WebSocketVersion version, String webSocketUrl, String subprotocols) {
this.version = version;
this.webSocketUrl = webSocketUrl;
if (subprotocols != null) {
String[] subprotocolArray = subprotocols.split(",");
for (int i = 0; i < subprotocolArray.length; i++) {
subprotocolArray[i] = subprotocolArray[i].trim();
}
this.subprotocols = subprotocolArray;
} else {
this.subprotocols = new String[0];
}
}
/**
* Returns the URL of the web socket
*/
public String getWebSocketUrl() {
return webSocketUrl;
}
/**
* Returns the CSV of supported sub protocols
*/
public Set<String> getSubprotocols() {
Set<String> ret = new LinkedHashSet<String>();
for (String p: this.subprotocols) {
ret.add(p);
}
return ret;
}
/**
* Returns the version of the specification being supported
*/
public WebSocketVersion getVersion() {
return version;
}
/**
* Performs the opening handshake
*
* @param channel
* Channel
* @param req
* HTTP Request
*/
public abstract ChannelFuture handshake(Channel channel, HttpRequest req);
/**
* Performs the closing handshake
*
* @param channel
* Channel
* @param frame
* Closing Frame that was received
*/
public abstract ChannelFuture close(Channel channel, CloseWebSocketFrame frame);
/**
* Selects the first matching supported sub protocol
*
* @param requestedSubprotocols
* CSV of protocols to be supported. e.g. "chat, superchat"
* @return First matching supported sub protocol. Null if not found.
*/
protected String selectSubprotocol(String requestedSubprotocols) {
if (requestedSubprotocols == null || subprotocols.length == 0) {
return null;
}
String[] requesteSubprotocolArray = requestedSubprotocols.split(",");
for (String p: requesteSubprotocolArray) {
String requestedSubprotocol = p.trim();
for (String supportedSubprotocol: subprotocols) {
if (requestedSubprotocol.equals(supportedSubprotocol)) {
return requestedSubprotocol;
}
}
}
// No match found
return null;
}
}
| apache-2.0 |
xloye/tddl5 | tddl-monitor/src/test/java/com/tddl/tddl/monitor/logger/DynamicLoggerTest.java | 792 | package com.tddl.tddl.monitor.logger;
import org.junit.Test;
import com.taobao.tddl.monitor.logger.LoggerInit;
public class DynamicLoggerTest {
// @Test
public void testLog4j() {
System.setProperty("tddl.application.logger", "log4j");
System.setProperty("user.home", System.getProperty("java.io.tmpdir", "/tmp"));
System.out.println(LoggerInit.logger.getDelegate().getClass());
LoggerInit.logger.error("this is test");
}
@Test
public void testLogback() {
System.setProperty("tddl.application.logger", "slf4j");
System.setProperty("user.home", System.getProperty("java.io.tmpdir", "/tmp"));
System.out.println(LoggerInit.logger.getDelegate().getClass());
LoggerInit.logger.error("this is test");
}
}
| apache-2.0 |
humorousz/HappyJoke | commonutils/src/test/java/com/humorousz/commonutils/JsonParseUnitTest.java | 3087 | package com.humorousz.commonutils;
import com.humorousz.commonutils.json.model.IJokeModel;
import com.humorousz.commonutils.json.model.JokeModel;
import com.humorousz.commonutils.json.model.Person;
import com.humorousz.commonutils.json.model.Team;
import com.humorousz.commonutils.json.JsonTools;
import org.json.JSONException;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by zhangzhiquan on 2017/5/1.
*/
public class JsonParseUnitTest {
String jsonTeam = "{\"persons\":[{\"name\":\"Bob\",\"age\":14,\"married\":false,\"salary\":null},{\"name\":\"Kate\",\"age\":26,\"married\":true,\"salary\":8888.88}],\"team\":\"Android\"}";
String jsonPerson = "{\"name\":null,\"age\":14,\"married\":false,\"salary\":null}";
String jsonString = "{\"code\":200,\"msg\":\"success\",\"newslist\":[{\"id\":2394,\"title\":\"正点火车\",\"content\":\"<br\\/>商人吉米在铁路上做了多年的买卖,这天偶然发现一列火车<br\\/>准时到了站。<br\\/>他连忙跑到列车员跟前说:“请吸烟,我祝贺你!我在这条<br\\/>铁路上跑了15年,这还是第一次见火车正点到站。”<br\\/>“留着你的烟吧,”列车员说,“这是昨天的列车!”<br\\/>\"}]}";
@Test
public void parseJson_isNotEmpty(){
Team team = JsonTools.parse(jsonTeam,Team.class);
Person person = JsonTools.parse(jsonPerson,Person.class);
IJokeModel model = JsonTools.parse(jsonString,JokeModel.class);
assertNotNull(team);
assertNotNull(person);
assertNotNull(model);
}
@Test
public void parseTeam_isCorrect(){
Team team = JsonTools.parse(jsonTeam,Team.class);
assertNotNull(team);
List<Person> persons = team.getPersons();
assertEquals(persons.size(),2);
Person person1 = persons.get(0);
Person person2 = persons.get(1);
assertPerson(person1,"Bob",14,false,0.0);
assertPerson(person2,"Kate",26,true,8888.88);
assertEquals(team.getTeam(),"Android");
}
@Test
public void parsePerson_isCorrect(){
Person person = JsonTools.parse(jsonPerson,Person.class);
assertNotNull(person);
assertPerson(person,null,14,false,0.0);
}
private void assertPerson(Person person,String name,int age,boolean married,double salary){
assertEquals(person.getName(),name);
assertEquals(person.getAge(),age);
assertEquals(person.isMarried(),married);
assertEquals(person.getSalary(),salary,0.5);
}
@Test
public void parseJson_isCorrect() throws JSONException {
IJokeModel model = JsonTools.parse(jsonString, JokeModel.class);
assertNotNull(model);
List<JokeModel.JokeItem> list = model.getJokeItems();
assertEquals(list.size(),1);
JokeModel.JokeItem item = list.get(0);
assertEquals(item.id,2394);
assertEquals(item.title,"正点火车");
assertTrue(item.content.contains("商人吉米在铁路上做了多年的买卖"));
}
}
| apache-2.0 |
vishnudevk/MiBandDecompiled | Original Files/source/src/android/support/v4/net/k.java | 520 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package android.support.v4.net;
// Referenced classes of package android.support.v4.net:
// l, j
class k extends ThreadLocal
{
final j a;
k(j j)
{
a = j;
super();
}
protected l a()
{
return new l(null);
}
protected Object initialValue()
{
return a();
}
}
| apache-2.0 |
robjcaskey/Unofficial-Coffee-Mud-Upstream | com/planet_ink/coffee_mud/Abilities/Poisons/Poison_Hives.java | 3604 | package com.planet_ink.coffee_mud.Abilities.Poisons;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Poison_Hives extends Poison
{
public String ID() { return "Poison_Hives"; }
public String name(){ return "Hives";}
public String displayText(){ return "(Hives)";}
protected int canAffectCode(){return CAN_MOBS;}
protected int canTargetCode(){return CAN_MOBS;}
public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
public boolean putInCommandlist(){return false;}
private static final String[] triggerStrings = {"POISONHIVES"};
public String[] triggerStrings(){return triggerStrings;}
protected int POISON_TICKS(){return 60;} // 0 means no adjustment!
protected int POISON_DELAY(){return 5;}
protected String POISON_DONE(){return "The hives clear up.";}
protected String POISON_START(){return "^G<S-NAME> break(s) out in hives!^?";}
protected String POISON_AFFECT(){return "^G<S-NAME> scratch(es) <S-HIM-HERSELF> as more hives break out.";}
protected String POISON_CAST(){return "^F^<FIGHT^><S-NAME> poison(s) <T-NAMESELF>!^</FIGHT^>^?";}
protected String POISON_FAIL(){return "<S-NAME> attempt(s) to poison <T-NAMESELF>, but fail(s).";}
protected int POISON_DAMAGE(){return 0;}
public Poison_Hives()
{
super();
poisonTick = 0;
}
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID)) return false;
if(affected==null) return false;
if(!(affected instanceof MOB)) return true;
MOB mob=(MOB)affected;
if((!mob.amDead())&&((--poisonTick)<=0))
{
poisonTick=POISON_DELAY();
mob.location().show(mob,null,CMMsg.MSG_NOISYMOVEMENT,POISON_AFFECT());
return true;
}
return true;
}
public void affectCharStats(MOB affected, CharStats affectableStats)
{
if(affected==null) return;
affectableStats.setStat(CharStats.STAT_CHARISMA,affectableStats.getStat(CharStats.STAT_CHARISMA)-1);
affectableStats.setStat(CharStats.STAT_DEXTERITY,affectableStats.getStat(CharStats.STAT_DEXTERITY)-3);
if(affectableStats.getStat(CharStats.STAT_CHARISMA)<=0)
affectableStats.setStat(CharStats.STAT_CHARISMA,1);
if(affectableStats.getStat(CharStats.STAT_DEXTERITY)<=0)
affectableStats.setStat(CharStats.STAT_DEXTERITY,1);
}
}
| apache-2.0 |
marubinotto/Piggydb | src/main/java/marubinotto/util/time/Week.java | 1785 | package marubinotto.util.time;
import java.util.Calendar;
import marubinotto.util.Assert;
/**
* marubinotto.util.time.Week
*/
public class Week extends Interval {
public Week() {
this(DateTime.getCurrentTime());
}
public Week(DateTime dateTime) {
super(getFirstInstantOfWeek(dateTime), getEndInstantOfWeek(dateTime));
}
public String toString() {
return "Week: " + getFirstDay() + " - " + getLastDay();
}
public DateTime getFirstDay() {
return getStartInstant();
}
public DateTime getLastDay() {
return getEndInstant();
}
public DateTime[] getDays() {
DateTime[] days = new DateTime[7];
DateTime firstDay = getFirstDay();
days[0] = firstDay;
for (int i = 1; i < 7; i++) {
days[i] = firstDay.addDays(i);
}
return days;
}
public Week getLastWeek() {
return new Week(getFirstDay().addDays(-1));
}
public Week getNextWeek() {
return new Week(getLastDay().addDays(1));
}
// Utility methods
public static DateTime getFirstInstantOfWeek(DateTime dateTime) {
Assert.Arg.notNull(dateTime, "dateTime");
Calendar calendar = DateTime.createCalendar(dateTime.getYear(),
dateTime.getMonth(), dateTime.getDayOfMonth());
while (true) {
if (calendar.get(Calendar.DAY_OF_WEEK) == calendar.getFirstDayOfWeek()) {
break;
}
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
return new DateTime(calendar);
}
public static DateTime getEndInstantOfWeek(DateTime dateTime) {
Assert.Arg.notNull(dateTime, "dateTime");
DateTime firstInstant = getFirstInstantOfWeek(dateTime);
Calendar calendar = firstInstant.toCalendar();
calendar.add(Calendar.DAY_OF_MONTH, 7);
calendar.add(Calendar.MILLISECOND, -1);
return new DateTime(calendar);
}
}
| apache-2.0 |
brmeyer/s-ramp | ui/src/main/java/org/artificer/ui/client/local/widgets/ontologies/LoadingAllOntologies.java | 1382 | /*
* Copyright 2013 JBoss 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.artificer.ui.client.local.widgets.ontologies;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import com.google.gwt.user.client.ui.Composite;
/**
* "Loading all ontologies" spinner.
* @author eric.wittmann@redhat.com
*/
@Templated("/org/artificer/ui/client/local/site/dialogs/modify-classifiers-dialog.html#modify-classifiers-dialog-spinner-all")
@Dependent
public class LoadingAllOntologies extends Composite {
/**
* Constructor.
*/
public LoadingAllOntologies() {
}
/**
* Called when the dialog is constructed by Errai.
*/
@PostConstruct
protected void onPostConstruct() {
getElement().removeClassName("hide");
}
}
| apache-2.0 |
apache/activemq-openwire | openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v2/OpenWireTempQueueMarshaller.java | 3566 | /**
* 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.activemq.openwire.codec.v2;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.DataStructure;
import org.apache.activemq.openwire.commands.OpenWireTempQueue;
public class OpenWireTempQueueMarshaller extends OpenWireTempDestinationMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return OpenWireTempQueue.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new OpenWireTempQueue();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
int rc = super.tightMarshal1(wireFormat, o, bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
super.looseMarshal(wireFormat, o, dataOut);
}
}
| apache-2.0 |
pacozaa/BoofCV | main/feature/generate/boofcv/alg/feature/orientation/impl/GenerateImplOrientationSlidingWindow.java | 6223 | /*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.feature.orientation.impl;
import boofcv.misc.AutoTypeImage;
import boofcv.misc.CodeGeneratorBase;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* @author Peter Abeles
*/
public class GenerateImplOrientationSlidingWindow extends CodeGeneratorBase {
AutoTypeImage imageType;
@Override
public void generate() throws FileNotFoundException {
printClass(AutoTypeImage.F32);
printClass(AutoTypeImage.S16);
printClass(AutoTypeImage.S32);
}
private void printClass( AutoTypeImage imageType ) throws FileNotFoundException {
this.imageType = imageType;
className = "ImplOrientationSlidingWindow_"+imageType.getAbbreviatedType();
out = new PrintStream(new FileOutputStream(className + ".java"));
printPreamble();
printComputeAngles();
printUnweighted();
printWeighted();
out.print("}\n");
}
private void printPreamble() throws FileNotFoundException {
setOutputFile(className);
out.print("import boofcv.alg.feature.orientation.OrientationSlidingWindow;\n" +
"import boofcv.struct.image."+imageType.getSingleBandName()+";\n" +
"import georegression.metric.UtilAngle;\n" +
"\n" +
"/**\n" +
" * <p>\n" +
" * Implementation of {@link OrientationSlidingWindow} for a specific image type.\n" +
" * </p>\n" +
" *\n" +
" * <p>\n" +
" * WARNING: Do not modify. Automatically generated by {@link GenerateImplOrientationSlidingWindow}.\n" +
" * </p>\n" +
" *\n" +
" * @author Peter Abeles\n" +
" */\n" +
"public class "+className+" extends OrientationSlidingWindow<"+imageType.getSingleBandName()+"> {\n" +
"\n" +
"\tpublic "+className+"(int numAngles, double windowSize, boolean isWeighted) {\n" +
"\t\tsuper(numAngles, windowSize, isWeighted);\n" +
"\t}\n" +
"\n" +
"\t@Override\n" +
"\tpublic Class<"+imageType.getSingleBandName()+"> getImageType() {\n" +
"\t\treturn "+imageType.getSingleBandName()+".class;\n" +
"\t}\n\n");
}
private void printComputeAngles() {
String bitWise = imageType.getBitWise();
String sumType = imageType.getSumType();
out.print("\tprivate void computeAngles() {\n" +
"\t\tint i = 0;\n" +
"\t\tfor( int y = rect.y0; y < rect.y1; y++ ) {\n" +
"\t\t\tint indexX = derivX.startIndex + derivX.stride*y + rect.x0;\n" +
"\t\t\tint indexY = derivY.startIndex + derivY.stride*y + rect.x0;\n" +
"\n" +
"\t\t\tfor( int x = rect.x0; x < rect.x1; x++ , indexX++ , indexY++ ) {\n" +
"\t\t\t\t"+sumType+" dx = derivX.data[indexX]"+bitWise+";\n" +
"\t\t\t\t"+sumType+" dy = derivY.data[indexY]"+bitWise+";\n" +
"\n" +
"\t\t\t\tangles[i++] = Math.atan2(dy,dx);\n" +
"\t\t\t}\n" +
"\t\t}\n" +
"\t}\n\n");
}
private void printUnweighted() {
out.print("\t@Override\n" +
"\tprotected double computeOrientation() {\n" +
"\t\tcomputeAngles();\n" +
"\n" +
"\t\tdouble windowRadius = windowSize/2.0;\n" +
"\t\tint w = rect.x1-rect.x0;\n" +
"\t\tdouble bestScore = -1;\n" +
"\t\tdouble bestAngle = 0;\n" +
"\t\tdouble stepAngle = Math.PI*2.0/numAngles;\n" +
"\n" +
"\t\tint N = w*(rect.y1-rect.y0);\n" +
"\t\tfor( double angle = -Math.PI; angle < Math.PI; angle += stepAngle ) {\n" +
"\t\t\tdouble dx = 0;\n" +
"\t\t\tdouble dy = 0;\n" +
"\t\t\tfor( int i = 0; i < N; i++ ) {\n" +
"\t\t\t\tdouble diff = UtilAngle.dist(angle,angles[i]);\n" +
"\t\t\t\tif( diff <= windowRadius) {\n" +
"\t\t\t\t\tint x = rect.x0 + i % w;\n" +
"\t\t\t\t\tint y = rect.y0 + i / w;\n" +
"\t\t\t\t\tdx += derivX.get(x,y);\n" +
"\t\t\t\t\tdy += derivY.get(x,y);\n" +
"\t\t\t\t}\n" +
"\t\t\t}\n" +
"\t\t\tdouble n = dx*dx + dy*dy;\n" +
"\t\t\tif( n > bestScore) {\n" +
"\t\t\t\tbestAngle = Math.atan2(dy,dx);\n" +
"\t\t\t\tbestScore = n;\n" +
"\t\t\t}\n" +
"\t\t}\n" +
"\n" +
"\t\treturn bestAngle;\n" +
"\t}\n\n");
}
private void printWeighted() {
out.print("\t@Override\n" +
"\tprotected double computeWeightedOrientation(int c_x, int c_y) {\n" +
"\t\tcomputeAngles();\n" +
"\n" +
"\t\tdouble windowRadius = windowSize/2.0;\n" +
"\t\tint w = rect.x1-rect.x0;\n" +
"\t\tdouble bestScore = -1;\n" +
"\t\tdouble bestAngle = 0;\n" +
"\t\tdouble stepAngle = Math.PI*2.0/numAngles;\n" +
"\t\tint N = w*(rect.y1-rect.y0);\n" +
"\n" +
"\t\tfor( double angle = -Math.PI; angle < Math.PI; angle += stepAngle ) {\n" +
"\t\t\tdouble dx = 0;\n" +
"\t\t\tdouble dy = 0;\n" +
"\t\t\tfor( int i = 0; i < N; i++ ) {\n" +
"\t\t\t\tdouble diff = UtilAngle.dist(angle,angles[i]);\n" +
"\t\t\t\tif( diff <= windowRadius) {\n" +
"\t\t\t\t\tint localX = i%w;\n" +
"\t\t\t\t\tint localY = i/w;\n" +
"\t\t\t\t\tdouble ww = weights.get(localX,localY);\n" +
"\t\t\t\t\tint x = rect.x0 + i % w;\n" +
"\t\t\t\t\tint y = rect.y0 + i / w;\n" +
"\t\t\t\t\tdx += ww*derivX.get(x,y);\n" +
"\t\t\t\t\tdy += ww*derivY.get(x,y);\n" +
"\t\t\t\t}\n" +
"\t\t\t}\n" +
"\t\t\tdouble n = dx*dx + dy*dy;\n" +
"\t\t\tif( n > bestScore) {\n" +
"\t\t\t\tbestAngle = Math.atan2(dy,dx);\n" +
"\t\t\t\tbestScore = n;\n" +
"\t\t\t}\n" +
"\t\t}\n" +
"\n" +
"\t\treturn bestAngle;\n" +
"\t}\n\n");
}
public static void main( String argsp[] ) throws FileNotFoundException {
GenerateImplOrientationSlidingWindow app = new GenerateImplOrientationSlidingWindow();
app.generate();
}
}
| apache-2.0 |
HonzaKral/elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/StringTermsAggregator.java | 8142 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.terms;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.BytesRefHash;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalOrder;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
/**
* An aggregator of string values.
*/
public class StringTermsAggregator extends AbstractStringTermsAggregator {
private final ValuesSource valuesSource;
protected final BytesRefHash bucketOrds;
private final IncludeExclude.StringFilter includeExclude;
public StringTermsAggregator(String name, AggregatorFactories factories, ValuesSource valuesSource,
BucketOrder order, DocValueFormat format, BucketCountThresholds bucketCountThresholds,
IncludeExclude.StringFilter includeExclude, SearchContext context,
Aggregator parent, SubAggCollectionMode collectionMode, boolean showTermDocCountError,
Map<String, Object> metadata) throws IOException {
super(name, factories, context, parent, order, format, bucketCountThresholds, collectionMode, showTermDocCountError, metadata);
this.valuesSource = valuesSource;
this.includeExclude = includeExclude;
bucketOrds = new BytesRefHash(1, context.bigArrays());
}
@Override
public ScoreMode scoreMode() {
if (valuesSource != null && valuesSource.needsScores()) {
return ScoreMode.COMPLETE;
}
return super.scoreMode();
}
@Override
public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
final LeafBucketCollector sub) throws IOException {
final SortedBinaryDocValues values = valuesSource.bytesValues(ctx);
return new LeafBucketCollectorBase(sub, values) {
final BytesRefBuilder previous = new BytesRefBuilder();
@Override
public void collect(int doc, long bucket) throws IOException {
assert bucket == 0;
if (values.advanceExact(doc)) {
final int valuesCount = values.docValueCount();
// SortedBinaryDocValues don't guarantee uniqueness so we
// need to take care of dups
previous.clear();
for (int i = 0; i < valuesCount; ++i) {
final BytesRef bytes = values.nextValue();
if (includeExclude != null && !includeExclude.accept(bytes)) {
continue;
}
if (i > 0 && previous.get().equals(bytes)) {
continue;
}
long bucketOrdinal = bucketOrds.add(bytes);
if (bucketOrdinal < 0) { // already seen
bucketOrdinal = -1 - bucketOrdinal;
collectExistingBucket(sub, doc, bucketOrdinal);
} else {
collectBucket(sub, doc, bucketOrdinal);
}
previous.copyBytes(bytes);
}
}
}
};
}
@Override
public InternalAggregation buildAggregation(long owningBucketOrdinal) throws IOException {
assert owningBucketOrdinal == 0;
if (bucketCountThresholds.getMinDocCount() == 0
&& (InternalOrder.isCountDesc(order) == false
|| bucketOrds.size() < bucketCountThresholds.getRequiredSize())) {
// we need to fill-in the blanks
for (LeafReaderContext ctx : context.searcher().getTopReaderContext().leaves()) {
final SortedBinaryDocValues values = valuesSource.bytesValues(ctx);
// brute force
for (int docId = 0; docId < ctx.reader().maxDoc(); ++docId) {
if (values.advanceExact(docId)) {
final int valueCount = values.docValueCount();
for (int i = 0; i < valueCount; ++i) {
final BytesRef term = values.nextValue();
if (includeExclude == null || includeExclude.accept(term)) {
bucketOrds.add(term);
}
}
}
}
}
}
final int size = (int) Math.min(bucketOrds.size(), bucketCountThresholds.getShardSize());
long otherDocCount = 0;
BucketPriorityQueue<StringTerms.Bucket> ordered = new BucketPriorityQueue<>(size, partiallyBuiltBucketComparator);
StringTerms.Bucket spare = null;
for (int i = 0; i < bucketOrds.size(); i++) {
if (spare == null) {
spare = new StringTerms.Bucket(new BytesRef(), 0, null, showTermDocCountError, 0, format);
}
bucketOrds.get(i, spare.termBytes);
spare.docCount = bucketDocCount(i);
otherDocCount += spare.docCount;
spare.bucketOrd = i;
if (bucketCountThresholds.getShardMinDocCount() <= spare.docCount) {
spare = ordered.insertWithOverflow(spare);
if (spare == null) {
consumeBucketsAndMaybeBreak(1);
}
}
}
// Get the top buckets
final StringTerms.Bucket[] list = new StringTerms.Bucket[ordered.size()];
long survivingBucketOrds[] = new long[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; --i) {
final StringTerms.Bucket bucket = ordered.pop();
survivingBucketOrds[i] = bucket.bucketOrd;
list[i] = bucket;
otherDocCount -= bucket.docCount;
}
// replay any deferred collections
runDeferredCollections(survivingBucketOrds);
// Now build the aggs
for (final StringTerms.Bucket bucket : list) {
bucket.termBytes = BytesRef.deepCopyOf(bucket.termBytes);
bucket.aggregations = bucketAggregations(bucket.bucketOrd);
bucket.docCountError = 0;
}
return new StringTerms(name, order, bucketCountThresholds.getRequiredSize(), bucketCountThresholds.getMinDocCount(),
metadata(), format, bucketCountThresholds.getShardSize(), showTermDocCountError, otherDocCount,
Arrays.asList(list), 0);
}
@Override
public void doClose() {
Releasables.close(bucketOrds);
}
}
| apache-2.0 |
Zhangsongsong/GraduationPro | 毕业设计/code/android/YYFramework/src/app/utils/db/SQLiteHelper.java | 7492 | package app.utils.db;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.ql.utils.debug.QLLog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
public class SQLiteHelper extends SQLiteOpenHelper {
private final String tag = SQLiteHelper.class.getSimpleName();
private SQLInstance instance;
private boolean close = false;
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
return super.getWritableDatabase();
}
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
/**
* 建数据库
*/
public SQLiteHelper(Context context,SQLInstance instance){
super(context,instance.getDatabaseName(),null,instance.getDatabaseVersion());
this.instance = instance;
}
@Override
public void onCreate(SQLiteDatabase db) {
List<SQLEntity> list = instance.getSQLEntity();
if (list == null || list.isEmpty())
return;
for(SQLEntity entity : list){
//执行建表操作
db.execSQL(entity.getCreateSql());
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
QLLog.e(tag, "===onUpgrade===");
QLLog.e(tag, "oldVersion is "+oldVersion);
QLLog.e(tag, "newVersion is "+newVersion);
upgradeTables(db);
instance.onUpdateFinish(db);
}
/**
* Upgrade tables. In this method, the sequence is:
* <b>
* <p>[1] Rename the specified table as a temporary table.
* <p>[2] Create a new table which name is the specified name.
* <p>[3] Insert data into the new created table, data from the temporary table.
* <p>[4] Drop the temporary table.
* </b>
* @param db The database.
* @param tableName The table name.
* @param columns The columns range, format is "ColA, ColB, ColC, ... ColN";
*/
protected void upgradeTables(SQLiteDatabase db) {
QLLog.e(tag,"upgradeTables");
List<SQLEntity> list = instance.getSQLEntity();
for(SQLEntity entity : list){
QLLog.e(tag, "table is "+entity.getTable());
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' and name='"+entity.getTable()+"' order by name",null);
int count = c.getCount();
if(count > 0){
String [] columnNames = getColumnNames(db, entity.getTable());
if(columnNames != null && columnNames.length > 0){
Map<String,String> field = entity.getField();
String columns = "";
boolean first = true;
for(int i=0,length=columnNames.length;i<length;i++){
if(field.containsKey(columnNames[i])){
columns += (first ? "" : ",")+columnNames[i];
first = false;
}
}
QLLog.e(tag, "columns is "+columns);
if(TextUtils.isEmpty(columns))
continue;
String tableName = entity.getTable();
String tempTableName = tableName + "_temp";
//表重命名
db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tempTableName);
//创建表
db.execSQL(entity.getCreateSql());
//旧数据转移
db.execSQL("INSERT INTO "+tableName+"("+columns+") SELECT "+columns+" FROM "+tempTableName);
//删除临时表
db.execSQL("DROP TABLE "+tempTableName);
}
}else{
db.execSQL(entity.getCreateSql());
}
}
}
public static String[] getColumnNames(SQLiteDatabase db, String tableName) {
String[] columnNames = null;
Cursor c = null;
try {
c = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
if (null != c) {
int columnIndex = c.getColumnIndex("name");
if (-1 == columnIndex) {
return null;
}
int index = 0;
columnNames = new String[c.getCount()];
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
columnNames[index] = c.getString(columnIndex);
index++;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(c != null) c.close();
}
return columnNames;
}
public synchronized boolean isClose(){
return close;
}
@Override
public synchronized void close() {
super.close();
close = true;
}
public synchronized boolean isEmpty(String table) {
String sql = "SELECT COUNT() FROM "+table;
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(sql, null);
int count = c.getCount();
closeDb(db, c);
return count > 0;
}
public synchronized boolean isEmpty(String table,String selection,String[] selectionArgs) {
String sql = "SELECT COUNT() FROM "+table;
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(sql, null,selection,selectionArgs,null,null,null);
int count = c.getCount();
closeDb(db, c);
return count > 0;
}
/**
* 更新数据库
* @param table
* @param values
* @param whereClause
* @param whereArgs
* @return
*/
public synchronized boolean update(String table, ContentValues values, String whereClause, String... whereArgs) {
SQLiteDatabase db = getWritableDatabase();
final int affectedRows = db.update(table, values, whereClause, whereArgs);
closeDb(db, null);
return affectedRows > 0;
}
/**
* 插入数据库
* @param table
* @param values
* @return
*/
public synchronized long insert(String table, ContentValues values) {
long result = 0L;
SQLiteDatabase db = getWritableDatabase();
result = db.insert(table, null, values);
closeDb(db, null);
return result;
}
/**
* 插入或更新
* @param table
* @param values
* @param whereClause
* @param whereArgs
* @return
*/
public synchronized boolean insertOrUpdate(String table, ContentValues values, String whereClause, String... whereArgs) {
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(table, null, whereClause, whereArgs, null, null, null);
int count = c.getCount();
closeDb(db, c);
if (count > 0) {
return update(table, values, whereClause, whereArgs);
} else {
return insert(table, values) > 0L;
}
}
/**
* 删除
* @param table
* @param whereClause
* @param whereArgs
* @return
*/
public synchronized boolean delete(String table, String whereClause, String... whereArgs) {
int rows = 0;
SQLiteDatabase db = getWritableDatabase();
try {
rows = db.delete(table, whereClause, whereArgs);
} catch (SQLException e) {
} catch (Exception e) {
} finally {
closeDb(db, null);
}
return rows > 0;
}
public synchronized Cursor query(String table, String whereClause, String... whereArgs){
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(table,null,whereClause,whereArgs,null,null,null);
closeDb(db,null);
return c;
}
public synchronized Cursor rawQuery(String sql, String... selectionArgs){
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(sql,selectionArgs);
closeDb(db,null);
return c;
}
public synchronized void execSQL(String sql){
SQLiteDatabase db = getWritableDatabase();
db.execSQL(sql);
closeDb(db, null);
}
public synchronized void execSQL(String sql, Object[] bindArgs){
SQLiteDatabase db = getWritableDatabase();
db.execSQL(sql,bindArgs);
closeDb(db, null);
}
/**
* 释放数据库资源
**/
public static void closeDb(SQLiteDatabase db, Cursor c) {
if (c != null) {
c.close();
}
if (db != null) {
// db.close();
}
}
public static void shutdownDataBase(SQLiteDatabase db){
if (db != null) {
db.close();
}
}
}
| apache-2.0 |
vesense/hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/RandomWriter.java | 10582 | /**
* 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.hadoop.mapreduce;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.ClusterStatus;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* This program uses map/reduce to just run a distributed job where there is
* no interaction between the tasks and each task write a large unsorted
* random binary sequence file of BytesWritable.
* In order for this program to generate data for terasort with 10-byte keys
* and 90-byte values, have the following config:
* <xmp>
* <?xml version="1.0"?>
* <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
* <configuration>
* <property>
* <name>mapreduce.randomwriter.minkey</name>
* <value>10</value>
* </property>
* <property>
* <name>mapreduce.randomwriter.maxkey</name>
* <value>10</value>
* </property>
* <property>
* <name>mapreduce.randomwriter.minvalue</name>
* <value>90</value>
* </property>
* <property>
* <name>mapreduce.randomwriter.maxvalue</name>
* <value>90</value>
* </property>
* <property>
* <name>mapreduce.randomwriter.totalbytes</name>
* <value>1099511627776</value>
* </property>
* </configuration></xmp>
*
* Equivalently, {@link RandomWriter} also supports all the above options
* and ones supported by {@link GenericOptionsParser} via the command-line.
*/
public class RandomWriter extends Configured implements Tool {
public static final String TOTAL_BYTES = "mapreduce.randomwriter.totalbytes";
public static final String BYTES_PER_MAP =
"mapreduce.randomwriter.bytespermap";
public static final String MAPS_PER_HOST =
"mapreduce.randomwriter.mapsperhost";
public static final String MAX_VALUE = "mapreduce.randomwriter.maxvalue";
public static final String MIN_VALUE = "mapreduce.randomwriter.minvalue";
public static final String MIN_KEY = "mapreduce.randomwriter.minkey";
public static final String MAX_KEY = "mapreduce.randomwriter.maxkey";
/**
* User counters
*/
static enum Counters { RECORDS_WRITTEN, BYTES_WRITTEN }
/**
* A custom input format that creates virtual inputs of a single string
* for each map.
*/
static class RandomInputFormat extends InputFormat<Text, Text> {
/**
* Generate the requested number of file splits, with the filename
* set to the filename of the output file.
*/
public List<InputSplit> getSplits(JobContext job) throws IOException {
List<InputSplit> result = new ArrayList<InputSplit>();
Path outDir = FileOutputFormat.getOutputPath(job);
int numSplits =
job.getConfiguration().getInt(MRJobConfig.NUM_MAPS, 1);
for(int i=0; i < numSplits; ++i) {
result.add(new FileSplit(new Path(outDir, "dummy-split-" + i), 0, 1,
(String[])null));
}
return result;
}
/**
* Return a single record (filename, "") where the filename is taken from
* the file split.
*/
static class RandomRecordReader extends RecordReader<Text, Text> {
Path name;
Text key = null;
Text value = new Text();
public RandomRecordReader(Path p) {
name = p;
}
public void initialize(InputSplit split,
TaskAttemptContext context)
throws IOException, InterruptedException {
}
public boolean nextKeyValue() {
if (name != null) {
key = new Text();
key.set(name.getName());
name = null;
return true;
}
return false;
}
public Text getCurrentKey() {
return key;
}
public Text getCurrentValue() {
return value;
}
public void close() {}
public float getProgress() {
return 0.0f;
}
}
public RecordReader<Text, Text> createRecordReader(InputSplit split,
TaskAttemptContext context) throws IOException, InterruptedException {
return new RandomRecordReader(((FileSplit) split).getPath());
}
}
static class RandomMapper extends Mapper<WritableComparable, Writable,
BytesWritable, BytesWritable> {
private long numBytesToWrite;
private int minKeySize;
private int keySizeRange;
private int minValueSize;
private int valueSizeRange;
private Random random = new Random();
private BytesWritable randomKey = new BytesWritable();
private BytesWritable randomValue = new BytesWritable();
private void randomizeBytes(byte[] data, int offset, int length) {
for(int i=offset + length - 1; i >= offset; --i) {
data[i] = (byte) random.nextInt(256);
}
}
/**
* Given an output filename, write a bunch of random records to it.
*/
public void map(WritableComparable key,
Writable value,
Context context) throws IOException,InterruptedException {
int itemCount = 0;
while (numBytesToWrite > 0) {
int keyLength = minKeySize +
(keySizeRange != 0 ? random.nextInt(keySizeRange) : 0);
randomKey.setSize(keyLength);
randomizeBytes(randomKey.getBytes(), 0, randomKey.getLength());
int valueLength = minValueSize +
(valueSizeRange != 0 ? random.nextInt(valueSizeRange) : 0);
randomValue.setSize(valueLength);
randomizeBytes(randomValue.getBytes(), 0, randomValue.getLength());
context.write(randomKey, randomValue);
numBytesToWrite -= keyLength + valueLength;
context.getCounter(Counters.BYTES_WRITTEN).increment(keyLength + valueLength);
context.getCounter(Counters.RECORDS_WRITTEN).increment(1);
if (++itemCount % 200 == 0) {
context.setStatus("wrote record " + itemCount + ". " +
numBytesToWrite + " bytes left.");
}
}
context.setStatus("done with " + itemCount + " records.");
}
/**
* Save the values out of the configuaration that we need to write
* the data.
*/
@Override
public void setup(Context context) {
Configuration conf = context.getConfiguration();
numBytesToWrite = conf.getLong(BYTES_PER_MAP,
1*1024*1024*1024);
minKeySize = conf.getInt(MIN_KEY, 10);
keySizeRange =
conf.getInt(MAX_KEY, 1000) - minKeySize;
minValueSize = conf.getInt(MIN_VALUE, 0);
valueSizeRange =
conf.getInt(MAX_VALUE, 20000) - minValueSize;
}
}
/**
* This is the main routine for launching a distributed random write job.
* It runs 10 maps/node and each node writes 1 gig of data to a DFS file.
* The reduce doesn't do anything.
*
* @throws IOException
*/
public int run(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Usage: writer <out-dir>");
ToolRunner.printGenericCommandUsage(System.out);
return 2;
}
Path outDir = new Path(args[0]);
Configuration conf = getConf();
JobClient client = new JobClient(conf);
ClusterStatus cluster = client.getClusterStatus();
int numMapsPerHost = conf.getInt(MAPS_PER_HOST, 10);
long numBytesToWritePerMap = conf.getLong(BYTES_PER_MAP,
1*1024*1024*1024);
if (numBytesToWritePerMap == 0) {
System.err.println("Cannot have" + BYTES_PER_MAP + " set to 0");
return -2;
}
long totalBytesToWrite = conf.getLong(TOTAL_BYTES,
numMapsPerHost*numBytesToWritePerMap*cluster.getTaskTrackers());
int numMaps = (int) (totalBytesToWrite / numBytesToWritePerMap);
if (numMaps == 0 && totalBytesToWrite > 0) {
numMaps = 1;
conf.setLong(BYTES_PER_MAP, totalBytesToWrite);
}
conf.setInt(MRJobConfig.NUM_MAPS, numMaps);
Job job = Job.getInstance(conf);
job.setJarByClass(RandomWriter.class);
job.setJobName("random-writer");
FileOutputFormat.setOutputPath(job, outDir);
job.setOutputKeyClass(BytesWritable.class);
job.setOutputValueClass(BytesWritable.class);
job.setInputFormatClass(RandomInputFormat.class);
job.setMapperClass(RandomMapper.class);
job.setReducerClass(Reducer.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
System.out.println("Running " + numMaps + " maps.");
// reducer NONE
job.setNumReduceTasks(0);
Date startTime = new Date();
System.out.println("Job started: " + startTime);
int ret = job.waitForCompletion(true) ? 0 : 1;
Date endTime = new Date();
System.out.println("Job ended: " + endTime);
System.out.println("The job took " +
(endTime.getTime() - startTime.getTime()) /1000 +
" seconds.");
return ret;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new RandomWriter(), args);
System.exit(res);
}
}
| apache-2.0 |
narfindustries/autopsy | Core/src/org/sleuthkit/autopsy/datamodel/RecentFilesFilterNode.java | 3475 | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2014 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.sleuthkit.autopsy.datamodel;
import java.util.Calendar;
import java.util.Locale;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.openide.nodes.Children;
import org.openide.nodes.Sheet;
import org.openide.util.lookup.Lookups;
import org.sleuthkit.autopsy.datamodel.RecentFiles.RecentFilesFilter;
import org.sleuthkit.datamodel.SleuthkitCase;
/**
* Node for recent files filter
*/
public class RecentFilesFilterNode extends DisplayableItemNode {
SleuthkitCase skCase;
RecentFilesFilter filter;
private final static Logger logger = Logger.getLogger(RecentFilesFilterNode.class.getName());
RecentFilesFilterNode(SleuthkitCase skCase, RecentFilesFilter filter, Calendar lastDay) {
super(Children.create(new RecentFilesFilterChildren(filter, skCase, lastDay), true), Lookups.singleton(filter.getDisplayName()));
super.setName(filter.getName());
this.skCase = skCase;
this.filter = filter;
Calendar prevDay = (Calendar) lastDay.clone();
prevDay.add(Calendar.DATE, -filter.getDurationDays());
String tooltip = prevDay.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH) + " "
+ prevDay.get(Calendar.DATE) + ", "
+ prevDay.get(Calendar.YEAR);
this.setShortDescription(tooltip);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/recent_files.png"); //NON-NLS
//get count of children without preloading all children nodes
final long count = new RecentFilesFilterChildren(filter, skCase, lastDay).calculateItems();
super.setDisplayName(filter.getDisplayName() + " (" + count + ")");
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
protected Sheet createSheet() {
Sheet s = super.createSheet();
Sheet.Set ss = s.get(Sheet.PROPERTIES);
if (ss == null) {
ss = Sheet.createPropertiesSet();
s.put(ss);
}
ss.put(new NodeProperty<>(
NbBundle.getMessage(this.getClass(), "RecentFilesFilterNode.createSheet.filterType.name"),
NbBundle.getMessage(this.getClass(), "RecentFilesFilterNode.createSheet.filterType.displayName"),
NbBundle.getMessage(this.getClass(), "RecentFilesFilterNode.createSheet.filterType.desc"),
filter.getDisplayName()));
return s;
}
@Override
public boolean isLeafTypeNode() {
return true;
}
@Override
public String getItemType() {
if (filter == null) {
return getClass().getName();
} else {
return getClass().getName() + filter.getName();
}
}
}
| apache-2.0 |
AndrewRosenberg/AuToBI | test/edu/cuny/qc/speech/AuToBI/core/SpectrumTest.java | 11912 | /* SpectrumTest.java
Copyright (c) 2011 Andrew Rosenberg
This file is part of the AuToBI prosodic analysis package.
AuToBI is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
AuToBI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with AuToBI. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.cuny.qc.speech.AuToBI.core;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;
/**
* Test class for Spectrum.
*
* @see Spectrum
*/
public class SpectrumTest {
@Test
public void testStartTime() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
assertEquals(1.0, s.getStartingTime(), 0.0001);
}
@Test
public void testFrameSize() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
assertEquals(0.01, s.getFrameSize(), 0.0001);
}
@Test
public void testNumFrames() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
assertEquals(20, s.numFrames());
}
@Test
public void testNumFreqs() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
assertEquals(10, s.numFreqs());
}
@Test
public void testGet() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
assertEquals(4.0, s.get(7, 4), 0.0001);
}
@Test
public void testGetTimeSlice() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
assertArrayEquals(new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, s.get(7), 0.0001);
}
@Test
public void testGetEmptySliceBelowRange() {
double[][] data = new double[10][10];
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = 0;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(0.1, 0.4);
assertEquals(0, sub_s.numFrames());
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetSliceThrowsExceptionOnNegativeSize() {
double[][] data = new double[10][10];
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = 0;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(0.6, 0.4);
fail();
} catch (AuToBIException e) {
// Expected.
}
}
@Test
public void testGetSliceIsNullOnEmptyData() {
double[][] data = new double[0][0];
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(0.4, 0.5);
assertNull(sub_s);
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetSliceGetsCorrectNumberOfFrames() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(1.034, 1.056);
assertEquals(2, sub_s.numFrames());
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetSliceGetsCorrectNumberOfFramesWithOverhang() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(1.034, 2.0);
assertEquals(16, sub_s.numFrames());
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetSliceGetsCorrectNumberOfFramesWithUnderhang() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(0.00, 1.034);
assertEquals(4, sub_s.numFrames());
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetSliceSetsParamsCorrectly() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(1.034, 1.056);
assertEquals(0.01, sub_s.getFrameSize());
assertEquals(10, sub_s.numFreqs());
assertEquals(1.04, sub_s.getStartingTime());
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetEmptySliceAboveRange() {
double[][] data = new double[10][10];
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = 0;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Spectrum sub_s = s.getSlice(10.1, 10.4);
assertEquals(0, sub_s.numFrames());
} catch (AuToBIException e) {
fail();
}
}
@Test
public void testGetPowerLength() {
double[][] data = new double[20][10];
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPower(false);
assertEquals(20, power.length);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerValues() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPower(false);
assertArrayEquals(new double[]{45.0, 45.0, 45.0, 45.0, 45.0}, power, 0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerLogValues() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPower(true);
assertArrayEquals(new double[]{Math.log(45.0), Math.log(45.0), Math.log(45.0), Math.log(45.0), Math.log(45.0)},
power, 0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerInBandValuesFullBand() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPowerInBand(0.0, 5000, false);
assertArrayEquals(new double[]{45.0, 45.0, 45.0, 45.0, 45.0}, power, 0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerInBandValuesPartialBand() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPowerInBand(15, 34, false);
assertArrayEquals(new double[]{5.0, 5.0, 5.0, 5.0, 5.0}, power, 0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerInBandValuesPartialBandLogValues() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPowerInBand(15, 34, true);
assertArrayEquals(new double[]{Math.log(5.0), Math.log(5.0), Math.log(5.0), Math.log(5.0), Math.log(5.0)}, power,
0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerInBandValuesPartialUnderrunBand() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPowerInBand(-15, 34, false);
assertArrayEquals(new double[]{6.0, 6.0, 6.0, 6.0, 6.0}, power, 0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerInBandValuesPartialOverrunBand() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPowerInBand(75, 340, false);
assertArrayEquals(new double[]{17.0, 17.0, 17.0, 17.0, 17.0}, power, 0.0001);
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerInBandThrowsAnErrorOnBadBounds() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
double[] power = s.getPowerInBand(750, 340, false);
fail();
} catch (AuToBIException e) {
// Expected.
}
}
@Test
public void testGetPowerContour() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Contour power = s.getPowerContour(15, 34, true);
assertEquals(5, power.size());
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetPowerTiltContour() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
try {
Contour power = s.getPowerTiltContour(15, 34, false);
assertEquals(5, power.size());
assertEquals(5.0 / 45.0, power.get(0));
} catch (AuToBIException e) {
e.printStackTrace();
}
}
@Test
public void testGetSpectralTiltContour() {
double[][] data = new double[5][10];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 10; ++j) {
data[i][j] = j;
}
}
Spectrum s = new Spectrum(data, 1.0, 0.01, 10);
Contour tilt = s.getSpectralTiltContour();
assertEquals(5, tilt.size());
assertEquals(0.025998492074700428, tilt.get(0));
}
}
| apache-2.0 |
jungyang/oauth-client-master | spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/password/ResourceOwnerPasswordTokenGranter.java | 3464 | /*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.provider.password;
import java.util.Map;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
/**
* @author Dave Syer
*
*/
public class ResourceOwnerPasswordTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "password";
private final AuthenticationManager authenticationManager;
public ResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager,
AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
this.authenticationManager = authenticationManager;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = tokenRequest.getRequestParameters();
String username = parameters.get("username");
String password = parameters.get("password");
Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
try {
userAuth = authenticationManager.authenticate(userAuth);
}
catch (AccountStatusException ase) {
//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
throw new InvalidGrantException(ase.getMessage());
}
catch (BadCredentialsException e) {
// If the username/password are wrong the spec says we should send 400/invlid grant
throw new InvalidGrantException(e.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + username);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
}
| apache-2.0 |
prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/forms/RuleFactPropertiesEditionPartForm.java | 27242 | /**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms;
// Start of user code for imports
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.ecore.util.EcoreAdapterFactory;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.eef.runtime.EEFRuntimePlugin;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.EMFComboViewer;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class RuleFactPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, RuleFactPropertiesEditionPart {
protected EMFComboViewer factType;
protected Text factCustomType;
protected Text factName;
protected EMFComboViewer valueType;
protected Text valueLiteral;
// Start of user code for propertyExpression widgets declarations
// End of user code
// Start of user code for valueReferenceKey widgets declarations
// End of user code
/**
* For {@link ISection} use only.
*/
public RuleFactPropertiesEditionPartForm() { super(); }
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public RuleFactPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
*
* @generated NOT
*/
public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
Form form = scrolledForm.getForm();
view = form.getBody();
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(widgetFactory, view);
return scrolledForm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(final FormToolkit widgetFactory, Composite view) {
CompositionSequence ruleFactStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = ruleFactStep.addStep(EsbViewsRepository.RuleFact.Properties.class);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.factType);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.factCustomType);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.factName);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.valueType);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.valueLiteral);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.propertyExpression);
propertiesStep.addStep(EsbViewsRepository.RuleFact.Properties.valueReferenceKey);
composer = new PartComposer(ruleFactStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.RuleFact.Properties.class) {
return createPropertiesGroup(widgetFactory, parent);
}
if (key == EsbViewsRepository.RuleFact.Properties.factType) {
return createFactTypeEMFComboViewer(widgetFactory, parent);
}
if (key == EsbViewsRepository.RuleFact.Properties.factCustomType) {
return createFactCustomTypeText(widgetFactory, parent);
}
if (key == EsbViewsRepository.RuleFact.Properties.factName) {
return createFactNameText(widgetFactory, parent);
}
if (key == EsbViewsRepository.RuleFact.Properties.valueType) {
return createValueTypeEMFComboViewer(widgetFactory, parent);
}
if (key == EsbViewsRepository.RuleFact.Properties.valueLiteral) {
return createValueLiteralText(widgetFactory, parent);
}
// Start of user code for propertyExpression addToPart creation
// End of user code
// Start of user code for valueReferenceKey addToPart creation
// End of user code
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
propertiesSection.setText(EsbMessages.RuleFactPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
propertiesSectionData.horizontalSpan = 3;
propertiesSection.setLayoutData(propertiesSectionData);
Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
propertiesSection.setClient(propertiesGroup);
return propertiesGroup;
}
/**
* @generated NOT
*/
protected Composite createFactTypeEMFComboViewer(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.RuleFact.Properties.factType, EsbMessages.RuleFactPropertiesEditionPart_FactTypeLabel);
factType = new EMFComboViewer(parent);
factType.setContentProvider(new ArrayContentProvider());
factType.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData factTypeData = new GridData(GridData.FILL_HORIZONTAL);
factType.getCombo().setLayoutData(factTypeData);
factType.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() {
@Override
public void handleEvent(Event arg0) {
arg0.doit = false;
}
});
factType.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(RuleFactPropertiesEditionPartForm.this, EsbViewsRepository.RuleFact.Properties.factType, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getFactType()));
}
});
factType.setID(EsbViewsRepository.RuleFact.Properties.factType);
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.RuleFact.Properties.factType, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createFactTypeEMFComboViewer
// End of user code
return parent;
}
protected Composite createFactCustomTypeText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.RuleFact.Properties.factCustomType, EsbMessages.RuleFactPropertiesEditionPart_FactCustomTypeLabel);
factCustomType = widgetFactory.createText(parent, ""); //$NON-NLS-1$
factCustomType.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData factCustomTypeData = new GridData(GridData.FILL_HORIZONTAL);
factCustomType.setLayoutData(factCustomTypeData);
factCustomType.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
EsbViewsRepository.RuleFact.Properties.factCustomType,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, factCustomType.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
EsbViewsRepository.RuleFact.Properties.factCustomType,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, factCustomType.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
factCustomType.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(RuleFactPropertiesEditionPartForm.this, EsbViewsRepository.RuleFact.Properties.factCustomType, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, factCustomType.getText()));
}
}
});
EditingUtils.setID(factCustomType, EsbViewsRepository.RuleFact.Properties.factCustomType);
EditingUtils.setEEFtype(factCustomType, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.RuleFact.Properties.factCustomType, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createFactCustomTypeText
// End of user code
return parent;
}
protected Composite createFactNameText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.RuleFact.Properties.factName, EsbMessages.RuleFactPropertiesEditionPart_FactNameLabel);
factName = widgetFactory.createText(parent, ""); //$NON-NLS-1$
factName.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData factNameData = new GridData(GridData.FILL_HORIZONTAL);
factName.setLayoutData(factNameData);
factName.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
EsbViewsRepository.RuleFact.Properties.factName,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, factName.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
EsbViewsRepository.RuleFact.Properties.factName,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, factName.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
factName.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(RuleFactPropertiesEditionPartForm.this, EsbViewsRepository.RuleFact.Properties.factName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, factName.getText()));
}
}
});
EditingUtils.setID(factName, EsbViewsRepository.RuleFact.Properties.factName);
EditingUtils.setEEFtype(factName, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.RuleFact.Properties.factName, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createFactNameText
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createValueTypeEMFComboViewer(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.RuleFact.Properties.valueType, EsbMessages.RuleFactPropertiesEditionPart_ValueTypeLabel);
valueType = new EMFComboViewer(parent);
valueType.setContentProvider(new ArrayContentProvider());
valueType.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData valueTypeData = new GridData(GridData.FILL_HORIZONTAL);
valueType.getCombo().setLayoutData(valueTypeData);
valueType.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() {
@Override
public void handleEvent(Event arg0) {
arg0.doit = false;
}
});
valueType.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(RuleFactPropertiesEditionPartForm.this, EsbViewsRepository.RuleFact.Properties.valueType, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getValueType()));
}
});
valueType.setID(EsbViewsRepository.RuleFact.Properties.valueType);
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.RuleFact.Properties.valueType, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createValueTypeEMFComboViewer
// End of user code
return parent;
}
protected Composite createValueLiteralText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.RuleFact.Properties.valueLiteral, EsbMessages.RuleFactPropertiesEditionPart_ValueLiteralLabel);
valueLiteral = widgetFactory.createText(parent, ""); //$NON-NLS-1$
valueLiteral.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData valueLiteralData = new GridData(GridData.FILL_HORIZONTAL);
valueLiteral.setLayoutData(valueLiteralData);
valueLiteral.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
EsbViewsRepository.RuleFact.Properties.valueLiteral,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, valueLiteral.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
EsbViewsRepository.RuleFact.Properties.valueLiteral,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, valueLiteral.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
RuleFactPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
valueLiteral.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(RuleFactPropertiesEditionPartForm.this, EsbViewsRepository.RuleFact.Properties.valueLiteral, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, valueLiteral.getText()));
}
}
});
EditingUtils.setID(valueLiteral, EsbViewsRepository.RuleFact.Properties.valueLiteral);
EditingUtils.setEEFtype(valueLiteral, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.RuleFact.Properties.valueLiteral, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createValueLiteralText
// End of user code
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#getFactType()
*
*/
public Enumerator getFactType() {
Enumerator selection = (Enumerator) ((StructuredSelection) factType.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#initFactType(Object input, Enumerator current)
*/
public void initFactType(Object input, Enumerator current) {
factType.setInput(input);
factType.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.factType);
if (eefElementEditorReadOnlyState && factType.isEnabled()) {
factType.setEnabled(false);
factType.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !factType.isEnabled()) {
factType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#setFactType(Enumerator newValue)
*
*/
public void setFactType(Enumerator newValue) {
factType.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.factType);
if (eefElementEditorReadOnlyState && factType.isEnabled()) {
factType.setEnabled(false);
factType.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !factType.isEnabled()) {
factType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#getFactCustomType()
*
*/
public String getFactCustomType() {
return factCustomType.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#setFactCustomType(String newValue)
*
*/
public void setFactCustomType(String newValue) {
if (newValue != null) {
factCustomType.setText(newValue);
} else {
factCustomType.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.factCustomType);
if (eefElementEditorReadOnlyState && factCustomType.isEnabled()) {
factCustomType.setEnabled(false);
factCustomType.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !factCustomType.isEnabled()) {
factCustomType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#getFactName()
*
*/
public String getFactName() {
return factName.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#setFactName(String newValue)
*
*/
public void setFactName(String newValue) {
if (newValue != null) {
factName.setText(newValue);
} else {
factName.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.factName);
if (eefElementEditorReadOnlyState && factName.isEnabled()) {
factName.setEnabled(false);
factName.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !factName.isEnabled()) {
factName.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#getValueType()
*
*/
public Enumerator getValueType() {
Enumerator selection = (Enumerator) ((StructuredSelection) valueType.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#initValueType(Object input, Enumerator current)
*/
public void initValueType(Object input, Enumerator current) {
valueType.setInput(input);
valueType.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.valueType);
if (eefElementEditorReadOnlyState && valueType.isEnabled()) {
valueType.setEnabled(false);
valueType.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !valueType.isEnabled()) {
valueType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#setValueType(Enumerator newValue)
*
*/
public void setValueType(Enumerator newValue) {
valueType.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.valueType);
if (eefElementEditorReadOnlyState && valueType.isEnabled()) {
valueType.setEnabled(false);
valueType.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !valueType.isEnabled()) {
valueType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#getValueLiteral()
*
*/
public String getValueLiteral() {
return valueLiteral.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.RuleFactPropertiesEditionPart#setValueLiteral(String newValue)
*
*/
public void setValueLiteral(String newValue) {
if (newValue != null) {
valueLiteral.setText(newValue);
} else {
valueLiteral.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.RuleFact.Properties.valueLiteral);
if (eefElementEditorReadOnlyState && valueLiteral.isEnabled()) {
valueLiteral.setEnabled(false);
valueLiteral.setToolTipText(EsbMessages.RuleFact_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !valueLiteral.isEnabled()) {
valueLiteral.setEnabled(true);
}
}
// Start of user code for propertyExpression specific getters and setters implementation
// End of user code
// Start of user code for valueReferenceKey specific getters and setters implementation
// End of user code
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.RuleFact_Part_Title;
}
@Override
public NamespacedProperty getPropertyExpression() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setPropertyExpression(NamespacedProperty nameSpacedProperty) {
// TODO Auto-generated method stub
}
@Override
public RegistryKeyProperty getValueReferenceKey() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setValueReferenceKey(RegistryKeyProperty registryKeyProperty) {
// TODO Auto-generated method stub
}
// Start of user code additional methods
// End of user code
}
| apache-2.0 |
smartnews/presto | presto-main/src/main/java/io/prestosql/execution/buffer/BroadcastOutputBuffer.java | 15729 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.prestosql.execution.buffer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.units.DataSize;
import io.prestosql.execution.StateMachine;
import io.prestosql.execution.StateMachine.StateChangeListener;
import io.prestosql.execution.buffer.OutputBuffers.OutputBufferId;
import io.prestosql.memory.context.LocalMemoryContext;
import javax.annotation.concurrent.GuardedBy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.execution.buffer.BufferState.FAILED;
import static io.prestosql.execution.buffer.BufferState.FINISHED;
import static io.prestosql.execution.buffer.BufferState.FLUSHING;
import static io.prestosql.execution.buffer.BufferState.NO_MORE_BUFFERS;
import static io.prestosql.execution.buffer.BufferState.NO_MORE_PAGES;
import static io.prestosql.execution.buffer.BufferState.OPEN;
import static io.prestosql.execution.buffer.OutputBuffers.BufferType.BROADCAST;
import static java.util.Objects.requireNonNull;
public class BroadcastOutputBuffer
implements OutputBuffer
{
private final String taskInstanceId;
private final StateMachine<BufferState> state;
private final OutputBufferMemoryManager memoryManager;
@GuardedBy("this")
private OutputBuffers outputBuffers = OutputBuffers.createInitialEmptyOutputBuffers(BROADCAST);
@GuardedBy("this")
private final Map<OutputBufferId, ClientBuffer> buffers = new ConcurrentHashMap<>();
@GuardedBy("this")
private final List<SerializedPageReference> initialPagesForNewBuffers = new ArrayList<>();
private final AtomicLong totalPagesAdded = new AtomicLong();
private final AtomicLong totalRowsAdded = new AtomicLong();
private final AtomicLong totalBufferedPages = new AtomicLong();
private final AtomicBoolean hasBlockedBefore = new AtomicBoolean();
private final Runnable notifyStatusChanged;
public BroadcastOutputBuffer(
String taskInstanceId,
StateMachine<BufferState> state,
DataSize maxBufferSize,
Supplier<LocalMemoryContext> systemMemoryContextSupplier,
Executor notificationExecutor,
Runnable notifyStatusChanged)
{
this.taskInstanceId = requireNonNull(taskInstanceId, "taskInstanceId is null");
this.state = requireNonNull(state, "state is null");
this.memoryManager = new OutputBufferMemoryManager(
requireNonNull(maxBufferSize, "maxBufferSize is null").toBytes(),
requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null"),
requireNonNull(notificationExecutor, "notificationExecutor is null"));
this.notifyStatusChanged = requireNonNull(notifyStatusChanged, "notifyStatusChanged is null");
}
@Override
public void addStateChangeListener(StateChangeListener<BufferState> stateChangeListener)
{
state.addStateChangeListener(stateChangeListener);
}
@Override
public boolean isFinished()
{
return state.get() == FINISHED;
}
@Override
public double getUtilization()
{
return memoryManager.getUtilization();
}
@Override
public boolean isOverutilized()
{
return (getUtilization() > 0.5) && state.get().canAddPages();
}
@Override
public OutputBufferInfo getInfo()
{
//
// NOTE: this code must be lock free so we do not hang for state machine updates
//
// always get the state first before any other stats
BufferState state = this.state.get();
// buffer it a concurrent collection so it is safe to access out side of guard
// in this case we only want a snapshot of the current buffers
@SuppressWarnings("FieldAccessNotGuarded")
Collection<ClientBuffer> buffers = this.buffers.values();
return new OutputBufferInfo(
"BROADCAST",
state,
state.canAddBuffers(),
state.canAddPages(),
memoryManager.getBufferedBytes(),
totalBufferedPages.get(),
totalRowsAdded.get(),
totalPagesAdded.get(),
buffers.stream()
.map(ClientBuffer::getInfo)
.collect(toImmutableList()));
}
@Override
public void setOutputBuffers(OutputBuffers newOutputBuffers)
{
checkState(!Thread.holdsLock(this), "Cannot set output buffers while holding a lock on this");
requireNonNull(newOutputBuffers, "newOutputBuffers is null");
synchronized (this) {
// ignore buffers added after query finishes, which can happen when a query is canceled
// also ignore old versions, which is normal
BufferState state = this.state.get();
if (state.isTerminal() || outputBuffers.getVersion() >= newOutputBuffers.getVersion()) {
return;
}
// verify this is valid state change
outputBuffers.checkValidTransition(newOutputBuffers);
outputBuffers = newOutputBuffers;
// add the new buffers
for (Entry<OutputBufferId, Integer> entry : outputBuffers.getBuffers().entrySet()) {
if (!buffers.containsKey(entry.getKey())) {
ClientBuffer buffer = getBuffer(entry.getKey());
if (!state.canAddPages()) {
buffer.setNoMorePages();
}
}
}
// update state if no more buffers is set
if (outputBuffers.isNoMoreBufferIds()) {
this.state.compareAndSet(OPEN, NO_MORE_BUFFERS);
this.state.compareAndSet(NO_MORE_PAGES, FLUSHING);
}
}
if (!state.get().canAddBuffers()) {
noMoreBuffers();
}
checkFlushComplete();
}
@Override
public ListenableFuture<?> isFull()
{
return memoryManager.getBufferBlockedFuture();
}
@Override
public void enqueue(List<SerializedPage> pages)
{
checkState(!Thread.holdsLock(this), "Cannot enqueue pages while holding a lock on this");
requireNonNull(pages, "pages is null");
// ignore pages after "no more pages" is set
// this can happen with a limit query
if (!state.get().canAddPages()) {
return;
}
// reserve memory
long bytesAdded = pages.stream().mapToLong(SerializedPage::getRetainedSizeInBytes).sum();
memoryManager.updateMemoryUsage(bytesAdded);
// update stats
long rowCount = pages.stream().mapToLong(SerializedPage::getPositionCount).sum();
totalRowsAdded.addAndGet(rowCount);
totalPagesAdded.addAndGet(pages.size());
totalBufferedPages.addAndGet(pages.size());
// create page reference counts with an initial single reference
List<SerializedPageReference> serializedPageReferences = pages.stream()
.map(pageSplit -> new SerializedPageReference(pageSplit, 1, () -> {
checkState(totalBufferedPages.decrementAndGet() >= 0);
memoryManager.updateMemoryUsage(-pageSplit.getRetainedSizeInBytes());
}))
.collect(toImmutableList());
// if we can still add buffers, remember the pages for the future buffers
Collection<ClientBuffer> buffers;
synchronized (this) {
if (state.get().canAddBuffers()) {
serializedPageReferences.forEach(SerializedPageReference::addReference);
initialPagesForNewBuffers.addAll(serializedPageReferences);
}
// make a copy while holding the lock to avoid race with initialPagesForNewBuffers.addAll above
buffers = safeGetBuffersSnapshot();
}
// add pages to all existing buffers (each buffer will increment the reference count)
buffers.forEach(partition -> partition.enqueuePages(serializedPageReferences));
// drop the initial reference
serializedPageReferences.forEach(SerializedPageReference::dereferencePage);
// if the buffer is full for first time and more clients are expected, update the task status
// notifying a status change will lead to the SourcePartitionedScheduler sending 'no-more-buffers' to unblock
if (!hasBlockedBefore.get()
&& state.get().canAddBuffers()
&& !isFull().isDone()
&& hasBlockedBefore.compareAndSet(false, true)) {
notifyStatusChanged.run();
}
}
@Override
public void enqueue(int partitionNumber, List<SerializedPage> pages)
{
checkState(partitionNumber == 0, "Expected partition number to be zero");
enqueue(pages);
}
@Override
public ListenableFuture<BufferResult> get(OutputBufferId outputBufferId, long startingSequenceId, DataSize maxSize)
{
checkState(!Thread.holdsLock(this), "Cannot get pages while holding a lock on this");
requireNonNull(outputBufferId, "outputBufferId is null");
checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte");
return getBuffer(outputBufferId).getPages(startingSequenceId, maxSize);
}
@Override
public void acknowledge(OutputBufferId bufferId, long sequenceId)
{
checkState(!Thread.holdsLock(this), "Cannot acknowledge pages while holding a lock on this");
requireNonNull(bufferId, "bufferId is null");
getBuffer(bufferId).acknowledgePages(sequenceId);
}
@Override
public void abort(OutputBufferId bufferId)
{
checkState(!Thread.holdsLock(this), "Cannot abort while holding a lock on this");
requireNonNull(bufferId, "bufferId is null");
getBuffer(bufferId).destroy();
checkFlushComplete();
}
@Override
public void setNoMorePages()
{
checkState(!Thread.holdsLock(this), "Cannot set no more pages while holding a lock on this");
state.compareAndSet(OPEN, NO_MORE_PAGES);
state.compareAndSet(NO_MORE_BUFFERS, FLUSHING);
memoryManager.setNoBlockOnFull();
safeGetBuffersSnapshot().forEach(ClientBuffer::setNoMorePages);
checkFlushComplete();
}
@Override
public void destroy()
{
checkState(!Thread.holdsLock(this), "Cannot destroy while holding a lock on this");
// ignore destroy if the buffer already in a terminal state.
if (state.setIf(FINISHED, oldState -> !oldState.isTerminal())) {
noMoreBuffers();
safeGetBuffersSnapshot().forEach(ClientBuffer::destroy);
memoryManager.setNoBlockOnFull();
forceFreeMemory();
}
}
@Override
public void fail()
{
// ignore fail if the buffer already in a terminal state.
if (state.setIf(FAILED, oldState -> !oldState.isTerminal())) {
memoryManager.setNoBlockOnFull();
forceFreeMemory();
// DO NOT destroy buffers or set no more pages. The coordinator manages the teardown of failed queries.
}
}
@Override
public long getPeakMemoryUsage()
{
return memoryManager.getPeakMemoryUsage();
}
@VisibleForTesting
void forceFreeMemory()
{
memoryManager.close();
}
private synchronized ClientBuffer getBuffer(OutputBufferId id)
{
ClientBuffer buffer = buffers.get(id);
if (buffer != null) {
return buffer;
}
// NOTE: buffers are allowed to be created in the FINISHED state because destroy() can move to the finished state
// without a clean "no-more-buffers" message from the scheduler. This happens with limit queries and is ok because
// the buffer will be immediately destroyed.
BufferState state = this.state.get();
checkState(state.canAddBuffers() || !outputBuffers.isNoMoreBufferIds(), "No more buffers already set");
// NOTE: buffers are allowed to be created before they are explicitly declared by setOutputBuffers
// When no-more-buffers is set, we verify that all created buffers have been declared
buffer = new ClientBuffer(taskInstanceId, id);
// do not setup the new buffer if we are already failed
if (state != FAILED) {
// add initial pages
buffer.enqueuePages(initialPagesForNewBuffers);
// update state
if (!state.canAddPages()) {
// BE CAREFUL: set no more pages only if not FAILED, because this allows clients to FINISH
buffer.setNoMorePages();
}
// buffer may have finished immediately before calling this method
if (state == FINISHED) {
buffer.destroy();
}
}
buffers.put(id, buffer);
return buffer;
}
private synchronized Collection<ClientBuffer> safeGetBuffersSnapshot()
{
return ImmutableList.copyOf(this.buffers.values());
}
private void noMoreBuffers()
{
checkState(!Thread.holdsLock(this), "Cannot set no more buffers while holding a lock on this");
List<SerializedPageReference> pages;
synchronized (this) {
pages = ImmutableList.copyOf(initialPagesForNewBuffers);
initialPagesForNewBuffers.clear();
if (outputBuffers.isNoMoreBufferIds()) {
// verify all created buffers have been declared
SetView<OutputBufferId> undeclaredCreatedBuffers = Sets.difference(buffers.keySet(), outputBuffers.getBuffers().keySet());
checkState(undeclaredCreatedBuffers.isEmpty(), "Final output buffers does not contain all created buffer ids: %s", undeclaredCreatedBuffers);
}
}
// dereference outside of synchronized to avoid making a callback while holding a lock
pages.forEach(SerializedPageReference::dereferencePage);
}
private void checkFlushComplete()
{
if (state.get() != FLUSHING && state.get() != NO_MORE_BUFFERS) {
return;
}
if (safeGetBuffersSnapshot().stream().allMatch(ClientBuffer::isDestroyed)) {
destroy();
}
}
@VisibleForTesting
OutputBufferMemoryManager getMemoryManager()
{
return memoryManager;
}
}
| apache-2.0 |
xuse/ef-orm | common-core/src/main/java/jef/tools/maven/jaxb/ReportSet.java | 8069 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.06.23 at 11:23:18 ���� CST
//
package jef.tools.maven.jaxb;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
/**
* Represents a set of reports and configuration to be used to generate them.
*
* <p>Java class for ReportSet complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ReportSet">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="configuration" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='skip' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="inherited" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="reports" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="report" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReportSet", propOrder = {
})
public class ReportSet {
@XmlElement(defaultValue = "default")
protected String id;
protected ReportSet.Configuration configuration;
protected String inherited;
protected ReportSet.Reports reports;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the configuration property.
*
* @return
* possible object is
* {@link ReportSet.Configuration }
*
*/
public ReportSet.Configuration getConfiguration() {
return configuration;
}
/**
* Sets the value of the configuration property.
*
* @param value
* allowed object is
* {@link ReportSet.Configuration }
*
*/
public void setConfiguration(ReportSet.Configuration value) {
this.configuration = value;
}
/**
* Gets the value of the inherited property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInherited() {
return inherited;
}
/**
* Sets the value of the inherited property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInherited(String value) {
this.inherited = value;
}
/**
* Gets the value of the reports property.
*
* @return
* possible object is
* {@link ReportSet.Reports }
*
*/
public ReportSet.Reports getReports() {
return reports;
}
/**
* Sets the value of the reports property.
*
* @param value
* allowed object is
* {@link ReportSet.Reports }
*
*/
public void setReports(ReportSet.Reports value) {
this.reports = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='skip' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"any"
})
public static class Configuration {
@XmlAnyElement
protected List<Element> any;
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
*
*
*/
public List<Element> getAny() {
if (any == null) {
any = new ArrayList<Element>();
}
return this.any;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="report" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"report"
})
public static class Reports {
protected List<String> report;
/**
* Gets the value of the report property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the report property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getReport().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getReport() {
if (report == null) {
report = new ArrayList<String>();
}
return this.report;
}
}
}
| apache-2.0 |
marksimu/killbill | api/src/main/java/org/killbill/billing/junction/BillingEventSet.java | 1235 | /*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2014-2016 Groupon, Inc
* Copyright 2014-2016 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES 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.killbill.billing.junction;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.UUID;
import org.killbill.billing.catalog.api.BillingMode;
import org.killbill.billing.catalog.api.Usage;
public interface BillingEventSet extends SortedSet<BillingEvent> {
public boolean isAccountAutoInvoiceOff();
public BillingMode getRecurringBillingMode();
public List<UUID> getSubscriptionIdsWithAutoInvoiceOff();
public Map<String, Usage> getUsages();
}
| apache-2.0 |
msebire/intellij-community | plugins/java-i18n/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaReferenceContributor.java | 2533 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.intellij.psi.impl.source.resolve.reference.impl.providers;
import com.intellij.codeInspection.i18n.JavaI18nUtil;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.*;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.position.FilterPattern;
import com.intellij.psi.impl.source.resolve.reference.CommentsReferenceContributor;
import com.intellij.psi.javadoc.PsiDocToken;
import org.jetbrains.annotations.NotNull;
import static com.intellij.patterns.XmlPatterns.xmlAttributeValue;
import static com.intellij.patterns.XmlPatterns.xmlTag;
/**
* @author peter
*/
public class JavaReferenceContributor extends PsiReferenceContributor{
@Override
public void registerReferenceProviders(@NotNull final PsiReferenceRegistrar registrar) {
final JavaClassListReferenceProvider classListProvider = new JavaClassListReferenceProvider();
registrar.registerReferenceProvider(xmlAttributeValue(), classListProvider, PsiReferenceRegistrar.LOWER_PRIORITY);
registrar.registerReferenceProvider(xmlTag(), classListProvider, PsiReferenceRegistrar.LOWER_PRIORITY);
final PsiReferenceProvider filePathReferenceProvider = new FilePathReferenceProvider();
registrar.registerReferenceProvider(PlatformPatterns.psiElement(PsiLiteralExpression.class).and(new FilterPattern(new ElementFilter() {
@Override
public boolean isAcceptable(Object element, PsiElement context) {
return !JavaI18nUtil.mustBePropertyKey((PsiLiteralExpression) context, null);
}
@Override
public boolean isClassAcceptable(Class hintClass) {
return true;
}
})), filePathReferenceProvider, PsiReferenceRegistrar.LOWER_PRIORITY);
registrar.registerReferenceProvider(PlatformPatterns.psiElement(PsiDocToken.class),
CommentsReferenceContributor.COMMENTS_REFERENCE_PROVIDER_TYPE.getProvider());
}
}
| apache-2.0 |
matzew/keycloak | testsuite/integration/src/test/java/org/keycloak/testsuite/federation/AbstractKerberosTest.java | 12601 | package org.keycloak.testsuite.federation;
import java.security.Principal;
import java.util.List;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.adapters.HttpClientBuilder;
import org.keycloak.events.Details;
import org.keycloak.federation.kerberos.CommonKerberosConfig;
import org.keycloak.constants.KerberosConstants;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserFederationProvider;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.mappers.UserSessionNoteMapper;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.pages.AccountPasswordPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.rule.KeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.openqa.selenium.WebDriver;
/**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/
public abstract class AbstractKerberosTest {
protected String KERBEROS_APP_URL = "http://localhost:8081/kerberos-portal";
protected KeycloakSPNegoSchemeFactory spnegoSchemeFactory;
protected ResteasyClient client;
@WebResource
protected OAuthClient oauth;
@WebResource
protected WebDriver driver;
@WebResource
protected LoginPage loginPage;
@WebResource
protected AccountPasswordPage changePasswordPage;
protected abstract CommonKerberosConfig getKerberosConfig();
protected abstract KeycloakRule getKeycloakRule();
protected abstract AssertEvents getAssertEvents();
@Before
public void before() {
CommonKerberosConfig kerberosConfig = getKerberosConfig();
spnegoSchemeFactory = new KeycloakSPNegoSchemeFactory(kerberosConfig);
initHttpClient(true);
removeAllUsers();
}
@After
public void after() {
client.close();
client = null;
}
@Test
public void spnegoNotAvailableTest() throws Exception {
initHttpClient(false);
driver.navigate().to(KERBEROS_APP_URL);
String kcLoginPageLocation = driver.getCurrentUrl();
Response response = client.target(kcLoginPageLocation).request().get();
Assert.assertEquals(401, response.getStatus());
Assert.assertEquals(KerberosConstants.NEGOTIATE, response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
String responseText = response.readEntity(String.class);
responseText.contains("Log in to test");
response.close();
}
protected void spnegoLoginTestImpl() throws Exception {
KeycloakRule keycloakRule = getKeycloakRule();
AssertEvents events = getAssertEvents();
Response spnegoResponse = spnegoLogin("hnelson", "secret");
Assert.assertEquals(302, spnegoResponse.getStatus());
events.expectLogin()
.client("kerberos-app")
.user(keycloakRule.getUser("test", "hnelson").getId())
.detail(Details.REDIRECT_URI, KERBEROS_APP_URL)
.detail(Details.AUTH_METHOD, "spnego")
.detail(Details.USERNAME, "hnelson")
.assertEvent();
String location = spnegoResponse.getLocation().toString();
driver.navigate().to(location);
String pageSource = driver.getPageSource();
Assert.assertTrue(pageSource.contains("Kerberos Test") && pageSource.contains("Kerberos servlet secured content"));
spnegoResponse.close();
events.clear();
}
@Test
public void usernamePasswordLoginTest() throws Exception {
KeycloakRule keycloakRule = getKeycloakRule();
AssertEvents events = getAssertEvents();
// Change editMode to READ_ONLY
updateProviderEditMode(UserFederationProvider.EditMode.READ_ONLY);
// Login with username/password from kerberos
changePasswordPage.open();
loginPage.assertCurrent();
loginPage.login("jduke", "theduke");
changePasswordPage.assertCurrent();
// Change password is not possible as editMode is READ_ONLY
changePasswordPage.changePassword("theduke", "newPass", "newPass");
Assert.assertTrue(driver.getPageSource().contains("You can't update your password as your account is read only"));
// Change editMode to UNSYNCED
updateProviderEditMode(UserFederationProvider.EditMode.UNSYNCED);
// Successfully change password now
changePasswordPage.changePassword("theduke", "newPass", "newPass");
Assert.assertTrue(driver.getPageSource().contains("Your password has been updated."));
changePasswordPage.logout();
// Login with old password doesn't work, but with new password works
loginPage.login("jduke", "theduke");
loginPage.assertCurrent();
loginPage.login("jduke", "newPass");
changePasswordPage.assertCurrent();
changePasswordPage.logout();
// Assert SPNEGO login still with the old password as mode is unsynced
events.clear();
Response spnegoResponse = spnegoLogin("jduke", "theduke");
Assert.assertEquals(302, spnegoResponse.getStatus());
events.expectLogin()
.client("kerberos-app")
.user(keycloakRule.getUser("test", "jduke").getId())
.detail(Details.REDIRECT_URI, KERBEROS_APP_URL)
.detail(Details.AUTH_METHOD, "spnego")
.detail(Details.USERNAME, "jduke")
.assertEvent();
spnegoResponse.close();
}
@Test
public void credentialDelegationTest() throws Exception {
// Add kerberos delegation credential mapper
getKeycloakRule().update(new KeycloakRule.KeycloakSetup() {
@Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME,
KerberosConstants.GSS_DELEGATION_CREDENTIAL,
KerberosConstants.GSS_DELEGATION_CREDENTIAL, "String",
true, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME,
true, false);
ClientModel kerberosApp = appRealm.getClientByClientId("kerberos-app");
kerberosApp.addProtocolMapper(protocolMapper);
}
});
// SPNEGO login
spnegoLoginTestImpl();
// Assert servlet authenticated to LDAP with delegated credential
driver.navigate().to(KERBEROS_APP_URL + KerberosCredDelegServlet.CRED_DELEG_TEST_PATH);
String pageSource = driver.getPageSource();
Assert.assertTrue(pageSource.contains("LDAP Data: Horatio Nelson"));
// Remove kerberos delegation credential mapper
getKeycloakRule().update(new KeycloakRule.KeycloakSetup() {
@Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
ClientModel kerberosApp = appRealm.getClientByClientId("kerberos-app");
ProtocolMapperModel toRemove = kerberosApp.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME);
kerberosApp.removeProtocolMapper(toRemove);
}
});
// Clear driver and login again. I can't invoke LDAP now as GSS Credential is not in accessToken
driver.manage().deleteAllCookies();
spnegoLoginTestImpl();
driver.navigate().to(KERBEROS_APP_URL + KerberosCredDelegServlet.CRED_DELEG_TEST_PATH);
pageSource = driver.getPageSource();
Assert.assertFalse(pageSource.contains("LDAP Data: Horatio Nelson"));
Assert.assertTrue(pageSource.contains("LDAP Data: ERROR"));
}
protected Response spnegoLogin(String username, String password) {
driver.navigate().to(KERBEROS_APP_URL);
String kcLoginPageLocation = driver.getCurrentUrl();
// Request for SPNEGO login sent with Resteasy client
spnegoSchemeFactory.setCredentials(username, password);
return client.target(kcLoginPageLocation).request().get();
}
protected void initHttpClient(boolean useSpnego) {
if (client != null) {
after();
}
DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().build();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory);
if (useSpnego) {
Credentials fake = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1, null),
fake);
}
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
client = new ResteasyClientBuilder().httpEngine(engine).build();
}
protected void removeAllUsers() {
KeycloakRule keycloakRule = getKeycloakRule();
KeycloakSession session = keycloakRule.startSession();
try {
RealmManager manager = new RealmManager(session);
RealmModel appRealm = manager.getRealm("test");
List<UserModel> users = session.userStorage().getUsers(appRealm);
for (UserModel user : users) {
if (!user.getUsername().equals(AssertEvents.DEFAULT_USERNAME)) {
session.userStorage().removeUser(appRealm, user);
}
}
Assert.assertEquals(1, session.userStorage().getUsers(appRealm).size());
} finally {
keycloakRule.stopSession(session, true);
}
}
protected void assertUser(String expectedUsername, String expectedEmail, String expectedFirstname, String expectedLastname, boolean updateProfileActionExpected) {
KeycloakRule keycloakRule = getKeycloakRule();
KeycloakSession session = keycloakRule.startSession();
try {
RealmManager manager = new RealmManager(session);
RealmModel appRealm = manager.getRealm("test");
UserModel user = session.users().getUserByUsername(expectedUsername, appRealm);
Assert.assertNotNull(user);
Assert.assertEquals(user.getEmail(), expectedEmail);
Assert.assertEquals(user.getFirstName(), expectedFirstname);
Assert.assertEquals(user.getLastName(), expectedLastname);
if (updateProfileActionExpected) {
Assert.assertEquals(UserModel.RequiredAction.UPDATE_PROFILE.toString(), user.getRequiredActions().iterator().next());
} else {
Assert.assertTrue(user.getRequiredActions().isEmpty());
}
} finally {
keycloakRule.stopSession(session, true);
}
}
protected void updateProviderEditMode(UserFederationProvider.EditMode editMode) {
KeycloakRule keycloakRule = getKeycloakRule();
KeycloakSession session = keycloakRule.startSession();
try {
RealmModel realm = session.realms().getRealm("test");
UserFederationProviderModel kerberosProviderModel = realm.getUserFederationProviders().get(0);
kerberosProviderModel.getConfig().put(LDAPConstants.EDIT_MODE, editMode.toString());
realm.updateUserFederationProvider(kerberosProviderModel);
} finally {
keycloakRule.stopSession(session, true);
}
}
}
| apache-2.0 |
studanshu/datacollector | json-dto/src/main/java/com/streamsets/datacollector/event/json/StageInfoJson.java | 1472 | /**
* Copyright 2016 StreamSets Inc.
*
* Licensed under 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 com.streamsets.datacollector.event.json;
public class StageInfoJson {
private String stageName;
private int stageVersion;
private String libraryName;
public String getStageName() {
return stageName;
}
public void setStageName(String stageName) {
this.stageName = stageName;
}
public int getStageVersion() {
return stageVersion;
}
public void setStageVersion(int stageVersion) {
this.stageVersion = stageVersion;
}
public String getLibraryName() {
return libraryName;
}
public void setLibraryName(String libraryName) {
this.libraryName = libraryName;
}
}
| apache-2.0 |
meetdestiny/geronimo-trader | modules/management/src/java/org/apache/geronimo/management/JMSResource.java | 811 | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.geronimo.management;
/**
* Represents the JSR-77 type with the same name
*
* @version $Rev$ $Date$
*/
public interface JMSResource extends J2EEResource {
}
| apache-2.0 |
facebook/presto | presto-prometheus/src/test/java/com/facebook/presto/plugin/prometheus/TestPrometheusConnectorConfig.java | 3417 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.presto.plugin.prometheus;
import com.google.common.collect.ImmutableMap;
import com.google.inject.ConfigurationException;
import io.airlift.units.Duration;
import org.testng.annotations.Test;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import static com.facebook.airlift.configuration.testing.ConfigAssertions.assertFullMapping;
import static com.facebook.airlift.configuration.testing.ConfigAssertions.assertRecordedDefaults;
import static com.facebook.airlift.configuration.testing.ConfigAssertions.recordDefaults;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class TestPrometheusConnectorConfig
{
@Test
public void testDefaults()
throws URISyntaxException
{
assertRecordedDefaults(recordDefaults(PrometheusConnectorConfig.class)
.setPrometheusURI(new URI("http://localhost:9090"))
.setQueryChunkSizeDuration(Duration.valueOf("10m"))
.setMaxQueryRangeDuration(Duration.valueOf("1h"))
.setCacheDuration(Duration.valueOf("30s"))
.setBearerTokenFile(null));
}
@Test
public void testExplicitPropertyMappings()
{
Map<String, String> properties = new ImmutableMap.Builder<String, String>()
.put("prometheus.uri", "file://test.json")
.put("prometheus.query-chunk-duration", "365d")
.put("prometheus.max-query-duration", "1095d")
.put("prometheus.cache-ttl", "60s")
.put("prometheus.bearer-token-file", "/tmp/bearer_token.txt")
.build();
URI uri = URI.create("file://test.json");
PrometheusConnectorConfig expected = new PrometheusConnectorConfig();
expected.setPrometheusURI(uri);
expected.setQueryChunkSizeDuration(Duration.valueOf("365d"));
expected.setMaxQueryRangeDuration(Duration.valueOf("1095d"));
expected.setCacheDuration(Duration.valueOf("60s"));
expected.setBearerTokenFile(new File("/tmp/bearer_token.txt"));
assertFullMapping(properties, expected);
}
@Test
public void testFailOnDurationLessThanQueryChunkConfig()
throws Exception
{
PrometheusConnectorConfig config = new PrometheusConnectorConfig();
config.setPrometheusURI(new URI("http://doesnotmatter.com"));
config.setQueryChunkSizeDuration(Duration.valueOf("21d"));
config.setMaxQueryRangeDuration(Duration.valueOf("1d"));
config.setCacheDuration(Duration.valueOf("30s"));
assertThatThrownBy(config::checkConfig)
.isInstanceOf(ConfigurationException.class)
.hasMessageContaining("prometheus.max-query-duration must be greater than prometheus.query-chunk-duration");
}
}
| apache-2.0 |
stanfy/helium | helium/src/main/groovy/com/stanfy/helium/handler/codegen/GeneratorOptions.java | 1275 | package com.stanfy.helium.handler.codegen;
import com.stanfy.helium.model.Message;
import com.stanfy.helium.model.Type;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Base class for generators options.
*/
public abstract class GeneratorOptions implements Serializable {
private static final long serialVersionUID = 1;
/** Include type name patterns. */
private Set<String> include = new HashSet<String>();
/** Exclude type name patterns. */
private Set<String> exclude = new HashSet<String>();
public Set<String> getInclude() {
return include;
}
public Set<String> getExclude() {
return exclude;
}
public boolean isTypeIncluded(final Type type) {
String name = type.getName();
for (String pattern : getExclude()) {
if (Pattern.compile(pattern).matcher(name).matches()) {
return false;
}
}
if (getInclude().isEmpty()) {
return true;
}
for (String pattern : getInclude()) {
if (Pattern.compile(pattern).matcher(name).matches()) {
return true;
}
}
return false;
}
public boolean isTypeUserDefinedMessage(final Type type) {
return !type.isAnonymous() && type instanceof Message;
}
}
| apache-2.0 |
Groostav/CMPT880-term-project | intruder/test/tests/benchmarks/testcases/TestRace6.java | 2169 | package benchmarks.testcases;
/**
* Copyright (c) 2007-2008,
* Koushik Sen <ksen@cs.berkeley.edu>
* All rights reserved.
* <p/>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* <p/>
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* <p/>
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* <p/>
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
* <p/>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class TestRace6 {
public static int x = 0;
public final static Object lock = new Object();
public final static Object lock2 = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
public void run() {
synchronized (lock) {
x++;
}
}
};
t1.start();
synchronized (lock2) {
x++;
}
t1.join();
System.out.println("x = "+x);
}
}
| apache-2.0 |
wangsongpeng/jdk-src | src/main/java/javax/naming/ldap/InitialLdapContext.java | 7297 | /*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.naming.ldap;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;
/**
* This class is the starting context for performing
* LDAPv3-style extended operations and controls.
*<p>
* See <tt>javax.naming.InitialContext</tt> and
* <tt>javax.naming.InitialDirContext</tt> for details on synchronization,
* and the policy for how an initial context is created.
*
* <h1>Request Controls</h1>
* When you create an initial context (<tt>InitialLdapContext</tt>),
* you can specify a list of request controls.
* These controls will be used as the request controls for any
* implicit LDAP "bind" operation performed by the context or contexts
* derived from the context. These are called <em>connection request controls</em>.
* Use <tt>getConnectControls()</tt> to get a context's connection request
* controls.
*<p>
* The request controls supplied to the initial context constructor
* are <em>not</em> used as the context request controls
* for subsequent context operations such as searches and lookups.
* Context request controls are set and updated by using
* <tt>setRequestControls()</tt>.
*<p>
* As shown, there can be two different sets of request controls
* associated with a context: connection request controls and context
* request controls.
* This is required for those applications needing to send critical
* controls that might not be applicable to both the context operation and
* any implicit LDAP "bind" operation.
* A typical user program would do the following:
*<blockquote><pre>
* InitialLdapContext lctx = new InitialLdapContext(env, critConnCtls);
* lctx.setRequestControls(critModCtls);
* lctx.modifyAttributes(name, mods);
* Controls[] respCtls = lctx.getResponseControls();
*</pre></blockquote>
* It specifies first the critical controls for creating the initial context
* (<tt>critConnCtls</tt>), and then sets the context's request controls
* (<tt>critModCtls</tt>) for the context operation. If for some reason
* <tt>lctx</tt> needs to reconnect to the server, it will use
* <tt>critConnCtls</tt>. See the <tt>LdapContext</tt> interface for
* more discussion about request controls.
*<p>
* Service provider implementors should read the "Service Provider" section
* in the <tt>LdapContext</tt> class description for implementation details.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see LdapContext
* @see InitialContext
* @see InitialDirContext
* @see javax.naming.spi.NamingManager#setInitialContextFactoryBuilder
* @since 1.3
*/
public class InitialLdapContext extends InitialDirContext implements LdapContext {
private static final String
BIND_CONTROLS_PROPERTY = "java.naming.ldap.control.connect";
/**
* Constructs an initial context using no environment properties or
* connection request controls.
* Equivalent to <tt>new InitialLdapContext(null, null)</tt>.
*
* @throws NamingException if a naming exception is encountered
*/
public InitialLdapContext() throws NamingException {
super(null);
}
/**
* Constructs an initial context
* using environment properties and connection request controls.
* See <tt>javax.naming.InitialContext</tt> for a discussion of
* environment properties.
*
* <p> This constructor will not modify its parameters or
* save references to them, but may save a clone or copy.
* Caller should not modify mutable keys and values in
* <tt>environment</tt> after it has been passed to the constructor.
*
* <p> <tt>connCtls</tt> is used as the underlying context instance's
* connection request controls. See the class description
* for details.
*
* @param environment
* environment used to create the initial DirContext.
* Null indicates an empty environment.
* @param connCtls
* connection request controls for the initial context.
* If null, no connection request controls are used.
*
* @throws NamingException if a naming exception is encountered
*
* @see #reconnect
* @see LdapContext#reconnect
*/
@SuppressWarnings("unchecked")
public InitialLdapContext(Hashtable<?,?> environment,
Control[] connCtls)
throws NamingException {
super(true); // don't initialize yet
// Clone environment since caller owns it.
Hashtable<Object,Object> env = (environment == null)
? new Hashtable<>(11)
: (Hashtable<Object,Object>)environment.clone();
// Put connect controls into environment. Copy them first since
// caller owns the array.
if (connCtls != null) {
Control[] copy = new Control[connCtls.length];
System.arraycopy(connCtls, 0, copy, 0, connCtls.length);
env.put(BIND_CONTROLS_PROPERTY, copy);
}
// set version to LDAPv3
env.put("java.naming.ldap.version", "3");
// Initialize with updated environment
init(env);
}
/**
* Retrieves the initial LDAP context.
*
* @return The non-null cached initial context.
* @exception NotContextException If the initial context is not an
* instance of <tt>LdapContext</tt>.
* @exception NamingException If a naming exception was encountered.
*/
private LdapContext getDefaultLdapInitCtx() throws NamingException{
Context answer = getDefaultInitCtx();
if (!(answer instanceof LdapContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of LdapContext");
}
}
return (LdapContext)answer;
}
// LdapContext methods
// Most Javadoc is deferred to the LdapContext interface.
public ExtendedResponse extendedOperation(ExtendedRequest request)
throws NamingException {
return getDefaultLdapInitCtx().extendedOperation(request);
}
public LdapContext newInstance(Control[] reqCtls)
throws NamingException {
return getDefaultLdapInitCtx().newInstance(reqCtls);
}
public void reconnect(Control[] connCtls) throws NamingException {
getDefaultLdapInitCtx().reconnect(connCtls);
}
public Control[] getConnectControls() throws NamingException {
return getDefaultLdapInitCtx().getConnectControls();
}
public void setRequestControls(Control[] requestControls)
throws NamingException {
getDefaultLdapInitCtx().setRequestControls(requestControls);
}
public Control[] getRequestControls() throws NamingException {
return getDefaultLdapInitCtx().getRequestControls();
}
public Control[] getResponseControls() throws NamingException {
return getDefaultLdapInitCtx().getResponseControls();
}
}
| apache-2.0 |
shroman/ignite | modules/tools/src/main/java/org/apache/ignite/tools/ant/beautifier/GridJavadocAntTask.java | 16526 | /*
* 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.ignite.tools.ant.beautifier;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import jodd.jerry.Jerry;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
/**
* Ant task fixing known HTML issues for Javadoc.
*/
public class GridJavadocAntTask extends MatchingTask {
/** */
private static final String SH_URL = "http://agorbatchev.typepad.com/pub/sh/3_0_83";
/** Directory. */
private File dir;
/** CSS file name. */
private String css;
/** Whether to verify JavaDoc HTML. */
private boolean verify = true;
/**
* Sets directory.
*
* @param dir Directory to set.
*/
public void setDir(File dir) {
assert dir != null;
this.dir = dir;
}
/**
* Sets CSS file name.
*
* @param css CSS file name to set.
*/
public void setCss(String css) {
assert css != null;
this.css = css;
}
/**
* Sets whether to verify JavaDoc HTML.
*
* @param verify Verify flag.
*/
public void setVerify(Boolean verify) {
assert verify != null;
this.verify = verify;
}
/**
* Closes resource.
*
* @param closeable Resource to close.
*/
private void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
}
catch (IOException e) {
log("Failed closing [resource=" + closeable + ", message=" + e.getLocalizedMessage() + ']',
Project.MSG_WARN);
}
}
}
/** {@inheritDoc} */
@Override public void execute() {
if (dir == null)
throw new BuildException("'dir' attribute must be specified.");
if (css == null)
throw new BuildException("'css' attribute must be specified.");
log("dir=" + dir, Project.MSG_DEBUG);
log("css=" + css, Project.MSG_DEBUG);
DirectoryScanner scanner = getDirectoryScanner(dir);
boolean fail = false;
ArrayList<String> errMsgs = new ArrayList<>();
for (String fileName : scanner.getIncludedFiles()) {
String file = dir.getAbsolutePath() + '/' + fileName;
try {
processFile(file);
}
catch (IOException e) {
throw new BuildException("IO error while processing: " + file, e);
}
catch (IllegalArgumentException e) {
System.err.println("JavaDoc error: " + e.getMessage());
errMsgs.add(e.getMessage());
fail = true;
}
}
if (fail)
throw new BuildException("Execution failed due to: " + prepareErrorSummary(errMsgs));
}
/**
* @param errMsgs Err msgs.
*/
private String prepareErrorSummary(ArrayList<String> errMsgs) {
StringBuilder strBdr = new StringBuilder();
for (String errMsg : errMsgs)
strBdr.append(errMsg).append(System.lineSeparator());
return strBdr.toString();
}
/**
* Processes file (validating and cleaning up Javadoc's HTML).
*
* @param file File to cleanup.
* @throws IOException Thrown in case of any I/O error.
* @throws IllegalArgumentException In JavaDoc HTML validation failed.
*/
private void processFile(String file) throws IOException {
assert file != null;
String fileContent = readFileToString(file, Charset.forName("UTF-8"));
if (verify) {
// Parse HTML.
Jerry doc = Jerry.jerry(fileContent);
if (file.endsWith("overview-summary.html")) {
// Try to find Other Packages section.
Jerry otherPackages =
doc.find("div.contentContainer table.overviewSummary caption span:contains('Other Packages')");
if (otherPackages.size() > 0) {
System.err.println("[ERROR]: 'Other Packages' section should not be present, but found: " +
doc.html());
throw new IllegalArgumentException("'Other Packages' section should not be present, " +
"all packages should have corresponding documentation groups: " + file + ";" +
"Please add packages description to parent/pom.xml into <plugin>(maven-javadoc-plugin) / <configuration> / <groups>");
}
}
else if (!isViewHtml(file)) {
// Try to find a class description block.
Jerry descBlock = doc.find("div.contentContainer div.description ul.blockList li.blockList div.block");
if (descBlock.size() == 0)
throw new IllegalArgumentException("Class doesn't have description in file: " + file);
}
}
GridJavadocCharArrayLexReader lexer = new GridJavadocCharArrayLexReader(fileContent.toCharArray());
Collection<GridJavadocToken> toks = new ArrayList<>();
StringBuilder tokBuf = new StringBuilder();
int ch;
while ((ch = lexer.read()) != GridJavadocCharArrayLexReader.EOF) {
// Instruction, tag or comment.
if (ch =='<') {
if (tokBuf.length() > 0) {
toks.add(new GridJavadocToken(GridJavadocTokenType.TOKEN_TEXT, tokBuf.toString()));
tokBuf.setLength(0);
}
tokBuf.append('<');
ch = lexer.read();
if (ch == GridJavadocCharArrayLexReader.EOF)
throw new IOException("Unexpected EOF: " + file);
// Instruction or comment.
if (ch == '!') {
for (; ch != GridJavadocCharArrayLexReader.EOF && ch != '>'; ch = lexer.read())
tokBuf.append((char)ch);
if (ch == GridJavadocCharArrayLexReader.EOF)
throw new IOException("Unexpected EOF: " + file);
assert ch == '>';
tokBuf.append('>');
String val = tokBuf.toString();
toks.add(new GridJavadocToken(val.startsWith("<!--") ? GridJavadocTokenType.TOKEN_COMM :
GridJavadocTokenType.TOKEN_INSTR, val));
tokBuf.setLength(0);
}
// Tag.
else {
for (; ch != GridJavadocCharArrayLexReader.EOF && ch != '>'; ch = lexer.read())
tokBuf.append((char)ch);
if (ch == GridJavadocCharArrayLexReader.EOF)
throw new IOException("Unexpected EOF: " + file);
assert ch == '>';
tokBuf.append('>');
if (tokBuf.length() <= 2)
throw new IOException("Invalid HTML in [file=" + file + ", html=" + tokBuf + ']');
String val = tokBuf.toString();
toks.add(new GridJavadocToken(val.startsWith("</") ?
GridJavadocTokenType.TOKEN_CLOSE_TAG : GridJavadocTokenType.TOKEN_OPEN_TAG, val));
tokBuf.setLength(0);
}
}
else
tokBuf.append((char)ch);
}
if (tokBuf.length() > 0)
toks.add(new GridJavadocToken(GridJavadocTokenType.TOKEN_TEXT, tokBuf.toString()));
for (GridJavadocToken tok : toks) {
String val = tok.value();
switch (tok.type()) {
case TOKEN_COMM: {
break;
}
case TOKEN_OPEN_TAG: {
tok.update(fixColors(tok.value()));
break;
}
case TOKEN_CLOSE_TAG: {
if ("</head>".equalsIgnoreCase(val))
tok.update(
"<link rel='shortcut icon' href='https://ignite.apache.org/favicon.ico'/>\n" +
"<link type='text/css' rel='stylesheet' href='" + SH_URL + "/styles/shCore.css'/>\n" +
"<link type='text/css' rel='stylesheet' href='" + SH_URL +
"/styles/shThemeDefault.css'/>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shCore.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shLegacy.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shBrushJava.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shBrushPlain.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL +
"/scripts/shBrushJScript.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shBrushBash.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shBrushXml.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shBrushScala.js'></script>\n" +
"<script type='text/javascript' src='" + SH_URL + "/scripts/shBrushGroovy.js'></script>\n" +
"</head>\n");
else if ("</body>".equalsIgnoreCase(val))
tok.update(
"<!--FOOTER-->" +
"<script type='text/javascript'>" +
"SyntaxHighlighter.all();" +
"dp.SyntaxHighlighter.HighlightAll('code');" +
"!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');" +
"</script>\n" +
"</body>\n");
break;
}
case TOKEN_INSTR: {
// No-op.
break;
}
case TOKEN_TEXT: {
tok.update(fixColors(val));
break;
}
default:
assert false;
}
}
StringBuilder buf = new StringBuilder();
StringBuilder tmp = new StringBuilder();
boolean inPre = false;
// Second pass for unstructured replacements.
for (GridJavadocToken tok : toks) {
String val = tok.value();
switch (tok.type()) {
case TOKEN_INSTR:
case TOKEN_TEXT:
case TOKEN_COMM: {
tmp.append(val);
break;
}
case TOKEN_OPEN_TAG: {
if (val.toLowerCase().startsWith("<pre name=")) {
inPre = true;
buf.append(fixBrackets(tmp.toString()));
tmp.setLength(0);
}
tmp.append(val);
break;
}
case TOKEN_CLOSE_TAG: {
if (val.toLowerCase().startsWith("</pre") && inPre) {
inPre = false;
buf.append(tmp.toString());
tmp.setLength(0);
}
tmp.append(val);
break;
}
default:
assert false;
}
}
String s = buf.append(fixBrackets(tmp.toString())).toString();
s = fixExternalLinks(s);
s = fixDeprecated(s);
s = fixNullable(s);
s = fixTodo(s);
replaceFile(file, s);
}
/**
* Checks whether a file is a view-related HTML file rather than a single
* class documentation.
*
* @param fileName HTML file name.
* @return {@code True} if it's a view-related HTML.
*/
private boolean isViewHtml(String fileName) {
String baseName = new File(fileName).getName();
return "index.html".equals(baseName) || baseName.contains("-");
}
/**
*
* @param s String token.
* @return Token with replaced colors.
*/
private String fixColors(String s) {
return s.replace("0000c0", "000000").
replace("000000", "333333").
replace("c00000", "333333").
replace("008000", "999999").
replace("990000", "336699").
replace("font color=\"#808080\"", "font size=-2 color=\"#aaaaaa\"");
}
/**
*
* @param s String token.
* @return Fixed token value.
*/
private String fixBrackets(String s) {
return s.replace("<", "<span class='angle_bracket'><</span>").
replace(">", "<span class='angle_bracket'>></span>");
}
/**
*
* @param s String token.
* @return Fixed token value.
*/
private String fixTodo(String s) {
return s.replace("TODO", "<span class='todo'>TODO</span>");
}
/**
*
* @param s String token.
* @return Fixed token value.
*/
private String fixNullable(String s) {
return s.replace("<FONT SIZE=\"-1\">@Nullable", "<FONT SIZE=\"-1\" class='nullable'>@Nullable");
}
/**
*
* @param s String token.
* @return Fixed token value.
*/
private String fixDeprecated(String s) {
return s.replace("<B>Deprecated.</B>", "<span class='deprecated'>Deprecated.</span>");
}
/**
*
* @param s String token.
* @return Fixed token value.
*/
private String fixExternalLinks(String s) {
return s.replace("A HREF=\"http://java.sun.com/j2se/1.6.0",
"A target='jse5javadoc' HREF=\"http://java.sun.com/j2se/1.6.0");
}
/**
* Replaces file with given body.
*
* @param file File to replace.
* @param body New body for the file.
* @throws IOException Thrown in case of any errors.
*/
private void replaceFile(String file, String body) throws IOException {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
out.write(body.getBytes());
}
}
/**
* Reads file to string using specified charset.
*
* @param fileName File name.
* @param charset File charset.
* @return File content.
* @throws IOException If error occurred.
*/
public static String readFileToString(String fileName, Charset charset) throws IOException {
Reader input = new InputStreamReader(new FileInputStream(fileName), charset);
StringWriter output = new StringWriter();
char[] buf = new char[4096];
int n;
while ((n = input.read(buf)) != -1)
output.write(buf, 0, n);
return output.toString();
}
}
| apache-2.0 |
objectiser/camel | core/camel-core-engine/src/main/java/org/apache/camel/model/SamplingDefinition.java | 5035 | /*
* 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.camel.model;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.camel.spi.Metadata;
/**
* Extract a sample of the messages passing through a route
*/
@Metadata(label = "eip,routing")
@XmlRootElement(name = "sample")
@XmlAccessorType(XmlAccessType.FIELD)
public class SamplingDefinition extends NoOutputDefinition<SamplingDefinition> {
// use Long to let it be optional in JAXB so when using XML the default is 1
// second
@XmlAttribute
@Metadata(defaultValue = "1")
private Long samplePeriod;
@XmlAttribute
private Long messageFrequency;
@XmlAttribute
@XmlJavaTypeAdapter(TimeUnitAdapter.class)
@Metadata(defaultValue = "SECONDS")
private TimeUnit units;
public SamplingDefinition() {
}
public SamplingDefinition(long samplePeriod, TimeUnit units) {
this.samplePeriod = samplePeriod;
this.units = units;
}
public SamplingDefinition(long messageFrequency) {
this.messageFrequency = messageFrequency;
}
@Override
public String getShortName() {
return "sample";
}
@Override
public String toString() {
return "Sample[" + description() + " -> " + getOutputs() + "]";
}
protected String description() {
if (messageFrequency != null) {
return "1 Exchange per " + getMessageFrequency() + " messages received";
} else {
TimeUnit tu = getUnits() != null ? getUnits() : TimeUnit.SECONDS;
return "1 Exchange per " + getSamplePeriod() + " " + tu.toString().toLowerCase(Locale.ENGLISH);
}
}
@Override
public String getLabel() {
return "sample[" + description() + "]";
}
// Fluent API
// -------------------------------------------------------------------------
/**
* Sets the sample message count which only a single
* {@link org.apache.camel.Exchange} will pass through after this many
* received.
*
* @param messageFrequency
* @return the builder
*/
public SamplingDefinition sampleMessageFrequency(long messageFrequency) {
setMessageFrequency(messageFrequency);
return this;
}
/**
* Sets the sample period during which only a single
* {@link org.apache.camel.Exchange} will pass through.
*
* @param samplePeriod the period
* @return the builder
*/
public SamplingDefinition samplePeriod(long samplePeriod) {
setSamplePeriod(samplePeriod);
return this;
}
/**
* Sets the time units for the sample period, defaulting to seconds.
*
* @param units the time unit of the sample period.
* @return the builder
*/
public SamplingDefinition timeUnits(TimeUnit units) {
setUnits(units);
return this;
}
// Properties
// -------------------------------------------------------------------------
public Long getSamplePeriod() {
return samplePeriod;
}
/**
* Sets the sample period during which only a single Exchange will pass
* through.
*/
public void setSamplePeriod(Long samplePeriod) {
this.samplePeriod = samplePeriod;
}
public Long getMessageFrequency() {
return messageFrequency;
}
/**
* Sets the sample message count which only a single Exchange will pass
* through after this many received.
*/
public void setMessageFrequency(Long messageFrequency) {
this.messageFrequency = messageFrequency;
}
/**
* Sets the time units for the sample period, defaulting to seconds.
*/
public void setUnits(String units) {
this.units = TimeUnit.valueOf(units);
}
/**
* Sets the time units for the sample period, defaulting to seconds.
*/
public void setUnits(TimeUnit units) {
this.units = units;
}
public TimeUnit getUnits() {
return units;
}
}
| apache-2.0 |
johandoornenbal/estatio | udo/base/dom/src/main/java/org/estatio/dom/package-info.java | 315 | /**
* Interfaces (such as {@link org.estatio.dom.WithCodeGetter}) and abstract classes (such as
* {@link org.estatio.dom.UdoDomainObject}) that are implemented/inherited by all domain classes.
*
* <p>
* Also contains global {@link org.estatio.dom.ApplicationSettingKey settings}.
*/
package org.estatio.dom; | apache-2.0 |
apache/incubator-taverna-engine | taverna-workflowmodel-api/src/main/java/org/apache/taverna/visit/VisitReport.java | 9547 | /*
* 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.taverna.visit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author alanrw
*/
public class VisitReport {
private static final String INDENTION = " ";
/**
* Enumeration of the possible status's in increasing severity: OK,
* WARNING,SEVERE
*/
public enum Status {
OK, WARNING, SEVERE
};
/**
* A short message describing the state of the report
*/
private String message;
/**
* An integer indicating the outcome of a visit relative to the VisitKind
*/
private int resultId;
/**
*
*/
private Status status;
/**
* The object about which the report is made
*/
private Object subject;
/**
* The sub-reports of the VisitReport
*/
private Collection<VisitReport> subReports = new ArrayList<>();
/**
* The kind of visit that was made e.g. to check the health of a service or
* examine its up-stream error fragility
*/
private VisitKind kind;
/**
* An indication of whether the visit report was generated by a time
* consuming visitor. This is used to check whether the VisitReport can be
* automatically junked.
*/
private boolean wasTimeConsuming;
private Map<String, Object> propertyMap = new HashMap<>();
private long checkTime;
/**
* @return whether the VisitReport was generated by a time consuming visitor
*/
public boolean wasTimeConsuming() {
return wasTimeConsuming;
}
/**
* @param wasTimeConsuming whether the VisitReport was generated by a time consuming visitot
*/
public void setWasTimeConsuming(boolean wasTimeConsuming) {
this.wasTimeConsuming = wasTimeConsuming;
}
/**
* Constructs the Visit Report. The sub reports default to an empty list.
*
* @param kind
* - the type of visit performed
* @param subject
* - the thing being tested.
* @param message
* - a summary of the result of the test.
* @param resultId
* - an identification of the type of result relative to the
* VisitKind
* @param status
* - the overall Status.
*/
public VisitReport(VisitKind kind, Object subject, String message,
int resultId, Status status) {
this(kind, subject, message, resultId, status,
new ArrayList<VisitReport>());
}
/**
* Used internally by {@link #clone()}.
*/
protected VisitReport() {}
/**
* Constructs the Visit Report
*
* @param kind
* - the type of visit performed
* @param subject
* - the thing being tested.
* @param message
* - a summary of the result of the test.
* @param resultId
* - an identification of the type of result relative to the
* VisitKind
* @param status - the overall Status.
* @param subReports
* - a List of sub reports.
*/
public VisitReport(VisitKind kind, Object subject, String message,
int resultId, Status status, Collection<VisitReport> subReports) {
this.kind = kind;
this.subject = subject;
this.status = status;
this.message = message;
this.resultId = resultId;
this.subReports = subReports;
this.wasTimeConsuming = false;
this.checkTime = 0;
}
/**
* @param kind The type of visit performed
* @param subject The thing that was visited
* @param message A summary of the result of the test
* @param resultId An indication of the type of the result relative to the kind of visit
* @param subReports A list of sub-reports
*/
public VisitReport(VisitKind kind, Object subject, String message,
int resultId, Collection<VisitReport> subReports) {
this(kind, subject, message, resultId, getWorstStatus(subReports),
subReports);
}
/**
* @return An indication of the type of the result relative to the kind of visit
*/
public int getResultId() {
return resultId;
}
/**
* @param resultId The type of the result of the visit relative to the kind of visit
*/
public void setResultId(int resultId) {
this.resultId = resultId;
}
/**
* @return a message summarizing the report
*/
public String getMessage() {
return message;
}
/**
* Sets the message
*
* @param message
* a message summarizing the report
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Determines the overall Status. This is the most severe status of this
* report and all its sub reports.
*
* @return the overall status
*/
public Status getStatus() {
Status result = status;
for (VisitReport report : subReports)
if (report.getStatus().compareTo(result) > 0)
result = report.getStatus();
return result;
}
/**
* Sets the status of this report. Be aware that the overall status of this
* report may also be affected by its sub reports if they have a more severe
* Status.
*
* @param status
* @see #getStatus
*/
public void setStatus(Status status) {
this.status = status;
}
/**
* @return an Object representing the subject of this visit report
*/
public Object getSubject() {
return subject;
}
/**
* @param subject
* an Object representing the subject of this visit report
*/
public void setSubject(Object subject) {
this.subject = subject;
}
/**
* Provides a list of sub reports. This list defaults an empty list, so it
* is safe to add new reports through this method.
*
* @return a list of sub reports associated with this Visit Report
*/
public Collection<VisitReport> getSubReports() {
return subReports;
}
/**
* Replaces the List of sub reports with those provided.
*
* @param subReports
* a list of sub reports
*/
public void setSubReports(Collection<VisitReport> subReports) {
this.subReports = subReports;
}
/**
*
* @return the kind of visit that was made.
*/
public VisitKind getKind() {
return kind;
}
/**
* @param kind Specify the kind of visit that was made
*/
public void setKind(VisitKind kind) {
this.kind = kind;
}
public void setProperty(String key, Object value) {
propertyMap.put(key, value);
}
public Object getProperty(String key) {
return propertyMap.get(key);
}
public Map<String, Object> getProperties() {
return propertyMap;
}
/**
* Find the most recent ancestor (earliest in the list) of a given class from the list of ancestors
*
* @param ancestors The list of ancestors to examine
* @param ancestorClass The class to search for
* @return The most recent ancestor, or null if no suitable ancestor
*/
public static Object findAncestor(List<Object> ancestors,
Class<?> ancestorClass) {
Object result = null;
for (Object o : ancestors)
if (ancestorClass.isInstance(o))
return o;
return result;
}
public void setCheckTime(long time) {
this.checkTime = time;
}
public long getCheckTime() {
return this.checkTime;
}
/**
* Determine the worst status from a collection of reports
*
* @param reports
* The collection of reports to examine
* @return The worst status
*/
public static Status getWorstStatus(Collection<VisitReport> reports) {
Status currentStatus = Status.OK;
for (VisitReport report : reports)
if (currentStatus.compareTo(report.getStatus()) < 0)
currentStatus = report.getStatus();
return currentStatus;
}
@Override
public String toString() {
// TODO Use StringBuilder instead
StringBuffer sb = new StringBuffer();
visitReportToStringBuffer(sb, "");
return sb.toString();
}
protected void visitReportToStringBuffer(
StringBuffer sb, String indent) {
sb.append(indent);
sb.append(getStatus());
sb.append(' ');
sb.append(getMessage());
if (! propertyMap.isEmpty()) {
sb.append(' ');
sb.append(propertyMap);
}
sb.append('\n');
indent = indent + INDENTION;
for (VisitReport subReport : getSubReports())
subReport.visitReportToStringBuffer(sb, indent);
}
@Override
public VisitReport clone() throws CloneNotSupportedException {
if (!getClass().equals(VisitReport.class))
throw new CloneNotSupportedException("Can't clone subclass "
+ getClass()
+ ", reimplement clone() and use internalClone()");
return internalClone(new VisitReport());
}
protected VisitReport internalClone(VisitReport newReport)
throws CloneNotSupportedException {
newReport.checkTime = this.checkTime;
newReport.kind = this.kind;
newReport.message = this.message;
newReport.propertyMap.putAll(this.propertyMap);
newReport.resultId = this.resultId;
newReport.status = this.status;
newReport.subject = this.subject;
newReport.wasTimeConsuming = this.wasTimeConsuming;
for (VisitReport childReport : this.subReports)
newReport.subReports.add(childReport.clone());
return newReport;
}
}
| apache-2.0 |
sdgdsffdsfff/dubbo-plus | akka/akka-remoting/src/main/java/net/dubboclub/akka/remoting/ActorExchanger.java | 595 | package net.dubboclub.akka.remoting;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Adaptive;
import com.alibaba.dubbo.common.extension.SPI;
import com.alibaba.dubbo.rpc.Invoker;
import net.dubboclub.akka.remoting.actor.BasicActor;
import com.alibaba.dubbo.common.URL;
/**
* Created by bieber on 2015/7/9.
*/
@SPI("akka")
public interface ActorExchanger {
@Adaptive({Constants.TRANSPORTER_KEY})
public BasicActor bind(Invoker<?> invoker);
@Adaptive({Constants.TRANSPORTER_KEY})
public BasicActor connect(Class<?> type,URL url);
}
| apache-2.0 |
harinigunabalan/PerformanceHat | cw-feedback-eclipse-base/src/eu/cloudwave/wp5/feedback/eclipse/base/resources/core/java/FeedbackJavaFileImpl.java | 2918 | /*******************************************************************************
* Copyright 2015 Software Evolution and Architecture Lab, University of Zurich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package eu.cloudwave.wp5.feedback.eclipse.base.resources.core.java;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.CompilationUnit;
import com.google.common.base.Optional;
import eu.cloudwave.wp5.feedback.eclipse.base.resources.core.FeedbackFileImpl;
import eu.cloudwave.wp5.feedback.eclipse.base.resources.core.FeedbackResourceExtensionFactory;
import eu.cloudwave.wp5.feedback.eclipse.base.resources.core.FeedbackResourceFactory;
import eu.cloudwave.wp5.feedback.eclipse.base.resources.decorators.AstCompilationUnitDecorator;
/**
* Implementation of {@link FeedbackJavaFile}. Acts as a decorator for the wrapped {@link IFile}.
*/
public class FeedbackJavaFileImpl extends FeedbackFileImpl implements FeedbackJavaFile {
private Optional<AstCompilationUnitDecorator> astCompilationUnitDecorator;
protected FeedbackJavaFileImpl(final IFile file, final FeedbackResourceExtensionFactory extensionFactory, final FeedbackResourceFactory resourceFactory) {
super(file, extensionFactory, resourceFactory);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<? extends ICompilationUnit> getCompilationUnit() {
return getAstCompilationUnitDecorator();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<CompilationUnit> getAstRoot() {
if (getAstCompilationUnitDecorator().isPresent()) {
return Optional.of(getAstCompilationUnitDecorator().get().getAst());
}
return Optional.absent();
}
private Optional<AstCompilationUnitDecorator> getAstCompilationUnitDecorator() {
if (astCompilationUnitDecorator == null) {
astCompilationUnitDecorator = loadJavaCompilationUnit();
}
return astCompilationUnitDecorator;
}
private Optional<AstCompilationUnitDecorator> loadJavaCompilationUnit() {
final ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);
if (compilationUnit != null) {
return Optional.of(AstCompilationUnitDecorator.of(compilationUnit));
}
return Optional.absent();
}
}
| apache-2.0 |
WonderfulFamily/HappyProject | bannder/src/main/java/com/qf/bannder/ViewPagerScroller.java | 978 | package com.qf.bannder;
import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;
public class ViewPagerScroller extends Scroller {
private int mDuration = BannerConfig.DURATION;
public ViewPagerScroller(Context context) {
super(context);
}
public ViewPagerScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public ViewPagerScroller(Context context, Interpolator interpolator, boolean flywheel) {
super(context, interpolator, flywheel);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, mDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
super.startScroll(startX, startY, dx, dy, mDuration);
}
public void setDuration(int time) {
mDuration = time;
}
}
| apache-2.0 |
ict-carch/hadoop-plus | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/partition/InputSampler.java | 16394 | /**
* 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.hadoop.mapreduce.lib.partition;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* Utility for collecting samples and writing a partition file for
* {@link TotalOrderPartitioner}.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class InputSampler<K,V> extends Configured implements Tool {
private static final Log LOG = LogFactory.getLog(InputSampler.class);
static int printUsage() {
System.out.println("sampler -r <reduces>\n" +
" [-inFormat <input format class>]\n" +
" [-keyClass <map input & output key class>]\n" +
" [-splitRandom <double pcnt> <numSamples> <maxsplits> | " +
" // Sample from random splits at random (general)\n" +
" -splitSample <numSamples> <maxsplits> | " +
" // Sample from first records in splits (random data)\n"+
" -splitInterval <double pcnt> <maxsplits>]" +
" // Sample from splits at intervals (sorted data)");
System.out.println("Default sampler: -splitRandom 0.1 10000 10");
ToolRunner.printGenericCommandUsage(System.out);
return -1;
}
public InputSampler(Configuration conf) {
setConf(conf);
}
/**
* Interface to sample using an
* {@link org.apache.hadoop.mapreduce.InputFormat}.
*/
public interface Sampler<K,V> {
/**
* For a given job, collect and return a subset of the keys from the
* input data.
*/
K[] getSample(InputFormat<K,V> inf, Job job)
throws IOException, InterruptedException;
}
/**
* Samples the first n records from s splits.
* Inexpensive way to sample random data.
*/
public static class SplitSampler<K,V> implements Sampler<K,V> {
protected final int numSamples;
protected final int maxSplitsSampled;
/**
* Create a SplitSampler sampling <em>all</em> splits.
* Takes the first numSamples / numSplits records from each split.
* @param numSamples Total number of samples to obtain from all selected
* splits.
*/
public SplitSampler(int numSamples) {
this(numSamples, Integer.MAX_VALUE);
}
/**
* Create a new SplitSampler.
* @param numSamples Total number of samples to obtain from all selected
* splits.
* @param maxSplitsSampled The maximum number of splits to examine.
*/
public SplitSampler(int numSamples, int maxSplitsSampled) {
this.numSamples = numSamples;
this.maxSplitsSampled = maxSplitsSampled;
}
/**
* From each split sampled, take the first numSamples / numSplits records.
*/
@SuppressWarnings("unchecked") // ArrayList::toArray doesn't preserve type
public K[] getSample(InputFormat<K,V> inf, Job job)
throws IOException, InterruptedException {
List<InputSplit> splits = inf.getSplits(job);
ArrayList<K> samples = new ArrayList<K>(numSamples);
int splitsToSample = Math.min(maxSplitsSampled, splits.size());
int samplesPerSplit = numSamples / splitsToSample;
long records = 0;
for (int i = 0; i < splitsToSample; ++i) {
TaskAttemptContext samplingContext = new TaskAttemptContextImpl(
job.getConfiguration(), new TaskAttemptID());
RecordReader<K,V> reader = inf.createRecordReader(
splits.get(i), samplingContext);
reader.initialize(splits.get(i), samplingContext);
while (reader.nextKeyValue()) {
samples.add(ReflectionUtils.copy(job.getConfiguration(),
reader.getCurrentKey(), null));
++records;
if ((i+1) * samplesPerSplit <= records) {
break;
}
}
reader.close();
}
return (K[])samples.toArray();
}
}
/**
* Sample from random points in the input.
* General-purpose sampler. Takes numSamples / maxSplitsSampled inputs from
* each split.
*/
public static class RandomSampler<K,V> implements Sampler<K,V> {
protected double freq;
protected final int numSamples;
protected final int maxSplitsSampled;
/**
* Create a new RandomSampler sampling <em>all</em> splits.
* This will read every split at the client, which is very expensive.
* @param freq Probability with which a key will be chosen.
* @param numSamples Total number of samples to obtain from all selected
* splits.
*/
public RandomSampler(double freq, int numSamples) {
this(freq, numSamples, Integer.MAX_VALUE);
}
/**
* Create a new RandomSampler.
* @param freq Probability with which a key will be chosen.
* @param numSamples Total number of samples to obtain from all selected
* splits.
* @param maxSplitsSampled The maximum number of splits to examine.
*/
public RandomSampler(double freq, int numSamples, int maxSplitsSampled) {
this.freq = freq;
this.numSamples = numSamples;
this.maxSplitsSampled = maxSplitsSampled;
}
/**
* Randomize the split order, then take the specified number of keys from
* each split sampled, where each key is selected with the specified
* probability and possibly replaced by a subsequently selected key when
* the quota of keys from that split is satisfied.
*/
@SuppressWarnings("unchecked") // ArrayList::toArray doesn't preserve type
public K[] getSample(InputFormat<K,V> inf, Job job)
throws IOException, InterruptedException {
List<InputSplit> splits = inf.getSplits(job);
ArrayList<K> samples = new ArrayList<K>(numSamples);
int splitsToSample = Math.min(maxSplitsSampled, splits.size());
Random r = new Random();
long seed = r.nextLong();
r.setSeed(seed);
LOG.debug("seed: " + seed);
// shuffle splits
for (int i = 0; i < splits.size(); ++i) {
InputSplit tmp = splits.get(i);
int j = r.nextInt(splits.size());
splits.set(i, splits.get(j));
splits.set(j, tmp);
}
// our target rate is in terms of the maximum number of sample splits,
// but we accept the possibility of sampling additional splits to hit
// the target sample keyset
for (int i = 0; i < splitsToSample ||
(i < splits.size() && samples.size() < numSamples); ++i) {
TaskAttemptContext samplingContext = new TaskAttemptContextImpl(
job.getConfiguration(), new TaskAttemptID());
RecordReader<K,V> reader = inf.createRecordReader(
splits.get(i), samplingContext);
reader.initialize(splits.get(i), samplingContext);
while (reader.nextKeyValue()) {
if (r.nextDouble() <= freq) {
if (samples.size() < numSamples) {
samples.add(ReflectionUtils.copy(job.getConfiguration(),
reader.getCurrentKey(), null));
} else {
// When exceeding the maximum number of samples, replace a
// random element with this one, then adjust the frequency
// to reflect the possibility of existing elements being
// pushed out
int ind = r.nextInt(numSamples);
if (ind != numSamples) {
samples.set(ind, ReflectionUtils.copy(job.getConfiguration(),
reader.getCurrentKey(), null));
}
freq *= (numSamples - 1) / (double) numSamples;
}
}
}
reader.close();
}
return (K[])samples.toArray();
}
}
/**
* Sample from s splits at regular intervals.
* Useful for sorted data.
*/
public static class IntervalSampler<K,V> implements Sampler<K,V> {
protected final double freq;
protected final int maxSplitsSampled;
/**
* Create a new IntervalSampler sampling <em>all</em> splits.
* @param freq The frequency with which records will be emitted.
*/
public IntervalSampler(double freq) {
this(freq, Integer.MAX_VALUE);
}
/**
* Create a new IntervalSampler.
* @param freq The frequency with which records will be emitted.
* @param maxSplitsSampled The maximum number of splits to examine.
* @see #getSample
*/
public IntervalSampler(double freq, int maxSplitsSampled) {
this.freq = freq;
this.maxSplitsSampled = maxSplitsSampled;
}
/**
* For each split sampled, emit when the ratio of the number of records
* retained to the total record count is less than the specified
* frequency.
*/
@SuppressWarnings("unchecked") // ArrayList::toArray doesn't preserve type
public K[] getSample(InputFormat<K,V> inf, Job job)
throws IOException, InterruptedException {
List<InputSplit> splits = inf.getSplits(job);
ArrayList<K> samples = new ArrayList<K>();
int splitsToSample = Math.min(maxSplitsSampled, splits.size());
long records = 0;
long kept = 0;
for (int i = 0; i < splitsToSample; ++i) {
TaskAttemptContext samplingContext = new TaskAttemptContextImpl(
job.getConfiguration(), new TaskAttemptID());
RecordReader<K,V> reader = inf.createRecordReader(
splits.get(i), samplingContext);
reader.initialize(splits.get(i), samplingContext);
while (reader.nextKeyValue()) {
++records;
if ((double) kept / records < freq) {
samples.add(ReflectionUtils.copy(job.getConfiguration(),
reader.getCurrentKey(), null));
++kept;
}
}
reader.close();
}
return (K[])samples.toArray();
}
}
/**
* Write a partition file for the given job, using the Sampler provided.
* Queries the sampler for a sample keyset, sorts by the output key
* comparator, selects the keys for each rank, and writes to the destination
* returned from {@link TotalOrderPartitioner#getPartitionFile}.
*/
@SuppressWarnings("unchecked") // getInputFormat, getOutputKeyComparator
public static <K,V> void writePartitionFile(Job job, Sampler<K,V> sampler)
throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = job.getConfiguration();
final InputFormat inf =
ReflectionUtils.newInstance(job.getInputFormatClass(), conf);
int numPartitions = job.getNumReduceTasks();
K[] samples = sampler.getSample(inf, job);
LOG.info("Using " + samples.length + " samples");
RawComparator<K> comparator =
(RawComparator<K>) job.getSortComparator();
Arrays.sort(samples, comparator);
Path dst = new Path(TotalOrderPartitioner.getPartitionFile(conf));
FileSystem fs = dst.getFileSystem(conf);
if (fs.exists(dst)) {
fs.delete(dst, false);
}
SequenceFile.Writer writer = SequenceFile.createWriter(fs,
conf, dst, job.getMapOutputKeyClass(), NullWritable.class);
NullWritable nullValue = NullWritable.get();
float stepSize = samples.length / (float) numPartitions;
int last = -1;
for(int i = 1; i < numPartitions; ++i) {
int k = Math.round(stepSize * i);
while (last >= k && comparator.compare(samples[last], samples[k]) == 0) {
++k;
}
writer.append(samples[k], nullValue);
last = k;
}
writer.close();
}
/**
* Driver for InputSampler from the command line.
* Configures a JobConf instance and calls {@link #writePartitionFile}.
*/
public int run(String[] args) throws Exception {
Job job = new Job(getConf());
ArrayList<String> otherArgs = new ArrayList<String>();
Sampler<K,V> sampler = null;
for(int i=0; i < args.length; ++i) {
try {
if ("-r".equals(args[i])) {
job.setNumReduceTasks(Integer.parseInt(args[++i]));
} else if ("-inFormat".equals(args[i])) {
job.setInputFormatClass(
Class.forName(args[++i]).asSubclass(InputFormat.class));
} else if ("-keyClass".equals(args[i])) {
job.setMapOutputKeyClass(
Class.forName(args[++i]).asSubclass(WritableComparable.class));
} else if ("-splitSample".equals(args[i])) {
int numSamples = Integer.parseInt(args[++i]);
int maxSplits = Integer.parseInt(args[++i]);
if (0 >= maxSplits) maxSplits = Integer.MAX_VALUE;
sampler = new SplitSampler<K,V>(numSamples, maxSplits);
} else if ("-splitRandom".equals(args[i])) {
double pcnt = Double.parseDouble(args[++i]);
int numSamples = Integer.parseInt(args[++i]);
int maxSplits = Integer.parseInt(args[++i]);
if (0 >= maxSplits) maxSplits = Integer.MAX_VALUE;
sampler = new RandomSampler<K,V>(pcnt, numSamples, maxSplits);
} else if ("-splitInterval".equals(args[i])) {
double pcnt = Double.parseDouble(args[++i]);
int maxSplits = Integer.parseInt(args[++i]);
if (0 >= maxSplits) maxSplits = Integer.MAX_VALUE;
sampler = new IntervalSampler<K,V>(pcnt, maxSplits);
} else {
otherArgs.add(args[i]);
}
} catch (NumberFormatException except) {
System.out.println("ERROR: Integer expected instead of " + args[i]);
return printUsage();
} catch (ArrayIndexOutOfBoundsException except) {
System.out.println("ERROR: Required parameter missing from " +
args[i-1]);
return printUsage();
}
}
if (job.getNumReduceTasks() <= 1) {
System.err.println("Sampler requires more than one reducer");
return printUsage();
}
if (otherArgs.size() < 2) {
System.out.println("ERROR: Wrong number of parameters: ");
return printUsage();
}
if (null == sampler) {
sampler = new RandomSampler<K,V>(0.1, 10000, 10);
}
Path outf = new Path(otherArgs.remove(otherArgs.size() - 1));
TotalOrderPartitioner.setPartitionFile(getConf(), outf);
for (String s : otherArgs) {
FileInputFormat.addInputPath(job, new Path(s));
}
InputSampler.<K,V>writePartitionFile(job, sampler);
return 0;
}
public static void main(String[] args) throws Exception {
InputSampler<?,?> sampler = new InputSampler(new Configuration());
int res = ToolRunner.run(sampler, args);
System.exit(res);
}
}
| apache-2.0 |
stevenhva/InfoLearn_OpenOLAT | src/main/java/org/olat/portfolio/ui/structel/view/TOCElement.java | 2379 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.portfolio.ui.structel.view;
import java.util.List;
import org.olat.core.gui.components.link.Link;
/**
* Description:<br>
* data container for a TOC element
*
* <P>
* Initial Date: 26.10.2010 <br>
* @author Roman Haag, roman.haag@frentix.com, http://www.frentix.com
*/
public class TOCElement {
private final int level;
private final String type;
private final Link iconLink;
private final Link titleLink;
private final Link userCommentLink;
private final List<TOCElement> childs;
public TOCElement(int level, String type, Link titleLink, Link iconLink, Link userCommentLink, List<TOCElement> childs){
this.level = level;
this.type = type;
this.iconLink = iconLink;
this.titleLink = titleLink;
this.userCommentLink = userCommentLink;
this.childs = childs;
}
/**
* @return Returns the level.
*/
public int getLevel() {
return level;
}
/**
* @return Returns the type.
*/
public String getType() {
return type;
}
/**
* @return Returns the link with an icon.
*/
public Link getIconLink() {
return iconLink;
}
/**
* @return Returns the link with the title
*/
public Link getTitleLink() {
return titleLink;
}
/**
* @return Return the link for user comments
*/
public Link getCommentLink() {
return userCommentLink;
}
public String getCommentLinkComponentName() {
return userCommentLink == null ? "comment-null" : userCommentLink.getComponentName();
}
/**
* @return Returns the child.
*/
public List<TOCElement> getChilds() {
return childs;
}
} | apache-2.0 |
oza/curator | curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder.java | 3513 | /**
* 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.curator.framework.api;
import org.apache.zookeeper.CreateMode;
public interface CreateBuilder extends
BackgroundPathAndBytesable<String>,
CreateModable<ACLBackgroundPathAndBytesable<String>>,
ACLCreateModeBackgroundPathAndBytesable<String>,
Compressible<CreateBackgroundModeACLable>
{
/**
* Causes any parent nodes to get created if they haven't already been
*
* @return this
*/
public ProtectACLCreateModePathAndBytesable<String> creatingParentsIfNeeded();
/**
* Causes any parent nodes to get created using {@link CreateMode#CONTAINER} if they haven't already been.
* IMPORTANT NOTE: container creation is a new feature in recent versions of ZooKeeper.
* If the ZooKeeper version you're using does not support containers, the parent nodes
* are created as ordinary PERSISTENT nodes.
*
* @return this
*/
public ProtectACLCreateModePathAndBytesable<String> creatingParentContainersIfNeeded();
/**
* @deprecated this has been generalized to support all create modes. Instead, use:
* <pre>
* client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)...
* </pre>
* @return this
*/
@Deprecated
public ACLPathAndBytesable<String> withProtectedEphemeralSequential();
/**
* <p>
* Hat-tip to https://github.com/sbridges for pointing this out
* </p>
*
* <p>
* It turns out there is an edge case that exists when creating sequential-ephemeral
* nodes. The creation can succeed on the server, but the server can crash before
* the created node name is returned to the client. However, the ZK session is still
* valid so the ephemeral node is not deleted. Thus, there is no way for the client to
* determine what node was created for them.
* </p>
*
* <p>
* Even without sequential-ephemeral, however, the create can succeed on the sever
* but the client (for various reasons) will not know it.
* </p>
*
* <p>
* Putting the create builder into protection mode works around this.
* The name of the node that is created is prefixed with a GUID. If node creation fails
* the normal retry mechanism will occur. On the retry, the parent path is first searched
* for a node that has the GUID in it. If that node is found, it is assumed to be the lost
* node that was successfully created on the first try and is returned to the caller.
* </p>
*
* @return this
*/
public ACLCreateModeBackgroundPathAndBytesable<String> withProtection();
}
| apache-2.0 |
eduarddedu/quickstart | ejb-security-plus/src/main/java/org/jboss/as/quickstarts/ejb_security_plus/RemoteClient.java | 1945 | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.ejb_security_plus;
import static org.jboss.as.quickstarts.ejb_security_plus.EJBUtil.lookupSecuredEJB;
import org.jboss.security.SimplePrincipal;
/**
* The remote client responsible for making a number of calls to the server to demonstrate the capabilities of the interceptors.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public class RemoteClient {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
System.out.println("\n\n\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\n");
SimplePrincipal principal = new SimplePrincipal("quickstartUser");
Object credential = new PasswordPlusCredential("quickstartPwd1!".toCharArray(), "7f5cc521-5061-4a5b-b814-bdc37f021acc");
SecurityActions.securityContextSetPrincipalCredential(principal, credential);
SecuredEJBRemote secured = lookupSecuredEJB();
System.out.println(secured.getPrincipalInformation());
System.out.println("\n\n\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\n");
}
}
| apache-2.0 |
Itvisors/mendix-DataTables | test/javasource/communitycommons/actions/GetCFInstanceIndex.java | 1853 | // This file was generated by Mendix Studio Pro.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.
package communitycommons.actions;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import communitycommons.Misc;
/**
* Returns the Cloud Foundry Instance Index that is set during deployment of the application in a Cloud native environment. Based on the Cloud Foundry Instance Index, Mendix determines what is the leader instance (index 0 executes scheduled events, db sync, session management etc.) or slave instance.
*
* Returns 0 for the leader instance, 1 or higher for slave instances or -1 when the environment variable could not be read (when running locally or on premise). When -1 is returned, it will probably be the leader in the cluster.
*
* Make sure emulate cloud security is disabled. Otherwise, the policy restrictions will prevent the method to be executed. Action is tested in Mendix Cloud on 19-12-2018.
*/
public class GetCFInstanceIndex extends CustomJavaAction<java.lang.Long>
{
public GetCFInstanceIndex(IContext context)
{
super(context);
}
@java.lang.Override
public java.lang.Long executeAction() throws Exception
{
// BEGIN USER CODE
return Misc.getCFInstanceIndex();
// END USER CODE
}
/**
* Returns a string representation of this action
*/
@java.lang.Override
public java.lang.String toString()
{
return "GetCFInstanceIndex";
}
// BEGIN EXTRA CODE
// END EXTRA CODE
}
| apache-2.0 |