repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
dlew/RxBinding | rxbinding-design/src/main/java/com/jakewharton/rxbinding/support/design/widget/RxAppBarLayout.java | 1307 | package com.jakewharton.rxbinding.support.design.widget;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import rx.Observable;
/**
* Static factory methods for creating {@linkplain Observable observables} for {@link AppBarLayout}.
*/
public final class RxAppBarLayout {
/**
* Create an observable which emits the offset change in {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
@CheckResult @NonNull
public static Observable<Integer> offsetChanges(@NonNull AppBarLayout view) {
return Observable.create(new AppBarLayoutOffsetChangeOnSubscribe(view));
}
/**
* Create an observable which emits offsetChange events for the {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
@CheckResult @NonNull
public static Observable<AppBarLayoutOffsetChangeEvent> offsetChangeEvents(@NonNull AppBarLayout view) {
return Observable.create(new AppBarLayoutOffsetChangeEventOnSubscribe(view));
}
private RxAppBarLayout() {
throw new AssertionError("No instances.");
}
}
| apache-2.0 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/variable/serializer/VariableSerializers.java | 3271 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.impl.variable.serializer;
import java.util.List;
import org.camunda.bpm.engine.variable.value.TypedValue;
/**
* Interface describing a container for all available {@link TypedValueSerializer}s of variables.
*
* @author dsyer
* @author Frederik Heremans
* @author Daniel Meyer
*/
public interface VariableSerializers {
/**
* Selects the {@link TypedValueSerializer} which should be used for persisting a VariableValue.
*
* @param value the value to persist
* @param fallBackSerializerFactory a factory to build a fallback serializer in case no suiting serializer
* can be determined. If this factory is not able to build serializer either, an exception is thrown. May be null
* @return the VariableValueserializer selected for persisting the value or 'null' in case no serializer can be found
*/
@SuppressWarnings("rawtypes")
public TypedValueSerializer findSerializerForValue(TypedValue value, VariableSerializerFactory fallBackSerializerFactory);
/**
* Same as calling {@link VariableSerializers#findSerializerForValue(TypedValue, VariableSerializerFactory)}
* with no fallback serializer factory.
*/
@SuppressWarnings("rawtypes")
public TypedValueSerializer findSerializerForValue(TypedValue value);
/**
*
* @return the serializer for the given serializerName name.
* Returns null if no type was found with the name.
*/
public TypedValueSerializer<?> getSerializerByName(String serializerName);
public VariableSerializers addSerializer(TypedValueSerializer<?> serializer);
/**
* Add type at the given index. The index is used when finding a serializer for a VariableValue. When
* different serializers can store a specific variable value, the one with the smallest
* index will be used.
*/
public VariableSerializers addSerializer(TypedValueSerializer<?> serializer, int index);
public VariableSerializers removeSerializer(TypedValueSerializer<?> serializer);
public int getSerializerIndex(TypedValueSerializer<?> serializer);
public int getSerializerIndexByName(String serializerName);
/**
* Merges two {@link VariableSerializers} instances into one. Implementations may apply
* different merging strategies.
*/
public VariableSerializers join(VariableSerializers other);
/**
* Returns the serializers as a list in the order of their indices.
*/
public List<TypedValueSerializer<?>> getSerializers();
} | apache-2.0 |
claudiu-stanciu/kylo | core/schema-discovery/schema-discovery-api/src/main/java/com/thinkbiganalytics/discovery/schema/QueryResultColumn.java | 2894 | package com.thinkbiganalytics.discovery.schema;
/*-
* #%L
* thinkbig-schema-discovery-api
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* Represent a column in the query result
*/
public interface QueryResultColumn {
/**
* Get column type
*
* @return data type
*/
String getDataType();
/**
* Set column type
*
* @param dataType data type
*/
void setDataType(String dataType);
/**
* Gets the database-specific type name.
*/
String getNativeDataType();
/**
* Sets the database-specific type name.
*/
void setNativeDataType(String nativeDataType);
/**
* Get table name
*
* @return table name
*/
String getTableName();
/**
* Set table name
*
* @param tableName table name
*/
void setTableName(String tableName);
/**
* Get database name
*
* @return database name
*/
String getDatabaseName();
/**
* Set database name
*
* @param databaseName database name
*/
void setDatabaseName(String databaseName);
/**
* Get column display name
*
* @return display name
*/
String getDisplayName();
/**
* Set column display name
*
* @param displayName display name
*/
void setDisplayName(String displayName);
/**
* Get column label in hive
*
* @return column label
*/
String getHiveColumnLabel();
/**
* Set column label in hive
*
* @param hiveColumnLabel column label
*/
void setHiveColumnLabel(String hiveColumnLabel);
/**
* Get column index
*
* @return index
*/
int getIndex();
/**
* Set column index
*
* @param index index
*/
void setIndex(int index);
/**
* Get column field
*
* @return field
*/
String getField();
/**
* Set column field
*
* @param field field
*/
void setField(String field);
/**
* Gets a human-readable description of this column.
*
* @return the comment
*/
String getComment();
/**
* Sets a human-readable description for this column.
*
* @param comment the comment
*/
void setComment(String comment);
}
| apache-2.0 |
jchambers/netty | transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueServerChannelConfig.java | 6298 | /*
* Copyright 2016 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 io.netty.channel.kqueue;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.socket.ServerSocketChannelConfig;
import io.netty.util.NetUtil;
import io.netty.util.internal.UnstableApi;
import java.io.IOException;
import java.util.Map;
import static io.netty.channel.ChannelOption.SO_BACKLOG;
import static io.netty.channel.ChannelOption.SO_RCVBUF;
import static io.netty.channel.ChannelOption.SO_REUSEADDR;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
@UnstableApi
public class KQueueServerChannelConfig extends KQueueChannelConfig implements ServerSocketChannelConfig {
private volatile int backlog = NetUtil.SOMAXCONN;
KQueueServerChannelConfig(AbstractKQueueChannel channel) {
super(channel);
}
@Override
public Map<ChannelOption<?>, Object> getOptions() {
return getOptions(super.getOptions(), SO_RCVBUF, SO_REUSEADDR, SO_BACKLOG);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getOption(ChannelOption<T> option) {
if (option == SO_RCVBUF) {
return (T) Integer.valueOf(getReceiveBufferSize());
}
if (option == SO_REUSEADDR) {
return (T) Boolean.valueOf(isReuseAddress());
}
if (option == SO_BACKLOG) {
return (T) Integer.valueOf(getBacklog());
}
return super.getOption(option);
}
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
validate(option, value);
if (option == SO_RCVBUF) {
setReceiveBufferSize((Integer) value);
} else if (option == SO_REUSEADDR) {
setReuseAddress((Boolean) value);
} else if (option == SO_BACKLOG) {
setBacklog((Integer) value);
} else {
return super.setOption(option, value);
}
return true;
}
public boolean isReuseAddress() {
try {
return ((AbstractKQueueChannel) channel).socket.isReuseAddress();
} catch (IOException e) {
throw new ChannelException(e);
}
}
public KQueueServerChannelConfig setReuseAddress(boolean reuseAddress) {
try {
((AbstractKQueueChannel) channel).socket.setReuseAddress(reuseAddress);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
}
public int getReceiveBufferSize() {
try {
return ((AbstractKQueueChannel) channel).socket.getReceiveBufferSize();
} catch (IOException e) {
throw new ChannelException(e);
}
}
public KQueueServerChannelConfig setReceiveBufferSize(int receiveBufferSize) {
try {
((AbstractKQueueChannel) channel).socket.setReceiveBufferSize(receiveBufferSize);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
}
public int getBacklog() {
return backlog;
}
public KQueueServerChannelConfig setBacklog(int backlog) {
checkPositiveOrZero(backlog, "backlog");
this.backlog = backlog;
return this;
}
@Override
public KQueueServerChannelConfig setRcvAllocTransportProvidesGuess(boolean transportProvidesGuess) {
super.setRcvAllocTransportProvidesGuess(transportProvidesGuess);
return this;
}
@Override
public KQueueServerChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
return this;
}
@Override
public KQueueServerChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) {
super.setConnectTimeoutMillis(connectTimeoutMillis);
return this;
}
@Override
@Deprecated
public KQueueServerChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) {
super.setMaxMessagesPerRead(maxMessagesPerRead);
return this;
}
@Override
public KQueueServerChannelConfig setWriteSpinCount(int writeSpinCount) {
super.setWriteSpinCount(writeSpinCount);
return this;
}
@Override
public KQueueServerChannelConfig setAllocator(ByteBufAllocator allocator) {
super.setAllocator(allocator);
return this;
}
@Override
public KQueueServerChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) {
super.setRecvByteBufAllocator(allocator);
return this;
}
@Override
public KQueueServerChannelConfig setAutoRead(boolean autoRead) {
super.setAutoRead(autoRead);
return this;
}
@Override
@Deprecated
public KQueueServerChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) {
super.setWriteBufferHighWaterMark(writeBufferHighWaterMark);
return this;
}
@Override
@Deprecated
public KQueueServerChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) {
super.setWriteBufferLowWaterMark(writeBufferLowWaterMark);
return this;
}
@Override
public KQueueServerChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark) {
super.setWriteBufferWaterMark(writeBufferWaterMark);
return this;
}
@Override
public KQueueServerChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) {
super.setMessageSizeEstimator(estimator);
return this;
}
}
| apache-2.0 |
apache/qpid-jms | qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/NoOpAsyncResult.java | 1270 | /*
* 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.qpid.jms.provider;
/**
* Simple NoOp implementation used when the result of the operation does not matter.
*/
public class NoOpAsyncResult implements AsyncResult {
public final static NoOpAsyncResult INSTANCE = new NoOpAsyncResult();
@Override
public void onFailure(ProviderException result) {
}
@Override
public void onSuccess() {
}
@Override
public boolean isComplete() {
return true;
}
}
| apache-2.0 |
Donnerbart/hazelcast | hazelcast-client/src/test/java/com/hazelcast/client/cache/jsr/CacheWriterExceptionTest.java | 1299 | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. 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 com.hazelcast.client.cache.jsr;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class CacheWriterExceptionTest extends javax.cache.integration.CacheWriterExceptionTest {
@BeforeClass
public static void setupInstance() {
JsrClientTestUtil.setupWithHazelcastInstance();
}
@AfterClass
public static void cleanup() {
JsrClientTestUtil.cleanup();
}
}
| apache-2.0 |
AlanJager/zstack | sdk/src/main/java/org/zstack/sdk/ReplicationRole.java | 89 | package org.zstack.sdk;
public enum ReplicationRole {
Primary,
Secondary,
Unknown,
}
| apache-2.0 |
vineetgarg02/hive | ql/src/java/org/apache/hadoop/hive/ql/ddl/table/misc/owner/AlterTableSetOwnerAnalyzer.java | 2554 | /*
* 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.hive.ql.ddl.table.misc.owner;
import java.util.Map;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.ddl.DDLWork;
import org.apache.hadoop.hive.ql.ddl.DDLSemanticAnalyzerFactory.DDLType;
import org.apache.hadoop.hive.ql.ddl.privilege.PrincipalDesc;
import org.apache.hadoop.hive.ql.ddl.table.AbstractAlterTableAnalyzer;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.authorization.AuthorizationParseUtils;
/**
* Analyzer for set owner commands.
*/
@DDLType(types = HiveParser.TOK_ALTERTABLE_OWNER)
public class AlterTableSetOwnerAnalyzer extends AbstractAlterTableAnalyzer {
public AlterTableSetOwnerAnalyzer(QueryState queryState) throws SemanticException {
super(queryState);
}
@Override
protected void analyzeCommand(TableName tableName, Map<String, String> partitionSpecFromFramework, ASTNode command)
throws SemanticException {
PrincipalDesc ownerPrincipal = AuthorizationParseUtils.getPrincipalDesc((ASTNode) command.getChild(0));
if (ownerPrincipal.getType() == null) {
throw new SemanticException("Owner type can't be null in alter table set owner command");
}
if (ownerPrincipal.getName() == null) {
throw new SemanticException("Owner name can't be null in alter table set owner command");
}
AlterTableSetOwnerDesc desc = new AlterTableSetOwnerDesc(tableName, ownerPrincipal);
rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(), desc), conf));
}
}
| apache-2.0 |
rmichela/grpc-java | core/src/test/java/io/grpc/internal/ManagedChannelImplGetNameResolverTest.java | 5491 | /*
* Copyright 2015, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.internal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import io.grpc.Attributes;
import io.grpc.NameResolver;
import io.grpc.NameResolver.Factory;
import java.net.URI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ManagedChannelImpl#getNameResolver}. */
@RunWith(JUnit4.class)
public class ManagedChannelImplGetNameResolverTest {
private static final Attributes NAME_RESOLVER_PARAMS =
Attributes.newBuilder().set(NameResolver.Factory.PARAMS_DEFAULT_PORT, 447).build();
@Test
public void invalidUriTarget() {
testInvalidTarget("defaultscheme:///[invalid]");
}
@Test
public void validTargetWithInvalidDnsName() throws Exception {
testValidTarget("[valid]", "defaultscheme:///%5Bvalid%5D",
new URI("defaultscheme", "", "/[valid]", null));
}
@Test
public void validAuthorityTarget() throws Exception {
testValidTarget("foo.googleapis.com:8080", "defaultscheme:///foo.googleapis.com:8080",
new URI("defaultscheme", "", "/foo.googleapis.com:8080", null));
}
@Test
public void validUriTarget() throws Exception {
testValidTarget("scheme:///foo.googleapis.com:8080", "scheme:///foo.googleapis.com:8080",
new URI("scheme", "", "/foo.googleapis.com:8080", null));
}
@Test
public void validIpv4AuthorityTarget() throws Exception {
testValidTarget("127.0.0.1:1234", "defaultscheme:///127.0.0.1:1234",
new URI("defaultscheme", "", "/127.0.0.1:1234", null));
}
@Test
public void validIpv4UriTarget() throws Exception {
testValidTarget("dns:///127.0.0.1:1234", "dns:///127.0.0.1:1234",
new URI("dns", "", "/127.0.0.1:1234", null));
}
@Test
public void validIpv6AuthorityTarget() throws Exception {
testValidTarget("[::1]:1234", "defaultscheme:///%5B::1%5D:1234",
new URI("defaultscheme", "", "/[::1]:1234", null));
}
@Test
public void invalidIpv6UriTarget() throws Exception {
testInvalidTarget("dns:///[::1]:1234");
}
@Test
public void validIpv6UriTarget() throws Exception {
testValidTarget("dns:///%5B::1%5D:1234", "dns:///%5B::1%5D:1234",
new URI("dns", "", "/[::1]:1234", null));
}
@Test
public void validTargetStartingWithSlash() throws Exception {
testValidTarget("/target", "defaultscheme:////target",
new URI("defaultscheme", "", "//target", null));
}
@Test
public void validTargetNoResovler() {
Factory nameResolverFactory = new NameResolver.Factory() {
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
return null;
}
@Override
public String getDefaultScheme() {
return "defaultscheme";
}
};
try {
ManagedChannelImpl.getNameResolver(
"foo.googleapis.com:8080", nameResolverFactory, NAME_RESOLVER_PARAMS);
fail("Should fail");
} catch (IllegalArgumentException e) {
// expected
}
}
private void testValidTarget(String target, String expectedUriString, URI expectedUri) {
Factory nameResolverFactory = new FakeNameResolverFactory(expectedUri.getScheme());
FakeNameResolver nameResolver = (FakeNameResolver) ManagedChannelImpl.getNameResolver(
target, nameResolverFactory, NAME_RESOLVER_PARAMS);
assertNotNull(nameResolver);
assertEquals(expectedUri, nameResolver.uri);
assertEquals(expectedUriString, nameResolver.uri.toString());
}
private void testInvalidTarget(String target) {
Factory nameResolverFactory = new FakeNameResolverFactory("dns");
try {
FakeNameResolver nameResolver = (FakeNameResolver) ManagedChannelImpl.getNameResolver(
target, nameResolverFactory, NAME_RESOLVER_PARAMS);
fail("Should have failed, but got resolver with " + nameResolver.uri);
} catch (IllegalArgumentException e) {
// expected
}
}
private static class FakeNameResolverFactory extends NameResolver.Factory {
final String expectedScheme;
FakeNameResolverFactory(String expectedScheme) {
this.expectedScheme = expectedScheme;
}
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
if (expectedScheme.equals(targetUri.getScheme())) {
return new FakeNameResolver(targetUri);
}
return null;
}
@Override
public String getDefaultScheme() {
return expectedScheme;
}
}
private static class FakeNameResolver extends NameResolver {
final URI uri;
FakeNameResolver(URI uri) {
this.uri = uri;
}
@Override public String getServiceAuthority() {
return uri.getAuthority();
}
@Override public void start(final Listener listener) {}
@Override public void shutdown() {}
}
}
| apache-2.0 |
rockmkd/datacollector | basic-lib/src/main/java/com/streamsets/pipeline/stage/processor/aggregation/aggregator/LongMinAggregator.java | 2988 | /*
* Copyright 2017 StreamSets 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.streamsets.pipeline.stage.processor.aggregation.aggregator;
import com.streamsets.pipeline.api.impl.Utils;
/**
* Long Minimum Aggregator.
*/
public class LongMinAggregator extends SimpleAggregator<LongMinAggregator, Long> {
public static class LongMinAggregatable implements Aggregatable<LongMinAggregator> {
private String name;
private long min;
@Override
public String getName() {
return name;
}
public LongMinAggregatable setName(String name) {
this.name = name;
return this;
}
public long getMin() {
return min;
}
public LongMinAggregatable setMin(long min) {
this.min = min;
return this;
}
}
private class Data extends AggregatorData<LongMinAggregator, Long> {
private Long current;
public Data(String name, long time) {
super(name, time);
}
@Override
public String getName() {
return LongMinAggregator.this.getName();
}
@Override
public void process(Long value) {
if (value != null) {
synchronized (this) {
if (current == null) {
current = value;
} else if (value < current) {
current = value;
}
}
}
}
@Override
public synchronized Long get() {
return current;
}
@Override
public Aggregatable<LongMinAggregator> getAggregatable() {
return new LongMinAggregatable().setName(getName()).setMin(get());
}
@Override
public void aggregate(Aggregatable<LongMinAggregator> aggregatable) {
Utils.checkNotNull(aggregatable, "aggregatable");
Utils.checkArgument(
getName().equals(aggregatable.getName()),
Utils.formatL("Aggregable '{}' does not match this aggregation '{}", aggregatable.getName(), getName())
);
Utils.checkArgument(aggregatable instanceof LongMinAggregatable, Utils.formatL(
"Aggregatable '{}' is a '{}' it should be '{}'",
getName(),
aggregatable.getClass().getSimpleName(),
LongMinAggregatable.class.getSimpleName()
));
process(((LongMinAggregatable) aggregatable).getMin());
}
}
public LongMinAggregator(String name) {
super(Long.class, name);
}
public AggregatorData createAggregatorData(long timeWindowMillis) {
return new Data(getName(), timeWindowMillis);
}
}
| apache-2.0 |
trentontrees/dawg | libraries/stb-io-api/src/test/java/com/comcast/video/stbio/KeyTest.java | 1885 | /**
* Copyright 2010 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.comcast.video.stbio;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class KeyTest {
@DataProvider(name="testKeysForChannelData")
public Object[][] testKeysForChannelData() {
return new Object[][] {
{"9", new Key[] {Key.NINE}},
{"20", new Key[] {Key.TWO, Key.ZERO}},
{"123", new Key[] {Key.ONE, Key.TWO, Key.THREE}},
};
}
@Test(dataProvider="testKeysForChannelData")
public void testKeysForChannel(String channel, Key[] expected) {
Key[] actual = Key.keysForChannel(channel);
Assert.assertEquals(actual.length, expected.length);
for (int k = 0; k < expected.length; k++) {
Assert.assertEquals(actual[k], expected[k]);
}
}
@DataProvider(name="testKeysForChannelInvalidData")
public Object[][] testKeysForChannelInvalidData() {
return new Object[][] {
{"-1"},
{"ABC"},
{"9B"},
};
}
@Test(dataProvider="testKeysForChannelInvalidData", expectedExceptions=IllegalArgumentException.class)
public void testKeysForChannelInvalid(String channel) {
Key.keysForChannel(channel);
}
}
| apache-2.0 |
psiroky/uberfire | uberfire-api/src/main/java/org/uberfire/backend/vfs/impl/ObservablePathImpl.java | 17683 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* 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.uberfire.backend.vfs.impl;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.ioc.client.container.IOC;
import org.jboss.errai.security.shared.api.identity.User;
import org.uberfire.backend.vfs.IsVersioned;
import org.uberfire.backend.vfs.ObservablePath;
import org.uberfire.backend.vfs.Path;
import org.uberfire.mvp.Command;
import org.uberfire.mvp.ParameterizedCommand;
import org.uberfire.rpc.SessionInfo;
import org.uberfire.workbench.events.ResourceBatchChangesEvent;
import org.uberfire.workbench.events.ResourceChange;
import org.uberfire.workbench.events.ResourceCopied;
import org.uberfire.workbench.events.ResourceCopiedEvent;
import org.uberfire.workbench.events.ResourceDeletedEvent;
import org.uberfire.workbench.events.ResourceRenamed;
import org.uberfire.workbench.events.ResourceRenamedEvent;
import org.uberfire.workbench.events.ResourceUpdatedEvent;
@Portable
@Dependent
public class ObservablePathImpl implements ObservablePath,
IsVersioned {
private Path path;
private transient Path original;
@Inject
private transient SessionInfo sessionInfo;
private transient List<Command> onRenameCommand = new ArrayList<Command>();
private transient List<Command> onDeleteCommand = new ArrayList<Command>();
private transient List<Command> onUpdateCommand = new ArrayList<Command>();
private transient List<Command> onCopyCommand = new ArrayList<Command>();
private transient List<ParameterizedCommand<OnConcurrentRenameEvent>> onConcurrentRenameCommand = new ArrayList<ParameterizedCommand<OnConcurrentRenameEvent>>();
private transient List<ParameterizedCommand<OnConcurrentDelete>> onConcurrentDeleteCommand = new ArrayList<ParameterizedCommand<OnConcurrentDelete>>();
private transient List<ParameterizedCommand<OnConcurrentUpdateEvent>> onConcurrentUpdateCommand = new ArrayList<ParameterizedCommand<OnConcurrentUpdateEvent>>();
private transient List<ParameterizedCommand<OnConcurrentCopyEvent>> onConcurrentCopyCommand = new ArrayList<ParameterizedCommand<OnConcurrentCopyEvent>>();
public ObservablePathImpl() {
}
@Override
public ObservablePath wrap( final Path path ) {
if ( path instanceof ObservablePathImpl ) {
this.original = ( (ObservablePathImpl) path ).path;
} else {
this.original = path;
}
this.path = this.original;
return this;
}
// Lazy-population of "original" for ObservablePathImpl de-serialized from a serialized PerspectiveDefinition that circumvent the "wrap" feature.
// Renamed resources hold a reference to the old "original" Path which is needed to maintain an immutable hashCode used as part of the compound
// Key for Activity and Place Management). However re-hydration stores the PartDefinition in a HashSet using the incorrect hashCode. By not
// storing the "original" in the serialized form we can guarantee hashCodes in de-serialized PerspectiveDefinitions remain immutable.
// See https://bugzilla.redhat.com/show_bug.cgi?id=1200472 for the re-producer.
private Path getOriginal() {
if ( this.original == null ) {
wrap( this.path );
}
return this.original;
}
@Override
public String getFileName() {
return path.getFileName();
}
public static String removeExtension( final String filename ) {
if ( filename == null ) {
return null;
}
final int index = indexOfExtension( filename );
if ( index == -1 ) {
return filename;
} else {
return filename.substring( 0, index );
}
}
public static int indexOfExtension( final String filename ) {
if ( filename == null ) {
return -1;
}
final int extensionPos = filename.lastIndexOf( "." );
return extensionPos;
}
@Override
public String toURI() {
return path.toURI();
}
@Override
public boolean hasVersionSupport() {
return path instanceof IsVersioned && ( (IsVersioned) path ).hasVersionSupport();
}
@Override
public int compareTo( final Path o ) {
return path.compareTo( o );
}
@Override
public void onRename( final Command command ) {
this.onRenameCommand.add( command );
}
@Override
public void onDelete( final Command command ) {
this.onDeleteCommand.add( command );
}
@Override
public void onUpdate( final Command command ) {
this.onUpdateCommand.add( command );
}
@Override
public void onCopy( final Command command ) {
this.onCopyCommand.add( command );
}
@Override
public void onConcurrentRename( final ParameterizedCommand<OnConcurrentRenameEvent> command ) {
this.onConcurrentRenameCommand.add( command );
}
@Override
public void onConcurrentDelete( final ParameterizedCommand<OnConcurrentDelete> command ) {
this.onConcurrentDeleteCommand.add( command );
}
@Override
public void onConcurrentUpdate( final ParameterizedCommand<OnConcurrentUpdateEvent> command ) {
this.onConcurrentUpdateCommand.add( command );
}
@Override
public void onConcurrentCopy( final ParameterizedCommand<OnConcurrentCopyEvent> command ) {
this.onConcurrentCopyCommand.add( command );
}
@Override
public void dispose() {
onRenameCommand.clear();
onDeleteCommand.clear();
onUpdateCommand.clear();
onCopyCommand.clear();
onConcurrentRenameCommand.clear();
onConcurrentDeleteCommand.clear();
onConcurrentUpdateCommand.clear();
onConcurrentCopyCommand.clear();
if ( IOC.getBeanManager() != null ) {
IOC.getBeanManager().destroyBean( this );
}
}
void onResourceRenamed( @Observes final ResourceRenamedEvent renamedEvent ) {
if ( path != null && path.equals( renamedEvent.getPath() ) ) {
path = renamedEvent.getDestinationPath();
if ( sessionInfo.getId().equals( renamedEvent.getSessionInfo().getId() ) ) {
executeRenameCommands();
} else {
executeConcurrentRenameCommand( renamedEvent.getPath(),
renamedEvent.getDestinationPath(),
renamedEvent.getSessionInfo().getId(),
renamedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceDeleted( @Observes final ResourceDeletedEvent deletedEvent ) {
if ( path != null && path.equals( deletedEvent.getPath() ) ) {
if ( sessionInfo.getId().equals( deletedEvent.getSessionInfo().getId() ) ) {
executeDeleteCommands();
} else {
executeConcurrentDeleteCommand( deletedEvent.getPath(),
deletedEvent.getSessionInfo().getId(),
deletedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceUpdated( @Observes final ResourceUpdatedEvent updatedEvent ) {
if ( path != null && path.equals( updatedEvent.getPath() ) ) {
if ( sessionInfo.getId().equals( updatedEvent.getSessionInfo().getId() ) ) {
executeUpdateCommands();
} else {
executeConcurrentUpdateCommand( updatedEvent.getPath(),
updatedEvent.getSessionInfo().getId(),
updatedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceCopied( @Observes final ResourceCopiedEvent copiedEvent ) {
if ( path != null && path.equals( copiedEvent.getPath() ) ) {
if ( sessionInfo.getId().equals( copiedEvent.getSessionInfo().getId() ) ) {
executeCopyCommands();
} else {
executeConcurrentCopyCommand( copiedEvent.getPath(),
copiedEvent.getDestinationPath(),
copiedEvent.getSessionInfo().getId(),
copiedEvent.getSessionInfo().getIdentity() );
}
}
}
void onResourceBatchEvent( @Observes final ResourceBatchChangesEvent batchEvent ) {
if ( path != null && batchEvent.containPath( path ) ) {
if ( sessionInfo.getId().equals( batchEvent.getSessionInfo().getId() ) ) {
for ( final ResourceChange change : batchEvent.getChanges( path ) ) {
switch ( change.getType() ) {
case COPY:
executeCopyCommands();
break;
case DELETE:
executeDeleteCommands();
break;
case RENAME:
path = ( (ResourceRenamed) change ).getDestinationPath();
executeRenameCommands();
break;
case UPDATE:
executeUpdateCommands();
break;
}
}
} else {
for ( final ResourceChange change : batchEvent.getChanges( path ) ) {
switch ( change.getType() ) {
case COPY:
executeConcurrentCopyCommand( path,
( (ResourceCopied) change ).getDestinationPath(),
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
case DELETE:
executeConcurrentDeleteCommand( path,
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
case RENAME:
path = ( (ResourceRenamed) change ).getDestinationPath();
executeConcurrentRenameCommand( path,
( (ResourceRenamed) change ).getDestinationPath(),
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
case UPDATE:
executeConcurrentUpdateCommand( path,
batchEvent.getSessionInfo().getId(),
batchEvent.getSessionInfo().getIdentity() );
break;
}
}
}
}
}
private void executeRenameCommands() {
if ( !onRenameCommand.isEmpty() ) {
for ( final Command command : onRenameCommand ) {
command.execute();
}
}
}
private void executeConcurrentRenameCommand( final Path path,
final Path destinationPath,
final String sessionId,
final User identity ) {
if ( !onConcurrentRenameCommand.isEmpty() ) {
for ( final ParameterizedCommand<OnConcurrentRenameEvent> command : onConcurrentRenameCommand ) {
final OnConcurrentRenameEvent event = new OnConcurrentRenameEvent() {
@Override
public Path getSource() {
return path;
}
@Override
public Path getTarget() {
return destinationPath;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
command.execute( event );
}
}
}
private void executeCopyCommands() {
if ( !onCopyCommand.isEmpty() ) {
for ( final Command command : onCopyCommand ) {
command.execute();
}
}
}
private void executeConcurrentCopyCommand( final Path path,
final Path destinationPath,
final String sessionId,
final User identity ) {
if ( !onConcurrentCopyCommand.isEmpty() ) {
final OnConcurrentCopyEvent copyEvent = new OnConcurrentCopyEvent() {
@Override
public Path getSource() {
return path;
}
@Override
public Path getTarget() {
return destinationPath;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
for ( final ParameterizedCommand<OnConcurrentCopyEvent> command : onConcurrentCopyCommand ) {
command.execute( copyEvent );
}
}
}
private void executeUpdateCommands() {
if ( !onUpdateCommand.isEmpty() ) {
for ( final Command command : onUpdateCommand ) {
command.execute();
}
}
}
private void executeConcurrentUpdateCommand( final Path path,
final String sessionId,
final User identity ) {
if ( !onConcurrentUpdateCommand.isEmpty() ) {
final OnConcurrentUpdateEvent event = new OnConcurrentUpdateEvent() {
@Override
public Path getPath() {
return path;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
for ( final ParameterizedCommand<OnConcurrentUpdateEvent> command : onConcurrentUpdateCommand ) {
command.execute( event );
}
}
}
private void executeDeleteCommands() {
if ( !onDeleteCommand.isEmpty() ) {
for ( final Command command : onDeleteCommand ) {
command.execute();
}
}
}
private void executeConcurrentDeleteCommand( final Path path,
final String sessionId,
final User identity ) {
if ( !onConcurrentDeleteCommand.isEmpty() ) {
final OnConcurrentDelete event = new OnConcurrentDelete() {
@Override
public Path getPath() {
return path;
}
@Override
public String getId() {
return sessionId;
}
@Override
public User getIdentity() {
return identity;
}
};
for ( final ParameterizedCommand<OnConcurrentDelete> command : onConcurrentDeleteCommand ) {
command.execute( event );
}
}
}
@Override
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( !( o instanceof Path ) ) {
return false;
}
if ( o instanceof ObservablePathImpl ) {
return this.getOriginal().equals( ( (ObservablePathImpl) o ).getOriginal() );
}
return this.getOriginal().equals( o );
}
@Override
public int hashCode() {
return this.getOriginal().toURI().hashCode();
}
@Override
public String toString() {
return toURI();
}
}
| apache-2.0 |
pf5512/android-openslmediaplayer | test/src/com/h6ah4i/android/media/test/methodtest/BasicMediaPlayerTestCase_ReleaseMethod.java | 4372 | /*
* Copyright (C) 2014 Haruki Hasegawa
*
* 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.h6ah4i.android.media.test.methodtest;
import java.io.IOException;
import junit.framework.TestSuite;
import com.h6ah4i.android.media.IBasicMediaPlayer;
import com.h6ah4i.android.media.IMediaPlayerFactory;
import com.h6ah4i.android.media.test.base.BasicMediaPlayerStateTestCaseBase;
import com.h6ah4i.android.media.test.base.BasicMediaPlayerTestCaseBase;
import com.h6ah4i.android.media.test.utils.CompletionListenerObject;
import com.h6ah4i.android.media.test.utils.ErrorListenerObject;
import com.h6ah4i.android.testing.ParameterizedTestArgs;
public class BasicMediaPlayerTestCase_ReleaseMethod
extends BasicMediaPlayerStateTestCaseBase {
public static TestSuite buildTestSuite(Class<? extends IMediaPlayerFactory> factoryClazz) {
return BasicMediaPlayerTestCaseBase.buildBasicTestSuite(
BasicMediaPlayerTestCase_ReleaseMethod.class, factoryClazz);
}
public BasicMediaPlayerTestCase_ReleaseMethod(ParameterizedTestArgs args) {
super(args);
}
private void expectsNoErrors(IBasicMediaPlayer player) throws IOException {
Object sharedSyncObj = new Object();
ErrorListenerObject err = new ErrorListenerObject(sharedSyncObj, false);
CompletionListenerObject comp = new CompletionListenerObject(sharedSyncObj);
// check no errors
player.setOnErrorListener(err);
player.setOnCompletionListener(comp);
player.release();
if (comp.await(SHORT_EVENT_WAIT_DURATION)) {
fail(comp + ", " + err);
}
assertFalse(comp.occurred());
assertFalse(err.occurred());
}
// private void expectsIllegalStateException(IBasicMediaPlayer player) {
// try {
// player.release();
// } catch (IllegalStateException e) {
// // expected
// return;
// }
// fail();
// }
@Override
protected void onTestStateIdle(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateInitialized(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePreparing(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePrepared(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateStarted(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePaused(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateStopped(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePlaybackCompleted(IBasicMediaPlayer player, Object args)
throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateErrorBeforePrepared(IBasicMediaPlayer player, Object args)
throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateErrorAfterPrepared(IBasicMediaPlayer player, Object args)
throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateEnd(IBasicMediaPlayer player, Object args) throws Throwable {
// NOTE: StandardMediaPlayer will fail on this test case. It throws
// IllegalStateException.
expectsNoErrors(player);
// expectsIllegalStateException(player);
}
}
| apache-2.0 |
camunda/camunda-bpmn-model | src/main/java/org/camunda/bpm/model/bpmn/instance/CompensateEventDefinition.java | 1171 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.model.bpmn.instance;
/**
* The BPMN compensateEventDefinition element
*
* @author Sebastian Menski
*/
public interface CompensateEventDefinition extends EventDefinition {
boolean isWaitForCompletion();
void setWaitForCompletion(boolean isWaitForCompletion);
Activity getActivity();
void setActivity(Activity activity);
}
| apache-2.0 |
haikuowuya/android_system_code | src/com/android/internal/os/ProcessStats.java | 31741 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.os;
import static android.os.Process.*;
import android.os.Process;
import android.os.StrictMode;
import android.os.SystemClock;
import android.util.Slog;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
public class ProcessStats {
private static final String TAG = "ProcessStats";
private static final boolean DEBUG = false;
private static final boolean localLOGV = DEBUG || false;
private static final int[] PROCESS_STATS_FORMAT = new int[] {
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_PARENS,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 9: minor faults
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 11: major faults
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 13: utime
PROC_SPACE_TERM|PROC_OUT_LONG // 14: stime
};
static final int PROCESS_STAT_MINOR_FAULTS = 0;
static final int PROCESS_STAT_MAJOR_FAULTS = 1;
static final int PROCESS_STAT_UTIME = 2;
static final int PROCESS_STAT_STIME = 3;
/** Stores user time and system time in 100ths of a second. */
private final long[] mProcessStatsData = new long[4];
/** Stores user time and system time in 100ths of a second. */
private final long[] mSinglePidStatsData = new long[4];
private static final int[] PROCESS_FULL_STATS_FORMAT = new int[] {
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_PARENS|PROC_OUT_STRING, // 1: name
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 9: minor faults
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 11: major faults
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 13: utime
PROC_SPACE_TERM|PROC_OUT_LONG, // 14: stime
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM,
PROC_SPACE_TERM|PROC_OUT_LONG, // 21: vsize
};
static final int PROCESS_FULL_STAT_MINOR_FAULTS = 1;
static final int PROCESS_FULL_STAT_MAJOR_FAULTS = 2;
static final int PROCESS_FULL_STAT_UTIME = 3;
static final int PROCESS_FULL_STAT_STIME = 4;
static final int PROCESS_FULL_STAT_VSIZE = 5;
private final String[] mProcessFullStatsStringData = new String[6];
private final long[] mProcessFullStatsData = new long[6];
private static final int[] SYSTEM_CPU_FORMAT = new int[] {
PROC_SPACE_TERM|PROC_COMBINE,
PROC_SPACE_TERM|PROC_OUT_LONG, // 1: user time
PROC_SPACE_TERM|PROC_OUT_LONG, // 2: nice time
PROC_SPACE_TERM|PROC_OUT_LONG, // 3: sys time
PROC_SPACE_TERM|PROC_OUT_LONG, // 4: idle time
PROC_SPACE_TERM|PROC_OUT_LONG, // 5: iowait time
PROC_SPACE_TERM|PROC_OUT_LONG, // 6: irq time
PROC_SPACE_TERM|PROC_OUT_LONG // 7: softirq time
};
private final long[] mSystemCpuData = new long[7];
private static final int[] LOAD_AVERAGE_FORMAT = new int[] {
PROC_SPACE_TERM|PROC_OUT_FLOAT, // 0: 1 min
PROC_SPACE_TERM|PROC_OUT_FLOAT, // 1: 5 mins
PROC_SPACE_TERM|PROC_OUT_FLOAT // 2: 15 mins
};
private final float[] mLoadAverageData = new float[3];
private final boolean mIncludeThreads;
private float mLoad1 = 0;
private float mLoad5 = 0;
private float mLoad15 = 0;
private long mCurrentSampleTime;
private long mLastSampleTime;
private long mCurrentSampleRealTime;
private long mLastSampleRealTime;
private long mBaseUserTime;
private long mBaseSystemTime;
private long mBaseIoWaitTime;
private long mBaseIrqTime;
private long mBaseSoftIrqTime;
private long mBaseIdleTime;
private int mRelUserTime;
private int mRelSystemTime;
private int mRelIoWaitTime;
private int mRelIrqTime;
private int mRelSoftIrqTime;
private int mRelIdleTime;
private int[] mCurPids;
private int[] mCurThreadPids;
private final ArrayList<Stats> mProcStats = new ArrayList<Stats>();
private final ArrayList<Stats> mWorkingProcs = new ArrayList<Stats>();
private boolean mWorkingProcsSorted;
private boolean mFirst = true;
private byte[] mBuffer = new byte[4096];
/**
* The time in microseconds that the CPU has been running at each speed.
*/
private long[] mCpuSpeedTimes;
/**
* The relative time in microseconds that the CPU has been running at each speed.
*/
private long[] mRelCpuSpeedTimes;
/**
* The different speeds that the CPU can be running at.
*/
private long[] mCpuSpeeds;
public static class Stats {
public final int pid;
final String statFile;
final String cmdlineFile;
final String threadsDir;
final ArrayList<Stats> threadStats;
final ArrayList<Stats> workingThreads;
public boolean interesting;
public String baseName;
public String name;
public int nameWidth;
public long base_uptime;
public long rel_uptime;
public long base_utime;
public long base_stime;
public int rel_utime;
public int rel_stime;
public long base_minfaults;
public long base_majfaults;
public int rel_minfaults;
public int rel_majfaults;
public boolean active;
public boolean working;
public boolean added;
public boolean removed;
Stats(int _pid, int parentPid, boolean includeThreads) {
pid = _pid;
if (parentPid < 0) {
final File procDir = new File("/proc", Integer.toString(pid));
statFile = new File(procDir, "stat").toString();
cmdlineFile = new File(procDir, "cmdline").toString();
threadsDir = (new File(procDir, "task")).toString();
if (includeThreads) {
threadStats = new ArrayList<Stats>();
workingThreads = new ArrayList<Stats>();
} else {
threadStats = null;
workingThreads = null;
}
} else {
final File procDir = new File("/proc", Integer.toString(
parentPid));
final File taskDir = new File(
new File(procDir, "task"), Integer.toString(pid));
statFile = new File(taskDir, "stat").toString();
cmdlineFile = null;
threadsDir = null;
threadStats = null;
workingThreads = null;
}
}
}
private final static Comparator<Stats> sLoadComparator = new Comparator<Stats>() {
public final int
compare(Stats sta, Stats stb) {
int ta = sta.rel_utime + sta.rel_stime;
int tb = stb.rel_utime + stb.rel_stime;
if (ta != tb) {
return ta > tb ? -1 : 1;
}
if (sta.added != stb.added) {
return sta.added ? -1 : 1;
}
if (sta.removed != stb.removed) {
return sta.added ? -1 : 1;
}
return 0;
}
};
public ProcessStats(boolean includeThreads) {
mIncludeThreads = includeThreads;
}
public void onLoadChanged(float load1, float load5, float load15) {
}
public int onMeasureProcessName(String name) {
return 0;
}
public void init() {
if (DEBUG) Slog.v(TAG, "Init: " + this);
mFirst = true;
update();
}
public void update() {
if (DEBUG) Slog.v(TAG, "Update: " + this);
mLastSampleTime = mCurrentSampleTime;
mCurrentSampleTime = SystemClock.uptimeMillis();
mLastSampleRealTime = mCurrentSampleRealTime;
mCurrentSampleRealTime = SystemClock.elapsedRealtime();
final long[] sysCpu = mSystemCpuData;
if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT,
null, sysCpu, null)) {
// Total user time is user + nice time.
final long usertime = sysCpu[0]+sysCpu[1];
// Total system time is simply system time.
final long systemtime = sysCpu[2];
// Total idle time is simply idle time.
final long idletime = sysCpu[3];
// Total irq time is iowait + irq + softirq time.
final long iowaittime = sysCpu[4];
final long irqtime = sysCpu[5];
final long softirqtime = sysCpu[6];
mRelUserTime = (int)(usertime - mBaseUserTime);
mRelSystemTime = (int)(systemtime - mBaseSystemTime);
mRelIoWaitTime = (int)(iowaittime - mBaseIoWaitTime);
mRelIrqTime = (int)(irqtime - mBaseIrqTime);
mRelSoftIrqTime = (int)(softirqtime - mBaseSoftIrqTime);
mRelIdleTime = (int)(idletime - mBaseIdleTime);
if (DEBUG) {
Slog.i("Load", "Total U:" + sysCpu[0] + " N:" + sysCpu[1]
+ " S:" + sysCpu[2] + " I:" + sysCpu[3]
+ " W:" + sysCpu[4] + " Q:" + sysCpu[5]
+ " O:" + sysCpu[6]);
Slog.i("Load", "Rel U:" + mRelUserTime + " S:" + mRelSystemTime
+ " I:" + mRelIdleTime + " Q:" + mRelIrqTime);
}
mBaseUserTime = usertime;
mBaseSystemTime = systemtime;
mBaseIoWaitTime = iowaittime;
mBaseIrqTime = irqtime;
mBaseSoftIrqTime = softirqtime;
mBaseIdleTime = idletime;
}
mCurPids = collectStats("/proc", -1, mFirst, mCurPids, mProcStats);
final float[] loadAverages = mLoadAverageData;
if (Process.readProcFile("/proc/loadavg", LOAD_AVERAGE_FORMAT,
null, null, loadAverages)) {
float load1 = loadAverages[0];
float load5 = loadAverages[1];
float load15 = loadAverages[2];
if (load1 != mLoad1 || load5 != mLoad5 || load15 != mLoad15) {
mLoad1 = load1;
mLoad5 = load5;
mLoad15 = load15;
onLoadChanged(load1, load5, load15);
}
}
if (DEBUG) Slog.i(TAG, "*** TIME TO COLLECT STATS: "
+ (SystemClock.uptimeMillis()-mCurrentSampleTime));
mWorkingProcsSorted = false;
mFirst = false;
}
private int[] collectStats(String statsFile, int parentPid, boolean first,
int[] curPids, ArrayList<Stats> allProcs) {
int[] pids = Process.getPids(statsFile, curPids);
int NP = (pids == null) ? 0 : pids.length;
int NS = allProcs.size();
int curStatsIndex = 0;
for (int i=0; i<NP; i++) {
int pid = pids[i];
if (pid < 0) {
NP = pid;
break;
}
Stats st = curStatsIndex < NS ? allProcs.get(curStatsIndex) : null;
if (st != null && st.pid == pid) {
// Update an existing process...
st.added = false;
st.working = false;
curStatsIndex++;
if (DEBUG) Slog.v(TAG, "Existing "
+ (parentPid < 0 ? "process" : "thread")
+ " pid " + pid + ": " + st);
if (st.interesting) {
final long uptime = SystemClock.uptimeMillis();
final long[] procStats = mProcessStatsData;
if (!Process.readProcFile(st.statFile.toString(),
PROCESS_STATS_FORMAT, null, procStats, null)) {
continue;
}
final long minfaults = procStats[PROCESS_STAT_MINOR_FAULTS];
final long majfaults = procStats[PROCESS_STAT_MAJOR_FAULTS];
final long utime = procStats[PROCESS_STAT_UTIME];
final long stime = procStats[PROCESS_STAT_STIME];
if (utime == st.base_utime && stime == st.base_stime) {
st.rel_utime = 0;
st.rel_stime = 0;
st.rel_minfaults = 0;
st.rel_majfaults = 0;
if (st.active) {
st.active = false;
}
continue;
}
if (!st.active) {
st.active = true;
}
if (parentPid < 0) {
getName(st, st.cmdlineFile);
if (st.threadStats != null) {
mCurThreadPids = collectStats(st.threadsDir, pid, false,
mCurThreadPids, st.threadStats);
}
}
if (DEBUG) Slog.v("Load", "Stats changed " + st.name + " pid=" + st.pid
+ " utime=" + utime + "-" + st.base_utime
+ " stime=" + stime + "-" + st.base_stime
+ " minfaults=" + minfaults + "-" + st.base_minfaults
+ " majfaults=" + majfaults + "-" + st.base_majfaults);
st.rel_uptime = uptime - st.base_uptime;
st.base_uptime = uptime;
st.rel_utime = (int)(utime - st.base_utime);
st.rel_stime = (int)(stime - st.base_stime);
st.base_utime = utime;
st.base_stime = stime;
st.rel_minfaults = (int)(minfaults - st.base_minfaults);
st.rel_majfaults = (int)(majfaults - st.base_majfaults);
st.base_minfaults = minfaults;
st.base_majfaults = majfaults;
st.working = true;
}
continue;
}
if (st == null || st.pid > pid) {
// We have a new process!
st = new Stats(pid, parentPid, mIncludeThreads);
allProcs.add(curStatsIndex, st);
curStatsIndex++;
NS++;
if (DEBUG) Slog.v(TAG, "New "
+ (parentPid < 0 ? "process" : "thread")
+ " pid " + pid + ": " + st);
final String[] procStatsString = mProcessFullStatsStringData;
final long[] procStats = mProcessFullStatsData;
st.base_uptime = SystemClock.uptimeMillis();
if (Process.readProcFile(st.statFile.toString(),
PROCESS_FULL_STATS_FORMAT, procStatsString,
procStats, null)) {
// This is a possible way to filter out processes that
// are actually kernel threads... do we want to? Some
// of them do use CPU, but there can be a *lot* that are
// not doing anything.
if (true || procStats[PROCESS_FULL_STAT_VSIZE] != 0) {
st.interesting = true;
st.baseName = procStatsString[0];
st.base_minfaults = procStats[PROCESS_FULL_STAT_MINOR_FAULTS];
st.base_majfaults = procStats[PROCESS_FULL_STAT_MAJOR_FAULTS];
st.base_utime = procStats[PROCESS_FULL_STAT_UTIME];
st.base_stime = procStats[PROCESS_FULL_STAT_STIME];
} else {
Slog.i(TAG, "Skipping kernel process pid " + pid
+ " name " + procStatsString[0]);
st.baseName = procStatsString[0];
}
} else {
Slog.w(TAG, "Skipping unknown process pid " + pid);
st.baseName = "<unknown>";
st.base_utime = st.base_stime = 0;
st.base_minfaults = st.base_majfaults = 0;
}
if (parentPid < 0) {
getName(st, st.cmdlineFile);
if (st.threadStats != null) {
mCurThreadPids = collectStats(st.threadsDir, pid, true,
mCurThreadPids, st.threadStats);
}
} else if (st.interesting) {
st.name = st.baseName;
st.nameWidth = onMeasureProcessName(st.name);
}
if (DEBUG) Slog.v("Load", "Stats added " + st.name + " pid=" + st.pid
+ " utime=" + st.base_utime + " stime=" + st.base_stime
+ " minfaults=" + st.base_minfaults + " majfaults=" + st.base_majfaults);
st.rel_utime = 0;
st.rel_stime = 0;
st.rel_minfaults = 0;
st.rel_majfaults = 0;
st.added = true;
if (!first && st.interesting) {
st.working = true;
}
continue;
}
// This process has gone away!
st.rel_utime = 0;
st.rel_stime = 0;
st.rel_minfaults = 0;
st.rel_majfaults = 0;
st.removed = true;
st.working = true;
allProcs.remove(curStatsIndex);
NS--;
if (DEBUG) Slog.v(TAG, "Removed "
+ (parentPid < 0 ? "process" : "thread")
+ " pid " + pid + ": " + st);
// Decrement the loop counter so that we process the current pid
// again the next time through the loop.
i--;
continue;
}
while (curStatsIndex < NS) {
// This process has gone away!
final Stats st = allProcs.get(curStatsIndex);
st.rel_utime = 0;
st.rel_stime = 0;
st.rel_minfaults = 0;
st.rel_majfaults = 0;
st.removed = true;
st.working = true;
allProcs.remove(curStatsIndex);
NS--;
if (localLOGV) Slog.v(TAG, "Removed pid " + st.pid + ": " + st);
}
return pids;
}
public long getCpuTimeForPid(int pid) {
final String statFile = "/proc/" + pid + "/stat";
final long[] statsData = mSinglePidStatsData;
if (Process.readProcFile(statFile, PROCESS_STATS_FORMAT,
null, statsData, null)) {
long time = statsData[PROCESS_STAT_UTIME]
+ statsData[PROCESS_STAT_STIME];
return time;
}
return 0;
}
/**
* Returns the times spent at each CPU speed, since the last call to this method. If this
* is the first time, it will return 1 for each value.
* @return relative times spent at different speed steps.
*/
public long[] getLastCpuSpeedTimes() {
if (mCpuSpeedTimes == null) {
mCpuSpeedTimes = getCpuSpeedTimes(null);
mRelCpuSpeedTimes = new long[mCpuSpeedTimes.length];
for (int i = 0; i < mCpuSpeedTimes.length; i++) {
mRelCpuSpeedTimes[i] = 1; // Initialize
}
} else {
getCpuSpeedTimes(mRelCpuSpeedTimes);
for (int i = 0; i < mCpuSpeedTimes.length; i++) {
long temp = mRelCpuSpeedTimes[i];
mRelCpuSpeedTimes[i] -= mCpuSpeedTimes[i];
mCpuSpeedTimes[i] = temp;
}
}
return mRelCpuSpeedTimes;
}
private long[] getCpuSpeedTimes(long[] out) {
long[] tempTimes = out;
long[] tempSpeeds = mCpuSpeeds;
final int MAX_SPEEDS = 60;
if (out == null) {
tempTimes = new long[MAX_SPEEDS]; // Hopefully no more than that
tempSpeeds = new long[MAX_SPEEDS];
}
int speed = 0;
String file = readFile("/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state", '\0');
// Note: file may be null on kernels without cpufreq (i.e. the emulator's)
if (file != null) {
StringTokenizer st = new StringTokenizer(file, "\n ");
while (st.hasMoreElements()) {
String token = st.nextToken();
try {
long val = Long.parseLong(token);
tempSpeeds[speed] = val;
token = st.nextToken();
val = Long.parseLong(token);
tempTimes[speed] = val;
speed++;
if (speed == MAX_SPEEDS) break; // No more
if (localLOGV && out == null) {
Slog.v(TAG, "First time : Speed/Time = " + tempSpeeds[speed - 1]
+ "\t" + tempTimes[speed - 1]);
}
} catch (NumberFormatException nfe) {
Slog.i(TAG, "Unable to parse time_in_state");
}
}
}
if (out == null) {
out = new long[speed];
mCpuSpeeds = new long[speed];
System.arraycopy(tempSpeeds, 0, mCpuSpeeds, 0, speed);
System.arraycopy(tempTimes, 0, out, 0, speed);
}
return out;
}
final public int getLastUserTime() {
return mRelUserTime;
}
final public int getLastSystemTime() {
return mRelSystemTime;
}
final public int getLastIoWaitTime() {
return mRelIoWaitTime;
}
final public int getLastIrqTime() {
return mRelIrqTime;
}
final public int getLastSoftIrqTime() {
return mRelSoftIrqTime;
}
final public int getLastIdleTime() {
return mRelIdleTime;
}
final public float getTotalCpuPercent() {
int denom = mRelUserTime+mRelSystemTime+mRelIrqTime+mRelIdleTime;
if (denom <= 0) {
return 0;
}
return ((float)(mRelUserTime+mRelSystemTime+mRelIrqTime)*100) / denom;
}
final void buildWorkingProcs() {
if (!mWorkingProcsSorted) {
mWorkingProcs.clear();
final int N = mProcStats.size();
for (int i=0; i<N; i++) {
Stats stats = mProcStats.get(i);
if (stats.working) {
mWorkingProcs.add(stats);
if (stats.threadStats != null && stats.threadStats.size() > 1) {
stats.workingThreads.clear();
final int M = stats.threadStats.size();
for (int j=0; j<M; j++) {
Stats tstats = stats.threadStats.get(j);
if (tstats.working) {
stats.workingThreads.add(tstats);
}
}
Collections.sort(stats.workingThreads, sLoadComparator);
}
}
}
Collections.sort(mWorkingProcs, sLoadComparator);
mWorkingProcsSorted = true;
}
}
final public int countStats() {
return mProcStats.size();
}
final public Stats getStats(int index) {
return mProcStats.get(index);
}
final public int countWorkingStats() {
buildWorkingProcs();
return mWorkingProcs.size();
}
final public Stats getWorkingStats(int index) {
return mWorkingProcs.get(index);
}
final public String printCurrentLoad() {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.print("Load: ");
pw.print(mLoad1);
pw.print(" / ");
pw.print(mLoad5);
pw.print(" / ");
pw.println(mLoad15);
return sw.toString();
}
final public String printCurrentState(long now) {
buildWorkingProcs();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.print("CPU usage from ");
if (now > mLastSampleTime) {
pw.print(now-mLastSampleTime);
pw.print("ms to ");
pw.print(now-mCurrentSampleTime);
pw.print("ms ago");
} else {
pw.print(mLastSampleTime-now);
pw.print("ms to ");
pw.print(mCurrentSampleTime-now);
pw.print("ms later");
}
long sampleTime = mCurrentSampleTime - mLastSampleTime;
long sampleRealTime = mCurrentSampleRealTime - mLastSampleRealTime;
long percAwake = sampleRealTime > 0 ? ((sampleTime*100) / sampleRealTime) : 0;
if (percAwake != 100) {
pw.print(" with ");
pw.print(percAwake);
pw.print("% awake");
}
pw.println(":");
final int totalTime = mRelUserTime + mRelSystemTime + mRelIoWaitTime
+ mRelIrqTime + mRelSoftIrqTime + mRelIdleTime;
if (DEBUG) Slog.i(TAG, "totalTime " + totalTime + " over sample time "
+ (mCurrentSampleTime-mLastSampleTime));
int N = mWorkingProcs.size();
for (int i=0; i<N; i++) {
Stats st = mWorkingProcs.get(i);
printProcessCPU(pw, st.added ? " +" : (st.removed ? " -": " "),
st.pid, st.name, (int)(st.rel_uptime+5)/10,
st.rel_utime, st.rel_stime, 0, 0, 0, st.rel_minfaults, st.rel_majfaults);
if (!st.removed && st.workingThreads != null) {
int M = st.workingThreads.size();
for (int j=0; j<M; j++) {
Stats tst = st.workingThreads.get(j);
printProcessCPU(pw,
tst.added ? " +" : (tst.removed ? " -": " "),
tst.pid, tst.name, (int)(st.rel_uptime+5)/10,
tst.rel_utime, tst.rel_stime, 0, 0, 0, 0, 0);
}
}
}
printProcessCPU(pw, "", -1, "TOTAL", totalTime, mRelUserTime, mRelSystemTime,
mRelIoWaitTime, mRelIrqTime, mRelSoftIrqTime, 0, 0);
return sw.toString();
}
private void printRatio(PrintWriter pw, long numerator, long denominator) {
long thousands = (numerator*1000)/denominator;
long hundreds = thousands/10;
pw.print(hundreds);
if (hundreds < 10) {
long remainder = thousands - (hundreds*10);
if (remainder != 0) {
pw.print('.');
pw.print(remainder);
}
}
}
private void printProcessCPU(PrintWriter pw, String prefix, int pid, String label,
int totalTime, int user, int system, int iowait, int irq, int softIrq,
int minFaults, int majFaults) {
pw.print(prefix);
if (totalTime == 0) totalTime = 1;
printRatio(pw, user+system+iowait+irq+softIrq, totalTime);
pw.print("% ");
if (pid >= 0) {
pw.print(pid);
pw.print("/");
}
pw.print(label);
pw.print(": ");
printRatio(pw, user, totalTime);
pw.print("% user + ");
printRatio(pw, system, totalTime);
pw.print("% kernel");
if (iowait > 0) {
pw.print(" + ");
printRatio(pw, iowait, totalTime);
pw.print("% iowait");
}
if (irq > 0) {
pw.print(" + ");
printRatio(pw, irq, totalTime);
pw.print("% irq");
}
if (softIrq > 0) {
pw.print(" + ");
printRatio(pw, softIrq, totalTime);
pw.print("% softirq");
}
if (minFaults > 0 || majFaults > 0) {
pw.print(" / faults:");
if (minFaults > 0) {
pw.print(" ");
pw.print(minFaults);
pw.print(" minor");
}
if (majFaults > 0) {
pw.print(" ");
pw.print(majFaults);
pw.print(" major");
}
}
pw.println();
}
private String readFile(String file, char endChar) {
// Permit disk reads here, as /proc/meminfo isn't really "on
// disk" and should be fast. TODO: make BlockGuard ignore
// /proc/ and /sys/ files perhaps?
StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
FileInputStream is = null;
try {
is = new FileInputStream(file);
int len = is.read(mBuffer);
is.close();
if (len > 0) {
int i;
for (i=0; i<len; i++) {
if (mBuffer[i] == endChar) {
break;
}
}
return new String(mBuffer, 0, i);
}
} catch (java.io.FileNotFoundException e) {
} catch (java.io.IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (java.io.IOException e) {
}
}
StrictMode.setThreadPolicy(savedPolicy);
}
return null;
}
private void getName(Stats st, String cmdlineFile) {
String newName = st.name;
if (st.name == null || st.name.equals("app_process")
|| st.name.equals("<pre-initialized>")) {
String cmdName = readFile(cmdlineFile, '\0');
if (cmdName != null && cmdName.length() > 1) {
newName = cmdName;
int i = newName.lastIndexOf("/");
if (i > 0 && i < newName.length()-1) {
newName = newName.substring(i+1);
}
}
if (newName == null) {
newName = st.baseName;
}
}
if (st.name == null || !newName.equals(st.name)) {
st.name = newName;
st.nameWidth = onMeasureProcessName(st.name);
}
}
}
| apache-2.0 |
hurricup/intellij-community | java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java | 75470 | /*
* Copyright 2000-2016 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.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootModificationTracker;
import com.intellij.openapi.util.*;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.psi.CommonClassNames.JAVA_LANG_STRING;
public class TypeConversionUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.util.TypeConversionUtil");
private static final boolean[][] IS_ASSIGNABLE_BIT_SET = {
{true, true, false, true, true, true, true}, // byte
{false, true, false, true, true, true, true}, // short
{false, false, true, true, true, true, true}, // char
{false, false, false, true, true, true, true}, // int
{false, false, false, false, true, true, true}, // long
{false, false, false, false, false, true, true}, // float
{false, false, false, false, false, false, true}, // double
};
private static final TObjectIntHashMap<PsiType> TYPE_TO_RANK_MAP = new TObjectIntHashMap<PsiType>();
public static final int BYTE_RANK = 1;
public static final int SHORT_RANK = 2;
public static final int CHAR_RANK = 3;
public static final int INT_RANK = 4;
public static final int LONG_RANK = 5;
private static final int FLOAT_RANK = 6;
private static final int DOUBLE_RANK = 7;
private static final int BOOL_RANK = 10;
private static final int STRING_RANK = 100;
private static final int MAX_NUMERIC_RANK = DOUBLE_RANK;
public static final PsiType NULL_TYPE = new PsiEllipsisType(PsiType.NULL) {
@Override
public boolean isValid() {
return true;
}
@NotNull
@Override
public String getPresentableText(boolean annotated) {
return "FAKE TYPE";
}
};
private static final Key<PsiElement> ORIGINAL_CONTEXT = Key.create("ORIGINAL_CONTEXT");
static {
TYPE_TO_RANK_MAP.put(PsiType.BYTE, BYTE_RANK);
TYPE_TO_RANK_MAP.put(PsiType.SHORT, SHORT_RANK);
TYPE_TO_RANK_MAP.put(PsiType.CHAR, CHAR_RANK);
TYPE_TO_RANK_MAP.put(PsiType.INT, INT_RANK);
TYPE_TO_RANK_MAP.put(PsiType.LONG, LONG_RANK);
TYPE_TO_RANK_MAP.put(PsiType.FLOAT, FLOAT_RANK);
TYPE_TO_RANK_MAP.put(PsiType.DOUBLE, DOUBLE_RANK);
TYPE_TO_RANK_MAP.put(PsiType.BOOLEAN, BOOL_RANK);
}
private TypeConversionUtil() { }
/**
* @return true if fromType can be casted to toType
*/
public static boolean areTypesConvertible(@NotNull PsiType fromType, @NotNull PsiType toType) {
return areTypesConvertible(fromType, toType, null);
}
/**
* @return true if fromType can be casted to toType
*/
public static boolean areTypesConvertible(@NotNull PsiType fromType, @NotNull PsiType toType, @Nullable LanguageLevel languageLevel) {
if (fromType == toType) return true;
final boolean fromIsPrimitive = isPrimitiveAndNotNull(fromType);
final boolean toIsPrimitive = isPrimitiveAndNotNull(toType);
if (fromIsPrimitive || toIsPrimitive) {
if (isVoidType(fromType) || isVoidType(toType)) return false;
final int fromTypeRank = getTypeRank(fromType);
final int toTypeRank = getTypeRank(toType);
if (!toIsPrimitive) {
if (fromTypeRank == toTypeRank) return true;
if (toType instanceof PsiIntersectionType) {
for (PsiType type : ((PsiIntersectionType)toType).getConjuncts()) {
if (!areTypesConvertible(fromType, type)) return false;
}
return true;
}
// JLS 5.5: A value of a primitive type can be cast to a reference type by boxing conversion(see 5.1.7)
if (!(toType instanceof PsiClassType)) return false;
PsiClass toClass = ((PsiClassType)toType).resolve();
if (toClass == null || toClass instanceof PsiTypeParameter) return false;
PsiClassType boxedType = ((PsiPrimitiveType)fromType).getBoxedType(toClass.getManager(), toType.getResolveScope());
return boxedType != null && areTypesConvertible(boxedType, toType);
}
if (!fromIsPrimitive) {
// 5.5. Casting Contexts
if ((fromTypeRank == SHORT_RANK || fromTypeRank == BYTE_RANK) && toTypeRank == CHAR_RANK) return false;
if (fromType instanceof PsiClassType) {
if (languageLevel == null) {
languageLevel = ((PsiClassType)fromType).getLanguageLevel();
}
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_7)) {
final PsiClassType classType = (PsiClassType)fromType;
final PsiClass psiClass = classType.resolve();
if (psiClass == null) return false;
final PsiClassType boxedType = ((PsiPrimitiveType)toType).getBoxedType(psiClass.getManager(), psiClass.getResolveScope());
if (boxedType != null && isNarrowingReferenceConversionAllowed(fromType, boxedType)) {
return true;
}
}
}
return fromTypeRank == toTypeRank ||
fromTypeRank <= MAX_NUMERIC_RANK && toTypeRank <= MAX_NUMERIC_RANK && fromTypeRank < toTypeRank;
}
return fromTypeRank == toTypeRank ||
fromTypeRank <= MAX_NUMERIC_RANK && toTypeRank <= MAX_NUMERIC_RANK;
}
//type can be casted via widening reference conversion
if (isAssignable(toType, fromType)) return true;
if (isNullType(fromType) || isNullType(toType)) return true;
// or narrowing reference conversion
return isNarrowingReferenceConversionAllowed(fromType, toType);
}
/**
* see JLS 5.1.5, JLS3 5.1.6
*/
private static boolean isNarrowingReferenceConversionAllowed(@NotNull PsiType fromType, @NotNull PsiType toType) {
if (toType instanceof PsiPrimitiveType || fromType instanceof PsiPrimitiveType) return fromType.equals(toType);
//Done with primitives
if (toType instanceof PsiDiamondType || fromType instanceof PsiDiamondType) return false;
if (toType instanceof PsiArrayType && !(fromType instanceof PsiArrayType)) {
if (fromType instanceof PsiClassType) {
final PsiClass resolved = ((PsiClassType)fromType).resolve();
if (resolved instanceof PsiTypeParameter) {
for (final PsiClassType boundType : resolved.getExtendsListTypes()) {
if (!isNarrowingReferenceConversionAllowed(boundType, toType)) return false;
}
return true;
}
}
if (fromType instanceof PsiCapturedWildcardType) {
return isNarrowingReferenceConversionAllowed(((PsiCapturedWildcardType)fromType).getUpperBound(), toType);
}
return isAssignable(fromType, toType);
}
if (fromType instanceof PsiArrayType) {
if (toType instanceof PsiClassType) {
final PsiClass resolved = ((PsiClassType)toType).resolve();
if (resolved instanceof PsiTypeParameter) {
for (final PsiClassType boundType : resolved.getExtendsListTypes()) {
if (!areTypesConvertible(fromType, boundType)) return false;
}
return true;
}
}
return toType instanceof PsiArrayType
&& isNarrowingReferenceConversionAllowed(((PsiArrayType)fromType).getComponentType(),
((PsiArrayType)toType).getComponentType());
}
//Done with array types
if (fromType instanceof PsiIntersectionType) {
final PsiType[] conjuncts = ((PsiIntersectionType)fromType).getConjuncts();
for (PsiType conjunct : conjuncts) {
if (isNarrowingReferenceConversionAllowed(conjunct, toType)) return true;
}
return false;
}
else if (toType instanceof PsiIntersectionType) {
if (fromType instanceof PsiClassType && ((PsiClassType)fromType).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_8)) {
for (PsiType conjunct : ((PsiIntersectionType)toType).getConjuncts()) {
if (!isNarrowingReferenceConversionAllowed(fromType, conjunct)) return false;
}
return true;
}
return false;
}
if (fromType instanceof PsiDisjunctionType) {
return isNarrowingReferenceConversionAllowed(((PsiDisjunctionType)fromType).getLeastUpperBound(), toType);
}
if (toType instanceof PsiDisjunctionType) {
return false;
}
if (fromType instanceof PsiWildcardType) {
final PsiWildcardType fromWildcard = (PsiWildcardType)fromType;
final PsiType bound = fromWildcard.getBound();
if (bound == null) return true;
if (fromWildcard.isSuper()) {
return isAssignable(toType, bound);
}
return isNarrowingReferenceConversionAllowed(bound, toType);
}
if (toType instanceof PsiWildcardType) {
final PsiWildcardType toWildcard = (PsiWildcardType)toType;
if (toWildcard.isSuper()) return false;
final PsiType bound = toWildcard.getBound();
return bound == null || isNarrowingReferenceConversionAllowed(fromType, bound);
}
if (toType instanceof PsiCapturedWildcardType) {
return isNarrowingReferenceConversionAllowed(fromType, ((PsiCapturedWildcardType)toType).getUpperBound());
}
if (fromType instanceof PsiCapturedWildcardType) {
return isNarrowingReferenceConversionAllowed(((PsiCapturedWildcardType)fromType).getUpperBound(), toType);
}
if (isAssignable(fromType, toType)) return true;
if (!(fromType instanceof PsiClassType) || !(toType instanceof PsiClassType)) return false;
PsiClassType fromClassType = (PsiClassType)fromType;
PsiClassType toClassType = (PsiClassType)toType;
PsiClassType.ClassResolveResult fromResult = fromClassType.resolveGenerics();
final PsiClass fromClass = fromResult.getElement();
if (fromClass == null) return false;
if (fromClass instanceof PsiTypeParameter) return isNarrowingReferenceConversionAllowed(obtainSafeSuperType((PsiTypeParameter)fromClass), toType);
PsiClassType.ClassResolveResult toResult = toClassType.resolveGenerics();
final PsiClass toClass = toResult.getElement();
if (toClass == null) return false;
if (toClass instanceof PsiTypeParameter) return isNarrowingReferenceConversionAllowed(fromType, obtainSafeSuperType((PsiTypeParameter)toClass));
//Done with type parameters
PsiManager manager = fromClass.getManager();
final LanguageLevel languageLevel = toClassType.getLanguageLevel();
if (!fromClass.isInterface()) {
if (toClass.isInterface()) {
return (!fromClass.hasModifierProperty(PsiModifier.FINAL) || fromClass.isInheritor(toClass, true))&&
checkSuperTypesWithDifferentTypeArguments(toResult, fromClass, manager, fromResult.getSubstitutor(), null, languageLevel);
}
else {
if (manager.areElementsEquivalent(fromClass, toClass)) {
return areSameParameterTypes(fromClassType, toClassType);
}
if (toClass.isInheritor(fromClass, true)) {
return checkSuperTypesWithDifferentTypeArguments(fromResult, toClass, manager, toResult.getSubstitutor(), null, languageLevel);
}
else if (fromClass.isInheritor(toClass, true)) {
return checkSuperTypesWithDifferentTypeArguments(toResult, fromClass, manager, fromResult.getSubstitutor(), null, languageLevel);
}
return false;
}
}
else if (!toClass.isInterface()) {
if (!toClass.hasModifierProperty(PsiModifier.FINAL)) {
return checkSuperTypesWithDifferentTypeArguments(fromResult, toClass, manager, toResult.getSubstitutor(), null, languageLevel);
}
else {
PsiSubstitutor toSubstitutor = getMaybeSuperClassSubstitutor(fromClass, toClass, toResult.getSubstitutor(), null);
return toSubstitutor != null && areSameArgumentTypes(fromClass, fromResult.getSubstitutor(), toSubstitutor);
}
}
else if (languageLevel.compareTo(LanguageLevel.JDK_1_5) < 0) {
//In jls2 check for method in both interfaces with the same signature but different return types.
Collection<HierarchicalMethodSignature> fromClassMethodSignatures = fromClass.getVisibleSignatures();
Collection<HierarchicalMethodSignature> toClassMethodSignatures = toClass.getVisibleSignatures();
for (HierarchicalMethodSignature fromMethodSignature : fromClassMethodSignatures) {
for (HierarchicalMethodSignature toMethodSignature : toClassMethodSignatures) {
if (fromMethodSignature.equals(toMethodSignature)) {
final PsiType fromClassReturnType = fromMethodSignature.getMethod().getReturnType();
final PsiType toClassReturnType = toMethodSignature.getMethod().getReturnType();
if (fromClassReturnType != null
&& toClassReturnType != null
&& !fromClassReturnType.equals(toClassReturnType)) {
return false;
}
}
}
}
return true;
}
else {
//In jls3 check for super interface with distinct type arguments
PsiClassType.ClassResolveResult baseResult;
PsiClass derived;
PsiSubstitutor derivedSubstitutor;
if (toClass.isInheritor(fromClass, true)) {
baseResult = fromResult;
derived = toClass;
derivedSubstitutor = toResult.getSubstitutor();
}
else {
baseResult = toResult;
derived = fromClass;
derivedSubstitutor = fromResult.getSubstitutor();
}
return checkSuperTypesWithDifferentTypeArguments(baseResult, derived, manager, derivedSubstitutor, null, languageLevel);
}
}
@NotNull
private static PsiClassType obtainSafeSuperType(@NotNull PsiTypeParameter typeParameter) {
final PsiClassType superType = typeParameter.getSuperTypes()[0];
final PsiClassType.ClassResolveResult result = superType.resolveGenerics();
final PsiClass superClass = result.getElement();
if (superClass != null) {
final PsiSubstitutor substitutor = result.getSubstitutor().put(typeParameter, null);
return JavaPsiFacade.getInstance(typeParameter.getProject()).getElementFactory().createType(superClass, substitutor);
}
return superType;
}
private static boolean checkSuperTypesWithDifferentTypeArguments(@NotNull PsiClassType.ClassResolveResult baseResult,
@NotNull PsiClass derived,
@NotNull PsiManager manager,
@NotNull PsiSubstitutor derivedSubstitutor,
Set<PsiClass> visited,
@NotNull LanguageLevel languageLevel) {
if (visited != null && visited.contains(derived)) return true;
if (languageLevel.compareTo(LanguageLevel.JDK_1_5) < 0) return true;
PsiClass base = baseResult.getElement();
PsiClass[] supers = derived.getSupers();
if (manager.areElementsEquivalent(base, derived)) {
derivedSubstitutor = getSuperClassSubstitutor(derived, derived, derivedSubstitutor);
return areSameArgumentTypes(derived, baseResult.getSubstitutor(), derivedSubstitutor, 1);
}
else {
PsiSubstitutor baseSubstitutor = getMaybeSuperClassSubstitutor(derived, base, baseResult.getSubstitutor(), null);
if (baseSubstitutor != null) {
derivedSubstitutor = getSuperClassSubstitutor(derived, derived, derivedSubstitutor);
if (!areSameArgumentTypes(derived, baseSubstitutor, derivedSubstitutor)) return false;
}
}
if (visited == null) visited = new THashSet<PsiClass>();
visited.add(derived);
for (PsiClass aSuper : supers) {
PsiSubstitutor s = getSuperClassSubstitutor(aSuper, derived, derivedSubstitutor);
if (!checkSuperTypesWithDifferentTypeArguments(baseResult, aSuper, manager, s, visited, languageLevel)) return false;
}
return true;
}
private static boolean areSameParameterTypes(@NotNull PsiClassType type1, @NotNull PsiClassType type2) {
PsiClassType.ClassResolveResult resolveResult1 = type1.resolveGenerics();
PsiClassType.ClassResolveResult resolveResult2 = type2.resolveGenerics();
final PsiClass aClass = resolveResult1.getElement();
final PsiClass bClass = resolveResult2.getElement();
return aClass != null &&
bClass != null &&
aClass.getManager().areElementsEquivalent(aClass, bClass) &&
areSameArgumentTypes(aClass, resolveResult1.getSubstitutor(), resolveResult2.getSubstitutor(), 1);
}
private static boolean areSameArgumentTypes(@NotNull PsiClass aClass, @NotNull PsiSubstitutor substitutor1, @NotNull PsiSubstitutor substitutor2) {
return areSameArgumentTypes(aClass, substitutor1, substitutor2, 0);
}
private static boolean areSameArgumentTypes(@NotNull PsiClass aClass,
@NotNull PsiSubstitutor substitutor1,
@NotNull PsiSubstitutor substitutor2,
int level) {
for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(aClass)) {
PsiType typeArg1 = substitutor1.substitute(typeParameter);
PsiType typeArg2 = substitutor2.substitute(typeParameter);
if (typeArg1 == null || typeArg2 == null) return true;
if (TypesDistinctProver.provablyDistinct(typeArg1, typeArg2, level)) return false;
}
return true;
}
public static boolean isPrimitiveAndNotNull(PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isPrimitiveAndNotNull(((PsiCapturedWildcardType)type).getUpperBound());
}
return type instanceof PsiPrimitiveType && !isNullType(type);
}
public static boolean isEnumType(PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isEnumType(((PsiCapturedWildcardType)type).getUpperBound());
}
if (type instanceof PsiClassType) {
final PsiClass psiClass = ((PsiClassType)type).resolve();
return psiClass != null && psiClass.isEnum();
}
return false;
}
public static boolean isNullType(PsiType type) {
return PsiType.NULL.equals(type);
}
public static boolean isFloatOrDoubleType(PsiType type) {
return isFloatType(type) || isDoubleType(type);
}
public static boolean isDoubleType(PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isDoubleType(((PsiCapturedWildcardType)type).getUpperBound());
}
return PsiType.DOUBLE.equals(type) || PsiType.DOUBLE.equals(PsiPrimitiveType.getUnboxedType(type));
}
public static boolean isFloatType(PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isFloatType(((PsiCapturedWildcardType)type).getUpperBound());
}
return PsiType.FLOAT.equals(type) || PsiType.FLOAT.equals(PsiPrimitiveType.getUnboxedType(type));
}
public static boolean isLongType(PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isLongType(((PsiCapturedWildcardType)type).getUpperBound());
}
return PsiType.LONG.equals(type) || PsiType.LONG.equals(PsiPrimitiveType.getUnboxedType(type));
}
public static boolean isVoidType(PsiType type) {
return PsiType.VOID.equals(type);
}
public static boolean isBooleanType(@Nullable PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isBooleanType(((PsiCapturedWildcardType)type).getUpperBound());
}
return PsiType.BOOLEAN.equals(type) || PsiType.BOOLEAN.equals(PsiPrimitiveType.getUnboxedType(type));
}
public static boolean isNumericType(int typeRank) {
return typeRank <= MAX_NUMERIC_RANK;
}
public static boolean isNumericType(PsiType type) {
return type != null && isNumericType(getTypeRank(type));
}
/**
* @return 1..MAX_NUMERIC_TYPE if type is primitive numeric type,
* BOOL_TYPE for boolean,
* STRING_TYPE for String,
* Integer.MAX_VALUE for others
*/
public static int getTypeRank(@NotNull PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
type = ((PsiCapturedWildcardType)type).getUpperBound();
}
PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(type);
if (unboxedType != null) {
type = unboxedType;
}
int rank = TYPE_TO_RANK_MAP.get(type);
if (rank != 0) return rank;
if (type.equalsToText(JAVA_LANG_STRING)) return STRING_RANK;
return Integer.MAX_VALUE;
}
/**
* @param tokenType JavaTokenType enumeration
* @param strict true if operator result type should be convertible to the left operand
* @return true if lOperand operator rOperand expression is syntactically correct
*/
public static boolean isBinaryOperatorApplicable(IElementType tokenType,
PsiExpression lOperand,
PsiExpression rOperand,
boolean strict) {
if (lOperand == null || rOperand == null) return true;
final PsiType ltype = lOperand.getType();
final PsiType rtype = rOperand.getType();
return isBinaryOperatorApplicable(tokenType, ltype, rtype, strict);
}
public static boolean isBinaryOperatorApplicable(final IElementType tokenType, final PsiType ltype, final PsiType rtype, final boolean strict) {
if (ltype == null || rtype == null) return true;
int resultTypeRank = BOOL_RANK;
boolean isApplicable = false;
final int ltypeRank = getTypeRank(ltype);
final int rtypeRank = getTypeRank(rtype);
Label:
if (tokenType == JavaTokenType.LT || tokenType == JavaTokenType.LE || tokenType == JavaTokenType.GT || tokenType == JavaTokenType.GE) {
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype)) {
isApplicable = ltypeRank <= MAX_NUMERIC_RANK && rtypeRank <= MAX_NUMERIC_RANK;
}
}
else if (tokenType == JavaTokenType.EQEQ || tokenType == JavaTokenType.NE) {
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype) &&
(isPrimitiveAndNotNull(ltype) || isPrimitiveAndNotNull(rtype))) {
isApplicable = ltypeRank <= MAX_NUMERIC_RANK && rtypeRank <= MAX_NUMERIC_RANK
|| ltypeRank == BOOL_RANK && rtypeRank == BOOL_RANK;
}
else {
if (isPrimitiveAndNotNull(ltype)) {
if (rtype instanceof PsiClassType) {
final LanguageLevel languageLevel = ((PsiClassType)rtype).getLanguageLevel();
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5) &&
!languageLevel.isAtLeast(LanguageLevel.JDK_1_8) &&
areTypesConvertible(ltype, rtype)) {
return true;
}
}
return false;
}
if (isPrimitiveAndNotNull(rtype)) {
if (ltype instanceof PsiClassType) {
final LanguageLevel level = ((PsiClassType)ltype).getLanguageLevel();
if (level.isAtLeast(LanguageLevel.JDK_1_7) && !level.isAtLeast(LanguageLevel.JDK_1_8) && areTypesConvertible(rtype, ltype)) {
return true;
}
}
return false;
}
isApplicable = areTypesConvertible(ltype, rtype) || areTypesConvertible(rtype, ltype);
}
}
else if (tokenType == JavaTokenType.PLUS) {
if (ltype.equalsToText(JAVA_LANG_STRING)) {
isApplicable = !isVoidType(rtype);
resultTypeRank = STRING_RANK;
break Label;
}
else if (rtype.equalsToText(JAVA_LANG_STRING)) {
isApplicable = !isVoidType(ltype);
resultTypeRank = STRING_RANK;
break Label;
}
//fallthrough
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype)) {
resultTypeRank = Math.max(ltypeRank, rtypeRank);
isApplicable = ltypeRank <= MAX_NUMERIC_RANK && rtypeRank <= MAX_NUMERIC_RANK;
}
}
else if (tokenType == JavaTokenType.ASTERISK || tokenType == JavaTokenType.DIV || tokenType == JavaTokenType.PERC ||
tokenType == JavaTokenType.MINUS) {
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype)) {
resultTypeRank = Math.max(ltypeRank, rtypeRank);
isApplicable = ltypeRank <= MAX_NUMERIC_RANK && rtypeRank <= MAX_NUMERIC_RANK;
}
}
else if (tokenType == JavaTokenType.LTLT || tokenType == JavaTokenType.GTGT || tokenType == JavaTokenType.GTGTGT) {
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype)) {
isApplicable = ltypeRank <= LONG_RANK && rtypeRank <= LONG_RANK;
resultTypeRank = INT_RANK;
}
}
else if (tokenType == JavaTokenType.AND || tokenType == JavaTokenType.OR || tokenType == JavaTokenType.XOR) {
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype)) {
isApplicable = ltypeRank <= LONG_RANK && rtypeRank <= LONG_RANK
|| isBooleanType(ltype) && isBooleanType(rtype);
resultTypeRank = ltypeRank <= LONG_RANK ? INT_RANK : BOOL_RANK;
}
}
else if (tokenType == JavaTokenType.ANDAND || tokenType == JavaTokenType.OROR) {
if (isPrimitiveAndNotNullOrWrapper(ltype) && isPrimitiveAndNotNullOrWrapper(rtype)) {
isApplicable = isBooleanType(ltype) && isBooleanType(rtype);
}
}
if (isApplicable && strict) {
if (resultTypeRank > MAX_NUMERIC_RANK) {
isApplicable = ltypeRank == resultTypeRank || ltype.equalsToText(CommonClassNames.JAVA_LANG_OBJECT);
}
else {
isApplicable = ltypeRank <= MAX_NUMERIC_RANK;
}
}
return isApplicable;
}
public static boolean isPrimitiveAndNotNullOrWrapper(PsiType type) {
if (type instanceof PsiCapturedWildcardType) {
return isPrimitiveAndNotNullOrWrapper(((PsiCapturedWildcardType)type).getUpperBound());
}
if (type instanceof PsiClassType) {
return PsiPrimitiveType.getUnboxedType(type) != null;
}
return isPrimitiveAndNotNull(type);
}
public static boolean isUnaryOperatorApplicable(@NotNull PsiJavaToken token, PsiExpression operand) {
if (operand == null) return false;
PsiType type = operand.getType();
return type != null && isUnaryOperatorApplicable(token, type);
}
public static boolean isUnaryOperatorApplicable(@NotNull PsiJavaToken token, @NotNull PsiType type) {
IElementType i = token.getTokenType();
int typeRank = getTypeRank(type);
if (i == JavaTokenType.MINUSMINUS || i == JavaTokenType.PLUSPLUS) {
return typeRank <= MAX_NUMERIC_RANK;
}
if (i == JavaTokenType.MINUS || i == JavaTokenType.PLUS) {
return typeRank <= MAX_NUMERIC_RANK;
}
if (i == JavaTokenType.TILDE) {
return typeRank <= LONG_RANK;
}
if (i == JavaTokenType.EXCL) {
return typeRank == BOOL_RANK;
}
LOG.error("unknown token: " + token);
return true;
}
/**
* @return true if expression can be the left part of assignment operator
*/
public static boolean isLValue(PsiExpression element) {
if (element instanceof PsiReferenceExpression) {
final PsiReferenceExpression expression = (PsiReferenceExpression)element;
final PsiElement resolved = expression.resolve();
return resolved instanceof PsiVariable;
}
if (element instanceof PsiParenthesizedExpression) {
return isLValue(((PsiParenthesizedExpression)element).getExpression());
}
if (element instanceof PsiArrayAccessExpression) {
final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)element;
final PsiExpression arrayExpression = arrayAccessExpression.getArrayExpression();
final PsiType type = arrayExpression.getType();
if (type == null || !(type instanceof PsiArrayType)) return false;
final PsiExpression indexExpression = arrayAccessExpression.getIndexExpression();
if (indexExpression == null) return false;
final PsiType indexType = indexExpression.getType();
if (indexType == null) return false;
if (getTypeRank(indexType) <= INT_RANK) return true;
}
return false;
}
/**
* JLS 5.2
*/
public static boolean areTypesAssignmentCompatible(PsiType lType, PsiExpression rExpr) {
if (lType == null || rExpr == null) return true;
PsiType rType = rExpr.getType();
if (rType == null) return false;
if (isAssignable(lType, rType)) return true;
if (lType instanceof PsiClassType) {
lType = PsiPrimitiveType.getUnboxedType(lType);
if (lType == null) return false;
}
final int rTypeRank = getTypeRank(rType);
if (lType instanceof PsiPrimitiveType
&& rType instanceof PsiPrimitiveType
&& rTypeRank >= BYTE_RANK && rTypeRank <= INT_RANK) {
final Object rValue = JavaPsiFacade.getInstance(rExpr.getProject()).getConstantEvaluationHelper().computeConstantExpression(rExpr);
final long value;
if (rValue instanceof Number) {
value = ((Number)rValue).longValue();
}
else if (rValue instanceof Character) {
value = (Character)rValue;
}
else {
return false;
}
if (PsiType.BYTE.equals(lType)) {
return -128 <= value && value <= 127;
}
else if (PsiType.SHORT.equals(lType)) {
return -32768 <= value && value <= 32767;
}
else if (PsiType.CHAR.equals(lType)) {
return 0 <= value && value <= 0xFFFF;
}
}
return false;
}
/**
* Checks whether values of one type can be assigned to another
*
* @param left type to assign to
* @param right type of value
* @return true if value of type <code>right</code> can be assigned to an l-value of
* type <code>left</code>
*/
public static boolean isAssignable(@NotNull PsiType left, @NotNull PsiType right) {
return isAssignable(left, right, true);
}
public static boolean isAssignable(@NotNull PsiType left, @NotNull PsiType right, boolean allowUncheckedConversion) {
return isAssignable(left, right, allowUncheckedConversion, true);
}
private static boolean isAssignable(@NotNull PsiType left,
@NotNull PsiType right,
boolean allowUncheckedConversion,
boolean capture) {
if (left == right || left.equals(right)) return true;
if (isNullType(right)) {
return !(left instanceof PsiPrimitiveType) || isNullType(left);
}
if (right instanceof PsiMethodReferenceType) {
final PsiMethodReferenceExpression methodReferenceExpression = ((PsiMethodReferenceType)right).getExpression();
if (left instanceof PsiLambdaExpressionType) {
final PsiType rType = methodReferenceExpression.getFunctionalInterfaceType();
final PsiType lType = ((PsiLambdaExpressionType)left).getExpression().getFunctionalInterfaceType();
return Comparing.equal(rType, lType);
} else if (left instanceof PsiMethodReferenceType) {
final PsiType rType = methodReferenceExpression.getFunctionalInterfaceType();
final PsiType lType = ((PsiMethodReferenceType)left).getExpression().getFunctionalInterfaceType();
return Comparing.equal(rType, lType);
}
return !(left instanceof PsiArrayType) && methodReferenceExpression.isAcceptable(left);
}
if (right instanceof PsiLambdaExpressionType) {
final PsiLambdaExpression rLambdaExpression = ((PsiLambdaExpressionType)right).getExpression();
if (left instanceof PsiLambdaExpressionType) {
final PsiLambdaExpression lLambdaExpression = ((PsiLambdaExpressionType)left).getExpression();
final PsiType rType = rLambdaExpression.getFunctionalInterfaceType();
final PsiType lType = lLambdaExpression.getFunctionalInterfaceType();
return Comparing.equal(rType, lType);
}
return !(left instanceof PsiArrayType) && rLambdaExpression.isAcceptable(left);
}
if (left instanceof PsiIntersectionType) {
PsiType[] conjuncts = ((PsiIntersectionType)left).getConjuncts();
for (PsiType conjunct : conjuncts) {
if (!isAssignable(conjunct, right, allowUncheckedConversion, capture)) return false;
}
return true;
}
if (right instanceof PsiIntersectionType) {
PsiType[] conjuncts = ((PsiIntersectionType)right).getConjuncts();
for (PsiType conjunct : conjuncts) {
if (isAssignable(left, conjunct, allowUncheckedConversion, capture)) return true;
}
return false;
}
if (right instanceof PsiCapturedWildcardType) {
return isAssignable(left, ((PsiCapturedWildcardType)right).getUpperBound(capture), allowUncheckedConversion, capture);
}
if (left instanceof PsiCapturedWildcardType) {
return left.equals(right) || isAssignable(((PsiCapturedWildcardType)left).getLowerBound(), right, allowUncheckedConversion, capture);
}
if (left instanceof PsiWildcardType) {
return isAssignableToWildcard((PsiWildcardType)left, right);
}
if (right instanceof PsiWildcardType) {
return isAssignableFromWildcard(left, (PsiWildcardType)right);
}
if (right instanceof PsiArrayType) {
if (!(left instanceof PsiArrayType)) {
if (left instanceof PsiPrimitiveType || PsiUtil.resolveClassInType(left) == null) return false;
PsiClass lClass = PsiUtil.resolveClassInType(left);
if (lClass == null) return false;
if (lClass.isInterface()) {
final String qualifiedName = lClass.getQualifiedName();
return "java.io.Serializable".equals(qualifiedName) || "java.lang.Cloneable".equals(qualifiedName);
}
else {
return left.equalsToText(CommonClassNames.JAVA_LANG_OBJECT);
}
}
PsiType lCompType = ((PsiArrayType)left).getComponentType();
PsiType rCompType = ((PsiArrayType)right).getComponentType();
if (lCompType instanceof PsiPrimitiveType) {
return lCompType.equals(rCompType);
}
return !(rCompType instanceof PsiPrimitiveType) && isAssignable(lCompType, rCompType, allowUncheckedConversion, capture);
}
if (left instanceof PsiDisjunctionType) {
for (PsiType type : ((PsiDisjunctionType)left).getDisjunctions()) {
if (isAssignable(type, right, allowUncheckedConversion, capture)) return true;
}
return false;
}
if (right instanceof PsiDisjunctionType) {
return isAssignable(left, ((PsiDisjunctionType)right).getLeastUpperBound(), allowUncheckedConversion, capture);
}
if (left instanceof PsiArrayType) return false;
if (right instanceof PsiPrimitiveType) {
if (isVoidType(right)) return false;
if (!(left instanceof PsiPrimitiveType)) {
return left instanceof PsiClassType && isBoxable((PsiClassType)left, (PsiPrimitiveType)right);
}
int leftTypeIndex = TYPE_TO_RANK_MAP.get(left) - 1;
int rightTypeIndex = TYPE_TO_RANK_MAP.get(right) - 1;
return leftTypeIndex >= 0 &&
rightTypeIndex >= 0 &&
rightTypeIndex < IS_ASSIGNABLE_BIT_SET.length &&
leftTypeIndex < IS_ASSIGNABLE_BIT_SET.length &&
IS_ASSIGNABLE_BIT_SET[rightTypeIndex][leftTypeIndex];
}
if (!(right instanceof PsiClassType)) {
return false; // must be TypeCook's PsiTypeVariable
}
if (left instanceof PsiPrimitiveType) {
return isUnboxable((PsiPrimitiveType)left, (PsiClassType)right, new HashSet<PsiClassType>());
}
final PsiClassType.ClassResolveResult leftResult = PsiUtil.resolveGenericsClassInType(left);
final PsiClassType.ClassResolveResult rightResult = PsiUtil.resolveGenericsClassInType(right);
if (leftResult.getElement() == null || rightResult.getElement() == null) {
if (leftResult.getElement() != rightResult.getElement()) return false;
// let's suppose 2 unknown classes, which could be the same to be the same
String lText = left.getPresentableText();
String rText = right.getPresentableText();
if (lText.equals(rText)) return true;
if (lText.length() > rText.length() && lText.endsWith(rText) &&
lText.charAt(lText.length() - rText.length() - 1) == '.') {
return true;
}
return rText.length() > lText.length()
&& rText.endsWith(lText)
&& rText.charAt(rText.length() - lText.length() - 1) == '.';
}
return isClassAssignable(leftResult, rightResult, allowUncheckedConversion, left.getResolveScope(), capture);
}
private static boolean isAssignableFromWildcard(@NotNull PsiType left, @NotNull PsiWildcardType rightWildcardType) {
if (rightWildcardType.isSuper()) {
final PsiClass aClass = PsiUtil.resolveClassInType(rightWildcardType.getSuperBound());
if (aClass instanceof PsiTypeParameter) {
final PsiClassType[] types = aClass.getExtendsListTypes();
for (PsiClassType type : types) {
if (isAssignable(left, type)) return true;
}
}
}
return isAssignable(left, rightWildcardType.getExtendsBound());
}
private static boolean isAssignableToWildcard(@NotNull PsiWildcardType wildcardType, @NotNull PsiType right) {
if (wildcardType.isSuper()) {
return isAssignable(wildcardType.getSuperBound(), right);
}
return isAssignable(wildcardType.getExtendsBound(), right);
}
private static boolean isUnboxable(@NotNull PsiPrimitiveType left, @NotNull PsiClassType right, @NotNull Set<PsiClassType> types) {
if (!right.getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) return false;
final PsiClass psiClass = right.resolve();
if (psiClass == null) return false;
if (psiClass instanceof PsiTypeParameter) {
for (PsiClassType bound : psiClass.getExtendsListTypes()) {
if (types.add(bound) && isUnboxable(left, bound, types)) {
return true;
}
}
return false;
}
final PsiPrimitiveType rightUnboxedType = PsiPrimitiveType.getUnboxedType(right);
return rightUnboxedType != null && isAssignable(left, rightUnboxedType);
}
public static boolean boxingConversionApplicable(final PsiType left, final PsiType right) {
if (left instanceof PsiPrimitiveType && !PsiType.NULL.equals(left)) {
return right instanceof PsiClassType && isAssignable(left, right);
}
if (left instanceof PsiIntersectionType) {
for (PsiType lConjunct : ((PsiIntersectionType)left).getConjuncts()) {
if (!boxingConversionApplicable(lConjunct, right)) return false;
}
return true;
}
return left instanceof PsiClassType
&& right instanceof PsiPrimitiveType
&& !PsiType.NULL.equals(right)
&& isAssignable(left, right);
}
private static final Key<CachedValue<Set<String>>> POSSIBLE_BOXED_HOLDER_TYPES = Key.create("Types that may be possibly assigned from primitive ones");
private static boolean isBoxable(@NotNull PsiClassType left, @NotNull PsiPrimitiveType right) {
if (!left.getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) return false;
final PsiClass psiClass = left.resolve();
if (psiClass == null) return false;
final String qname = psiClass.getQualifiedName();
if (qname == null || !(psiClass instanceof PsiTypeParameter || getAllBoxedTypeSupers(psiClass).contains(qname))) {
return false;
}
final PsiClassType rightBoxed = right.getBoxedType(psiClass.getManager(), left.getResolveScope());
return rightBoxed != null && isAssignable(left, rightBoxed);
}
@NotNull
private static Set<String> getAllBoxedTypeSupers(@NotNull PsiClass psiClass) {
PsiManager manager = psiClass.getManager();
final Project project = psiClass.getProject();
CachedValue<Set<String>> boxedHolderTypes = project.getUserData(POSSIBLE_BOXED_HOLDER_TYPES);
if (boxedHolderTypes == null) {
project.putUserData(POSSIBLE_BOXED_HOLDER_TYPES, boxedHolderTypes = CachedValuesManager.getManager(manager.getProject()).createCachedValue(new CachedValueProvider<Set<String>>() {
@Override
public Result<Set<String>> compute() {
final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
final Set<String> set = new THashSet<String>();
for (final String qname : PsiPrimitiveType.getAllBoxedTypeNames()) {
final PsiClass boxedClass = facade.findClass(qname, GlobalSearchScope.allScope(project));
InheritanceUtil.processSupers(boxedClass, true, new Processor<PsiClass>() {
@Override
public boolean process(PsiClass psiClass) {
ContainerUtil.addIfNotNull(set, psiClass.getQualifiedName());
return true;
}
});
}
return Result.create(set, ProjectRootModificationTracker.getInstance(project));
}
}, false));
}
return boxedHolderTypes.getValue();
}
private static boolean isClassAssignable(@NotNull PsiClassType.ClassResolveResult leftResult,
@NotNull PsiClassType.ClassResolveResult rightResult,
boolean allowUncheckedConversion,
GlobalSearchScope resolveScope,
boolean capture) {
final PsiClass leftClass = leftResult.getElement();
final PsiClass rightClass = rightResult.getElement();
if (leftClass == null || rightClass == null) return false;
PsiSubstitutor superSubstitutor = JavaClassSupers.getInstance().getSuperClassSubstitutor(leftClass, rightClass, resolveScope,
rightResult.getSubstitutor());
return superSubstitutor != null && typeParametersAgree(leftResult, rightResult, allowUncheckedConversion, superSubstitutor, capture);
}
private static boolean typeParametersAgree(@NotNull PsiClassType.ClassResolveResult leftResult,
@NotNull PsiClassType.ClassResolveResult rightResult,
boolean allowUncheckedConversion, PsiSubstitutor superSubstitutor,
boolean capture) {
PsiSubstitutor rightSubstitutor = rightResult.getSubstitutor();
PsiClass leftClass = leftResult.getElement();
PsiClass rightClass = rightResult.getElement();
Iterator<PsiTypeParameter> li = PsiUtil.typeParametersIterator(leftClass);
if (!li.hasNext()) return true;
PsiSubstitutor leftSubstitutor = leftResult.getSubstitutor();
if (!leftClass.getManager().areElementsEquivalent(leftClass, rightClass)) {
rightSubstitutor = superSubstitutor;
rightClass = leftClass;
}
else if (!PsiUtil.typeParametersIterator(rightClass).hasNext()) return true;
Iterator<PsiTypeParameter> ri = PsiUtil.typeParametersIterator(rightClass);
while (li.hasNext()) {
if (!ri.hasNext()) return false;
PsiTypeParameter lp = li.next();
PsiTypeParameter rp = ri.next();
final PsiType typeLeft = leftSubstitutor.substitute(lp);
if (typeLeft == null) continue;
final PsiType typeRight = PsiCapturedWildcardType.isCapture() && capture
? rightSubstitutor.substituteWithBoundsPromotion(rp)
: rightSubstitutor.substitute(rp);
if (typeRight == null) {
// compatibility feature: allow to assign raw types to generic ones
return allowUncheckedConversion;
}
if (!typesAgree(typeLeft, typeRight, allowUncheckedConversion)) {
return false;
}
}
return true;
}
private static final RecursionGuard ourGuard = RecursionManager.createGuard("isAssignable");
public static boolean typesAgree(final @NotNull PsiType typeLeft,
final @NotNull PsiType typeRight,
final boolean allowUncheckedConversion) {
if (typeLeft instanceof PsiWildcardType) {
final PsiWildcardType leftWildcard = (PsiWildcardType)typeLeft;
final PsiType leftBound = leftWildcard.getBound();
if (leftBound == null) return true;
if (leftBound.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
if (!leftWildcard.isSuper()) return true;
if (typeRight.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return true;
}
if (typeRight instanceof PsiWildcardType) {
final PsiWildcardType rightWildcard = (PsiWildcardType)typeRight;
if (leftWildcard.isExtends()) {
return rightWildcard.isExtends() && isAssignable(leftBound, rightWildcard.getBound(), allowUncheckedConversion, false);
}
else { //isSuper
if (rightWildcard.isSuper()) {
final Boolean assignable = ourGuard.doPreventingRecursion(rightWildcard, true, new NotNullComputable<Boolean>() {
@NotNull
@Override
public Boolean compute() {
return isAssignable(rightWildcard.getBound(), leftBound, allowUncheckedConversion, false);
}
});
if (assignable != null && assignable) {
return true;
}
}
return false;
}
}
else {
if (leftWildcard.isExtends()) {
return isAssignable(leftBound, typeRight, false, false);
}
else { // isSuper
final Boolean assignable = ourGuard.doPreventingRecursion(leftWildcard, true, new NotNullComputable<Boolean>() {
@NotNull
@Override
public Boolean compute() {
return isAssignable(typeRight, leftBound, false, false);
}
});
return assignable == null || assignable.booleanValue();
}
}
}
else {
return typeLeft.equals(typeRight);
}
}
@Nullable
public static PsiSubstitutor getClassSubstitutor(@NotNull PsiClass superClassCandidate,
@NotNull PsiClass derivedClassCandidate,
@NotNull PsiSubstitutor derivedSubstitutor) {
if (superClassCandidate.getManager().areElementsEquivalent(superClassCandidate, derivedClassCandidate)) {
PsiTypeParameter[] baseParams = superClassCandidate.getTypeParameters();
PsiTypeParameter[] derivedParams = derivedClassCandidate.getTypeParameters();
if (baseParams.length > 0 && derivedParams.length == 0) {
return JavaPsiFacade.getInstance(superClassCandidate.getProject()).getElementFactory().createRawSubstitutor(superClassCandidate);
}
return derivedSubstitutor;
}
return getMaybeSuperClassSubstitutor(superClassCandidate, derivedClassCandidate, derivedSubstitutor, null);
}
private static final Set<String> ourReportedSuperClassSubstitutorExceptions = ContainerUtil.newConcurrentSet();
/**
* Calculates substitutor that binds type parameters in <code>superClass</code> with
* values that they have in <code>derivedClass</code>, given that type parameters in
* <code>derivedClass</code> are bound by <code>derivedSubstitutor</code>.
* <code>superClass</code> must be a super class/interface of <code>derivedClass</code> (as in
* <code>InheritanceUtil.isInheritorOrSelf(derivedClass, superClass, true)</code>
*
* @return substitutor (never returns <code>null</code>)
* @see PsiClass#isInheritor(PsiClass, boolean)
* @see InheritanceUtil#isInheritorOrSelf(PsiClass, PsiClass, boolean)
*/
@NotNull
public static PsiSubstitutor getSuperClassSubstitutor(@NotNull PsiClass superClass,
@NotNull PsiClass derivedClass,
@NotNull PsiSubstitutor derivedSubstitutor) {
if (!superClass.hasTypeParameters() && superClass.getContainingClass() == null) return PsiSubstitutor.EMPTY; //optimization and protection against EJB queer hierarchy
Set<PsiClass> visited = new THashSet<PsiClass>();
PsiSubstitutor substitutor = getMaybeSuperClassSubstitutor(superClass, derivedClass, derivedSubstitutor, visited);
if (substitutor == null) {
if (ourReportedSuperClassSubstitutorExceptions.add(derivedClass.getQualifiedName() + "/" + superClass.getQualifiedName())) {
reportHierarchyInconsistency(superClass, derivedClass, visited);
}
return PsiSubstitutor.EMPTY;
}
return substitutor;
}
// the same as getSuperClassSubstitutor() but can return null, which means that classes were not inheritors
@Nullable
public static PsiSubstitutor getMaybeSuperClassSubstitutor(@NotNull PsiClass superClass,
@NotNull PsiClass derivedClass,
@NotNull PsiSubstitutor derivedSubstitutor,
@Nullable Set<PsiClass> visited) {
return JavaClassSupers.getInstance().getSuperClassSubstitutor(superClass, derivedClass, derivedClass.getResolveScope(), derivedSubstitutor);
}
private static void reportHierarchyInconsistency(@NotNull PsiClass superClass, @NotNull PsiClass derivedClass, @NotNull Set<PsiClass> visited) {
final StringBuilder msg = new StringBuilder("Super: " + classInfo(superClass));
msg.append("visited:\n");
for (PsiClass aClass : visited) {
msg.append(" each: " + classInfo(aClass));
}
msg.append("isInheritor: " + InheritanceUtil.isInheritorOrSelf(derivedClass, superClass, true) + " " + derivedClass.isInheritor(superClass, true));
msg.append("\nhierarchy:\n");
InheritanceUtil.processSupers(derivedClass, true, new Processor<PsiClass>() {
@Override
public boolean process(PsiClass psiClass) {
msg.append("each: " + classInfo(psiClass));
return true;
}
});
LOG.error(msg.toString());
}
@NotNull
private static String classInfo(@NotNull PsiClass aClass) {
String s = aClass.getQualifiedName() + "(" + aClass.getClass().getName() + "; " + PsiUtilCore.getVirtualFile(aClass) + ");\n";
s += "extends: ";
for (PsiClassType type : aClass.getExtendsListTypes()) {
s += type + " (" + type.getClass().getName() + "; " + type.resolve() + ") ";
}
s += "\nimplements: ";
for (PsiClassType type : aClass.getImplementsListTypes()) {
s += type + " (" + type.getClass().getName() + "; " + type.resolve() + ") ";
}
return s + "\n";
}
@NotNull
public static PsiSubstitutor getSuperClassSubstitutor(@NotNull PsiClass superClass, @NotNull PsiClassType classType) {
final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
return getSuperClassSubstitutor(superClass, classResolveResult.getElement(), classResolveResult.getSubstitutor());
}
/**
* see JLS 5.6.2
*/
@NotNull
public static PsiType binaryNumericPromotion(PsiType type1, PsiType type2) {
if (isDoubleType(type1)) return unbox(type1);
if (isDoubleType(type2)) return unbox(type2);
if (isFloatType(type1)) return unbox(type1);
if (isFloatType(type2)) return unbox(type2);
if (isLongType(type1)) return unbox(type1);
if (isLongType(type2)) return unbox(type2);
return PsiType.INT;
}
@NotNull
private static PsiType unbox(@NotNull PsiType type) {
if (type instanceof PsiPrimitiveType) return type;
if (type instanceof PsiClassType) {
type = PsiPrimitiveType.getUnboxedType(type);
LOG.assertTrue(type != null);
return type;
}
LOG.error("Invalid type for unboxing "+type);
return type;
}
private static final Set<String> INTEGER_NUMBER_TYPES = new THashSet<String>(5);
static {
INTEGER_NUMBER_TYPES.add(PsiType.BYTE.getCanonicalText());
INTEGER_NUMBER_TYPES.add(PsiType.CHAR.getCanonicalText());
INTEGER_NUMBER_TYPES.add(PsiType.LONG.getCanonicalText());
INTEGER_NUMBER_TYPES.add(PsiType.INT.getCanonicalText());
INTEGER_NUMBER_TYPES.add(PsiType.SHORT.getCanonicalText());
}
private static final Set<String> PRIMITIVE_TYPES = new THashSet<String>(9);
static {
PRIMITIVE_TYPES.add(PsiType.VOID.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.BYTE.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.CHAR.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.DOUBLE.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.FLOAT.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.LONG.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.INT.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.SHORT.getCanonicalText());
PRIMITIVE_TYPES.add(PsiType.BOOLEAN.getCanonicalText());
}
private static final Set<String> PRIMITIVE_WRAPPER_TYPES = new THashSet<String>(8);
static {
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Byte");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Character");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Double");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Float");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Long");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Integer");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Short");
PRIMITIVE_WRAPPER_TYPES.add("java.lang.Boolean");
}
public static boolean isIntegerNumber(String typeName) {
return INTEGER_NUMBER_TYPES.contains(typeName);
}
public static boolean isPrimitive(String typeName) {
return PRIMITIVE_TYPES.contains(typeName);
}
public static boolean isPrimitiveWrapper(String typeName) {
return PRIMITIVE_WRAPPER_TYPES.contains(typeName);
}
@Contract("null -> false")
public static boolean isAssignableFromPrimitiveWrapper(final PsiType type) {
if (type == null) return false;
return isPrimitiveWrapper(type) ||
type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) ||
type.equalsToText(CommonClassNames.JAVA_LANG_NUMBER);
}
@Contract("null -> false")
public static boolean isPrimitiveWrapper(final PsiType type) {
return type != null && isPrimitiveWrapper(type.getCanonicalText());
}
@Contract("null -> false")
public static boolean isComposite(final PsiType type) {
return type instanceof PsiDisjunctionType || type instanceof PsiIntersectionType;
}
public static PsiType typeParameterErasure(@NotNull PsiTypeParameter typeParameter) {
return typeParameterErasure(typeParameter, PsiSubstitutor.EMPTY);
}
private static PsiType typeParameterErasure(@NotNull PsiTypeParameter typeParameter, @NotNull PsiSubstitutor beforeSubstitutor) {
final PsiClassType[] extendsList = typeParameter.getExtendsList().getReferencedTypes();
if (extendsList.length > 0) {
final PsiClass psiClass = extendsList[0].resolve();
if (psiClass instanceof PsiTypeParameter) {
Set<PsiClass> visited = new THashSet<PsiClass>();
visited.add(psiClass);
final PsiTypeParameter boundTypeParameter = (PsiTypeParameter)psiClass;
if (beforeSubstitutor.getSubstitutionMap().containsKey(boundTypeParameter)) {
return erasure(beforeSubstitutor.substitute(boundTypeParameter));
}
return typeParameterErasureInner(boundTypeParameter, visited, beforeSubstitutor);
}
else if (psiClass != null) {
return JavaPsiFacade.getInstance(typeParameter.getProject()).getElementFactory().createType(psiClass);
}
}
return PsiType.getJavaLangObject(typeParameter.getManager(), typeParameter.getResolveScope());
}
private static PsiClassType typeParameterErasureInner(PsiTypeParameter typeParameter,
Set<PsiClass> visited,
PsiSubstitutor beforeSubstitutor) {
final PsiClassType[] extendsList = typeParameter.getExtendsList().getReferencedTypes();
if (extendsList.length > 0) {
final PsiClass psiClass = extendsList[0].resolve();
if (psiClass instanceof PsiTypeParameter) {
if (!visited.contains(psiClass)) {
visited.add(psiClass);
if (beforeSubstitutor.getSubstitutionMap().containsKey(psiClass)) {
return (PsiClassType)erasure(beforeSubstitutor.substitute((PsiTypeParameter)psiClass));
}
return typeParameterErasureInner((PsiTypeParameter)psiClass, visited, beforeSubstitutor);
}
}
else if (psiClass != null) {
return JavaPsiFacade.getInstance(typeParameter.getProject()).getElementFactory().createType(psiClass);
}
}
return PsiType.getJavaLangObject(typeParameter.getManager(), typeParameter.getResolveScope());
}
@Contract("null -> null")
public static PsiType erasure(@Nullable PsiType type) {
return erasure(type, PsiSubstitutor.EMPTY);
}
@Contract("null, _ -> null")
public static PsiType erasure(@Nullable final PsiType type, @NotNull final PsiSubstitutor beforeSubstitutor) {
if (type == null) return null;
return type.accept(new PsiTypeVisitor<PsiType>() {
@Nullable
@Override
public PsiType visitType(PsiType type) {
return type;
}
@Override
public PsiType visitClassType(PsiClassType classType) {
final PsiClass aClass = classType.resolve();
if (aClass instanceof PsiTypeParameter && !isFreshVariable((PsiTypeParameter)aClass)) {
return typeParameterErasure((PsiTypeParameter)aClass, beforeSubstitutor);
}
return classType.rawType();
}
@Override
public PsiType visitWildcardType(PsiWildcardType wildcardType) {
return wildcardType;
}
@Nullable
@Override
public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
return capturedWildcardType.getUpperBound().accept(this);
}
@Override
public PsiType visitPrimitiveType(PsiPrimitiveType primitiveType) {
return primitiveType;
}
@Override
public PsiType visitEllipsisType(PsiEllipsisType ellipsisType) {
final PsiType componentType = ellipsisType.getComponentType();
final PsiType newComponentType = componentType.accept(this);
if (newComponentType == componentType) return ellipsisType;
return newComponentType != null ? newComponentType.createArrayType() : null;
}
@Override
public PsiType visitArrayType(PsiArrayType arrayType) {
final PsiType componentType = arrayType.getComponentType();
final PsiType newComponentType = componentType.accept(this);
if (newComponentType == componentType) return arrayType;
return newComponentType != null ? newComponentType.createArrayType() : null;
}
@Override
public PsiType visitDisjunctionType(PsiDisjunctionType disjunctionType) {
final PsiClassType lub = PsiTypesUtil.getLowestUpperBoundClassType(disjunctionType);
return lub != null ? erasure(lub, beforeSubstitutor) : disjunctionType;
}
});
}
public static Object computeCastTo(final Object operand, final PsiType castType) {
if (operand == null || castType == null) return null;
Object value;
if (operand instanceof String && castType.equalsToText(JAVA_LANG_STRING) ||
operand instanceof Boolean && PsiType.BOOLEAN.equals(castType)) {
value = operand;
}
else {
final PsiType primitiveType = wrapperToPrimitive(operand);
if (primitiveType == null) return null;
// identity cast, including (boolean)boolValue
if (castType.equals(primitiveType)) return operand;
final int rankFrom = getTypeRank(primitiveType);
if (rankFrom > caster.length) return null;
final int rankTo = getTypeRank(castType);
if (rankTo > caster.length) return null;
value = caster[rankFrom - 1][rankTo - 1].cast(operand);
}
return value;
}
@NotNull
public static PsiType unboxAndBalanceTypes(PsiType type1, PsiType type2) {
if (type1 instanceof PsiClassType) type1 = PsiPrimitiveType.getUnboxedType(type1);
if (type2 instanceof PsiClassType) type2 = PsiPrimitiveType.getUnboxedType(type2);
if (PsiType.DOUBLE.equals(type1) || PsiType.DOUBLE.equals(type2)) return PsiType.DOUBLE;
if (PsiType.FLOAT.equals(type1) || PsiType.FLOAT.equals(type2)) return PsiType.FLOAT;
if (PsiType.LONG.equals(type1) || PsiType.LONG.equals(type2)) return PsiType.LONG;
return PsiType.INT;
}
public static IElementType convertEQtoOperation(IElementType eqOpSign) {
IElementType opSign = null;
if (eqOpSign == JavaTokenType.ANDEQ) {
opSign = JavaTokenType.AND;
}
else if (eqOpSign == JavaTokenType.ASTERISKEQ) {
opSign = JavaTokenType.ASTERISK;
}
else if (eqOpSign == JavaTokenType.DIVEQ) {
opSign = JavaTokenType.DIV;
}
else if (eqOpSign == JavaTokenType.GTGTEQ) {
opSign = JavaTokenType.GTGT;
}
else if (eqOpSign == JavaTokenType.GTGTGTEQ) {
opSign = JavaTokenType.GTGTGT;
}
else if (eqOpSign == JavaTokenType.LTLTEQ) {
opSign = JavaTokenType.LTLT;
}
else if (eqOpSign == JavaTokenType.MINUSEQ) {
opSign = JavaTokenType.MINUS;
}
else if (eqOpSign == JavaTokenType.OREQ) {
opSign = JavaTokenType.OR;
}
else if (eqOpSign == JavaTokenType.PERCEQ) {
opSign = JavaTokenType.PERC;
}
else if (eqOpSign == JavaTokenType.PLUSEQ) {
opSign = JavaTokenType.PLUS;
}
else if (eqOpSign == JavaTokenType.XOREQ) {
opSign = JavaTokenType.XOR;
}
return opSign;
}
@Nullable
public static PsiType calcTypeForBinaryExpression(PsiType lType, PsiType rType, @NotNull IElementType sign, boolean accessLType) {
if (sign == JavaTokenType.PLUS) {
// evaluate right argument first, since '+-/*%' is left associative and left operand tends to be bigger
if (rType == null) return null;
if (rType.equalsToText(JAVA_LANG_STRING)) {
return rType;
}
if (!accessLType) return NULL_TYPE;
if (lType == null) return null;
if (lType.equalsToText(JAVA_LANG_STRING)) {
return lType;
}
return unboxAndBalanceTypes(lType, rType);
}
if (sign == JavaTokenType.MINUS || sign == JavaTokenType.ASTERISK || sign == JavaTokenType.DIV || sign == JavaTokenType.PERC) {
if (rType == null) return null;
if (!accessLType) return NULL_TYPE;
if (lType == null) return null;
return unboxAndBalanceTypes(lType, rType);
}
if (sign == JavaTokenType.LTLT || sign == JavaTokenType.GTGT || sign == JavaTokenType.GTGTGT) {
if (!accessLType) return NULL_TYPE;
if (PsiType.BYTE.equals(lType) || PsiType.CHAR.equals(lType) || PsiType.SHORT.equals(lType)) {
return PsiType.INT;
}
if (lType instanceof PsiClassType) lType = PsiPrimitiveType.getUnboxedType(lType);
return lType;
}
if (PsiBinaryExpression.BOOLEAN_OPERATION_TOKENS.contains(sign)) {
return PsiType.BOOLEAN;
}
if (sign == JavaTokenType.OR || sign == JavaTokenType.XOR || sign == JavaTokenType.AND) {
if (rType instanceof PsiClassType) rType = PsiPrimitiveType.getUnboxedType(rType);
if (lType instanceof PsiClassType) lType = PsiPrimitiveType.getUnboxedType(lType);
if (rType == null) return null;
if (PsiType.BOOLEAN.equals(rType)) return PsiType.BOOLEAN;
if (!accessLType) return NULL_TYPE;
if (lType == null) return null;
if (PsiType.BOOLEAN.equals(lType)) return PsiType.BOOLEAN;
if (PsiType.LONG.equals(lType) || PsiType.LONG.equals(rType)) return PsiType.LONG;
return PsiType.INT;
}
LOG.error("Unknown token: "+sign);
return null;
}
/**
* See JLS 3.10.2. Floating-Point Literals
* @return true if floating point literal consists of zeros only
*/
public static boolean isFPZero(@NotNull final String text) {
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (Character.isDigit(c) && c != '0') return false;
final char d = Character.toUpperCase(c);
if (d == 'E' || d == 'P') break;
}
return true;
}
public static boolean areSameFreshVariables(PsiTypeParameter p1, PsiTypeParameter p2) {
final PsiElement originalContext = p1.getUserData(ORIGINAL_CONTEXT);
return originalContext != null && originalContext == p2.getUserData(ORIGINAL_CONTEXT);
}
public static boolean isFreshVariable(PsiTypeParameter typeParameter) {
return typeParameter.getUserData(ORIGINAL_CONTEXT) != null;
}
public static void markAsFreshVariable(PsiTypeParameter parameter, PsiElement context) {
parameter.putUserData(ORIGINAL_CONTEXT, context);
}
private interface Caster {
@NotNull
Object cast(@NotNull Object operand);
}
private static final Caster[][] caster = {
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (short)((Number)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (char)((Number)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return ((Number)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (long)((Number)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (float)((Number)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (double)((Number)operand).intValue();
}
}
}
,
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (byte)((Short)operand).shortValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (char)((Short)operand).shortValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (int)(Short)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (long)(Short)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (float)(Short)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (double)(Short)operand;
}
}
}
,
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (byte)((Character)operand).charValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (short)((Character)operand).charValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (int)(Character)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (long)(Character)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (float)(Character)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (double)(Character)operand;
}
}
}
,
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (byte)((Integer)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (short)((Integer)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (char)((Integer)operand).intValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (long)(Integer)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (float)(Integer)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (double)(Integer)operand;
}
}
}
,
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (byte)((Long)operand).longValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (short)((Long)operand).longValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (char)((Long)operand).longValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (int)((Long)operand).longValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (float)(Long)operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (double)(Long)operand;
}
}
}
,
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (byte)((Float)operand).floatValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (short)((Float)operand).floatValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (char)((Float)operand).floatValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (int)((Float)operand).floatValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (long)((Float)operand).floatValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (double)(Float)operand;
}
}
}
,
{
new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (byte)((Double)operand).doubleValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (short)((Double)operand).doubleValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (char)((Double)operand).doubleValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (int)((Double)operand).doubleValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return (long)((Double)operand).doubleValue();
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return new Float((Double)operand);
}
}
, new Caster() {
@NotNull
@Override
public Object cast(@NotNull Object operand) {
return operand;
}
}
}
};
private static final Map<Class, PsiType> WRAPPER_TO_PRIMITIVE = new THashMap<Class, PsiType>(8);
static {
WRAPPER_TO_PRIMITIVE.put(Boolean.class, PsiType.BOOLEAN);
WRAPPER_TO_PRIMITIVE.put(Byte.class, PsiType.BYTE);
WRAPPER_TO_PRIMITIVE.put(Character.class, PsiType.CHAR);
WRAPPER_TO_PRIMITIVE.put(Short.class, PsiType.SHORT);
WRAPPER_TO_PRIMITIVE.put(Integer.class, PsiType.INT);
WRAPPER_TO_PRIMITIVE.put(Long.class, PsiType.LONG);
WRAPPER_TO_PRIMITIVE.put(Float.class, PsiType.FLOAT);
WRAPPER_TO_PRIMITIVE.put(Double.class, PsiType.DOUBLE);
}
private static PsiType wrapperToPrimitive(@NotNull Object o) {
return WRAPPER_TO_PRIMITIVE.get(o.getClass());
}
}
| apache-2.0 |
tufangorel/hazelcast | hazelcast/src/test/java/com/hazelcast/internal/management/ManagementCenterServiceTest.java | 2166 | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. 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 com.hazelcast.internal.management;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static com.hazelcast.internal.management.ManagementCenterService.cleanupUrl;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ManagementCenterServiceTest extends HazelcastTestSupport {
@After
public void tearDown() {
Hazelcast.shutdownAll();
}
@Test(expected = IllegalStateException.class)
public void testConstructor_withNullConfiguration() {
HazelcastInstance instance = Hazelcast.newHazelcastInstance();
instance.getConfig().setManagementCenterConfig(null);
new ManagementCenterService(getNode(instance).hazelcastInstance);
}
@Test
public void testCleanupUrl() {
String url = cleanupUrl("http://noCleanupNeeded/");
assertTrue(url.endsWith("/"));
}
@Test
public void testCleanupUrl_needsCleanup() {
String url = cleanupUrl("http://needsCleanUp");
assertTrue(url.endsWith("/"));
}
@Test
public void testCleanupUrl_withNull() {
assertNull(cleanupUrl(null));
}
}
| apache-2.0 |
G1DR4/client | app/src/androidTest/java/org/projectbuendia/client/ui/newpatient/PatientCreationControllerTest.java | 19459 | // Copyright 2015 The Project Buendia 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 distrib-
// uted 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
// specific language governing permissions and limitations under the License.
package org.projectbuendia.client.ui.newpatient;
import android.test.AndroidTestCase;
import com.google.common.base.Optional;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.projectbuendia.client.App;
import org.projectbuendia.client.FakeAppLocationTreeFactory;
import org.projectbuendia.client.R;
import org.projectbuendia.client.data.app.AppLocationTree;
import org.projectbuendia.client.data.app.AppModel;
import org.projectbuendia.client.data.app.AppPatient;
import org.projectbuendia.client.data.app.AppPatientDelta;
import org.projectbuendia.client.events.data.AppLocationTreeFetchedEvent;
import org.projectbuendia.client.events.data.PatientAddFailedEvent;
import org.projectbuendia.client.events.data.ItemCreatedEvent;
import org.projectbuendia.client.model.Zone;
import org.projectbuendia.client.ui.FakeEventBus;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
import static org.projectbuendia.client.ui.matchers.AppPatientMatchers.matchesPatientDelta;
/** Tests for {@link NewPatientController}. */
public class PatientCreationControllerTest extends AndroidTestCase {
private static final String VALID_ID = "123";
private static final String VALID_GIVEN_NAME = "Jane";
private static final String VALID_FAMILY_NAME = "Doe";
private static final String VALID_AGE = "56";
private static final int VALID_AGE_UNITS = NewPatientController.AGE_YEARS;
private static final int VALID_SEX = NewPatientController.SEX_FEMALE;
private static final LocalDate VALID_ADMISSION_DATE = LocalDate.now().minusDays(5);
private static final LocalDate VALID_SYMPTOMS_ONSET_DATE = LocalDate.now().minusDays(8);
private static final String VALID_LOCATION_UUID = Zone.SUSPECT_ZONE_UUID;
private NewPatientController mNewPatientController;
@Mock private NewPatientController.Ui mMockUi;
@Mock private AppModel mMockAppModel;
private FakeEventBus mFakeCrudEventBus;
@Override
protected void setUp() {
MockitoAnnotations.initMocks(this);
mFakeCrudEventBus = new FakeEventBus();
mNewPatientController =
new NewPatientController(mMockUi, mFakeCrudEventBus, mMockAppModel);
}
/** Tests that initializing the controller fetches a location tree for the location dialog. */
public void testInit_requestsLocationTree() {
// GIVEN an uninitialized controller
// WHEN controller is initialized
mNewPatientController.init();
// THEN controller requests a location tree
verify(mMockAppModel).fetchLocationTree(any(FakeEventBus.class), anyString());
}
/** Tests that suspending the controller unregisters the controller from the event bus. */
public void testSuspend_unregistersFromEventBus() {
// GIVEN an initialized controller with a location tree
mNewPatientController.init();
mFakeCrudEventBus.post(new AppLocationTreeFetchedEvent(FakeAppLocationTreeFactory.build()));
// WHEN controller is suspended
mNewPatientController.suspend();
// THEN controller unregisters from the event bus
assertEquals(0, mFakeCrudEventBus.countRegisteredReceivers());
}
/** Tests that the controller does not crash if it suspends before location tree is present. */
public void testSuspend_handlesNullLocationTree() {
// GIVEN an initialized controller without a location tree
mNewPatientController.init();
// WHEN controller is suspended
mNewPatientController.suspend();
// THEN controller doesn't crash
}
/** Tests that the controller passes its location tree to the activity when received. */
public void testEventSubscriber_passesLocationTreeToUi() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN location tree is fetched
AppLocationTree locationTree = FakeAppLocationTreeFactory.build();
mFakeCrudEventBus.post(new AppLocationTreeFetchedEvent(locationTree));
// THEN controller passes the location to the UI
verify(mMockUi).setLocationTree(locationTree);
}
/** Tests that the controller displays an error when the patient was not successfully added. */
public void testEventSubscriber_showsErrorMessageWhenPatientAddFails() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN a patient fails to be added
mFakeCrudEventBus.post(new PatientAddFailedEvent(
PatientAddFailedEvent.REASON_DUPLICATE_ID, null));
// THEN controller reports the error in the UI
verify(mMockUi).showErrorMessage(anyInt());
}
/** Tests that the controller causes the activity to quit when a patient is added. */
public void testEventSubscriber_quitsWhenPatientAddSucceeds() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN a patient is successfully added
AppPatient patient = AppPatient.builder().build();
mFakeCrudEventBus.post(new ItemCreatedEvent<>(patient));
// THEN controller tries to quit the activity
verify(mMockUi).quitActivity();
}
/** Tests that all fields are set correctly when adding a fully-populated patient. */
public void testCreatePatient_setsAllFieldsCorrectly() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN patient creation is requested with all fields
AppPatientDelta patientDelta = getValidAppPatientDelta();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller forwards request to model with correct fields
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that clicking 'create patient' clears any existing validation errors. */
public void testCreatePatient_clearsOldValidationErrors() {
// GIVEN an initialized controller with previously-entered incorrect data
mNewPatientController.init();
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.id = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// WHEN new data is added and 'create' is pressed
patientDelta.id = Optional.of(VALID_ID);
createPatientFromAppPatientDelta(patientDelta);
// THEN controller clears old errors
verify(mMockUi, atLeastOnce()).clearValidationErrors();
}
/** Tests that patient id is treated as a required field. */
public void testCreatePatient_requiresId() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields but id are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.id = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that given name is replaced by a default if not specified. */
public void testCreatePatient_givenNameDefaultsToUnknown() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields but given name are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.givenName = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller adds the patient with a default given name
patientDelta.givenName = Optional.of(App.getInstance().getString(R.string.unknown_name));
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that family name is replaced by a default if not specified. */
public void testCreatePatient_familyNameDefaultsToUnknown() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields but family name are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.familyName = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller adds the patient with a default family name
patientDelta.familyName =
Optional.of(App.getInstance().getString(R.string.unknown_name));
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that negative ages are not allowed. */
public void testCreatePatient_rejectsNegativeAge() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated, age is negative (birthdate in future)
mNewPatientController.createPatient(
VALID_ID,
VALID_GIVEN_NAME,
VALID_FAMILY_NAME,
"-1",
VALID_AGE_UNITS,
VALID_SEX,
VALID_ADMISSION_DATE,
VALID_SYMPTOMS_ONSET_DATE,
VALID_LOCATION_UUID);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that either 'years' or 'months' must be specified for patient age. */
public void testCreatePatient_requiresYearsOrMonthsSet() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields but years/months choice are populated
mNewPatientController.createPatient(
VALID_ID,
VALID_GIVEN_NAME,
VALID_FAMILY_NAME,
VALID_AGE,
-1,
VALID_SEX,
VALID_ADMISSION_DATE,
VALID_SYMPTOMS_ONSET_DATE,
VALID_LOCATION_UUID);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that gender is a required field (though it shouldn't be). */
public void testCreatePatient_requiresGender() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields but gender are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.gender = Optional.of(-1);
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that admission date must be specified. */
public void testCreatePatient_requiresAdmissionDate() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields but admission date are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.admissionDate = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that admission date cannot be a future date. */
public void testCreatePatient_rejectsFutureAdmissionDate() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated, admission date is in the future
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.admissionDate = Optional.of(LocalDate.now().plusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that admission date can be in the past. */
public void testCreatePatient_allowsPastAdmissionDate() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated, admission date is in the past
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.admissionDate = Optional.of(LocalDate.now().minusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that symptoms onset date can be left blank. */
public void testCreatePatient_doesNotRequireSymptomsOnsetDate() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated except symptoms onset date
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.firstSymptomDate = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation with no symptoms onset date
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that symptoms onset date cannot be in the future. */
public void testCreatePatient_rejectsFutureSymptomsOnsetDate() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated, symptoms onset date is in the future
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.firstSymptomDate = Optional.of(LocalDate.now().plusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that symptoms onset date can be in the past. */
public void testCreatePatient_allowsPastSymptomsOnsetDate() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated, symptoms onset date is in the past
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.firstSymptomDate = Optional.of(LocalDate.now().minusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that location can be left blank. */
public void testCreatePatient_doesNotRequireLocation() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated except location
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.assignedLocationUuid = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation, defaulting to Triage
patientDelta.assignedLocationUuid = Optional.of(Zone.TRIAGE_ZONE_UUID);
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that unicode characters can be used in the patient's name. */
public void testCreatePatient_supportsUnicodePatientName() {
// GIVEN an initialized controller
mNewPatientController.init();
// WHEN all fields are populated and given name contains unicode characters
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.givenName = Optional.of("ஸ்றீனிவாஸ ராமானுஜன் ஐயங்கார்");
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
private void createPatientFromAppPatientDelta(AppPatientDelta appPatientDelta) {
int age = -1;
int ageUnit = -1;
if (appPatientDelta.birthdate.isPresent()) {
Period agePeriod = new Period(appPatientDelta.birthdate.get(), DateTime.now());
if (agePeriod.getYears() < 1) {
age = agePeriod.getMonths();
ageUnit = NewPatientController.AGE_MONTHS;
} else {
age = agePeriod.getYears();
ageUnit = NewPatientController.AGE_YEARS;
}
}
mNewPatientController.createPatient(
appPatientDelta.id.orNull(),
appPatientDelta.givenName.orNull(),
appPatientDelta.familyName.orNull(),
age == -1 ? null : Integer.toString(age),
ageUnit,
appPatientDelta.gender.get(),
appPatientDelta.admissionDate.orNull(),
appPatientDelta.firstSymptomDate.orNull(),
appPatientDelta.assignedLocationUuid.orNull()
);
}
private AppPatientDelta getValidAppPatientDelta() {
AppPatientDelta appPatientDelta = new AppPatientDelta();
appPatientDelta.id = Optional.of(VALID_ID);
appPatientDelta.givenName = Optional.of(VALID_GIVEN_NAME);
appPatientDelta.familyName = Optional.of(VALID_FAMILY_NAME);
appPatientDelta.birthdate = Optional.of(getBirthdateFromAge(
Integer.parseInt(VALID_AGE), VALID_AGE_UNITS));
appPatientDelta.gender = Optional.of(VALID_SEX);
appPatientDelta.admissionDate = Optional.of(VALID_ADMISSION_DATE);
appPatientDelta.firstSymptomDate = Optional.of(VALID_SYMPTOMS_ONSET_DATE);
appPatientDelta.assignedLocationUuid = Optional.of(VALID_LOCATION_UUID);
return appPatientDelta;
}
private DateTime getBirthdateFromAge(int ageInt, int ageUnits) {
DateTime now = DateTime.now();
switch (ageUnits) {
case NewPatientController.AGE_YEARS:
return now.minusYears(ageInt);
case NewPatientController.AGE_MONTHS:
return now.minusMonths(ageInt);
default:
throw new IllegalArgumentException("Unknown age unit");
}
}
}
| apache-2.0 |
tufangorel/hazelcast | hazelcast/src/main/java/com/hazelcast/collection/impl/set/SetProxyImpl.java | 1343 | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. 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 com.hazelcast.collection.impl.set;
import com.hazelcast.collection.impl.collection.AbstractCollectionProxyImpl;
import com.hazelcast.config.CollectionConfig;
import com.hazelcast.core.ISet;
import com.hazelcast.spi.NodeEngine;
public class SetProxyImpl<E> extends AbstractCollectionProxyImpl<SetService, E> implements ISet<E> {
public SetProxyImpl(String name, NodeEngine nodeEngine, SetService service) {
super(name, nodeEngine, service);
}
@Override
protected CollectionConfig getConfig(NodeEngine nodeEngine) {
return nodeEngine.getConfig().findSetConfig(name);
}
@Override
public String getServiceName() {
return SetService.SERVICE_NAME;
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/ReconciliationReportServiceInterfacegetReconciliationReportsByStatement.java | 2796 |
package com.google.api.ads.dfp.jaxws.v201405;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Gets an {@link ReconciliationReportPage} of {@link ReconciliationReport} objects that satisfy
* the given {@link Statement#query}. The following fields are supported for filtering.
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ReconciliationReport#id}</td>
* </tr>
* <tr>
* <td>{@code status}</td>
* <td>{@link ReconciliationReport#status}</td>
* </tr>
* <tr>
* <td>{@code startDate}</td>
* <td>{@link ReconciliationReport#startDate}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to
* filter a set of reconciliation reports
* @return the reconciliation reports that match the given filter
*
*
* <p>Java class for getReconciliationReportsByStatement element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getReconciliationReportsByStatement">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v201405}Statement" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"filterStatement"
})
@XmlRootElement(name = "getReconciliationReportsByStatement")
public class ReconciliationReportServiceInterfacegetReconciliationReportsByStatement {
protected Statement filterStatement;
/**
* Gets the value of the filterStatement property.
*
* @return
* possible object is
* {@link Statement }
*
*/
public Statement getFilterStatement() {
return filterStatement;
}
/**
* Sets the value of the filterStatement property.
*
* @param value
* allowed object is
* {@link Statement }
*
*/
public void setFilterStatement(Statement value) {
this.filterStatement = value;
}
}
| apache-2.0 |
arifogel/batfish | projects/batfish/src/main/java/org/batfish/representation/f5_bigip/BuiltinProfileNetflow.java | 1104 | package org.batfish.representation.f5_bigip;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
/** Enumeration of built-in ltm profile netflow configurations */
@ParametersAreNonnullByDefault
public enum BuiltinProfileNetflow implements BuiltinProfile {
NETFLOW("netflow");
private static final Map<String, BuiltinProfileNetflow> FOR_NAME_MAP =
Arrays.stream(values())
.collect(
ImmutableMap.toImmutableMap(BuiltinProfileNetflow::getName, Function.identity()));
public static @Nullable BuiltinProfileNetflow forName(String name) {
return FOR_NAME_MAP.get(name);
}
private final @Nonnull String _name;
private BuiltinProfileNetflow(String name) {
_name = name;
}
@Override
public @Nonnull String getName() {
return _name;
}
@Override
public F5BigipStructureType getType() {
return F5BigipStructureType.PROFILE_NETFLOW;
}
}
| apache-2.0 |
misaochan/apps-android-commons | app/src/main/java/fr/free/nrw/commons/filepicker/PickedFiles.java | 5833 | package fr.free.nrw.commons.filepicker;
import android.content.ContentResolver;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.webkit.MimeTypeMap;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import timber.log.Timber;
class PickedFiles implements Constants {
private static String getFolderName(@NonNull Context context) {
return FilePicker.configuration(context).getFolderName();
}
private static File tempImageDirectory(@NonNull Context context) {
File privateTempDir = new File(context.getCacheDir(), DEFAULT_FOLDER_NAME);
if (!privateTempDir.exists()) privateTempDir.mkdirs();
return privateTempDir;
}
private static void writeToFile(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
writeToFile(in, dst);
}
static void copyFilesInSeparateThread(final Context context, final List<UploadableFile> filesToCopy) {
new Thread(() -> {
List<File> copiedFiles = new ArrayList<>();
int i = 1;
for (UploadableFile uploadableFile : filesToCopy) {
File fileToCopy = uploadableFile.getFile();
File dstDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getFolderName(context));
if (!dstDir.exists()) dstDir.mkdirs();
String[] filenameSplit = fileToCopy.getName().split("\\.");
String extension = "." + filenameSplit[filenameSplit.length - 1];
String filename = String.format("IMG_%s_%d.%s", new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()), i, extension);
File dstFile = new File(dstDir, filename);
try {
dstFile.createNewFile();
copyFile(fileToCopy, dstFile);
copiedFiles.add(dstFile);
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
scanCopiedImages(context, copiedFiles);
}).run();
}
static List<UploadableFile> singleFileList(UploadableFile file) {
List<UploadableFile> list = new ArrayList<>();
list.add(file);
return list;
}
static void scanCopiedImages(Context context, List<File> copiedImages) {
String[] paths = new String[copiedImages.size()];
for (int i = 0; i < copiedImages.size(); i++) {
paths[i] = copiedImages.get(i).toString();
}
MediaScannerConnection.scanFile(context,
paths, null,
(path, uri) -> {
Timber.d("Scanned " + path + ":");
Timber.d("-> uri=%s", uri);
});
}
static UploadableFile pickedExistingPicture(@NonNull Context context, Uri photoUri) throws IOException, SecurityException {// SecurityException for those file providers who share URI but forget to grant necessary permissions
InputStream pictureInputStream = context.getContentResolver().openInputStream(photoUri);
File directory = tempImageDirectory(context);
File photoFile = new File(directory, UUID.randomUUID().toString() + "." + getMimeType(context, photoUri));
if (photoFile.createNewFile()) {
writeToFile(pictureInputStream, photoFile);
} else {
throw new IOException("could not create photoFile to write upon");
}
return new UploadableFile(photoUri, photoFile);
}
static File getCameraPicturesLocation(@NonNull Context context) throws IOException {
File dir = tempImageDirectory(context);
return File.createTempFile(UUID.randomUUID().toString(), ".jpg", dir);
}
/**
* To find out the extension of required object in given uri
* Solution by http://stackoverflow.com/a/36514823/1171484
*/
private static String getMimeType(@NonNull Context context, @NonNull Uri uri) {
String extension;
//Check uri format to avoid null
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
//If scheme is a content
extension = MimeTypeMapWrapper.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
//If scheme is a File
//This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
static Uri getUriToFile(@NonNull Context context, @NonNull File file) {
String packageName = context.getApplicationContext().getPackageName();
String authority = packageName + ".provider";
return FileProvider.getUriForFile(context, authority, file);
}
} | apache-2.0 |
EArdeleanu/gateway | transport/wsn/src/test/java/org/kaazing/gateway/transport/wsn/HttpBindingsIT.java | 3236 | /**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.transport.wsn;
import static org.junit.rules.RuleChain.outerRule;
import java.net.URI;
import org.apache.log4j.PropertyConfigurator;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.kaazing.gateway.server.test.GatewayRule;
import org.kaazing.gateway.server.test.config.GatewayConfiguration;
import org.kaazing.gateway.server.test.config.builder.GatewayConfigurationBuilder;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
public class HttpBindingsIT {
private K3poRule robot = new K3poRule();
private static final boolean ENABLE_DIAGNOSTICS = false;
@BeforeClass
public static void init()
throws Exception {
if (ENABLE_DIAGNOSTICS) {
PropertyConfigurator.configure("src/test/resources/log4j-diagnostic.properties");
}
}
public GatewayRule gateway = new GatewayRule() {
{
GatewayConfiguration configuration = new GatewayConfigurationBuilder()
.service()
.accept(URI.create("ws://localhost:8001/echo"))
.type("echo")
.crossOrigin()
.allowOrigin("*")
.done()
.acceptOption("ws.inactivity.timeout", "2sec")
.done()
.service()
.accept(URI.create("ws://localhost:80/echo80"))
.type("echo")
.crossOrigin()
.allowOrigin("*")
.done()
.acceptOption("ws.inactivity.timeout", "2sec")
.acceptOption("tcp.bind", "8002")
.done()
.done();
init(configuration);
}
};
@Rule
public TestRule chain = outerRule(robot).around(gateway);
@Specification("connectingOnService1ShouldNotGetAccessToService2")
@Test(timeout = 8 * 1000) //4s should suffice (twice the expected 2 second timeout), but leave a margin just in case
// Test case for KG-10516
public void connectingOnService1ShouldNotGetAccessToService2() throws Exception {
robot.finish();
}
}
| apache-2.0 |
SaiNadh001/aws-sdk-for-java | src/main/java/com/amazonaws/services/elasticbeanstalk/model/ConfigurationOptionValueType.java | 1700 | /*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticbeanstalk.model;
/**
* Configuration Option Value Type
*/
public enum ConfigurationOptionValueType {
Scalar("Scalar"),
List("List");
private String value;
private ConfigurationOptionValueType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return ConfigurationOptionValueType corresponding to the value
*/
public static ConfigurationOptionValueType fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
} else if ("Scalar".equals(value)) {
return ConfigurationOptionValueType.Scalar;
} else if ("List".equals(value)) {
return ConfigurationOptionValueType.List;
} else {
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
}
| apache-2.0 |
q474818917/solr-5.2.0 | solr/contrib/clustering/src/test/org/apache/solr/handler/clustering/DistributedClusteringComponentTest.java | 2113 | package org.apache.solr.handler.clustering;
/*
* 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.solr.BaseDistributedSearchTestCase;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.common.params.CommonParams;
import org.junit.Test;
@SuppressSSL
public class DistributedClusteringComponentTest extends
BaseDistributedSearchTestCase {
@Override
public String getSolrHome() {
return getFile("clustering/solr/collection1").getParent();
}
@Test
public void test() throws Exception {
del("*:*");
int numberOfDocs = 0;
for (String[] doc : AbstractClusteringTestCase.DOCUMENTS) {
index(id, Integer.toString(numberOfDocs++), "url", doc[0], "title", doc[1], "snippet", doc[2]);
}
commit();
handle.clear();
// Only really care about the clusters for this test case, so drop the header and response
handle.put("responseHeader", SKIP);
handle.put("response", SKIP);
query(
ClusteringComponent.COMPONENT_NAME, "true",
CommonParams.Q, "*:*",
CommonParams.SORT, id + " desc",
ClusteringParams.USE_SEARCH_RESULTS, "true");
// destroy is not needed because distribTearDown method of base class does it.
//destroyServers();
}
}
| apache-2.0 |
thinkernel/buck | test/com/facebook/buck/java/CleanClasspathIntegrationTest.java | 2859 | /*
* Copyright 2013-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.java;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.ProjectWorkspace.ProcessResult;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
* Integration test to verify that when a {@code java_library} rule is built, the classpath that is
* used to build it does not contain any leftover artifacts from the previous build.
*/
public class CleanClasspathIntegrationTest {
@Rule
public DebuggableTemporaryFolder tmp = new DebuggableTemporaryFolder();
@Test
public void testJavaLibraryRuleDoesNotIncludeItsOwnOldOutputOnTheClasspath() throws IOException {
ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(
this, "classpath_corruption_regression", tmp);
workspace.setUp();
// Build //:example so that content is written to buck-out/gen/.
ProcessResult processResult1 = workspace.runBuckCommand("build", "//:example");
processResult1.assertExitCode(0);
assertTrue(
"example.jar should be written. This should not be on the classpath on the next build.",
workspace.getFile("buck-out/gen/lib__example__output/example.jar").isFile());
// Overwrite the existing BUCK file, redefining the java_library rule to exclude Bar.java from
// its srcs.
File buildFile = workspace.getFile("BUCK");
String newBuildFileContents = Joiner.on('\n').join(
"java_library(",
" name = 'example',",
" srcs = [ 'Foo.java' ], ",
")");
Files.write(newBuildFileContents, buildFile, Charsets.UTF_8);
// Rebuilding //:example should fail even though Bar.class is in
// buck-out/gen/lib__example__output/example.jar.
ProcessResult processResult2 = workspace.runBuckCommand("build", "//:example");
processResult2.assertExitCode("Build should fail because Foo.java depends on Bar.java.", 1);
}
}
| apache-2.0 |
sensui/guava-libraries | guava-tests/test/com/google/common/base/OptionalTest.java | 9755 | /*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Unit test for {@link Optional}.
*
* @author Kurt Alfred Kluever
*/
@GwtCompatible(emulated = true)
public final class OptionalTest extends TestCase {
public void testAbsent() {
Optional<String> optionalName = Optional.absent();
assertFalse(optionalName.isPresent());
}
public void testOf() {
assertEquals("training", Optional.of("training").get());
}
public void testOf_null() {
try {
Optional.of(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testFromNullable() {
Optional<String> optionalName = Optional.fromNullable("bob");
assertEquals("bob", optionalName.get());
}
public void testFromNullable_null() {
// not promised by spec, but easier to test
assertSame(Optional.absent(), Optional.fromNullable(null));
}
public void testIsPresent_no() {
assertFalse(Optional.absent().isPresent());
}
public void testIsPresent_yes() {
assertTrue(Optional.of("training").isPresent());
}
public void testGet_absent() {
Optional<String> optional = Optional.absent();
try {
optional.get();
fail();
} catch (IllegalStateException expected) {
}
}
public void testGet_present() {
assertEquals("training", Optional.of("training").get());
}
public void testOr_T_present() {
assertEquals("a", Optional.of("a").or("default"));
}
public void testOr_T_absent() {
assertEquals("default", Optional.absent().or("default"));
}
public void testOr_supplier_present() {
assertEquals("a", Optional.of("a").or(Suppliers.ofInstance("fallback")));
}
public void testOr_supplier_absent() {
assertEquals("fallback", Optional.absent().or(Suppliers.ofInstance("fallback")));
}
public void testOr_nullSupplier_absent() {
Supplier<Object> nullSupplier = Suppliers.ofInstance(null);
Optional<Object> absentOptional = Optional.absent();
try {
absentOptional.or(nullSupplier);
fail();
} catch (NullPointerException expected) {
}
}
public void testOr_nullSupplier_present() {
Supplier<String> nullSupplier = Suppliers.ofInstance(null);
assertEquals("a", Optional.of("a").or(nullSupplier));
}
public void testOr_Optional_present() {
assertEquals(Optional.of("a"), Optional.of("a").or(Optional.of("fallback")));
}
public void testOr_Optional_absent() {
assertEquals(Optional.of("fallback"), Optional.absent().or(Optional.of("fallback")));
}
public void testOrNull_present() {
assertEquals("a", Optional.of("a").orNull());
}
public void testOrNull_absent() {
assertNull(Optional.absent().orNull());
}
public void testAsSet_present() {
Set<String> expected = Collections.singleton("a");
assertEquals(expected, Optional.of("a").asSet());
}
public void testAsSet_absent() {
assertTrue("Returned set should be empty", Optional.absent().asSet().isEmpty());
}
public void testAsSet_presentIsImmutable() {
Set<String> presentAsSet = Optional.of("a").asSet();
try {
presentAsSet.add("b");
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void testAsSet_absentIsImmutable() {
Set<Object> absentAsSet = Optional.absent().asSet();
try {
absentAsSet.add("foo");
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void testTransform_absent() {
assertEquals(Optional.absent(), Optional.absent().transform(Functions.identity()));
assertEquals(Optional.absent(), Optional.absent().transform(Functions.toStringFunction()));
}
public void testTransform_presentIdentity() {
assertEquals(Optional.of("a"), Optional.of("a").transform(Functions.identity()));
}
public void testTransform_presentToString() {
assertEquals(Optional.of("42"), Optional.of(42).transform(Functions.toStringFunction()));
}
public void testTransform_present_functionReturnsNull() {
try {
Optional.of("a").transform(
new Function<String, String>() {
@Override public String apply(String input) {
return null;
}
});
fail("Should throw if Function returns null.");
} catch (NullPointerException expected) {
}
}
public void testTransform_abssent_functionReturnsNull() {
assertEquals(Optional.absent(),
Optional.absent().transform(
new Function<Object, Object>() {
@Override public Object apply(Object input) {
return null;
}
}));
}
// TODO(kevinb): use EqualsTester
public void testEqualsAndHashCode_absent() {
assertEquals(Optional.<String>absent(), Optional.<Integer>absent());
assertEquals(Optional.absent().hashCode(), Optional.absent().hashCode());
}
public void testEqualsAndHashCode_present() {
assertEquals(Optional.of("training"), Optional.of("training"));
assertFalse(Optional.of("a").equals(Optional.of("b")));
assertFalse(Optional.of("a").equals(Optional.absent()));
assertEquals(Optional.of("training").hashCode(), Optional.of("training").hashCode());
}
public void testToString_absent() {
assertEquals("Optional.absent()", Optional.absent().toString());
}
public void testToString_present() {
assertEquals("Optional.of(training)", Optional.of("training").toString());
}
public void testPresentInstances_allPresent() {
List<Optional<String>> optionals =
ImmutableList.of(Optional.of("a"), Optional.of("b"), Optional.of("c"));
ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "b", "c");
}
public void testPresentInstances_allAbsent() {
List<Optional<Object>> optionals =
ImmutableList.of(Optional.absent(), Optional.absent());
ASSERT.that(Optional.presentInstances(optionals)).isEmpty();
}
public void testPresentInstances_somePresent() {
List<Optional<String>> optionals =
ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c"));
ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "c");
}
public void testPresentInstances_callingIteratorTwice() {
List<Optional<String>> optionals =
ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c"));
Iterable<String> onlyPresent = Optional.presentInstances(optionals);
ASSERT.that(onlyPresent).iteratesOverSequence("a", "c");
ASSERT.that(onlyPresent).iteratesOverSequence("a", "c");
}
public void testPresentInstances_wildcards() {
List<Optional<? extends Number>> optionals =
ImmutableList.<Optional<? extends Number>>of(Optional.<Double>absent(), Optional.of(2));
Iterable<Number> onlyPresent = Optional.presentInstances(optionals);
ASSERT.that(onlyPresent).iteratesOverSequence(2);
}
private static Optional<Integer> getSomeOptionalInt() {
return Optional.of(1);
}
private static FluentIterable<? extends Number> getSomeNumbers() {
return FluentIterable.from(ImmutableList.<Number>of());
}
/*
* The following tests demonstrate the shortcomings of or() and test that the casting workaround
* mentioned in the method Javadoc does in fact compile.
*/
public void testSampleCodeError1() {
Optional<Integer> optionalInt = getSomeOptionalInt();
// Number value = optionalInt.or(0.5); // error
}
public void testSampleCodeError2() {
FluentIterable<? extends Number> numbers = getSomeNumbers();
Optional<? extends Number> first = numbers.first();
// Number value = first.or(0.5); // error
}
@SuppressWarnings("unchecked") // safe covariant cast
public void testSampleCodeFine1() {
Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
Number value = optionalInt.or(0.5); // fine
}
@SuppressWarnings("unchecked") // safe covariant cast
public void testSampleCodeFine2() {
FluentIterable<? extends Number> numbers = getSomeNumbers();
Optional<Number> first = (Optional) numbers.first();
Number value = first.or(0.5); // fine
}
@GwtIncompatible("SerializableTester")
public void testSerialization() {
SerializableTester.reserializeAndAssert(Optional.absent());
SerializableTester.reserializeAndAssert(Optional.of("foo"));
}
@GwtIncompatible("NullPointerTester")
public void testNullPointers() {
NullPointerTester npTester = new NullPointerTester();
npTester.testAllPublicConstructors(Optional.class);
npTester.testAllPublicStaticMethods(Optional.class);
npTester.testAllPublicInstanceMethods(Optional.absent());
npTester.testAllPublicInstanceMethods(Optional.of("training"));
}
}
| apache-2.0 |
smartan/lucene | src/main/java/org/apache/lucene/util/automaton/Automata.java | 10398 | /*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
package org.apache.lucene.util.automaton;
import java.util.*;
import org.apache.lucene.util.BytesRef;
/**
* Construction of basic automata.
*
* @lucene.experimental
*/
final public class Automata {
private Automata() {}
/**
* Returns a new (deterministic) automaton with the empty language.
*/
public static Automaton makeEmpty() {
Automaton a = new Automaton();
a.finishState();
return a;
}
/**
* Returns a new (deterministic) automaton that accepts only the empty string.
*/
public static Automaton makeEmptyString() {
Automaton a = new Automaton();
a.createState();
a.setAccept(0, true);
return a;
}
/**
* Returns a new (deterministic) automaton that accepts all strings.
*/
public static Automaton makeAnyString() {
Automaton a = new Automaton();
int s = a.createState();
a.setAccept(s, true);
a.addTransition(s, s, Character.MIN_CODE_POINT, Character.MAX_CODE_POINT);
a.finishState();
return a;
}
/**
* Returns a new (deterministic) automaton that accepts any single codepoint.
*/
public static Automaton makeAnyChar() {
return makeCharRange(Character.MIN_CODE_POINT, Character.MAX_CODE_POINT);
}
/** Accept any single character starting from the specified state, returning the new state */
public static int appendAnyChar(Automaton a, int state) {
int newState = a.createState();
a.addTransition(state, newState, Character.MIN_CODE_POINT, Character.MAX_CODE_POINT);
return newState;
}
/**
* Returns a new (deterministic) automaton that accepts a single codepoint of
* the given value.
*/
public static Automaton makeChar(int c) {
return makeCharRange(c, c);
}
/** Appends the specified character to the specified state, returning a new state. */
public static int appendChar(Automaton a, int state, int c) {
int newState = a.createState();
a.addTransition(state, newState, c, c);
return newState;
}
/**
* Returns a new (deterministic) automaton that accepts a single codepoint whose
* value is in the given interval (including both end points).
*/
public static Automaton makeCharRange(int min, int max) {
if (min > max) {
return makeEmpty();
}
Automaton a = new Automaton();
int s1 = a.createState();
int s2 = a.createState();
a.setAccept(s2, true);
a.addTransition(s1, s2, min, max);
a.finishState();
return a;
}
/**
* Constructs sub-automaton corresponding to decimal numbers of length
* x.substring(n).length().
*/
private static int anyOfRightLength(Automaton.Builder builder, String x, int n) {
int s = builder.createState();
if (x.length() == n) {
builder.setAccept(s, true);
} else {
builder.addTransition(s, anyOfRightLength(builder, x, n + 1), '0', '9');
}
return s;
}
/**
* Constructs sub-automaton corresponding to decimal numbers of value at least
* x.substring(n) and length x.substring(n).length().
*/
private static int atLeast(Automaton.Builder builder, String x, int n, Collection<Integer> initials,
boolean zeros) {
int s = builder.createState();
if (x.length() == n) {
builder.setAccept(s, true);
} else {
if (zeros) {
initials.add(s);
}
char c = x.charAt(n);
builder.addTransition(s, atLeast(builder, x, n + 1, initials, zeros && c == '0'), c);
if (c < '9') {
builder.addTransition(s, anyOfRightLength(builder, x, n + 1), (char) (c + 1), '9');
}
}
return s;
}
/**
* Constructs sub-automaton corresponding to decimal numbers of value at most
* x.substring(n) and length x.substring(n).length().
*/
private static int atMost(Automaton.Builder builder, String x, int n) {
int s = builder.createState();
if (x.length() == n) {
builder.setAccept(s, true);
} else {
char c = x.charAt(n);
builder.addTransition(s, atMost(builder, x, (char) n + 1), c);
if (c > '0') {
builder.addTransition(s, anyOfRightLength(builder, x, n + 1), '0', (char) (c - 1));
}
}
return s;
}
/**
* Constructs sub-automaton corresponding to decimal numbers of value between
* x.substring(n) and y.substring(n) and of length x.substring(n).length()
* (which must be equal to y.substring(n).length()).
*/
private static int between(Automaton.Builder builder,
String x, String y, int n,
Collection<Integer> initials, boolean zeros) {
int s = builder.createState();
if (x.length() == n) {
builder.setAccept(s, true);
} else {
if (zeros) {
initials.add(s);
}
char cx = x.charAt(n);
char cy = y.charAt(n);
if (cx == cy) {
builder.addTransition(s, between(builder, x, y, n + 1, initials, zeros && cx == '0'), cx);
} else { // cx<cy
builder.addTransition(s, atLeast(builder, x, n + 1, initials, zeros && cx == '0'), cx);
builder.addTransition(s, atMost(builder, y, n + 1), cy);
if (cx + 1 < cy) {
builder.addTransition(s, anyOfRightLength(builder, x, n+1), (char) (cx + 1), (char) (cy - 1));
}
}
}
return s;
}
/**
* Returns a new automaton that accepts strings representing decimal
* non-negative integers in the given interval.
*
* @param min minimal value of interval
* @param max maximal value of interval (both end points are included in the
* interval)
* @param digits if >0, use fixed number of digits (strings must be prefixed
* by 0's to obtain the right length) - otherwise, the number of
* digits is not fixed (any number of leading 0s is accepted)
* @exception IllegalArgumentException if min>max or if numbers in the
* interval cannot be expressed with the given fixed number of
* digits
*/
public static Automaton makeInterval(int min, int max, int digits)
throws IllegalArgumentException {
String x = Integer.toString(min);
String y = Integer.toString(max);
if (min > max || (digits > 0 && y.length() > digits)) {
throw new IllegalArgumentException();
}
int d;
if (digits > 0) d = digits;
else d = y.length();
StringBuilder bx = new StringBuilder();
for (int i = x.length(); i < d; i++) {
bx.append('0');
}
bx.append(x);
x = bx.toString();
StringBuilder by = new StringBuilder();
for (int i = y.length(); i < d; i++) {
by.append('0');
}
by.append(y);
y = by.toString();
Automaton.Builder builder = new Automaton.Builder();
if (digits <= 0) {
// Reserve the "real" initial state:
builder.createState();
}
Collection<Integer> initials = new ArrayList<>();
between(builder, x, y, 0, initials, digits <= 0);
Automaton a1 = builder.finish();
if (digits <= 0) {
a1.addTransition(0, 0, '0');
for (int p : initials) {
a1.addEpsilon(0, p);
}
a1.finishState();
}
return a1;
}
/**
* Returns a new (deterministic) automaton that accepts the single given
* string.
*/
public static Automaton makeString(String s) {
Automaton a = new Automaton();
int lastState = a.createState();
for (int i = 0, cp = 0; i < s.length(); i += Character.charCount(cp)) {
int state = a.createState();
cp = s.codePointAt(i);
a.addTransition(lastState, state, cp, cp);
lastState = state;
}
a.setAccept(lastState, true);
a.finishState();
assert a.isDeterministic();
assert Operations.hasDeadStates(a) == false;
return a;
}
/**
* Returns a new (deterministic) automaton that accepts the single given
* string from the specified unicode code points.
*/
public static Automaton makeString(int[] word, int offset, int length) {
Automaton a = new Automaton();
a.createState();
int s = 0;
for (int i = offset; i < offset+length; i++) {
int s2 = a.createState();
a.addTransition(s, s2, word[i]);
s = s2;
}
a.setAccept(s, true);
a.finishState();
return a;
}
/**
* Returns a new (deterministic and minimal) automaton that accepts the union
* of the given collection of {@link BytesRef}s representing UTF-8 encoded
* strings.
*
* @param utf8Strings
* The input strings, UTF-8 encoded. The collection must be in sorted
* order.
*
* @return An {@link Automaton} accepting all input strings. The resulting
* automaton is codepoint based (full unicode codepoints on
* transitions).
*/
public static Automaton makeStringUnion(Collection<BytesRef> utf8Strings) {
if (utf8Strings.isEmpty()) {
return makeEmpty();
} else {
return DaciukMihovAutomatonBuilder.build(utf8Strings);
}
}
}
| apache-2.0 |
dhalperi/batfish | projects/question/src/main/java/org/batfish/question/specifiers/SpecifiersReachabilityQuestionPlugin.java | 674 | package org.batfish.question.specifiers;
import com.google.auto.service.AutoService;
import org.batfish.common.Answerer;
import org.batfish.common.plugin.IBatfish;
import org.batfish.common.plugin.Plugin;
import org.batfish.datamodel.questions.Question;
import org.batfish.question.QuestionPlugin;
@AutoService(Plugin.class)
public final class SpecifiersReachabilityQuestionPlugin extends QuestionPlugin {
@Override
protected Answerer createAnswerer(Question question, IBatfish batfish) {
return new SpecifiersReachabilityAnswerer(question, batfish);
}
@Override
protected Question createQuestion() {
return new SpecifiersReachabilityQuestion();
}
}
| apache-2.0 |
shuyouliu/zycloud | config-service/src/main/java/demo/ConfigApplication.java | 395 | package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
| apache-2.0 |
ern/elasticsearch | server/src/test/java/org/elasticsearch/rest/action/search/RestSearchActionTests.java | 2395 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.rest.action.search;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.test.rest.FakeRestRequest;
import org.elasticsearch.test.rest.RestActionTestCase;
import org.junit.Before;
import org.mockito.Mockito;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RestSearchActionTests extends RestActionTestCase {
final List<String> contentTypeHeader = Collections.singletonList(randomCompatibleMediaType(RestApiVersion.V_7));
private RestSearchAction action;
@Before
public void setUpAction() {
action = new RestSearchAction();
controller().registerHandler(action);
verifyingClient.setExecuteVerifier((actionType, request) -> Mockito.mock(SearchResponse.class));
verifyingClient.setExecuteLocallyVerifier((actionType, request) -> Mockito.mock(SearchResponse.class));
}
public void testTypeInPath() {
RestRequest request = new FakeRestRequest.Builder(xContentRegistry())
.withHeaders(Map.of("Content-Type", contentTypeHeader, "Accept", contentTypeHeader))
.withMethod(RestRequest.Method.GET)
.withPath("/some_index/some_type/_search")
.build();
dispatchRequest(request);
assertWarnings(RestSearchAction.TYPES_DEPRECATION_MESSAGE);
}
public void testTypeParameter() {
Map<String, String> params = new HashMap<>();
params.put("type", "some_type");
RestRequest request = new FakeRestRequest.Builder(xContentRegistry())
.withHeaders(Map.of("Content-Type", contentTypeHeader, "Accept", contentTypeHeader))
.withMethod(RestRequest.Method.GET)
.withPath("/some_index/_search")
.withParams(params)
.build();
dispatchRequest(request);
assertWarnings(RestSearchAction.TYPES_DEPRECATION_MESSAGE);
}
}
| apache-2.0 |
android-ia/platform_tools_idea | platform/lang-impl/src/com/intellij/ide/macro/FileNameWithoutExtension.java | 1335 | /*
* Copyright 2000-2009 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.ide.macro;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
public final class FileNameWithoutExtension extends FileNameMacro {
@Override
public String getName() {
return "FileNameWithoutExtension";
}
@Override
public String getDescription() {
return IdeBundle.message("macro.file.name.without.extension");
}
@Override
public String expand(DataContext dataContext) {
VirtualFile file = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
if (file == null) {
return null;
}
return file.getNameWithoutExtension();
}
} | apache-2.0 |
y1011/cas-server | cas-server-core-webflow/src/main/java/org/jasig/cas/web/flow/BasicSubflowExpression.java | 1023 | package org.jasig.cas.web.flow;
import org.springframework.binding.expression.EvaluationException;
import org.springframework.binding.expression.support.AbstractGetValueExpression;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
/**
* Creates a custom subflow expression.
*
* @author Misagh Moayyed
* @since 4.2
*/
public class BasicSubflowExpression extends AbstractGetValueExpression {
private final String subflowId;
private final FlowDefinitionRegistry flowDefinitionRegistry;
/**
* Instantiates a new Basic subflow expression.
*
* @param subflowId the subflow id
*/
BasicSubflowExpression(final String subflowId, final FlowDefinitionRegistry definitionRegistry) {
this.subflowId = subflowId;
this.flowDefinitionRegistry = definitionRegistry;
}
@Override
public Object getValue(final Object context) throws EvaluationException {
return this.flowDefinitionRegistry.getFlowDefinition(this.subflowId);
}
}
| apache-2.0 |
paplorinc/intellij-community | java/java-impl/src/com/intellij/ide/hierarchy/method/OverrideMethodAction.java | 865 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.hierarchy.method;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.Presentation;
public final class OverrideMethodAction extends OverrideImplementMethodAction {
@Override
protected final void update(final Presentation presentation, final int toImplement, final int toOverride) {
if (toOverride > 0) {
presentation.setEnabled(true);
presentation.setVisible(true);
presentation.setText(toOverride == 1 ? IdeBundle.message("action.override.method")
: IdeBundle.message("action.override.methods"));
}
else {
presentation.setEnabled(false);
presentation.setVisible(false);
}
}
}
| apache-2.0 |
EdwardLee03/guava | guava/src/com/google/common/util/concurrent/ExecutionSequencer.java | 6950 | /*
* Copyright (C) 2018 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.ExecutionSequencer.RunningState.CANCELLED;
import static com.google.common.util.concurrent.ExecutionSequencer.RunningState.NOT_RUN;
import static com.google.common.util.concurrent.ExecutionSequencer.RunningState.STARTED;
import static com.google.common.util.concurrent.Futures.immediateCancelledFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import com.google.common.annotations.Beta;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
/**
* Serializes execution of a set of operations. This class guarantees that a submitted callable will
* not be called before previously submitted callables (and any {@code Future}s returned from them)
* have completed.
*
* <p>This class implements a superset of the behavior of {@link
* MoreExecutors#newSequentialExecutor}. If your tasks all run on the same underlying executor and
* don't need to wait for {@code Future}s returned from {@code AsyncCallable}s, use it instead.
*
* @since 26.0
*/
@Beta
public final class ExecutionSequencer {
private ExecutionSequencer() {}
/** Creates a new instance. */
public static ExecutionSequencer create() {
return new ExecutionSequencer();
}
enum RunningState {
NOT_RUN,
CANCELLED,
STARTED,
}
/** This reference acts as a pointer tracking the head of a linked list of ListenableFutures. */
private final AtomicReference<ListenableFuture<Object>> ref =
new AtomicReference<>(immediateFuture(null));
/**
* Enqueues a task to run when the previous task (if any) completes.
*
* <p>Cancellation does not propagate from the output future to a callable that has begun to
* execute, but if the output future is cancelled before {@link Callable#call()} is invoked,
* {@link Callable#call()} will not be invoked.
*/
public <T> ListenableFuture<T> submit(final Callable<T> callable, Executor executor) {
checkNotNull(callable);
return submitAsync(
new AsyncCallable<T>() {
@Override
public ListenableFuture<T> call() throws Exception {
return immediateFuture(callable.call());
}
@Override
public String toString() {
return callable.toString();
}
},
executor);
}
/**
* Enqueues a task to run when the previous task (if any) completes.
*
* <p>Cancellation does not propagate from the output future to the future returned from {@code
* callable} or a callable that has begun to execute, but if the output future is cancelled before
* {@link AsyncCallable#call()} is invoked, {@link AsyncCallable#call()} will not be invoked.
*/
public <T> ListenableFuture<T> submitAsync(
final AsyncCallable<T> callable, final Executor executor) {
checkNotNull(callable);
final AtomicReference<RunningState> runningState = new AtomicReference<>(NOT_RUN);
final AsyncCallable<T> task =
new AsyncCallable<T>() {
@Override
public ListenableFuture<T> call() throws Exception {
if (!runningState.compareAndSet(NOT_RUN, STARTED)) {
return immediateCancelledFuture();
}
return callable.call();
}
@Override
public String toString() {
return callable.toString();
}
};
/*
* Four futures are at play here:
* taskFuture is the future tracking the result of the callable.
* newFuture is a future that completes after this and all prior tasks are done.
* oldFuture is the previous task's newFuture.
* outputFuture is the future we return to the caller, a nonCancellationPropagating taskFuture.
*
* newFuture is guaranteed to only complete once all tasks previously submitted to this instance
* have completed - namely after oldFuture is done, and taskFuture has either completed or been
* cancelled before the callable started execution.
*/
final SettableFuture<Object> newFuture = SettableFuture.create();
final ListenableFuture<?> oldFuture = ref.getAndSet(newFuture);
// Invoke our task once the previous future completes.
final ListenableFuture<T> taskFuture =
Futures.submitAsync(
task,
new Executor() {
@Override
public void execute(Runnable runnable) {
oldFuture.addListener(runnable, executor);
}
});
final ListenableFuture<T> outputFuture = Futures.nonCancellationPropagating(taskFuture);
// newFuture's lifetime is determined by taskFuture, which can't complete before oldFuture
// unless taskFuture is cancelled, in which case it falls back to oldFuture. This ensures that
// if the future we return is cancelled, we don't begin execution of the next task until after
// oldFuture completes.
Runnable listener =
new Runnable() {
@Override
public void run() {
if (taskFuture.isDone()
// If this CAS succeeds, we know that the provided callable will never be invoked,
// so when oldFuture completes it is safe to allow the next submitted task to
// proceed.
|| (outputFuture.isCancelled() && runningState.compareAndSet(NOT_RUN, CANCELLED))) {
// Since the value of oldFuture can only ever be immediateFuture(null) or setFuture of
// a future that eventually came from immediateFuture(null), this doesn't leak
// throwables or completion values.
newFuture.setFuture(oldFuture);
}
}
};
// Adding the listener to both futures guarantees that newFuture will aways be set. Adding to
// taskFuture guarantees completion if the callable is invoked, and adding to outputFuture
// propagates cancellation if the callable has not yet been invoked.
outputFuture.addListener(listener, directExecutor());
taskFuture.addListener(listener, directExecutor());
return outputFuture;
}
}
| apache-2.0 |
tbrooks8/netty | codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java | 28305 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* 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.netty.handler.codec.http2;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.AsciiString;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ImmediateEventExecutor;
import junit.framework.AssertionFailedError;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_LIST_SIZE;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_TABLE_SIZE;
import static io.netty.util.ReferenceCountUtil.release;
import static java.lang.Math.min;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyShort;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
/**
* Utilities for the integration tests.
*/
public final class Http2TestUtil {
/**
* Interface that allows for running a operation that throws a {@link Http2Exception}.
*/
interface Http2Runnable {
void run() throws Http2Exception;
}
/**
* Runs the given operation within the event loop thread of the given {@link Channel}.
*/
static void runInChannel(Channel channel, final Http2Runnable runnable) {
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
runnable.run();
} catch (Http2Exception e) {
throw new RuntimeException(e);
}
}
});
}
/**
* Returns a byte array filled with random data.
*/
public static byte[] randomBytes() {
return randomBytes(100);
}
/**
* Returns a byte array filled with random data.
*/
public static byte[] randomBytes(int size) {
byte[] data = new byte[size];
new Random().nextBytes(data);
return data;
}
/**
* Returns an {@link AsciiString} that wraps a randomly-filled byte array.
*/
public static AsciiString randomString() {
return new AsciiString(randomBytes());
}
public static CharSequence of(String s) {
return s;
}
public static HpackEncoder newTestEncoder() {
try {
return newTestEncoder(true, MAX_HEADER_LIST_SIZE, MAX_HEADER_TABLE_SIZE);
} catch (Http2Exception e) {
throw new Error("max size not allowed?", e);
}
}
public static HpackEncoder newTestEncoder(boolean ignoreMaxHeaderListSize,
long maxHeaderListSize, long maxHeaderTableSize) throws Http2Exception {
HpackEncoder hpackEncoder = new HpackEncoder();
ByteBuf buf = Unpooled.buffer();
try {
hpackEncoder.setMaxHeaderTableSize(buf, maxHeaderTableSize);
hpackEncoder.setMaxHeaderListSize(maxHeaderListSize);
} finally {
buf.release();
}
return hpackEncoder;
}
public static HpackDecoder newTestDecoder() {
try {
return newTestDecoder(MAX_HEADER_LIST_SIZE, MAX_HEADER_TABLE_SIZE);
} catch (Http2Exception e) {
throw new Error("max size not allowed?", e);
}
}
public static HpackDecoder newTestDecoder(long maxHeaderListSize, long maxHeaderTableSize) throws Http2Exception {
HpackDecoder hpackDecoder = new HpackDecoder(maxHeaderListSize, 32);
hpackDecoder.setMaxHeaderTableSize(maxHeaderTableSize);
return hpackDecoder;
}
private Http2TestUtil() {
}
static class FrameAdapter extends ByteToMessageDecoder {
private final Http2Connection connection;
private final Http2FrameListener listener;
private final DefaultHttp2FrameReader reader;
private final CountDownLatch latch;
FrameAdapter(Http2FrameListener listener, CountDownLatch latch) {
this(null, listener, latch);
}
FrameAdapter(Http2Connection connection, Http2FrameListener listener, CountDownLatch latch) {
this(connection, new DefaultHttp2FrameReader(false), listener, latch);
}
FrameAdapter(Http2Connection connection, DefaultHttp2FrameReader reader, Http2FrameListener listener,
CountDownLatch latch) {
this.connection = connection;
this.listener = listener;
this.reader = reader;
this.latch = latch;
}
private Http2Stream getOrCreateStream(int streamId, boolean halfClosed) throws Http2Exception {
return getOrCreateStream(connection, streamId, halfClosed);
}
public static Http2Stream getOrCreateStream(Http2Connection connection, int streamId, boolean halfClosed)
throws Http2Exception {
if (connection != null) {
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
if (connection.isServer() && streamId % 2 == 0 || !connection.isServer() && streamId % 2 != 0) {
stream = connection.local().createStream(streamId, halfClosed);
} else {
stream = connection.remote().createStream(streamId, halfClosed);
}
}
return stream;
}
return null;
}
private void closeStream(Http2Stream stream) {
closeStream(stream, false);
}
protected void closeStream(Http2Stream stream, boolean dataRead) {
if (stream != null) {
stream.close();
}
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
reader.readFrame(ctx, in, new Http2FrameListener() {
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
boolean endOfStream) throws Http2Exception {
Http2Stream stream = getOrCreateStream(streamId, endOfStream);
int processed = listener.onDataRead(ctx, streamId, data, padding, endOfStream);
if (endOfStream) {
closeStream(stream, true);
}
latch.countDown();
return processed;
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream) throws Http2Exception {
Http2Stream stream = getOrCreateStream(streamId, endStream);
listener.onHeadersRead(ctx, streamId, headers, padding, endStream);
if (endStream) {
closeStream(stream);
}
latch.countDown();
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
throws Http2Exception {
Http2Stream stream = getOrCreateStream(streamId, endStream);
listener.onHeadersRead(ctx, streamId, headers, streamDependency, weight, exclusive, padding,
endStream);
if (endStream) {
closeStream(stream);
}
latch.countDown();
}
@Override
public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,
boolean exclusive) throws Http2Exception {
listener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);
latch.countDown();
}
@Override
public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
throws Http2Exception {
Http2Stream stream = getOrCreateStream(streamId, false);
listener.onRstStreamRead(ctx, streamId, errorCode);
closeStream(stream);
latch.countDown();
}
@Override
public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {
listener.onSettingsAckRead(ctx);
latch.countDown();
}
@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {
listener.onSettingsRead(ctx, settings);
latch.countDown();
}
@Override
public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
listener.onPingRead(ctx, data);
latch.countDown();
}
@Override
public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
listener.onPingAckRead(ctx, data);
latch.countDown();
}
@Override
public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
Http2Headers headers, int padding) throws Http2Exception {
getOrCreateStream(promisedStreamId, false);
listener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);
latch.countDown();
}
@Override
public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
throws Http2Exception {
listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);
latch.countDown();
}
@Override
public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)
throws Http2Exception {
getOrCreateStream(streamId, false);
listener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);
latch.countDown();
}
@Override
public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
ByteBuf payload) throws Http2Exception {
listener.onUnknownFrame(ctx, frameType, streamId, flags, payload);
latch.countDown();
}
});
}
}
/**
* A decorator around a {@link Http2FrameListener} that counts down the latch so that we can await the completion of
* the request.
*/
static class FrameCountDown implements Http2FrameListener {
private final Http2FrameListener listener;
private final CountDownLatch messageLatch;
private final CountDownLatch settingsAckLatch;
private final CountDownLatch dataLatch;
private final CountDownLatch trailersLatch;
private final CountDownLatch goAwayLatch;
FrameCountDown(Http2FrameListener listener, CountDownLatch settingsAckLatch, CountDownLatch messageLatch) {
this(listener, settingsAckLatch, messageLatch, null, null);
}
FrameCountDown(Http2FrameListener listener, CountDownLatch settingsAckLatch, CountDownLatch messageLatch,
CountDownLatch dataLatch, CountDownLatch trailersLatch) {
this(listener, settingsAckLatch, messageLatch, dataLatch, trailersLatch, messageLatch);
}
FrameCountDown(Http2FrameListener listener, CountDownLatch settingsAckLatch, CountDownLatch messageLatch,
CountDownLatch dataLatch, CountDownLatch trailersLatch, CountDownLatch goAwayLatch) {
this.listener = listener;
this.messageLatch = messageLatch;
this.settingsAckLatch = settingsAckLatch;
this.dataLatch = dataLatch;
this.trailersLatch = trailersLatch;
this.goAwayLatch = goAwayLatch;
}
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
throws Http2Exception {
int numBytes = data.readableBytes();
int processed = listener.onDataRead(ctx, streamId, data, padding, endOfStream);
messageLatch.countDown();
if (dataLatch != null) {
for (int i = 0; i < numBytes; ++i) {
dataLatch.countDown();
}
}
return processed;
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream) throws Http2Exception {
listener.onHeadersRead(ctx, streamId, headers, padding, endStream);
messageLatch.countDown();
if (trailersLatch != null && endStream) {
trailersLatch.countDown();
}
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
listener.onHeadersRead(ctx, streamId, headers, streamDependency, weight, exclusive, padding, endStream);
messageLatch.countDown();
if (trailersLatch != null && endStream) {
trailersLatch.countDown();
}
}
@Override
public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,
boolean exclusive) throws Http2Exception {
listener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);
messageLatch.countDown();
}
@Override
public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {
listener.onRstStreamRead(ctx, streamId, errorCode);
messageLatch.countDown();
}
@Override
public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {
listener.onSettingsAckRead(ctx);
settingsAckLatch.countDown();
}
@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {
listener.onSettingsRead(ctx, settings);
messageLatch.countDown();
}
@Override
public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
listener.onPingRead(ctx, data);
messageLatch.countDown();
}
@Override
public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
listener.onPingAckRead(ctx, data);
messageLatch.countDown();
}
@Override
public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
Http2Headers headers, int padding) throws Http2Exception {
listener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);
messageLatch.countDown();
}
@Override
public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
throws Http2Exception {
listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);
goAwayLatch.countDown();
}
@Override
public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)
throws Http2Exception {
listener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);
messageLatch.countDown();
}
@Override
public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
ByteBuf payload) throws Http2Exception {
listener.onUnknownFrame(ctx, frameType, streamId, flags, payload);
messageLatch.countDown();
}
}
static ChannelPromise newVoidPromise(final Channel channel) {
return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE) {
@Override
public ChannelPromise addListener(
GenericFutureListener<? extends Future<? super Void>> listener) {
throw new AssertionFailedError();
}
@Override
public ChannelPromise addListeners(
GenericFutureListener<? extends Future<? super Void>>... listeners) {
throw new AssertionFailedError();
}
@Override
public boolean isVoid() {
return true;
}
@Override
public boolean tryFailure(Throwable cause) {
channel().pipeline().fireExceptionCaught(cause);
return true;
}
@Override
public ChannelPromise setFailure(Throwable cause) {
tryFailure(cause);
return this;
}
@Override
public ChannelPromise unvoid() {
ChannelPromise promise =
new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
channel().pipeline().fireExceptionCaught(future.cause());
}
}
});
return promise;
}
};
}
static final class TestStreamByteDistributorStreamState implements StreamByteDistributor.StreamState {
private final Http2Stream stream;
boolean isWriteAllowed;
long pendingBytes;
boolean hasFrame;
TestStreamByteDistributorStreamState(Http2Stream stream, long pendingBytes, boolean hasFrame,
boolean isWriteAllowed) {
this.stream = stream;
this.isWriteAllowed = isWriteAllowed;
this.pendingBytes = pendingBytes;
this.hasFrame = hasFrame;
}
@Override
public Http2Stream stream() {
return stream;
}
@Override
public long pendingBytes() {
return pendingBytes;
}
@Override
public boolean hasFrame() {
return hasFrame;
}
@Override
public int windowSize() {
return isWriteAllowed ? (int) min(pendingBytes, Integer.MAX_VALUE) : -1;
}
}
static Http2FrameWriter mockedFrameWriter() {
Http2FrameWriter.Configuration configuration = new Http2FrameWriter.Configuration() {
private final Http2HeadersEncoder.Configuration headerConfiguration =
new Http2HeadersEncoder.Configuration() {
@Override
public void maxHeaderTableSize(long max) {
// NOOP
}
@Override
public long maxHeaderTableSize() {
return 0;
}
@Override
public void maxHeaderListSize(long max) {
// NOOP
}
@Override
public long maxHeaderListSize() {
return 0;
}
};
private final Http2FrameSizePolicy policy = new Http2FrameSizePolicy() {
@Override
public void maxFrameSize(int max) {
// NOOP
}
@Override
public int maxFrameSize() {
return 0;
}
};
@Override
public Http2HeadersEncoder.Configuration headersConfiguration() {
return headerConfiguration;
}
@Override
public Http2FrameSizePolicy frameSizePolicy() {
return policy;
}
};
final ConcurrentLinkedQueue<ByteBuf> buffers = new ConcurrentLinkedQueue<ByteBuf>();
Http2FrameWriter frameWriter = Mockito.mock(Http2FrameWriter.class);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) {
for (;;) {
ByteBuf buf = buffers.poll();
if (buf == null) {
break;
}
buf.release();
}
return null;
}
}).when(frameWriter).close();
when(frameWriter.configuration()).thenReturn(configuration);
when(frameWriter.writeSettings(any(ChannelHandlerContext.class), any(Http2Settings.class),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(2)).setSuccess();
}
});
when(frameWriter.writeSettingsAck(any(ChannelHandlerContext.class), any(ChannelPromise.class)))
.thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(1)).setSuccess();
}
});
when(frameWriter.writeGoAway(any(ChannelHandlerContext.class), anyInt(),
anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
buffers.offer((ByteBuf) invocationOnMock.getArgument(3));
return ((ChannelPromise) invocationOnMock.getArgument(4)).setSuccess();
}
});
when(frameWriter.writeHeaders(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(),
anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
when(frameWriter.writeHeaders(any(ChannelHandlerContext.class), anyInt(),
any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(8)).setSuccess();
}
});
when(frameWriter.writeData(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(),
anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
buffers.offer((ByteBuf) invocationOnMock.getArgument(2));
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
when(frameWriter.writeRstStream(any(ChannelHandlerContext.class), anyInt(),
anyLong(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess();
}
});
when(frameWriter.writeWindowUpdate(any(ChannelHandlerContext.class), anyInt(), anyInt(),
any(ChannelPromise.class))).then(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess();
}
});
when(frameWriter.writePushPromise(any(ChannelHandlerContext.class), anyInt(), anyInt(), any(Http2Headers.class),
anyInt(), anyChannelPromise())).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
when(frameWriter.writeFrame(any(ChannelHandlerContext.class), anyByte(), anyInt(), any(Http2Flags.class),
any(ByteBuf.class), anyChannelPromise())).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
buffers.offer((ByteBuf) invocationOnMock.getArgument(4));
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
return frameWriter;
}
static ChannelPromise anyChannelPromise() {
return any(ChannelPromise.class);
}
static Http2Settings anyHttp2Settings() {
return any(Http2Settings.class);
}
static ByteBuf bb(String s) {
return ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, s);
}
static void assertEqualsAndRelease(Http2Frame expected, Http2Frame actual) {
try {
assertEquals(expected, actual);
} finally {
release(expected);
release(actual);
// Will return -1 when not implements ReferenceCounted.
assertTrue(ReferenceCountUtil.refCnt(expected) <= 0);
assertTrue(ReferenceCountUtil.refCnt(actual) <= 0);
}
}
}
| apache-2.0 |
LimelightNetworks/ISMT-Patcher | src/net/sourceforge/jaad/mp4/boxes/impl/sampleentries/codec/QCELPSpecificBox.java | 1240 | /*
* Copyright (C) 2011 in-somnia
*
* This file is part of JAAD.
*
* JAAD is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* JAAD is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.jaad.mp4.boxes.impl.sampleentries.codec;
import java.io.IOException;
import net.sourceforge.jaad.mp4.MP4InputStream;
public class QCELPSpecificBox extends CodecSpecificBox {
private int framesPerSample;
public QCELPSpecificBox() {
super("QCELP Specific Box");
}
@Override
public void decode(MP4InputStream in) throws IOException {
decodeCommon(in);
framesPerSample = in.read();
}
public int getFramesPerSample() {
return framesPerSample;
}
}
| bsd-2-clause |
drmacro/basex | basex-core/src/main/java/org/basex/gui/layout/BaseXHeader.java | 619 | package org.basex.gui.layout;
import static org.basex.gui.GUIConstants.*;
import javax.swing.border.*;
/**
* Header label.
*
* @author BaseX Team 2005-16, BSD License
* @author Christian Gruen
*/
public final class BaseXHeader extends BaseXLabel {
/**
* Constructor.
* @param string string
*/
public BaseXHeader(final String string) {
super(string, true, false);
setForeground(dgray);
}
/**
* Called when GUI design has changed.
*/
public void refreshLayout() {
setBorder(new EmptyBorder(-4, 0, -LABEL.getFontMetrics(lfont).getLeading() / 2, 2));
setFont(lfont);
}
}
| bsd-3-clause |
wjkohnen/antlr4 | runtime/Java/src/org/antlr/v4/runtime/atn/ArrayPredictionContext.java | 2765 | /*
* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.atn;
import java.util.Arrays;
public class ArrayPredictionContext extends PredictionContext {
/** Parent can be null only if full ctx mode and we make an array
* from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and
* returnState == {@link #EMPTY_RETURN_STATE}.
*/
public final PredictionContext[] parents;
/** Sorted for merge, no duplicates; if present,
* {@link #EMPTY_RETURN_STATE} is always last.
*/
public final int[] returnStates;
public ArrayPredictionContext(SingletonPredictionContext a) {
this(new PredictionContext[] {a.parent}, new int[] {a.returnState});
}
public ArrayPredictionContext(PredictionContext[] parents, int[] returnStates) {
super(calculateHashCode(parents, returnStates));
assert parents!=null && parents.length>0;
assert returnStates!=null && returnStates.length>0;
// System.err.println("CREATE ARRAY: "+Arrays.toString(parents)+", "+Arrays.toString(returnStates));
this.parents = parents;
this.returnStates = returnStates;
}
@Override
public boolean isEmpty() {
// since EMPTY_RETURN_STATE can only appear in the last position, we
// don't need to verify that size==1
return returnStates[0]==EMPTY_RETURN_STATE;
}
@Override
public int size() {
return returnStates.length;
}
@Override
public PredictionContext getParent(int index) {
return parents[index];
}
@Override
public int getReturnState(int index) {
return returnStates[index];
}
// @Override
// public int findReturnState(int returnState) {
// return Arrays.binarySearch(returnStates, returnState);
// }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
else if ( !(o instanceof ArrayPredictionContext) ) {
return false;
}
if ( this.hashCode() != o.hashCode() ) {
return false; // can't be same if hash is different
}
ArrayPredictionContext a = (ArrayPredictionContext)o;
return Arrays.equals(returnStates, a.returnStates) &&
Arrays.equals(parents, a.parents);
}
@Override
public String toString() {
if ( isEmpty() ) return "[]";
StringBuilder buf = new StringBuilder();
buf.append("[");
for (int i=0; i<returnStates.length; i++) {
if ( i>0 ) buf.append(", ");
if ( returnStates[i]==EMPTY_RETURN_STATE ) {
buf.append("$");
continue;
}
buf.append(returnStates[i]);
if ( parents[i]!=null ) {
buf.append(' ');
buf.append(parents[i].toString());
}
else {
buf.append("null");
}
}
buf.append("]");
return buf.toString();
}
}
| bsd-3-clause |
ryanniehaus/lucida | lucida/learn/ParserDaemon.java | 2648 | // Thrift java libraries
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
// Thrift client-side code
import org.apache.thrift.protocol.TBinaryProtocol;
// Generated code
import parserstubs.ParserService;
/**
* Starts the parser server and listens for requests.
*/
public class ParserDaemon {
/**
* An object whose methods are implementations of the parser thrift
* interface.
*/
public static ParserServiceHandler handler;
/**
* An object responsible for communication between the handler
* and the server. It decodes serialized data using the input protocol,
* delegates processing to the handler, and writes the response
* using the output protocol.
*/
public static ParserService.Processor<ParserServiceHandler> processor;
/**
* Entry point for parser.
* @param args the argument list. Provide port number.
*/
public static void main(String [] args) {
try {
// collect the port number
int tmp_port = 8080;
if (args.length == 1) {
tmp_port = Integer.parseInt(args[0].trim());
} else {
System.out.println("Using default port for parser: "
+ tmp_port);
}
// create a new thread to handle the requests
final int port = tmp_port;
handler = new ParserServiceHandler();
processor = new ParserService.Processor<ParserServiceHandler>(handler);
Runnable simple = new Runnable() {
public void run() {
simple(processor, port);
}
};
new Thread(simple).start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Listens for requests and forwards request information
* to handler.
* @param processor the thrift processor that will handle serialization
* and communication with the handler once a request is received.
* @param port the port at which the parser service will listen.
*/
public static void simple(ParserService.Processor<ParserServiceHandler> processor, final int port) {
try {
// create a multi-threaded server: TNonblockingServer
TNonblockingServerTransport transport = new TNonblockingServerSocket(port);
TNonblockingServer.Args args = new TNonblockingServer.Args(transport)
.processor(processor)
.protocolFactory(new TBinaryProtocol.Factory())
.transportFactory(new TFramedTransport.Factory());
TNonblockingServer server = new TNonblockingServer(args);
System.out.println("Starting parser at port " + port + "...");
server.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| bsd-3-clause |
yugangw-msft/autorest | src/generator/AutoRest.Java.Azure.Fluent.Tests/src/test/java/fixtures/head/HttpSuccessTests.java | 761 | package fixtures.head;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import fixtures.head.implementation.AutoRestHeadTestServiceImpl;
public class HttpSuccessTests {
private static AutoRestHeadTestServiceImpl client;
@BeforeClass
public static void setup() {
client = new AutoRestHeadTestServiceImpl("http://localhost.:3000", null);
}
@Test
public void head200() throws Exception {
Assert.assertTrue(client.httpSuccess().head200());
}
@Test
public void head204() throws Exception {
Assert.assertTrue(client.httpSuccess().head204());
}
@Test
public void head404() throws Exception {
Assert.assertFalse(client.httpSuccess().head404());
}
}
| mit |
gaborkolozsy/XChange | xchange-empoex/src/test/java/org/knowm/xchange/empoex/service/marketdata/TickerFetchIntegration.java | 892 | package org.knowm.xchange.empoex.service.marketdata;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Test;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.empoex.EmpoExExchange;
import org.knowm.xchange.service.marketdata.MarketDataService;
/**
* @author timmolter
*/
public class TickerFetchIntegration {
@Test
public void tickerFetchTest() throws Exception {
Exchange exchange = ExchangeFactory.INSTANCE.createExchange(EmpoExExchange.class.getName());
MarketDataService marketDataService = exchange.getMarketDataService();
Ticker ticker = marketDataService.getTicker(new CurrencyPair("DOGE", "BTC"));
System.out.println(ticker.toString());
assertThat(ticker).isNotNull();
}
}
| mit |
matheusmmcs/SPMF-UseSkill | src/ca/pfv/spmf/algorithms/sequentialpatterns/fournier2008_seqdim/kmeans_for_fournier08/AlgoKMeansWithSupport.java | 7520 | package ca.pfv.spmf.algorithms.sequentialpatterns.fournier2008_seqdim.kmeans_for_fournier08;
/* This file is copyright (c) 2008-2013 Philippe Fournier-Viger
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF 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.
*
* SPMF 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
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ca.pfv.spmf.algorithms.sequentialpatterns.fournier2008_seqdim.AlgoFournierViger08;
import ca.pfv.spmf.algorithms.sequentialpatterns.fournier2008_seqdim.ItemValued;
/**
* This algorithm is a modified K-Means algorithm to be used with the Fournier-Viger-2008 algorithm, which.
* adds the constraint of a minimum number of items per clusters (minimum support).
* <br/><br/>
* This implementation should only be used for the Fournier-Viger 2008 as it is specially designed
* for it (e.g. it clusters valued items and it keep the
* min max and avg values of each clusters). For other purposes, one should use the general KMeans implementation
* in the package "clustering". This latter implementation is more general (uses vector of doubles instead
* of items) and is more optimized.
* <br/><br/>
* This algorithm works as follows <br/>
* We specify a maximum K.<br/>
* The algorithmm executes K-Means from K=1 to K=Kmax and try to find
* the largest number of clusters such that each cluster has a size that is larger
* than the minimum support (as an integer).<br/>
* The algorithm returns this set of clusters.<br/>
* The algorithm stops at k=k+1 or when the number of clusters does not increase for
* two successives K.
*
* @see AlgoFournierViger08
* @see ItemValued
* @author Philippe Fournier-Viger
*/
public class AlgoKMeansWithSupport{
// the maximum number of clusters to be found
//
private int maxK;
// the minimum support threshold as an integer value. It indicates
// the minimum size that a cluster should have.
private int minsuppRelative;
// the number of times that K-Means should be executed for each value
// of k
private final int numberOfTriesForEachK;
// an implementation of the regular k-means.
private final AlgoKMeans_forFournier08 algoKMeans;
/**
* Constructor
* @param maxK the maximum number of cluster to be found
* @param relativeMinsup a relative minimum support threshold
* @param algoKMeans an implementation of the regular K-Means
* @param numberOfTriesForEachK the number of times that K-Means should
* be executed for each value of k.
*/
public AlgoKMeansWithSupport(int maxK, int relativeMinsup, AlgoKMeans_forFournier08 algoKMeans, int numberOfTriesForEachK){
// save the parameters
this.maxK = maxK;
this.minsuppRelative = relativeMinsup;
this.algoKMeans = algoKMeans;
this.numberOfTriesForEachK = numberOfTriesForEachK;
// if the minimum support is 0, we set it to 1
// so that no empty cluster is found.
if(minsuppRelative <= 0){
minsuppRelative = 1;
}
}
/**
* Constructor
* @param maxK the maximum number of cluster to be found
* @param minsup minimum support threshold as a percentage (double)
* @param algoKMeans an implementation of the regular K-Means
* @param numberOfTriesForEachK the number of times that K-Means should
* be executed for each value of k.
*/
public AlgoKMeansWithSupport(int maxK, double minsup, int transactioncount, AlgoKMeans_forFournier08 algoKMeans, int numberOfTriesForEachK){
this.maxK = maxK;
// convert to a relative minimum support by multiplying
// by the database size.
this.minsuppRelative = (int) Math.ceil(minsup * transactioncount);
this.algoKMeans = algoKMeans;
this.numberOfTriesForEachK = numberOfTriesForEachK;
// if the minimum support is 0, we set it to 1
// so that no empty cluster is found.
if(minsuppRelative <= 0){
minsuppRelative = 1;
}
}
/**
* Run the algorithm
* @param items the values to be clustered
* @return a list of clusters found.
*/
public List<Cluster> runAlgorithm(List<ItemValued> items){
// if the maximum number of clusters is larger than
// the number of items, then set it to the number of items.
if(maxK > items.size()){
maxK = items.size();
}
// The number of clusters that will be found
int nbClustersFound = -1;
// The list of clusters that will be found
List<Cluster> clustersFound = null;
// For each K.
for(int k=1; k <= maxK; k++){
// we try numberOfTriesForEachK times.
for(int j=0; j<numberOfTriesForEachK; j++){
// We execute K-Means with k
algoKMeans.setK(k);
// K-means return a set of clusters
List<Cluster> clusters = algoKMeans.runAlgorithm(items);
// We count the numbers of clusters with size >= minsupp
// and we remove clusters with size < minsupp
int frequentClustersCount = 0;
// for each cluster
for(int i=0; i< clusters.size();){
// if the cluster has a size >= minsup
if(isAFrequentCluster(clusters.get(i))){
// increase the count of frequent clusters
frequentClustersCount++;
i++; // go to next cluster
}else{
// if size < minsup, we delete the cluster
clusters.remove(i);
}
}
// If the number of clusters found is higher than
// the number of clusters found by other execution
// of k-means, we keep the clusters from this execution.
if(frequentClustersCount > nbClustersFound){
nbClustersFound = frequentClustersCount;
clustersFound = clusters;
}
}
}
// We associate the items to their respective clusters because we called
// K-Means many times with different K and it is possible
// that items are not associated to the last set of clusters that was found.
for(ItemValued item : items){
// for each cluster
for(Cluster cluster : clustersFound){
// if the current item is contained in this
// cluster
for(ItemValued item2 : cluster.getItems()){
if(item == item2){
// we re-associate the item to the cluster.
item.setCluster(cluster);
}
}
}
}
// We return the list of clusters found.
return clustersFound;
}
/**
* Check if the support of a cluster is higher than minsupp.
* To do this, we should not count two times the items that have
* the same SequenceID.
* @param cluster
* @return
*/
private boolean isAFrequentCluster(Cluster cluster) {
// Create a set to store the sequence IDs where
// each item appears
Set<Integer> sequenceIds = new HashSet<Integer>();
// for ea item
for(ItemValued item : cluster.getItems()){
// store the sequence IDs in the set
sequenceIds.add(item.getSequenceID());
}
// if the set of sequence IDs is >= minsup
return sequenceIds.size() >= minsuppRelative;
}
}
| mit |
brunyuriy/quick-fix-scout | org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/internal/corext/refactoring/scripting/RenameCompilationUnitRefactoringContribution.java | 2450 | /*******************************************************************************
* Copyright (c) 2005, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.corext.refactoring.scripting;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
import org.eclipse.jdt.core.refactoring.IJavaRefactorings;
import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor;
import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory;
import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
/**
* Refactoring contribution for the rename compilation unit refactoring.
*
* @since 3.2
*/
public final class RenameCompilationUnitRefactoringContribution extends JavaUIRefactoringContribution {
/**
* {@inheritDoc}
*/
@Override
public Refactoring createRefactoring(JavaRefactoringDescriptor descriptor, RefactoringStatus status) throws CoreException {
JavaRefactoringArguments arguments= new JavaRefactoringArguments(descriptor.getProject(), retrieveArgumentMap(descriptor));
RenameCompilationUnitProcessor processor= new RenameCompilationUnitProcessor(arguments, status);
return new RenameRefactoring(processor);
}
@Override
public RefactoringDescriptor createDescriptor() {
return RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_COMPILATION_UNIT);
}
@Override
public RefactoringDescriptor createDescriptor(String id, String project, String description, String comment, Map arguments, int flags) {
return RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(id, project, description, comment, arguments, flags);
}
}
| mit |
dusensong/SwipeMenuListView | library/src/main/java/com/baoyz/swipemenulistview/SwipeMenuListView.java | 12876 | package com.baoyz.swipemenulistview;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* @author baoyz
* @date 2014-8-18
*/
public class SwipeMenuListView extends ListView {
private static final int TOUCH_STATE_NONE = 0;
private static final int TOUCH_STATE_X = 1;
private static final int TOUCH_STATE_Y = 2;
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
private int mDirection = 1;//swipe from right to left by default
private int MAX_Y = 5;
private int MAX_X = 3;
private float mDownX;
private float mDownY;
private int mTouchState;
private int mTouchPosition;
private SwipeMenuLayout mTouchView;
private OnSwipeListener mOnSwipeListener;
private SwipeMenuCreator mMenuCreator;
private OnMenuItemClickListener mOnMenuItemClickListener;
private OnMenuStateChangeListener mOnMenuStateChangeListener;
private Interpolator mCloseInterpolator;
private Interpolator mOpenInterpolator;
public SwipeMenuListView(Context context) {
super(context);
init();
}
public SwipeMenuListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public SwipeMenuListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
MAX_X = dp2px(MAX_X);
MAX_Y = dp2px(MAX_Y);
mTouchState = TOUCH_STATE_NONE;
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(new SwipeMenuAdapter(getContext(), adapter) {
@Override
public void createMenu(SwipeMenu menu) {
if (mMenuCreator != null) {
mMenuCreator.create(menu);
}
}
@Override
public void onItemClick(SwipeMenuView view, SwipeMenu menu,
int index) {
boolean flag = false;
if (mOnMenuItemClickListener != null) {
flag = mOnMenuItemClickListener.onMenuItemClick(
view.getPosition(), menu, index);
}
if (mTouchView != null && !flag) {
mTouchView.smoothCloseMenu();
}
}
});
}
public void setCloseInterpolator(Interpolator interpolator) {
mCloseInterpolator = interpolator;
}
public void setOpenInterpolator(Interpolator interpolator) {
mOpenInterpolator = interpolator;
}
public Interpolator getOpenInterpolator() {
return mOpenInterpolator;
}
public Interpolator getCloseInterpolator() {
return mCloseInterpolator;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//在拦截处处理,在滑动设置了点击事件的地方也能swip,点击时又不能影响原来的点击事件
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
boolean handled = super.onInterceptTouchEvent(ev);
mTouchState = TOUCH_STATE_NONE;
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
View view = getChildAt(mTouchPosition - getFirstVisiblePosition());
//只在空的时候赋值 以免每次触摸都赋值,会有多个open状态
if (view instanceof SwipeMenuLayout) {
//如果有打开了 就拦截.
if (mTouchView != null && mTouchView.isOpen() && !inRangeOfView(mTouchView.getMenuView(), ev)) {
return true;
}
mTouchView = (SwipeMenuLayout) view;
mTouchView.setSwipeDirection(mDirection);
}
//如果摸在另外个view
if (mTouchView != null && mTouchView.isOpen() && view != mTouchView) {
handled = true;
}
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
return handled;
case MotionEvent.ACTION_MOVE:
float dy = Math.abs((ev.getY() - mDownY));
float dx = Math.abs((ev.getX() - mDownX));
if (Math.abs(dy) > MAX_Y || Math.abs(dx) > MAX_X) {
//每次拦截的down都把触摸状态设置成了TOUCH_STATE_NONE 只有返回true才会走onTouchEvent 所以写在这里就够了
if (mTouchState == TOUCH_STATE_NONE) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_STATE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_STATE_X;
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeStart(mTouchPosition);
}
}
}
return true;
}
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() != MotionEvent.ACTION_DOWN && mTouchView == null)
return super.onTouchEvent(ev);
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
int oldPos = mTouchPosition;
mDownX = ev.getX();
mDownY = ev.getY();
mTouchState = TOUCH_STATE_NONE;
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
if (mTouchPosition == oldPos && mTouchView != null
&& mTouchView.isOpen()) {
mTouchState = TOUCH_STATE_X;
mTouchView.onSwipe(ev);
return true;
}
View view = getChildAt(mTouchPosition - getFirstVisiblePosition());
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
mTouchView = null;
// return super.onTouchEvent(ev);
// try to cancel the touch event
MotionEvent cancelEvent = MotionEvent.obtain(ev);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
onTouchEvent(cancelEvent);
if (mOnMenuStateChangeListener != null) {
mOnMenuStateChangeListener.onMenuClose(oldPos);
}
return true;
}
if (view instanceof SwipeMenuLayout) {
mTouchView = (SwipeMenuLayout) view;
mTouchView.setSwipeDirection(mDirection);
}
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
break;
case MotionEvent.ACTION_MOVE:
//有些可能有header,要减去header再判断
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY()) - getHeaderViewsCount();
//如果滑动了一下没完全展现,就收回去,这时候mTouchView已经赋值,再滑动另外一个不可以swip的view
//会导致mTouchView swip 。 所以要用位置判断是否滑动的是一个view
if (!mTouchView.getSwipEnable() || mTouchPosition != mTouchView.getPosition()) {
break;
}
float dy = Math.abs((ev.getY() - mDownY));
float dx = Math.abs((ev.getX() - mDownX));
if (mTouchState == TOUCH_STATE_X) {
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
getSelector().setState(new int[]{0});
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
} else if (mTouchState == TOUCH_STATE_NONE) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_STATE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_STATE_X;
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeStart(mTouchPosition);
}
}
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_X) {
if (mTouchView != null) {
boolean isBeforeOpen = mTouchView.isOpen();
mTouchView.onSwipe(ev);
boolean isAfterOpen = mTouchView.isOpen();
if (isBeforeOpen != isAfterOpen && mOnMenuStateChangeListener != null) {
if (isAfterOpen) {
mOnMenuStateChangeListener.onMenuOpen(mTouchPosition);
} else {
mOnMenuStateChangeListener.onMenuClose(mTouchPosition);
}
}
if (!isAfterOpen) {
mTouchPosition = -1;
mTouchView = null;
}
}
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeEnd(mTouchPosition);
}
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
}
break;
}
return super.onTouchEvent(ev);
}
public void smoothOpenMenu(int position) {
if (position >= getFirstVisiblePosition()
&& position <= getLastVisiblePosition()) {
View view = getChildAt(position - getFirstVisiblePosition());
if (view instanceof SwipeMenuLayout) {
mTouchPosition = position;
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
}
mTouchView = (SwipeMenuLayout) view;
mTouchView.setSwipeDirection(mDirection);
mTouchView.smoothOpenMenu();
}
}
}
public void smoothCloseMenu(){
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
}
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getContext().getResources().getDisplayMetrics());
}
public void setMenuCreator(SwipeMenuCreator menuCreator) {
this.mMenuCreator = menuCreator;
}
public void setOnMenuItemClickListener(
OnMenuItemClickListener onMenuItemClickListener) {
this.mOnMenuItemClickListener = onMenuItemClickListener;
}
public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
this.mOnSwipeListener = onSwipeListener;
}
public void setOnMenuStateChangeListener(OnMenuStateChangeListener onMenuStateChangeListener) {
mOnMenuStateChangeListener = onMenuStateChangeListener;
}
public static interface OnMenuItemClickListener {
boolean onMenuItemClick(int position, SwipeMenu menu, int index);
}
public static interface OnSwipeListener {
void onSwipeStart(int position);
void onSwipeEnd(int position);
}
public static interface OnMenuStateChangeListener {
void onMenuOpen(int position);
void onMenuClose(int position);
}
public void setSwipeDirection(int direction) {
mDirection = direction;
}
/**
* 判断点击事件是否在某个view内
*
* @param view
* @param ev
* @return
*/
public static boolean inRangeOfView(View view, MotionEvent ev) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (ev.getRawX() < x || ev.getRawX() > (x + view.getWidth()) || ev.getRawY() < y || ev.getRawY() > (y + view.getHeight())) {
return false;
}
return true;
}
}
| mit |
sk89q/CommandHelper | src/main/java/com/laytonsmith/core/exceptions/MarshalException.java | 701 | package com.laytonsmith.core.exceptions;
import com.laytonsmith.core.natives.interfaces.Mixed;
/**
*
*
*/
public class MarshalException extends Exception {
/**
* Creates a new instance of <code>MarshalException</code> without detail message.
*/
public MarshalException() {
}
/**
* Constructs an instance of <code>MarshalException</code> with the specified detail message.
*
* @param msg the detail message.
*/
public MarshalException(String msg) {
super(msg);
}
/**
* This is caused when a particular Construct was given that is incompatible.
*
* @param msg
* @param c
*/
public MarshalException(String msg, Mixed c) {
super(msg + ": " + c.toString());
}
}
| mit |
philomatic/smarthome | bundles/storage/org.eclipse.smarthome.storage.json.test/src/main/java/org/eclipse/smarthome/storage/json/test/JSonStorageTest.java | 2563 | /**
* Copyright (c) 2014-2017 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.storage.json.test;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.smarthome.storage.json.JsonStorage;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* This test makes sure that the JSonStorage loads all stored numbers as BigDecimal
*
* @author Stefan Triller - Initial Contribution
*/
public class JSonStorageTest {
private JsonStorage<Object> objectStorage;
@Before
public void setUp() throws IOException {
File tmpFile = File.createTempFile("storage-debug", ".json");
tmpFile.deleteOnExit();
objectStorage = new JsonStorage<>(tmpFile, this.getClass().getClassLoader(), 0, 0, 0);
}
@Test
public void allInsertedNumbersAreLoadedAsBigDecimal() {
objectStorage.put("DummyObject", new DummyObject());
DummyObject dummy = (DummyObject) objectStorage.get("DummyObject");
Assert.assertTrue(dummy.myMap.get("testShort") instanceof BigDecimal);
Assert.assertTrue(dummy.myMap.get("testInt") instanceof BigDecimal);
Assert.assertTrue(dummy.myMap.get("testLong") instanceof BigDecimal);
Assert.assertTrue(dummy.myMap.get("testDouble") instanceof BigDecimal);
Assert.assertTrue(dummy.myMap.get("testFloat") instanceof BigDecimal);
Assert.assertTrue(dummy.myMap.get("testBigDecimal") instanceof BigDecimal);
Assert.assertTrue(dummy.myMap.get("testBoolean") instanceof Boolean);
Assert.assertTrue(dummy.myMap.get("testString") instanceof String);
}
private class DummyObject {
public Map<String, Object> myMap = new HashMap<String, Object>();
public DummyObject() {
myMap.put("testShort", Short.valueOf("12"));
myMap.put("testInt", Integer.valueOf("12"));
myMap.put("testLong", Long.valueOf("12"));
myMap.put("testDouble", Double.valueOf("12.12"));
myMap.put("testFloat", Float.valueOf("12.12"));
myMap.put("testBigDecimal", new BigDecimal(12));
myMap.put("testBoolean", true);
myMap.put("testString", "hello world");
}
}
}
| epl-1.0 |
dipakmankumbare/idecore | com.salesforce.ide.ui/src/com/salesforce/ide/ui/viewer/TreeItemNotifyingTreeViewer.java | 1732 | /*******************************************************************************
* Copyright (c) 2014 Salesforce.com, inc..
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Salesforce.com, inc. - initial API and implementation
******************************************************************************/
package com.salesforce.ide.ui.viewer;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
public class TreeItemNotifyingTreeViewer extends CheckboxTreeViewer {
Set<ITreeItemCreatedListener> itemCreationListeners = new HashSet<>();
public TreeItemNotifyingTreeViewer(Composite parent, int style) {
super(parent, style);
}
public TreeItemNotifyingTreeViewer(Composite parent) {
super(parent);
}
public TreeItemNotifyingTreeViewer(Tree tree) {
super(tree);
}
@Override
protected void doUpdateItem(Widget item, Object element, boolean fullMap) {
super.doUpdateItem(item, element, fullMap);
for (ITreeItemCreatedListener listener : itemCreationListeners) {
listener.treeItemCreated((TreeItem) item, element);
}
}
public void addTreeItemCreationListener(ITreeItemCreatedListener listener) {
itemCreationListeners.add(listener);
}
public void removeTreeItemCreationListener(ITreeItemCreatedListener listener) {
itemCreationListeners.remove(listener);
}
}
| epl-1.0 |
computergeek1507/openhab | bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/config/ZWaveDbAssociationGroup.java | 965 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.zwave.internal.config;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
/**
* This implements the configuration group for the XML product database.
*
* @author Chris Jackson
* @since 1.4.0
*
*/
public class ZWaveDbAssociationGroup {
public Integer Index;
public Integer Maximum;
public boolean SetToController;
@XStreamImplicit
public List<ZWaveDbLabel> Label;
@XStreamImplicit
public List<ZWaveDbLabel> Help;
ZWaveDbAssociationGroup() {
SetToController = false;
}
}
| epl-1.0 |
ssalonen/openhab | bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/converter/command/MultiLevelPercentCommandConverter.java | 1047 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zwave.internal.converter.command;
import org.openhab.core.items.Item;
import org.openhab.core.library.types.PercentType;
/**
* Converts from {@link PercentType} command to a Z-Wave value.
*
* @author Jan-Willem Spuij
* @since 1.4.0
*/
public class MultiLevelPercentCommandConverter extends ZWaveCommandConverter<PercentType, Integer> {
/**
* {@inheritDoc}
*/
@Override
protected Integer convert(Item item, PercentType command) {
if (command.intValue() <= 0) {
return 0x00;
}
if (command.intValue() > 0 && command.intValue() < 0x63) {
return command.intValue();
} else {
return 0x63;
}
}
} | epl-1.0 |
jekey/my-oscgit-android | mygitosc/src/main/java/com/bill/mygitosc/ui/ProjectReadMeActivity.java | 3630 | package com.bill.mygitosc.ui;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bill.mygitosc.R;
import com.bill.mygitosc.bean.ReadMe;
import com.bill.mygitosc.gson.GsonRequest;
import com.bill.mygitosc.utils.OscApiUtils;
import com.bill.mygitosc.widget.TipInfoLayout;
import org.apache.http.protocol.HTTP;
import butterknife.InjectView;
public class ProjectReadMeActivity extends BaseActivity {
@InjectView(R.id.webView)
WebView webView;
@InjectView(R.id.tip_info)
TipInfoLayout tipInfoLayout;
public String linkCss = "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/readme_style.css\">";
public static String PROJECT_ID = "project_id";
private int projectID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent() != null) {
projectID = getIntent().getIntExtra(PROJECT_ID, 0);
}
initView();
loadData();
}
@Override
protected void initToolbar() {
super.initToolbar();
toolbar.setTitle("README.md");
}
private void loadData() {
RequestQueue mQueue = Volley.newRequestQueue(this);
GsonRequest<ReadMe> gsonRequest = new GsonRequest<ReadMe>(OscApiUtils.getReadmeURL(projectID), ReadMe.class,
new Response.Listener<ReadMe>() {
@Override
public void onResponse(ReadMe response) {
if (response != null && response.getContent() != null) {
setWebView(true);
String body = linkCss + "<div class='markdown-body'>" + response.getContent() + "</div>";
webView.loadDataWithBaseURL(null, body, "text/html", HTTP.UTF_8, null);
} else {
setWebView(false);
tipInfoLayout.setEmptyData(getString(R.string.no_readme_hint));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
setWebView(false);
tipInfoLayout.setLoadError(getString(R.string.request_data_error_but_hint));
}
});
mQueue.add(gsonRequest);
}
private void initView() {
setWebView(false);
tipInfoLayout.setLoading();
tipInfoLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWebView(false);
tipInfoLayout.setLoading();
loadData();
}
});
}
private void setWebView(boolean visiable){
if(visiable){
webView.setVisibility(View.VISIBLE);
tipInfoLayout.setVisibility(View.GONE);
}else{
webView.setVisibility(View.GONE);
tipInfoLayout.setVisibility(View.VISIBLE);
}
}
@Override
protected int getLayoutView() {
return R.layout.activity_project_read_me;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| gpl-2.0 |
mdaniel/svn-caucho-com-resin | modules/resin/src/com/caucho/admin/PasswordApi.java | 238 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* @author Scott Ferguson
*/
package com.caucho.admin;
public interface PasswordApi {
public String encrypt(String value, String salt)
throws Exception;
}
| gpl-2.0 |
uprasad/fred | src/freenet/node/NodeDispatcher.java | 39866 | /* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package freenet.node;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import freenet.crypt.HMAC;
import freenet.io.comm.ByteCounter;
import freenet.io.comm.DMT;
import freenet.io.comm.Dispatcher;
import freenet.io.comm.Message;
import freenet.io.comm.MessageType;
import freenet.io.comm.NotConnectedException;
import freenet.io.comm.Peer;
import freenet.keys.Key;
import freenet.keys.KeyBlock;
import freenet.keys.NodeCHK;
import freenet.keys.NodeSSK;
import freenet.node.NodeStats.PeerLoadStats;
import freenet.node.NodeStats.RejectReason;
import freenet.node.probe.Probe;
import freenet.store.BlockMetadata;
import freenet.support.Fields;
import freenet.support.LogThresholdCallback;
import freenet.support.Logger;
import freenet.support.Logger.LogLevel;
import freenet.support.ShortBuffer;
import freenet.support.io.NativeThread;
/**
* @author amphibian
*
* Dispatcher for unmatched FNP messages.
*
* What can we get?
*
* SwapRequests
*
* DataRequests
*
* InsertRequests
*
* Probably a few others; those are the important bits.
*
* Requests:
* - Loop detection only works when the request is actually running. We do
* NOT remember what UID's we have routed in the past. Hence there is no
* possibility of an attacker probing for old UID's. Also, even in the rare-ish
* case where a request forks because an Accepted is delayed, this isn't a
* big problem: Since we moved on, we're not waiting for it, there will be
* no timeout/snarl-up beyond what has already happened.
* - We should parse the message completely before checking the UID,
* overload, and passing it to the handler. Invalid requests should never
* be accepted. However, because of inserts, we cannot guarantee that we
* never check the UID before we know the request is fully routable.
*/
public class NodeDispatcher implements Dispatcher, Runnable {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerLogThresholdCallback(new LogThresholdCallback(){
@Override
public void shouldUpdate(){
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this);
}
});
}
final Node node;
final RequestTracker tracker;
private NodeStats nodeStats;
private NodeDispatcherCallback callback;
final Probe probe;
private static final long STALE_CONTEXT=20000;
private static final long STALE_CONTEXT_CHECK=20000;
NodeDispatcher(Node node) {
this.node = node;
this.tracker = node.tracker;
this.nodeStats = node.nodeStats;
node.getTicker().queueTimedJob(this, STALE_CONTEXT_CHECK);
this.probe = new Probe(node);
}
ByteCounter pingCounter = new ByteCounter() {
@Override
public void receivedBytes(int x) {
node.nodeStats.pingCounterReceived(x);
}
@Override
public void sentBytes(int x) {
node.nodeStats.pingCounterSent(x);
}
@Override
public void sentPayload(int x) {
// Ignore
}
};
public interface NodeDispatcherCallback {
public void snoop(Message m, Node n);
}
@Override
public boolean handleMessage(Message m) {
PeerNode source = (PeerNode)m.getSource();
if(source == null) {
// Node has been disconnected and garbage collected already! Ouch.
return true;
}
if(logMINOR) Logger.minor(this, "Dispatching "+m+" from "+source);
if(callback != null) {
try {
callback.snoop(m, node);
} catch (Throwable t) {
Logger.error(this, "Callback threw "+t, t);
}
}
MessageType spec = m.getSpec();
if(spec == DMT.FNPPing) {
// Send an FNPPong
Message reply = DMT.createFNPPong(m.getInt(DMT.PING_SEQNO));
try {
source.sendAsync(reply, null, pingCounter); // nothing we can do if can't contact source
} catch (NotConnectedException e) {
if(logMINOR) Logger.minor(this, "Lost connection replying to "+m);
}
return true;
} else if(spec == DMT.FNPDetectedIPAddress) {
Peer p = (Peer) m.getObject(DMT.EXTERNAL_ADDRESS);
source.setRemoteDetectedPeer(p);
node.ipDetector.redetectAddress();
return true;
} else if(spec == DMT.FNPTime) {
return handleTime(m, source);
} else if(spec == DMT.FNPUptime) {
return handleUptime(m, source);
} else if(spec == DMT.FNPVisibility && source instanceof DarknetPeerNode) {
((DarknetPeerNode)source).handleVisibility(m);
return true;
} else if(spec == DMT.FNPVoid) {
return true;
} else if(spec == DMT.FNPDisconnect) {
handleDisconnect(m, source);
return true;
} else if(spec == DMT.nodeToNodeMessage) {
node.receivedNodeToNodeMessage(m, source);
return true;
} else if(spec == DMT.UOMAnnounce && source.isRealConnection()) {
// Treat as a UOMAnnouncement, as it's a strict subset, and new UOM handles revocations.
return node.nodeUpdater.uom.handleAnnounce(m, source);
} else if(spec == DMT.UOMAnnouncement && source.isRealConnection()) {
return node.nodeUpdater.uom.handleAnnounce(m, source);
} else if(spec == DMT.UOMRequestRevocation && source.isRealConnection()) {
return node.nodeUpdater.uom.handleRequestRevocation(m, source);
} else if(spec == DMT.UOMSendingRevocation && source.isRealConnection()) {
return node.nodeUpdater.uom.handleSendingRevocation(m, source);
} else if(spec == DMT.UOMRequestMain && node.nodeUpdater.isEnabled() && source.isRealConnection()) {
node.nodeUpdater.legacyUOM.handleRequestJar(m, source, false);
return true;
} else if(spec == DMT.UOMRequestMainJar && node.nodeUpdater.isEnabled() && source.isRealConnection()) {
node.nodeUpdater.uom.handleRequestJar(m, source);
return true;
} else if(spec == DMT.UOMRequestExtra && node.nodeUpdater.isEnabled() && source.isRealConnection()) {
node.nodeUpdater.legacyUOM.handleRequestJar(m, source, true);
return true;
} else if(spec == DMT.UOMSendingMainJar && node.nodeUpdater.isEnabled() && source.isRealConnection()) {
return node.nodeUpdater.uom.handleSendingMain(m, source);
} else if(spec == DMT.UOMFetchDependency && node.nodeUpdater.isEnabled() && source.isRealConnection()) {
node.nodeUpdater.uom.handleFetchDependency(m, source);
return true;
} else if(spec == DMT.FNPOpennetAnnounceRequest) {
return handleAnnounceRequest(m, source);
} else if(spec == DMT.FNPRoutingStatus) {
if(source instanceof DarknetPeerNode) {
boolean value = m.getBoolean(DMT.ROUTING_ENABLED);
if(logMINOR)
Logger.minor(this, "The peer ("+source+") asked us to set routing="+value);
((DarknetPeerNode)source).setRoutingStatus(value, false);
}
// We claim it in any case
return true;
} else if(source.isRealConnection() && spec == DMT.FNPLocChangeNotificationNew) {
double newLoc = m.getDouble(DMT.LOCATION);
ShortBuffer buffer = ((ShortBuffer) m.getObject(DMT.PEER_LOCATIONS));
double[] locs = Fields.bytesToDoubles(buffer.getData());
/**
* Do *NOT* remove the sanity check below!
* @see http://archives.freenetproject.org/message/20080718.144240.359e16d3.en.html
*/
if((OpennetManager.MAX_PEERS_FOR_SCALING < locs.length) && (source.isOpennet())) {
if(locs.length > OpennetManager.PANIC_MAX_PEERS) {
// This can't happen by accident
Logger.error(this, "We received "+locs.length+ " locations from "+source.toString()+"! That should *NOT* happen! Possible attack!");
source.forceDisconnect();
return true;
} else {
// A few extra can happen by accident. Just use the first 20.
Logger.normal(this, "Too many locations from "+source.toString()+" : "+locs.length+" could be an accident, using the first "+OpennetManager.MAX_PEERS_FOR_SCALING);
locs = Arrays.copyOf(locs, OpennetManager.MAX_PEERS_FOR_SCALING);
}
}
// We are on darknet and we trust our peers OR we are on opennet
// and the amount of locations sent to us seems reasonable
source.updateLocation(newLoc, locs);
return true;
} else if(spec == DMT.FNPPeerLoadStatusByte || spec == DMT.FNPPeerLoadStatusShort || spec == DMT.FNPPeerLoadStatusInt) {
// Must be handled before doing the routable check!
// We may not have received the Location yet, etc.
return handlePeerLoadStatus(m, source);
}
if(!source.isRoutable()) {
if(logDEBUG) Logger.debug(this, "Not routable");
if(spec == DMT.FNPCHKDataRequest) {
rejectRequest(m, node.nodeStats.chkRequestCtr);
} else if(spec == DMT.FNPSSKDataRequest) {
rejectRequest(m, node.nodeStats.sskRequestCtr);
} else if(spec == DMT.FNPInsertRequest) {
rejectRequest(m, node.nodeStats.chkInsertCtr);
} else if(spec == DMT.FNPSSKInsertRequest) {
rejectRequest(m, node.nodeStats.sskInsertCtr);
} else if(spec == DMT.FNPSSKInsertRequestNew) {
rejectRequest(m, node.nodeStats.sskInsertCtr);
} else if(spec == DMT.FNPGetOfferedKey) {
rejectRequest(m, node.failureTable.senderCounter);
}
return false;
}
if(spec == DMT.FNPSwapRequest) {
return node.lm.handleSwapRequest(m, source);
} else if(spec == DMT.FNPSwapReply) {
return node.lm.handleSwapReply(m, source);
} else if(spec == DMT.FNPSwapRejected) {
return node.lm.handleSwapRejected(m, source);
} else if(spec == DMT.FNPSwapCommit) {
return node.lm.handleSwapCommit(m, source);
} else if(spec == DMT.FNPSwapComplete) {
return node.lm.handleSwapComplete(m, source);
} else if(spec == DMT.FNPCHKDataRequest) {
handleDataRequest(m, source, false);
return true;
} else if(spec == DMT.FNPSSKDataRequest) {
handleDataRequest(m, source, true);
return true;
} else if(spec == DMT.FNPInsertRequest) {
handleInsertRequest(m, source, false);
return true;
} else if(spec == DMT.FNPSSKInsertRequest) {
handleInsertRequest(m, source, true);
return true;
} else if(spec == DMT.FNPSSKInsertRequestNew) {
handleInsertRequest(m, source, true);
return true;
} else if(spec == DMT.FNPRoutedPing) {
return handleRouted(m, source);
} else if(spec == DMT.FNPRoutedPong) {
return handleRoutedReply(m);
} else if(spec == DMT.FNPRoutedRejected) {
return handleRoutedRejected(m);
} else if(spec == DMT.FNPOfferKey) {
return handleOfferKey(m, source);
} else if(spec == DMT.FNPGetOfferedKey) {
return handleGetOfferedKey(m, source);
} else if(spec == DMT.FNPGetYourFullNoderef && source instanceof DarknetPeerNode) {
((DarknetPeerNode)source).sendFullNoderef();
return true;
} else if(spec == DMT.FNPMyFullNoderef && source instanceof DarknetPeerNode) {
((DarknetPeerNode)source).handleFullNoderef(m);
return true;
} else if(spec == DMT.ProbeRequest) {
//Response is handled by callbacks within probe.
probe.request(m, source);
return true;
}
return false;
}
private void rejectRequest(Message m, ByteCounter ctr) {
long uid = m.getLong(DMT.UID);
Message msg = DMT.createFNPRejectedOverload(uid, true, false, false);
// Send the load status anyway, hopefully this is a temporary problem.
msg.setNeedsLoadBulk();
msg.setNeedsLoadRT();
try {
m.getSource().sendAsync(msg, null, ctr);
} catch (NotConnectedException e) {
// Ignore
}
}
private boolean handlePeerLoadStatus(Message m, PeerNode source) {
PeerLoadStats stat = node.nodeStats.parseLoadStats(source, m);
source.reportLoadStatus(stat);
return true;
}
private boolean handleUptime(Message m, PeerNode source) {
byte uptime = m.getByte(DMT.UPTIME_PERCENT_48H);
source.setUptime(uptime);
return true;
}
private boolean handleOfferKey(Message m, PeerNode source) {
Key key = (Key) m.getObject(DMT.KEY);
byte[] authenticator = ((ShortBuffer) m.getObject(DMT.OFFER_AUTHENTICATOR)).getData();
node.failureTable.onOffer(key, source, authenticator);
return true;
}
private boolean handleGetOfferedKey(Message m, PeerNode source) {
Key key = (Key) m.getObject(DMT.KEY);
byte[] authenticator = ((ShortBuffer) m.getObject(DMT.OFFER_AUTHENTICATOR)).getData();
long uid = m.getLong(DMT.UID);
if(!HMAC.verifyWithSHA256(node.failureTable.offerAuthenticatorKey, key.getFullKey(), authenticator)) {
Logger.error(this, "Invalid offer request from "+source+" : authenticator did not verify");
try {
source.sendAsync(DMT.createFNPGetOfferedKeyInvalid(uid, DMT.GET_OFFERED_KEY_REJECTED_BAD_AUTHENTICATOR), null, node.failureTable.senderCounter);
} catch (NotConnectedException e) {
// Too bad.
}
return true;
}
if(logMINOR) Logger.minor(this, "Valid GetOfferedKey for "+key+" from "+source);
// Do we want it? We can RejectOverload if we don't have the bandwidth...
boolean isSSK = key instanceof NodeSSK;
boolean realTimeFlag = DMT.getRealTimeFlag(m);
OfferReplyTag tag = new OfferReplyTag(isSSK, source, realTimeFlag, uid, node);
if(!tracker.lockUID(uid, isSSK, false, true, false, realTimeFlag, tag)) {
if(logMINOR) Logger.minor(this, "Could not lock ID "+uid+" -> rejecting (already running)");
Message rejected = DMT.createFNPRejectedLoop(uid);
try {
source.sendAsync(rejected, null, node.failureTable.senderCounter);
} catch (NotConnectedException e) {
Logger.normal(this, "Rejecting request from "+source.getPeer()+": "+e);
}
return true;
} else {
if(logMINOR) Logger.minor(this, "Locked "+uid);
}
boolean needPubKey;
try {
needPubKey = m.getBoolean(DMT.NEED_PUB_KEY);
RejectReason reject =
nodeStats.shouldRejectRequest(true, false, isSSK, false, true, source, false, false, realTimeFlag, tag);
if(reject != null) {
Logger.normal(this, "Rejecting FNPGetOfferedKey from "+source+" for "+key+" : "+reject);
Message rejected = DMT.createFNPRejectedOverload(uid, true, true, realTimeFlag);
if(reject.soft)
rejected.addSubMessage(DMT.createFNPRejectIsSoft());
try {
source.sendAsync(rejected, null, node.failureTable.senderCounter);
} catch (NotConnectedException e) {
Logger.normal(this, "Rejecting (overload) data request from "+source.getPeer()+": "+e);
}
tag.unlockHandler(reject.soft);
return true;
}
} catch (Error e) {
tag.unlockHandler();
throw e;
} catch (RuntimeException e) {
tag.unlockHandler();
throw e;
} // Otherwise, sendOfferedKey is responsible for unlocking.
// Accept it.
try {
node.failureTable.sendOfferedKey(key, isSSK, needPubKey, uid, source, tag,realTimeFlag);
} catch (NotConnectedException e) {
// Too bad.
}
return true;
}
private void handleDisconnect(final Message m, final PeerNode source) {
// Wait for 1 second to ensure that the ack gets sent first.
node.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
finishDisconnect(m, source);
}
}, 1000);
}
private void finishDisconnect(final Message m, final PeerNode source) {
source.disconnected(true, true);
// If true, remove from active routing table, likely to be down for a while.
// Otherwise just dump all current connection state and keep trying to connect.
boolean remove = m.getBoolean(DMT.REMOVE);
if(remove) {
node.peers.disconnectAndRemove(source, false, false, false);
if(source instanceof DarknetPeerNode)
// FIXME remove, dirty logs.
// FIXME add a useralert?
System.out.println("Disconnecting permanently from your friend \""+((DarknetPeerNode)source).getName()+"\" because they asked us to remove them.");
}
// If true, purge all references to this node. Otherwise, we can keep the node
// around in secondary tables etc in order to more easily reconnect later.
// (Mostly used on opennet)
boolean purge = m.getBoolean(DMT.PURGE);
if(purge) {
OpennetManager om = node.getOpennet();
if(om != null && source instanceof OpennetPeerNode)
om.purgeOldOpennetPeer((OpennetPeerNode)source);
}
// Process parting message
int type = m.getInt(DMT.NODE_TO_NODE_MESSAGE_TYPE);
ShortBuffer messageData = (ShortBuffer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_DATA);
if(messageData.getLength() == 0) return;
node.receivedNodeToNodeMessage(source, type, messageData, true);
}
private boolean handleTime(Message m, PeerNode source) {
long delta = m.getLong(DMT.TIME) - System.currentTimeMillis();
source.setTimeDelta(delta);
return true;
}
// We need to check the datastore before deciding whether to accept a request.
// This can block - in bad cases, for a long time.
// So we need to run it on a separate thread.
private final PrioRunnable queueRunner = new PrioRunnable() {
@Override
public void run() {
while(true) {
try {
Message msg = requestQueue.take();
boolean isSSK = msg.getSpec() == DMT.FNPSSKDataRequest;
innerHandleDataRequest(msg, (PeerNode)msg.getSource(), isSSK);
} catch (InterruptedException e) {
// Ignore
}
}
}
@Override
public int getPriority() {
// Slightly less than the actual requests themselves because accepting requests increases load.
return NativeThread.HIGH_PRIORITY-1;
}
};
private final ArrayBlockingQueue<Message> requestQueue = new ArrayBlockingQueue<Message>(100);
private void handleDataRequest(Message m, PeerNode source, boolean isSSK) {
// FIXME check probablyInStore and if not, we can handle it inline.
// This and DatastoreChecker require that method be implemented...
// For now just handle everything on the thread...
if(!requestQueue.offer(m)) {
rejectRequest(m, isSSK ? node.nodeStats.sskRequestCtr : node.nodeStats.chkRequestCtr);
}
}
/**
* Handle an incoming FNPDataRequest. We should parse it and determine
* whether it is valid before we accept it.
*/
private void innerHandleDataRequest(Message m, PeerNode source, boolean isSSK) {
if(!source.isConnected()) {
if(logMINOR) Logger.minor(this, "Handling request off thread, source disconnected: "+source+" for "+m);
return;
}
if(!source.isRoutable()) {
if(logMINOR) Logger.minor(this, "Handling request off thread, source no longer routable: "+source+" for "+m);
rejectRequest(m, isSSK ? node.nodeStats.sskRequestCtr : node.nodeStats.chkRequestCtr);
return;
}
long id = m.getLong(DMT.UID);
ByteCounter ctr = isSSK ? node.nodeStats.sskRequestCtr : node.nodeStats.chkRequestCtr;
short htl = m.getShort(DMT.HTL);
if(htl <= 0) htl = 1;
Key key = (Key) m.getObject(DMT.FREENET_ROUTING_KEY);
boolean realTimeFlag = DMT.getRealTimeFlag(m);
final RequestTag tag = new RequestTag(isSSK, RequestTag.START.REMOTE, source, realTimeFlag, id, node);
if(!tracker.lockUID(id, isSSK, false, false, false, realTimeFlag, tag)) {
if(logMINOR) Logger.minor(this, "Could not lock ID "+id+" -> rejecting (already running)");
Message rejected = DMT.createFNPRejectedLoop(id);
try {
source.sendAsync(rejected, null, ctr);
} catch (NotConnectedException e) {
Logger.normal(this, "Rejecting request from "+source.getPeer()+": "+e);
}
node.failureTable.onFinalFailure(key, null, htl, htl, -1, -1, source);
return;
} else {
if(logMINOR) Logger.minor(this, "Locked "+id);
}
// There are at least 2 threads that call this function.
// DO NOT reuse the meta object, unless on a per-thread basis.
// Object allocation is pretty cheap in modern Java anyway...
// If we do reuse it, call reset().
BlockMetadata meta = new BlockMetadata();
KeyBlock block = node.fetch(key, false, false, false, false, meta);
if(block != null)
tag.setNotRoutedOnwards();
RejectReason rejectReason = nodeStats.shouldRejectRequest(!isSSK, false, isSSK, false, false, source, block != null, false, realTimeFlag, tag);
if(rejectReason != null) {
// can accept 1 CHK request every so often, but not with SSKs because they aren't throttled so won't sort out bwlimitDelayTime, which was the whole reason for accepting them when overloaded...
Logger.normal(this, "Rejecting "+(isSSK ? "SSK" : "CHK")+" request from "+source.getPeer()+" preemptively because "+rejectReason);
Message rejected = DMT.createFNPRejectedOverload(id, true, true, realTimeFlag);
if(rejectReason.soft)
rejected.addSubMessage(DMT.createFNPRejectIsSoft());
try {
source.sendAsync(rejected, null, ctr);
} catch (NotConnectedException e) {
Logger.normal(this, "Rejecting (overload) data request from "+source.getPeer()+": "+e);
}
tag.setRejected();
tag.unlockHandler(rejectReason.soft);
// Do not tell failure table.
// Otherwise an attacker can flood us with requests very cheaply and purge our
// failure table even though we didn't accept any of them.
return;
}
nodeStats.reportIncomingRequestLocation(key.toNormalizedDouble());
//if(!node.lockUID(id)) return false;
boolean needsPubKey = false;
if(key instanceof NodeSSK)
needsPubKey = m.getBoolean(DMT.NEED_PUB_KEY);
RequestHandler rh = new RequestHandler(source, id, node, htl, key, tag, block, realTimeFlag, needsPubKey);
rh.receivedBytes(m.receivedByteCount());
node.executor.execute(rh, "RequestHandler for UID "+id+" on "+node.getDarknetPortNumber());
}
/**
* Handle an incoming insert. We should parse it and determine whether it
* is valid before we accept it. However in the case of inserts it *IS*
* possible for the request sender to cause it to fail later during the
* receive of the data or the DataInsert.
* @param m The incoming message.
* @param source The node that sent the message.
* @param isSSK True if it is an SSK insert, false if it is a CHK insert.
*/
private void handleInsertRequest(Message m, PeerNode source, boolean isSSK) {
ByteCounter ctr = isSSK ? node.nodeStats.sskInsertCtr : node.nodeStats.chkInsertCtr;
long id = m.getLong(DMT.UID);
boolean realTimeFlag = DMT.getRealTimeFlag(m);
InsertTag tag = new InsertTag(isSSK, InsertTag.START.REMOTE, source, realTimeFlag, id, node);
if(!tracker.lockUID(id, isSSK, true, false, false, realTimeFlag, tag)) {
if(logMINOR) Logger.minor(this, "Could not lock ID "+id+" -> rejecting (already running)");
Message rejected = DMT.createFNPRejectedLoop(id);
try {
source.sendAsync(rejected, null, ctr);
} catch (NotConnectedException e) {
Logger.normal(this, "Rejecting insert request from "+source.getPeer()+": "+e);
}
return;
}
boolean preferInsert = Node.PREFER_INSERT_DEFAULT;
boolean ignoreLowBackoff = Node.IGNORE_LOW_BACKOFF_DEFAULT;
boolean forkOnCacheable = Node.FORK_ON_CACHEABLE_DEFAULT;
Message forkControl = m.getSubMessage(DMT.FNPSubInsertForkControl);
if(forkControl != null)
forkOnCacheable = forkControl.getBoolean(DMT.ENABLE_INSERT_FORK_WHEN_CACHEABLE);
Message lowBackoff = m.getSubMessage(DMT.FNPSubInsertIgnoreLowBackoff);
if(lowBackoff != null)
ignoreLowBackoff = lowBackoff.getBoolean(DMT.IGNORE_LOW_BACKOFF);
Message preference = m.getSubMessage(DMT.FNPSubInsertPreferInsert);
if(preference != null)
preferInsert = preference.getBoolean(DMT.PREFER_INSERT);
// SSKs don't fix bwlimitDelayTime so shouldn't be accepted when overloaded.
RejectReason rejectReason = nodeStats.shouldRejectRequest(!isSSK, true, isSSK, false, false, source, false, preferInsert, realTimeFlag, tag);
if(rejectReason != null) {
Logger.normal(this, "Rejecting insert from "+source.getPeer()+" preemptively because "+rejectReason);
Message rejected = DMT.createFNPRejectedOverload(id, true, true, realTimeFlag);
if(rejectReason.soft)
rejected.addSubMessage(DMT.createFNPRejectIsSoft());
try {
source.sendAsync(rejected, null, ctr);
} catch (NotConnectedException e) {
Logger.normal(this, "Rejecting (overload) insert request from "+source.getPeer()+": "+e);
}
tag.unlockHandler(rejectReason.soft);
return;
}
long now = System.currentTimeMillis();
if(m.getSpec().equals(DMT.FNPSSKInsertRequest)) {
NodeSSK key = (NodeSSK) m.getObject(DMT.FREENET_ROUTING_KEY);
byte[] data = ((ShortBuffer) m.getObject(DMT.DATA)).getData();
byte[] headers = ((ShortBuffer) m.getObject(DMT.BLOCK_HEADERS)).getData();
short htl = m.getShort(DMT.HTL);
if(htl <= 0) htl = 1;
SSKInsertHandler rh = new SSKInsertHandler(key, data, headers, htl, source, id, node, now, tag, node.canWriteDatastoreInsert(htl), forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag);
rh.receivedBytes(m.receivedByteCount());
node.executor.execute(rh, "SSKInsertHandler for "+id+" on "+node.getDarknetPortNumber());
} else if(m.getSpec().equals(DMT.FNPSSKInsertRequestNew)) {
NodeSSK key = (NodeSSK) m.getObject(DMT.FREENET_ROUTING_KEY);
short htl = m.getShort(DMT.HTL);
if(htl <= 0) htl = 1;
SSKInsertHandler rh = new SSKInsertHandler(key, null, null, htl, source, id, node, now, tag, node.canWriteDatastoreInsert(htl), forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag);
rh.receivedBytes(m.receivedByteCount());
node.executor.execute(rh, "SSKInsertHandler for "+id+" on "+node.getDarknetPortNumber());
} else {
NodeCHK key = (NodeCHK) m.getObject(DMT.FREENET_ROUTING_KEY);
short htl = m.getShort(DMT.HTL);
if(htl <= 0) htl = 1;
CHKInsertHandler rh = new CHKInsertHandler(key, htl, source, id, node, now, tag, forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag);
rh.receivedBytes(m.receivedByteCount());
node.executor.execute(rh, "CHKInsertHandler for "+id+" on "+node.getDarknetPortNumber());
}
if(logMINOR) Logger.minor(this, "Started InsertHandler for "+id);
}
private boolean handleAnnounceRequest(Message m, PeerNode source) {
long uid = m.getLong(DMT.UID);
double target = m.getDouble(DMT.TARGET_LOCATION); // FIXME validate
short htl = (short) Math.min(m.getShort(DMT.HTL), node.maxHTL());
long xferUID = m.getLong(DMT.TRANSFER_UID);
int noderefLength = m.getInt(DMT.NODEREF_LENGTH);
int paddedLength = m.getInt(DMT.PADDED_LENGTH);
// Only accept a valid message. See comments at top of NodeDispatcher, but it's a good idea anyway.
if(target < 0.0 || target >= 1.0 || htl <= 0 ||
paddedLength < 0 || paddedLength > OpennetManager.MAX_OPENNET_NODEREF_LENGTH ||
noderefLength > paddedLength) {
Message msg = DMT.createFNPRejectedOverload(uid, true, false, false);
try {
source.sendAsync(msg, null, node.nodeStats.announceByteCounter);
} catch (NotConnectedException e) {
// OK
}
if(logMINOR) Logger.minor(this, "Got bogus announcement message from "+source);
return true;
}
OpennetManager om = node.getOpennet();
if(om == null || !source.canAcceptAnnouncements()) {
if(om != null && source instanceof SeedClientPeerNode)
om.seedTracker.rejectedAnnounce((SeedClientPeerNode)source);
Message msg = DMT.createFNPOpennetDisabled(uid);
try {
source.sendAsync(msg, null, node.nodeStats.announceByteCounter);
} catch (NotConnectedException e) {
// OK
}
if(logMINOR) Logger.minor(this, "Rejected announcement (opennet or announcement disabled) from "+source);
return true;
}
boolean success = false;
try {
// UIDs for announcements are separate from those for requests.
// So we don't need to, and should not, ask Node.
if(!node.nodeStats.shouldAcceptAnnouncement(uid)) {
if(om != null && source instanceof SeedClientPeerNode)
om.seedTracker.rejectedAnnounce((SeedClientPeerNode)source);
Message msg = DMT.createFNPRejectedOverload(uid, true, false, false);
try {
source.sendAsync(msg, null, node.nodeStats.announceByteCounter);
} catch (NotConnectedException e) {
// OK
}
if(logMINOR) Logger.minor(this, "Rejected announcement (overall overload) from "+source);
return true;
}
if(!source.shouldAcceptAnnounce(uid)) {
if(om != null && source instanceof SeedClientPeerNode)
om.seedTracker.rejectedAnnounce((SeedClientPeerNode)source);
node.nodeStats.endAnnouncement(uid);
Message msg = DMT.createFNPRejectedOverload(uid, true, false, false);
try {
source.sendAsync(msg, null, node.nodeStats.announceByteCounter);
} catch (NotConnectedException e) {
// OK
}
if(logMINOR) Logger.minor(this, "Rejected announcement (peer limit) from "+source);
return true;
}
if(om != null && source instanceof SeedClientPeerNode) {
if(!om.seedTracker.acceptAnnounce((SeedClientPeerNode)source, node.fastWeakRandom)) {
node.nodeStats.endAnnouncement(uid);
Message msg = DMT.createFNPRejectedOverload(uid, true, false, false);
try {
source.sendAsync(msg, null, node.nodeStats.announceByteCounter);
} catch (NotConnectedException e) {
// OK
}
if(logMINOR) Logger.minor(this, "Rejected announcement (seednode limit) from "+source);
return true;
}
}
if(source instanceof SeedClientPeerNode) {
short maxHTL = node.maxHTL();
if(htl < maxHTL-1) {
Logger.error(this, "Announcement from seed client not at max HTL: "+htl+" for "+source);
htl = maxHTL;
}
}
AnnouncementCallback cb = null;
if(logMINOR) {
final String origin = source.toString()+" (htl "+htl+")";
// Log the progress of the announcement.
// This is similar to Announcer's logging.
cb = new AnnouncementCallback() {
private int totalAdded;
private int totalNotWanted;
private boolean acceptedSomewhere;
@Override
public synchronized void acceptedSomewhere() {
acceptedSomewhere = true;
}
@Override
public void addedNode(PeerNode pn) {
synchronized(this) {
totalAdded++;
}
Logger.minor(this, "Announcement from "+origin+" added node "+pn+(pn instanceof SeedClientPeerNode ? " (seed server added the peer directly)" : ""));
return;
}
@Override
public void bogusNoderef(String reason) {
Logger.minor(this, "Announcement from "+origin+" got bogus noderef: "+reason, new Exception("debug"));
}
@Override
public void completed() {
synchronized(this) {
Logger.minor(this, "Announcement from "+origin+" completed");
}
int shallow=node.maxHTL()-(totalAdded+totalNotWanted);
if(acceptedSomewhere)
Logger.minor(this, "Announcement from "+origin+" completed ("+totalAdded+" added, "+totalNotWanted+" not wanted, "+shallow+" shallow)");
else
Logger.minor(this, "Announcement from "+origin+" not accepted anywhere.");
}
@Override
public void nodeFailed(PeerNode pn, String reason) {
Logger.minor(this, "Announcement from "+origin+" failed: "+reason);
}
@Override
public void noMoreNodes() {
Logger.minor(this, "Announcement from "+origin+" ran out of nodes (route not found)");
}
@Override
public void nodeNotWanted() {
synchronized(this) {
totalNotWanted++;
}
Logger.minor(this, "Announcement from "+origin+" returned node not wanted for a total of "+totalNotWanted+" from this announcement)");
}
@Override
public void nodeNotAdded() {
Logger.minor(this, "Announcement from "+origin+" : node not wanted (maybe already have it, opennet just turned off, etc)");
}
@Override
public void relayedNoderef() {
synchronized(this) {
totalAdded++;
Logger.minor(this, "Announcement from "+origin+" accepted by a downstream node, relaying noderef for a total of "+totalAdded+" from this announcement)");
}
}
};
}
AnnounceSender sender = new AnnounceSender(target, htl, uid, source, om, node, xferUID, noderefLength, paddedLength, cb);
node.executor.execute(sender, "Announcement sender for "+uid);
success = true;
if(logMINOR) Logger.minor(this, "Accepted announcement from "+source);
return true;
} finally {
if(!success)
source.completedAnnounce(uid);
}
}
final Hashtable<Long, RoutedContext> routedContexts = new Hashtable<Long, RoutedContext>();
static class RoutedContext {
long createdTime;
long accessTime;
PeerNode source;
final HashSet<PeerNode> routedTo;
Message msg;
short lastHtl;
final byte[] identity;
RoutedContext(Message msg, PeerNode source, byte[] identity) {
createdTime = accessTime = System.currentTimeMillis();
this.source = source;
routedTo = new HashSet<PeerNode>();
this.msg = msg;
lastHtl = msg.getShort(DMT.HTL);
this.identity = identity;
}
void addSent(PeerNode n) {
routedTo.add(n);
}
}
/**
* Cleanup any old/stale routing contexts and reschedule execution.
*/
@Override
public void run() {
long now=System.currentTimeMillis();
synchronized (routedContexts) {
Iterator<RoutedContext> i = routedContexts.values().iterator();
while (i.hasNext()) {
RoutedContext rc = i.next();
if (now-rc.createdTime > STALE_CONTEXT) {
i.remove();
}
}
}
node.getTicker().queueTimedJob(this, STALE_CONTEXT_CHECK);
}
/**
* Handle an FNPRoutedRejected message.
*/
private boolean handleRoutedRejected(Message m) {
if(!node.enableRoutedPing()) return true;
long id = m.getLong(DMT.UID);
Long lid = Long.valueOf(id);
RoutedContext rc = routedContexts.get(lid);
if(rc == null) {
// Gah
Logger.error(this, "Unrecognized FNPRoutedRejected");
return false; // locally originated??
}
short htl = rc.lastHtl;
if(rc.source != null)
htl = rc.source.decrementHTL(htl);
short ohtl = m.getShort(DMT.HTL);
if(ohtl < htl) htl = ohtl;
if(htl == 0) {
// Equivalent to DNF.
// Relay.
if(rc.source != null) {
try {
rc.source.sendAsync(DMT.createFNPRoutedRejected(id, (short)0), null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
// Ouch.
Logger.error(this, "Unable to relay probe DNF: peer disconnected: "+rc.source);
}
}
} else {
// Try routing to the next node
forward(rc.msg, id, rc.source, htl, rc.msg.getDouble(DMT.TARGET_LOCATION), rc, rc.identity);
}
return true;
}
/**
* Handle a routed-to-a-specific-node message.
* @param m
* @return False if we want the message put back on the queue.
*/
boolean handleRouted(Message m, PeerNode source) {
if(!node.enableRoutedPing()) return true;
if(logMINOR) Logger.minor(this, "handleRouted("+m+ ')');
long id = m.getLong(DMT.UID);
Long lid = Long.valueOf(id);
short htl = m.getShort(DMT.HTL);
byte[] identity = ((ShortBuffer) m.getObject(DMT.NODE_IDENTITY)).getData();
if(source != null) htl = source.decrementHTL(htl);
RoutedContext ctx;
ctx = routedContexts.get(lid);
if(ctx != null) {
try {
source.sendAsync(DMT.createFNPRoutedRejected(id, htl), null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
if(logMINOR) Logger.minor(this, "Lost connection rejecting "+m);
}
return true;
}
ctx = new RoutedContext(m, source, identity);
synchronized (routedContexts) {
routedContexts.put(lid, ctx);
}
// source == null => originated locally, keep full htl
double target = m.getDouble(DMT.TARGET_LOCATION);
if(logMINOR) Logger.minor(this, "id "+id+" from "+source+" htl "+htl+" target "+target);
if(Math.abs(node.lm.getLocation() - target) <= Double.MIN_VALUE) {
if(logMINOR) Logger.minor(this, "Dispatching "+m.getSpec()+" on "+node.getDarknetPortNumber());
// Handle locally
// Message type specific processing
dispatchRoutedMessage(m, source, id);
return true;
} else if(htl == 0) {
Message reject = DMT.createFNPRoutedRejected(id, (short)0);
if(source != null) try {
source.sendAsync(reject, null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
if(logMINOR) Logger.minor(this, "Lost connection rejecting "+m);
}
return true;
} else {
return forward(m, id, source, htl, target, ctx, identity);
}
}
boolean handleRoutedReply(Message m) {
if(!node.enableRoutedPing()) return true;
long id = m.getLong(DMT.UID);
if(logMINOR) Logger.minor(this, "Got reply: "+m);
Long lid = Long.valueOf(id);
RoutedContext ctx = routedContexts.get(lid);
if(ctx == null) {
Logger.error(this, "Unrecognized routed reply: "+m);
return false;
}
PeerNode pn = ctx.source;
if(pn == null) return false;
try {
pn.sendAsync(m.cloneAndDropSubMessages(), null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
if(logMINOR) Logger.minor(this, "Lost connection forwarding "+m+" to "+pn);
}
return true;
}
private boolean forward(Message m, long id, PeerNode pn, short htl, double target, RoutedContext ctx, byte[] targetIdentity) {
if(logMINOR) Logger.minor(this, "Should forward");
// Forward
m = preForward(m, htl);
while(true) {
PeerNode next = node.peers.getByPubKeyHash(targetIdentity);
if(next != null && !next.isConnected()) {
Logger.error(this, "Found target but disconnected!: "+next);
next = null;
}
if(next == null)
next = node.peers.closerPeer(pn, ctx.routedTo, target, true, node.isAdvancedModeEnabled(), -1, null,
null, htl, 0, pn == null, false, false);
if(logMINOR) Logger.minor(this, "Next: "+next+" message: "+m);
if(next != null) {
// next is connected, or at least has been => next.getPeer() CANNOT be null.
if(logMINOR) Logger.minor(this, "Forwarding "+m.getSpec()+" to "+next.getPeer().getPort());
ctx.addSent(next);
try {
next.sendAsync(m, null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
continue;
}
} else {
if(logMINOR) Logger.minor(this, "Reached dead end for "+m.getSpec()+" on "+node.getDarknetPortNumber());
// Reached a dead end...
Message reject = DMT.createFNPRoutedRejected(id, htl);
if(pn != null) try {
pn.sendAsync(reject, null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
Logger.error(this, "Cannot send reject message back to source "+pn);
return true;
}
}
return true;
}
}
/**
* Prepare a routed-to-node message for forwarding.
*/
private Message preForward(Message m, short newHTL) {
m = m.cloneAndDropSubMessages();
m.set(DMT.HTL, newHTL); // update htl
if(m.getSpec() == DMT.FNPRoutedPing) {
int x = m.getInt(DMT.COUNTER);
x++;
m.set(DMT.COUNTER, x);
}
return m;
}
/**
* Deal with a routed-to-node message that landed on this node.
* This is where message-type-specific code executes.
* @param m
* @return
*/
private boolean dispatchRoutedMessage(Message m, PeerNode src, long id) {
if(m.getSpec() == DMT.FNPRoutedPing) {
if(logMINOR) Logger.minor(this, "RoutedPing reached other side! ("+id+")");
int x = m.getInt(DMT.COUNTER);
Message reply = DMT.createFNPRoutedPong(id, x);
if(logMINOR) Logger.minor(this, "Replying - counter = "+x+" for "+id);
try {
src.sendAsync(reply, null, nodeStats.routedMessageCtr);
} catch (NotConnectedException e) {
if(logMINOR) Logger.minor(this, "Lost connection replying to "+m+" in dispatchRoutedMessage");
}
return true;
}
return false;
}
void start(NodeStats stats) {
this.nodeStats = stats;
node.executor.execute(queueRunner);
}
public static String peersUIDsToString(long[] peerUIDs, double[] peerLocs) {
StringBuilder sb = new StringBuilder(peerUIDs.length*23+peerLocs.length*26);
int min=Math.min(peerUIDs.length, peerLocs.length);
for(int i=0;i<min;i++) {
double loc = peerLocs[i];
long uid = peerUIDs[i];
sb.append(loc);
sb.append('=');
sb.append(uid);
if(i != min-1)
sb.append('|');
}
if(peerUIDs.length > min) {
for(int i=min;i<peerUIDs.length;i++) {
sb.append("|U:");
sb.append(peerUIDs[i]);
}
} else if(peerLocs.length > min) {
for(int i=min;i<peerLocs.length;i++) {
sb.append("|L:");
sb.append(peerLocs[i]);
}
}
return sb.toString();
}
public void setHook(NodeDispatcherCallback cb) {
this.callback = cb;
}
}
| gpl-2.0 |
greenlion/mysql-server | storage/ndb/clusterj/clusterj-jdbc/src/main/java/com/mysql/clusterj/jdbc/SQLExecutor.java | 27046 | /*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms,
* as designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
*
* 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, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.clusterj.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mysql.clusterj.ClusterJDatastoreException;
import com.mysql.clusterj.ClusterJFatalInternalException;
import com.mysql.clusterj.ClusterJUserException;
import com.mysql.clusterj.LockMode;
import com.mysql.clusterj.core.query.QueryDomainTypeImpl;
import com.mysql.clusterj.core.spi.DomainTypeHandler;
import com.mysql.clusterj.core.spi.SessionSPI;
import com.mysql.clusterj.core.spi.ValueHandler;
import com.mysql.clusterj.core.spi.ValueHandlerBatching;
import com.mysql.clusterj.core.store.Operation;
import com.mysql.clusterj.core.store.ResultData;
import com.mysql.clusterj.core.util.I18NHelper;
import com.mysql.clusterj.core.util.Logger;
import com.mysql.clusterj.core.util.LoggerFactoryService;
import com.mysql.jdbc.ParameterBindings;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSetInternalMethods;
import com.mysql.jdbc.ServerPreparedStatement;
import com.mysql.jdbc.ServerPreparedStatement.BindValue;
/** This class contains behavior to execute various SQL commands. There is one subclass for each
* command to be executed.
*/
public class SQLExecutor {
/** My message translator */
static final I18NHelper local = I18NHelper.getInstance(SQLExecutor.class);
/** My logger */
static final Logger logger = LoggerFactoryService.getFactory().getInstance(SQLExecutor.class);
/** The domain type handler for this SQL statement */
DomainTypeHandler<?> domainTypeHandler = null;
/** The column names in the SQL statement */
protected List<String> columnNames = null;
/** The number of fields in the domain object (also the number of mapped columns) */
protected int numberOfFields;
/** The number of parameters in the where clause */
protected int numberOfParameters;
/** The map of field numbers to parameter numbers */
protected int[] fieldNumberToColumnNumberMap = null;
/** The map of column numbers to field numbers */
protected int[] columnNumberToFieldNumberMap = null;
/** The map of column names to parameter numbers */
protected Map<String, Integer> columnNameToFieldNumberMap = new HashMap<String, Integer>();
/** The query domain type for qualified SELECT and DELETE operations */
protected QueryDomainTypeImpl<?> queryDomainType;
/** Does the jdbc driver support bind values (mysql 5.1.17 and later)? */
static boolean bindValueSupport = getBindValueSupport();
static boolean getBindValueSupport() {
try {
com.mysql.jdbc.ServerPreparedStatement.class.getMethod("getParameterBindValues", (Class<?>[])null);
return true;
} catch (Exception e) {
return false;
}
}
public SQLExecutor(DomainTypeHandlerImpl<?> domainTypeHandler, List<String> columnNames, int numberOfParameters) {
this(domainTypeHandler, columnNames);
this.numberOfParameters = numberOfParameters;
}
public SQLExecutor(DomainTypeHandlerImpl<?> domainTypeHandler, List<String> columnNames) {
this.domainTypeHandler = domainTypeHandler;
this.columnNames = columnNames;
initializeFieldNumberMap();
}
public SQLExecutor(DomainTypeHandlerImpl<?> domainTypeHandler) {
this.domainTypeHandler = domainTypeHandler;
}
public SQLExecutor(DomainTypeHandlerImpl<?> domainTypeHandler, List<String> columnNames,
QueryDomainTypeImpl<?> queryDomainType) {
this(domainTypeHandler, columnNames);
this.queryDomainType = queryDomainType;
initializeFieldNumberMap();
}
public SQLExecutor(DomainTypeHandlerImpl<?> domainTypeHandler, QueryDomainTypeImpl<?> queryDomainType,
int numberOfParameters) {
this.domainTypeHandler = domainTypeHandler;
this.queryDomainType = queryDomainType;
this.numberOfParameters = numberOfParameters;
}
/** This is the public interface exposed to other parts of the component. Calling this
* method executes the SQL statement via the clusterj api, or returns null indicating that
* the JDBC driver should execute the SQL statement.
*/
public interface Executor {
/** Execute the SQL command
* @param session the clusterj session which must not be null
* @param preparedStatement the prepared statement
* @return the result of executing the statement, or null
* @throws SQLException
*/
ResultSetInternalMethods execute(InterceptorImpl interceptor,
PreparedStatement preparedStatement) throws SQLException;
}
/** This class implements the Executor contract but returns null, indicating that
* the JDBC driver should implement the call itself.
*/
public static class Noop implements Executor {
public ResultSetInternalMethods execute(InterceptorImpl interceptor,
PreparedStatement preparedStatement) throws SQLException {
return null;
}
}
/** This class implements the Executor contract for Select operations.
*/
public static class Select extends SQLExecutor implements Executor {
private LockMode lockMode;
public Select(DomainTypeHandlerImpl<?> domainTypeHandler, List<String> columnNames,
QueryDomainTypeImpl<?> queryDomainType, LockMode lockMode, int numberOfParameters) {
super(domainTypeHandler, columnNames, queryDomainType);
this.numberOfParameters = numberOfParameters;
this.lockMode = lockMode;
if (queryDomainType == null) {
throw new ClusterJFatalInternalException("queryDomainType must not be null for Select.");
}
}
public Select(DomainTypeHandlerImpl<?> domainTypeHandler,
List<String> columnNames, QueryDomainTypeImpl<?> queryDomainType, LockMode lockMode) {
this(domainTypeHandler, columnNames, queryDomainType, lockMode, 0);
}
public ResultSetInternalMethods execute(InterceptorImpl interceptor,
PreparedStatement preparedStatement) throws SQLException {
SessionSPI session = interceptor.getSession();
session.setLockMode(lockMode);
// create value handler to copy data from parameters to ndb
ValueHandlerBatching valueHandlerBatching = getValueHandler(preparedStatement, null);
if (valueHandlerBatching == null) {
return null;
}
int numberOfStatements = valueHandlerBatching.getNumberOfStatements();
if (numberOfStatements != 1) {
return null;
}
QueryExecutionContextJDBCImpl context =
new QueryExecutionContextJDBCImpl(session, valueHandlerBatching, numberOfParameters);
session.startAutoTransaction();
try {
valueHandlerBatching.next();
// TODO get skip and limit and ordering from the SQL query
ResultData resultData = queryDomainType.getResultData(context, 0L, Long.MAX_VALUE, null, null);
// session.endAutoTransaction();
return new ResultSetInternalMethodsImpl(resultData, columnNumberToFieldNumberMap,
columnNameToFieldNumberMap, session);
} catch (Exception e) {
e.printStackTrace();
session.failAutoTransaction();
return null;
}
}
}
/** This class implements the Executor contract for Delete operations.
*/
public static class Delete extends SQLExecutor implements Executor {
public Delete (DomainTypeHandlerImpl<?> domainTypeHandler, QueryDomainTypeImpl<?> queryDomainType,
int numberOfParameters) {
super(domainTypeHandler, queryDomainType, numberOfParameters);
}
public Delete (DomainTypeHandlerImpl<?> domainTypeHandler) {
super(domainTypeHandler);
}
public ResultSetInternalMethods execute(InterceptorImpl interceptor,
PreparedStatement preparedStatement) throws SQLException {
SessionSPI session = interceptor.getSession();
if (queryDomainType == null) {
int rowsDeleted = session.deletePersistentAll(domainTypeHandler);
if (logger.isDebugEnabled())
logger.debug("deleteAll deleted: " + rowsDeleted);
return new ResultSetInternalMethodsUpdateCount(rowsDeleted);
} else {
ValueHandlerBatching valueHandlerBatching = getValueHandler(preparedStatement, null);
if (valueHandlerBatching == null) {
return null;
}
int numberOfStatements = valueHandlerBatching.getNumberOfStatements();
if (logger.isDebugEnabled())
logger.debug("executing numberOfStatements: " + numberOfStatements
+ " with numberOfParameters: " + numberOfParameters);
long[] deleteResults = new long[numberOfStatements];
QueryExecutionContextJDBCImpl context =
new QueryExecutionContextJDBCImpl(session, valueHandlerBatching, numberOfParameters);
int i = 0;
while (valueHandlerBatching.next()) {
// this will execute each statement in the batch using different parameters
int statementRowsDeleted = queryDomainType.deletePersistentAll(context);
if (logger.isDebugEnabled())
logger.debug("statement " + i + " deleted " + statementRowsDeleted);
deleteResults[i++] = statementRowsDeleted;
}
return new ResultSetInternalMethodsUpdateCount(deleteResults);
}
}
}
/** This class implements the Executor contract for Insert operations.
*/
public static class Insert extends SQLExecutor implements Executor {
public Insert(DomainTypeHandlerImpl<?> domainTypeHandler, List<String> columnNames) {
super(domainTypeHandler, columnNames, columnNames.size());
}
public ResultSetInternalMethods execute(InterceptorImpl interceptor,
PreparedStatement preparedStatement) throws SQLException {
SessionSPI session = interceptor.getSession();
int numberOfBoundParameters = preparedStatement.getParameterMetaData().getParameterCount();
int numberOfStatements = numberOfBoundParameters / numberOfParameters;
if (logger.isDebugEnabled())
logger.debug("numberOfParameters: " + numberOfParameters
+ " numberOfBoundParameters: " + numberOfBoundParameters
+ " numberOfFields: " + numberOfFields
+ " numberOfStatements: " + numberOfStatements
);
// interceptor.beforeClusterjStart();
// session asks for values by field number which are converted to parameter number
ValueHandlerBatching valueHandler = getValueHandler(preparedStatement, fieldNumberToColumnNumberMap);
if (valueHandler == null) {
// we cannot handle this request
return null;
}
int count = 0;
while(valueHandler.next()) {
if (logger.isDetailEnabled()) logger.detail("inserting row " + count++);
session.insert(domainTypeHandler, valueHandler);
}
session.flush();
// interceptor.afterClusterjStart();
return new ResultSetInternalMethodsUpdateCount(numberOfStatements);
}
}
/** This class implements the Executor contract for Update operations.
*/
public static class Update extends SQLExecutor implements Executor {
/** Column names in the SET clause */
List<String> setColumnNames;
/** Parameter numbers corresponding to the columns in the SET clause */
List<Integer> setParameterNumbers;
/** Names of the columns in the WHERE clause */
List<String> whereColumnNames;
/** */
int[] fieldNumberToParameterNumberMap;
/** Construct an Update instance that encapsulates the information from the UPDATE statement.
* We begin with the simple case of a primary key or unique key update. We have the list
* of column names and parameter numbers that map to the SET clause,
* and the list of parameter numbers that map to the WHERE clause.
*
* @param domainTypeHandler the domain type handler
* @param queryDomainType the query domain type
* @param numberOfParameters the number of parameters per statement
* @param setColumnNames the column names in the SET clause
* @param setParameterNumbers the parameter numbers (1 origin) in the VALUES clause
*/
public Update (DomainTypeHandlerImpl<?> domainTypeHandler, QueryDomainTypeImpl<?> queryDomainType,
int numberOfParameters, List<String> setColumnNames, List<String> topLevelWhereColumnNames) {
super(domainTypeHandler, setColumnNames, queryDomainType);
if (logger.isDetailEnabled()) logger.detail("Constructor with numberOfParameters: " + numberOfParameters +
" setColumnNames: " + setColumnNames + " topLevelWhereColumnNames " + topLevelWhereColumnNames);
this.numberOfParameters = numberOfParameters;
this.whereColumnNames = topLevelWhereColumnNames;
initializeFieldNumberToParameterNumberMap(setColumnNames, topLevelWhereColumnNames);
}
/** Initialize the map from field number to parameter number.
* This map is used for the ValueHandler that handles the SET statement.
* The value handler is given the field number to update and this map
* returns the parameter number which is then given to the batching value handler
* to get the actual parameter from the parameter set of the batch.
*
* @param setColumnNames the names in the SET clause
* @param topLevelWhereColumnNames the names in the WHERE clause
*/
private void initializeFieldNumberToParameterNumberMap(List<String> setColumnNames,
List<String> topLevelWhereColumnNames) {
String[] fieldNames = this.domainTypeHandler.getFieldNames();
this.fieldNumberToParameterNumberMap = new int[fieldNames.length];
// the columns in the update statement include
// all the columns in the SET clause plus the columns in the WHERE clause
List<String> updateColumnNames = new ArrayList<String>(setColumnNames);
updateColumnNames.addAll(topLevelWhereColumnNames);
int columnNumber = 1;
for (String columnName: updateColumnNames) {
// for each column name, find the field number
for (int i = 0; i < fieldNames.length; ++i) {
if (fieldNames[i].equals(columnName)) {
fieldNumberToParameterNumberMap[i] = columnNumber;
break;
}
}
columnNumber++;
}
}
/** Execute the update statement.
* The list of column names and parameter numbers that map to the SET clause, and
* the list of column names and parameter numbers that map to the WHERE clause are provided.
* Construct a value handler that can handle primary key or unique key parameters,
* where clause parameters, and set clause parameters.
* Next, construct a context that allows iteration over the value handler for
* each set of parameters in the batch.
* @param interceptor the statement interceptor
* @param preparedStatement the prepared statement
* @return the result of executing the statement
*/
public ResultSetInternalMethods execute(InterceptorImpl interceptor,
PreparedStatement preparedStatement) throws SQLException {
SessionSPI session = interceptor.getSession();
// use the field-to-parameter-number map to create the value handler
int numberOfBoundParameters = preparedStatement.getParameterMetaData().getParameterCount();
int numberOfStatements = numberOfBoundParameters / numberOfParameters;
if (logger.isDebugEnabled())
logger.debug("numberOfParameters: " + numberOfParameters
+ " numberOfBoundParameters: " + numberOfBoundParameters
+ " numberOfFields: " + numberOfFields
+ " numberOfStatements: " + numberOfStatements
);
// valueHandlerBatching handles the WHERE clause parameters
ValueHandlerBatching valueHandlerBatching = getValueHandler(preparedStatement, null);
// valueHandlerSet handles the SET clause parameter value
ValueHandlerBatching valueHandlerSet =
new ValueHandlerBatchingJDBCSetImpl(fieldNumberToParameterNumberMap, valueHandlerBatching);
if (valueHandlerBatching == null) {
return null;
}
long[] updateResults = new long[numberOfStatements];
QueryExecutionContextJDBCImpl context =
new QueryExecutionContextJDBCImpl(session, valueHandlerBatching, numberOfParameters);
// execute the batch of updates
updateResults = queryDomainType.updatePersistentAll(context, valueHandlerSet);
if (logger.isDebugEnabled())
logger.debug("executing update with numberOfStatements: " + numberOfStatements
+ " and numberOfParameters: " + numberOfParameters
+ " results: " + Arrays.toString(updateResults));
if (updateResults == null) {
// cannot execute this update
return null;
} else {
return new ResultSetInternalMethodsUpdateCount(updateResults);
}
}
}
protected ValueHandlerBatching getValueHandler(
PreparedStatement preparedStatement, int[] fieldNumberToColumnNumberMap) {
ValueHandlerBatching result = null;
try {
int numberOfBoundParameters = preparedStatement.getParameterMetaData().getParameterCount();
int numberOfStatements = numberOfParameters == 0 ? 1 : numberOfBoundParameters / numberOfParameters;
if (logger.isDebugEnabled()) logger.debug(
" numberOfParameters: " + numberOfParameters
+ " numberOfBoundParameters: " + numberOfBoundParameters
+ " numberOfStatements: " + numberOfStatements
+ " fieldNumberToColumnNumberMap: " + Arrays.toString(fieldNumberToColumnNumberMap)
);
if (preparedStatement instanceof ServerPreparedStatement) {
if (bindValueSupport) {
ServerPreparedStatement serverPreparedStatement = (ServerPreparedStatement)preparedStatement;
BindValue[] bindValues = serverPreparedStatement.getParameterBindValues();
result = new ValueHandlerBindValuesImpl(bindValues, fieldNumberToColumnNumberMap,
numberOfStatements, numberOfParameters);
} else {
// note if you try to get parameter bindings from a server prepared statement, NPE in the driver
// so if it's a server prepared statement without bind value support, e.g. using a JDBC driver
// earlier than 5.1.17, returning null will allow the driver to pursue its normal path.
}
} else {
// not a server prepared statement; treat as regular prepared statement
ParameterBindings parameterBindings = preparedStatement.getParameterBindings();
result = new ValueHandlerImpl(parameterBindings, fieldNumberToColumnNumberMap,
numberOfStatements, numberOfParameters);
}
} catch (SQLException ex) {
throw new ClusterJDatastoreException(ex);
} catch (Throwable t) {
t.printStackTrace();
}
return result;
}
/** Create the parameter map assigning each bound parameter a number.
* The result is a map in which the key is a String whose key is a cardinal number
* starting with 1 (for JDBC which uses 1-origin for numbering)
* and whose value is the parameter's value.
* @param queryDomainType the query domain type
* @param parameterBindings the parameter bindings
* @param offset the number of parameters to skip
* @param count the number of parameters to use
* @return
* @throws SQLException
*/
protected Map<String, Object> createParameterMap(QueryDomainTypeImpl<?> queryDomainType,
ParameterBindings parameterBindings, int offset, int count) throws SQLException {
Map<String, Object> result = new HashMap<String, Object>();
int first = offset + 1;
int last = offset + count + 1;
for (int i = first; i < last; ++i) {
Object placeholder = parameterBindings.getObject(i);
if (logger.isDetailEnabled())
logger.detail("Put placeholder " + i + " value: " + placeholder + " of type " + placeholder.getClass());
result.put(String.valueOf(i), placeholder);
}
return result;
}
/** Initialize the mappings between the Java representation of the row (domain type handler)
* and the JDBC/database representation of the row. The JDBC driver asks for columns by column
* index or column name, 1-origin. The domain type handler returns data by field number, 0-origin.
* The domain type handler has representations for all columns in the database, whereas the JDBC
* driver has a specific set of columns referenced by the SQL statement.
* For insert, the column number to field number mapping will map parameters to field numbers,
* e.g. INSERT INTO EMPLOYEE (id, name, age) VALUES (?, ?, ?)
* For select, the column number to field number mapping will map result set columns to field numbers,
* e.g. SELECT id, name, age FROM EMPLOYEE
* For update, the column number to field number mapping will map parameters to field numbers,
* e.g. UPDATE EMPLOYEE SET age = ?, name = ? WHERE id = ?
*/
private void initializeFieldNumberMap() {
// the index into the int[] is the 0-origin field number (columns in order of definition in the schema)
// the value is the index into the parameter bindings (columns in order of the sql insert statement)
String[] fieldNames = domainTypeHandler.getFieldNames();
numberOfFields = fieldNames.length;
fieldNumberToColumnNumberMap = new int[numberOfFields];
columnNumberToFieldNumberMap = new int[1 + columnNames.size()];
for (int i= 0; i < numberOfFields; ++i) {
columnNameToFieldNumberMap.put(fieldNames[i], i);
int index = columnNames.indexOf(fieldNames[i]);
if (index >= 0) {
// index origin 1 for JDBC interfaces
fieldNumberToColumnNumberMap[i] = index + 1;
columnNumberToFieldNumberMap[index + 1] = i;
} else {
// field is not in column list
fieldNumberToColumnNumberMap[i] = -1;
}
}
// make sure all columns are fields and if not, throw an exception
for (String columnName: columnNames) {
if (columnNameToFieldNumberMap.get(columnName) == null) {
throw new ClusterJUserException(
local.message("ERR_Column_Name_Not_In_Table", columnName,
Arrays.toString(fieldNames),
domainTypeHandler.getTableName()));
}
}
if (logger.isDetailEnabled()) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < fieldNumberToColumnNumberMap.length; ++i) {
int columnNumber = fieldNumberToColumnNumberMap[i];
buffer.append("field ");
buffer.append(i);
buffer.append(" mapped to ");
buffer.append(columnNumber);
buffer.append("[");
buffer.append(columnNumber == -1?"nothing":(columnNames.get(columnNumber - 1)));
buffer.append("];");
}
logger.detail(buffer.toString());
}
}
/** If detailed logging is enabled write the parameter bindings to the log.
* @param parameterBindings the jdbc parameter bindings
*/
protected static void logParameterBindings(ParameterBindings parameterBindings) {
if (logger.isDetailEnabled()) {
int i = 0;
while (true) {
try {
String value = parameterBindings.getObject(++i).toString();
// parameters are 1-origin per jdbc specification
logger.detail("parameterBinding: parameter " + i + " has value: " + value);
} catch (Exception e) {
// we don't know how many parameters are bound...
break;
}
}
}
}
}
| gpl-2.0 |
release-engineering/pom-version-manipulator | src/main/java/com/redhat/rcm/version/maven/VManWorkspaceReader.java | 3414 | package com.redhat.rcm.version.maven;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.mae.project.key.VersionlessProjectKey;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.repository.WorkspaceReader;
import org.sonatype.aether.repository.WorkspaceRepository;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
public class VManWorkspaceReader
implements WorkspaceReader
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
private final WorkspaceRepository repo = new WorkspaceRepository( "vman", "vman" );
private final VersionManagerSession session;
private final Map<FullProjectKey, File> projectFiles = new HashMap<FullProjectKey, File>();
public VManWorkspaceReader( final VersionManagerSession session )
{
this.session = session;
}
@Override
public WorkspaceRepository getRepository()
{
return repo;
}
@Override
public synchronized File findArtifact( final Artifact artifact )
{
if ( !"pom".equals( artifact.getExtension() ) )
{
return null;
}
final FullProjectKey key =
new FullProjectKey( artifact.getArtifactId(), artifact.getGroupId(), artifact.getVersion() );
File f = projectFiles.get( key );
if ( f == null )
{
f = getSessionPOM( key );
if ( f != null )
{
projectFiles.put( key, f );
}
}
return f;
}
public File getSessionPOM( final FullProjectKey key )
{
File pom = session.getPeekedPom( key );
logger.info( "Peeked file for key: '{}' is: {}", key, pom );
if ( pom == null && key.equals( session.getToolchainKey() ) )
{
final MavenProject p = session.getToolchainProject();
pom = p.getFile();
}
if ( pom == null && session.isBom( key ) )
{
final MavenProject p = session.getBOMProject( key );
pom = p.getFile();
}
return pom;
}
@Override
public List<String> findVersions( final Artifact artifact )
{
final List<String> versions = new ArrayList<String>( 1 );
final VersionlessProjectKey vpk = new VersionlessProjectKey( artifact.getGroupId(), artifact.getArtifactId() );
final Project project = session.getCurrentProject( vpk );
if ( project != null )
{
versions.add( project.getVersion() );
}
else if ( vpk.equals( session.getToolchainKey() ) )
{
versions.add( session.getToolchainKey()
.getVersion() );
}
else
{
final List<FullProjectKey> bomCoords = session.getBomCoords();
for ( final FullProjectKey bomCoord : bomCoords )
{
if ( vpk.equals( bomCoord ) )
{
versions.add( bomCoord.getVersion() );
break;
}
}
}
return versions;
}
}
| gpl-3.0 |
bruni68510/flazr | src/main/java/com/flazr/rtmp/server/ServerStream.java | 3452 | /*
* Flazr <http://flazr.com> Copyright (C) 2009 Peter Thomas.
*
* This file is part of Flazr.
*
* Flazr is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Flazr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Flazr. If not, see <http://www.gnu.org/licenses/>.
*/
package com.flazr.rtmp.server;
import com.flazr.rtmp.RtmpMessage;
import com.flazr.util.Utils;
import java.util.ArrayList;
import java.util.List;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServerStream {
public static enum PublishType {
LIVE,
APPEND,
RECORD;
public String asString() {
return this.name().toLowerCase();
}
public static PublishType parse(final String raw) {
return PublishType.valueOf(raw.toUpperCase());
}
}
private final String name;
private final PublishType publishType;
private final ChannelGroup subscribers;
private final List<RtmpMessage> configMessages;
private Channel publisher;
private static final Logger logger = LoggerFactory.getLogger(ServerStream.class);
public ServerStream(final String rawName, final String typeString) {
this.name = Utils.trimSlashes(rawName).toLowerCase();
if(typeString != null) {
this.publishType = PublishType.parse(typeString); // TODO record, append
subscribers = new DefaultChannelGroup(name);
configMessages = new ArrayList<RtmpMessage>();
} else {
this.publishType = null;
subscribers = null;
configMessages = null;
}
logger.info("Created ServerStream {}", this);
}
public boolean isLive() {
return publishType != null && publishType == PublishType.LIVE;
}
public PublishType getPublishType() {
return publishType;
}
public ChannelGroup getSubscribers() {
return subscribers;
}
public String getName() {
return name;
}
public List<RtmpMessage> getConfigMessages() {
return configMessages;
}
public void addConfigMessage(final RtmpMessage message) {
configMessages.add(message);
}
public void setPublisher(Channel publisher) {
this.publisher = publisher;
configMessages.clear();
}
public Channel getPublisher() {
return publisher;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("[name: '").append(name);
sb.append("' type: ").append(publishType);
sb.append(" publisher: ").append(publisher);
sb.append(" subscribers: ").append(subscribers);
sb.append(" config: ").append(configMessages);
sb.append(']');
return sb.toString();
}
}
| gpl-3.0 |
jtux270/translate | ovirt/backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/RoleGroupMapDAO.java | 1252 | package org.ovirt.engine.core.dao;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.RoleGroupMap;
import org.ovirt.engine.core.compat.Guid;
/**
* <code>RoleGroupMapDOA</code> defines a type for performing CRUD operations on instances of {@link RoleGroupMap}.
*
*
*/
public interface RoleGroupMapDAO extends DAO {
/**
* Retrieves the mapping for the given group and role id.
*
* @param group
* the action group
* @param id
* the role id
* @return the mapping
*/
RoleGroupMap getByActionGroupAndRole(ActionGroup group, Guid id);
/**
* Retrieves the list of mappings for the given role id.
*
* @param id
* the role id
* @return the list of mappings
*/
List<RoleGroupMap> getAllForRole(Guid id);
/**
* Saves the specified map.
*
* @param map
* the map
*/
void save(RoleGroupMap map);
/**
* Removes the specified map.
*
* @param group
* the action group
* @param id
* the role id
*/
void remove(ActionGroup group, Guid id);
}
| gpl-3.0 |
khmarbaise/jqassistant | plugin/jaxrs/src/test/java/com/buschmais/jqassistant/plugin/jaxrs/test/set/beans/MySubResource.java | 188 | /**
*
*/
package com.buschmais.jqassistant.plugin.jaxrs.test.set.beans;
/**
* A simple sub resource interface.
*
* @author Aparna Chaudhary
*/
public interface MySubResource {
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Converter/src/test0177/Test.java | 169 | package test0177;
import java.util.*;
public class Test {
void bar() {
double i = 1.0;
System.out.println(i);
}
int foo() {
int i = 0;
i++;
return i;
}
} | gpl-3.0 |
cswhite2000/ProjectAres | Util/bukkit/src/main/java/tc/oc/commons/bukkit/util/NullPermissible.java | 3777 | package tc.oc.commons.bukkit.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
/**
* {@link Permissible} that never has any permissions. Mutating methods can be called,
* but will have no effect. The {@link #addAttachment} methods will create and return a
* {@link PermissionAttachment}, with the given permission set, but it will not actually
* be attached to anything.
*/
public class NullPermissible implements Permissible {
public static final NullPermissible INSTANCE = new NullPermissible();
@Override
public boolean isOp() {
return false;
}
@Override
public void setOp(boolean value) {
}
@Override
public boolean isPermissionSet(String name) {
return false;
}
@Override
public boolean isPermissionSet(Permission perm) {
return false;
}
@Override
public boolean hasPermission(String inName) {
return false;
}
@Override
public boolean hasPermission(Permission perm) {
return false;
}
@Override
public PermissionAttachment addAttachment(Plugin plugin) {
return new PermissionAttachment(plugin, this);
}
@Override
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) {
PermissionAttachment attachment = addAttachment(plugin);
attachment.setPermission(name, value);
return attachment;
}
@Override
public PermissionAttachment addAttachment(Plugin plugin, int i) {
return addAttachment(plugin);
}
@Override
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) {
return addAttachment(plugin, name, value);
}
@Override
public void removeAttachment(PermissionAttachment attachment) {
}
@Override
public void recalculatePermissions() {
}
@Override
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
return Collections.emptySet();
}
@Override
public boolean removeAttachments(Plugin plugin) {
return false;
}
@Override
public boolean removeAttachments(String name) {
return false;
}
@Override
public boolean removeAttachments(Permission permission) {
return false;
}
@Override
public boolean removeAttachments(Plugin plugin, String name) {
return false;
}
@Override
public boolean removeAttachments(Plugin plugin, Permission permission) {
return false;
}
@Override
public PermissionAttachmentInfo getEffectivePermission(String name) {
return null;
}
@Override
public Collection<PermissionAttachmentInfo> getAttachments() {
return Collections.emptyList();
}
@Override
public Collection<PermissionAttachmentInfo> getAttachments(Plugin plugin) {
return Collections.emptyList();
}
@Override
public Collection<PermissionAttachmentInfo> getAttachments(String name) {
return Collections.emptyList();
}
@Override
public Collection<PermissionAttachmentInfo> getAttachments(Permission permission) {
return Collections.emptyList();
}
@Override
public Collection<PermissionAttachmentInfo> getAttachments(Plugin plugin, String name) {
return Collections.emptyList();
}
@Override
public Collection<PermissionAttachmentInfo> getAttachments(Plugin plugin, Permission permission) {
return Collections.emptyList();
}
} | agpl-3.0 |
sanjupolus/KC6.oLatest | coeus-impl/src/main/java/org/kuali/kra/irb/auth/ProtocolReturnToPIAuthorizer.java | 2029 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.irb.auth;
import org.kuali.coeus.sys.framework.workflow.KcWorkflowService;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.irb.actions.ProtocolActionType;
/**
* Determine if a user can return a protocol to the principal investigator.
*/
public class ProtocolReturnToPIAuthorizer extends ProtocolAuthorizer {
private KcWorkflowService kraWorkflowService;
@Override
public boolean isAuthorized(String username, ProtocolTask task) {
return kraWorkflowService.isInWorkflow(task.getProtocol().getProtocolDocument()) &&
kraWorkflowService.isDocumentOnNode(task.getProtocol().getProtocolDocument(), Constants.PROTOCOL_IRBREVIEW_ROUTE_NODE_NAME) &&
canExecuteAction(task.getProtocol(), ProtocolActionType.RETURNED_TO_PI) &&
hasPermission(username, task.getProtocol(), PermissionConstants.PERFORM_IRB_ACTIONS_ON_PROTO);
}
public KcWorkflowService getKraWorkflowService() {
return kraWorkflowService;
}
public void setKraWorkflowService(KcWorkflowService kraWorkflowService) {
this.kraWorkflowService = kraWorkflowService;
}
}
| agpl-3.0 |
cswhite2000/ProjectAres | API/api/src/main/java/tc/oc/api/model/ModelsManifest.java | 1298 | package tc.oc.api.model;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import javax.inject.Singleton;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Key;
import com.google.inject.Provides;
import tc.oc.commons.core.inject.HybridManifest;
public class ModelsManifest extends HybridManifest implements ModelBinders {
@Provides @Singleton @ModelSync
ListeningExecutorService listeningModelSync(@ModelSync ExecutorService modelSync) {
return MoreExecutors.listeningDecorator(modelSync);
}
@Override
protected void configure() {
// @ModelSync ExecutorService must be bound elsewhere
final Key<Executor> executorKey = Key.get(Executor.class, ModelSync.class);
final Key<ExecutorService> executorServiceKey = Key.get(ExecutorService.class, ModelSync.class);
final Key<ListeningExecutorService> listeningExecutorServiceKey = Key.get(ListeningExecutorService.class, ModelSync.class);
bind(executorKey).to(executorServiceKey);
expose(executorKey);
expose(executorServiceKey);
expose(listeningExecutorServiceKey);
new ModelListenerBinder(publicBinder());
}
}
| agpl-3.0 |
evolvedmicrobe/beast-mcmc | src/dr/inference/model/JointParameter.java | 5735 | /*
* CompositeParameter.java
*
* Copyright (C) 2002-2013 Alexei Drummond, Andrew Rambaut & Marc A. Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.inference.model;
import java.util.ArrayList;
/**
* A parameter which controls the values of a set of other parameters
*
* @author Andrew Rambaut
* @version $Id$
*/
public class JointParameter extends Parameter.Abstract implements VariableListener {
public JointParameter(String name, Parameter[] params) {
this(name);
for (Parameter parameter : params) {
addParameter(parameter);
}
}
public JointParameter(String name) {
this.name = name;
dimension = 0;
}
public void addParameter(Parameter param) {
if (dimension == 0) {
dimension = param.getDimension();
} else {
for (int dim = 0; dim < dimension; dim++) {
param.setParameterValue(dim, parameters.get(0).getParameterValue(dim));
}
if (param.getDimension() != dimension) {
throw new RuntimeException("subsequent parameters do not match the dimensionality of the first");
}
}
// AR - I think we ignore the messages from the containing parameters. Possibly would be a good
// idea to check they don't change independently of this one.
// param.addParameterListener(this);
parameters.add(param);
}
/**
* @return name if the parameter has been given a specific name, else it returns getId()
*/
public final String getParameterName() {
if (name != null) return name;
return getId();
}
public int getDimension() {
return dimension;
}
public void setDimension(int dim) {
throw new RuntimeException();
}
public void addBounds(Bounds<Double> bounds) {
throw new RuntimeException("Can't add bounds to a joint parameter, only its components");
}
public Bounds<Double> getBounds() {
return parameters.get(0).getBounds();
}
public void addDimension(int index, double value) {
throw new RuntimeException();
}
public double removeDimension(int index) {
throw new RuntimeException();
}
public double getParameterValue(int dim) {
return parameters.get(0).getParameterValue(dim);
}
public void setParameterValue(int dim, double value) {
for (Parameter parameter : parameters) {
parameter.setParameterValue(dim, value);
}
}
public void setParameterValueQuietly(int dim, double value) {
for (Parameter parameter : parameters) {
parameter.setParameterValueQuietly(dim, value);
}
}
public void setParameterValueNotifyChangedAll(int dim, double value){
for (Parameter parameter : parameters) {
parameter.setParameterValueNotifyChangedAll(dim, value);
}
}
protected void storeValues() {
for (Parameter parameter : parameters) {
parameter.storeParameterValues();
}
}
protected void restoreValues() {
for (Parameter parameter : parameters) {
parameter.restoreParameterValues();
}
}
protected final void acceptValues() {
for (Parameter parameter : parameters) {
parameter.acceptParameterValues();
}
}
protected final void adoptValues(Parameter source) {
// the parameters that make up a compound parameter will have
// this function called on them individually so we don't need
// to do anything here.
}
public String toString() {
StringBuffer buffer = new StringBuffer(String.valueOf(getParameterValue(0)));
final Bounds bounds = getBounds();
buffer.append("[").append(String.valueOf(bounds.getLowerLimit(0)));
buffer.append(",").append(String.valueOf(bounds.getUpperLimit(0))).append("]");
for (int i = 1; i < getDimension(); i++) {
buffer.append(", ").append(String.valueOf(getParameterValue(i)));
buffer.append("[").append(String.valueOf(bounds.getLowerLimit(i)));
buffer.append(",").append(String.valueOf(bounds.getUpperLimit(i))).append("]");
}
return buffer.toString();
}
// ****************************************************************
// Parameter listener interface
// ****************************************************************
public void variableChangedEvent(Variable variable, int index, ChangeType type) {
if (variable.getSize() > 1) {
fireParameterChangedEvent(index, type);
} else {
fireParameterChangedEvent();
}
}
private final ArrayList<Parameter> parameters = new ArrayList<Parameter>();
private int dimension;
private String name;
}
| lgpl-2.1 |
rbharath26/abixen-platform | abixen-platform-core/src/main/java/com/abixen/platform/core/controller/application/ApplicationPageController.java | 2375 | /**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.abixen.platform.core.controller.application;
import com.abixen.platform.core.controller.common.AbstractPageController;
import com.abixen.platform.core.converter.PageToPageDtoConverter;
import com.abixen.platform.core.dto.PageDto;
import com.abixen.platform.core.model.impl.Page;
import com.abixen.platform.core.service.LayoutService;
import com.abixen.platform.core.service.PageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequestMapping(value = "/api/application/pages")
public class ApplicationPageController extends AbstractPageController {
private final PageService pageService;
private final LayoutService layoutService;
private final PageToPageDtoConverter pageToPageDtoConverter;
@Autowired
public ApplicationPageController(PageService pageService,
LayoutService layoutService,
PageToPageDtoConverter pageToPageDtoConverter) {
super(pageService);
this.pageService = pageService;
this.layoutService = layoutService;
this.pageToPageDtoConverter = pageToPageDtoConverter;
}
@RequestMapping(value = "", method = RequestMethod.GET)
public List<PageDto> getPages() {
log.debug("getPages()");
List<Page> pages = pageService.findAllPages();
pages.forEach(page -> {
layoutService.convertPageLayoutToJson(page);
});
return pageToPageDtoConverter.convertToList(pages);
}
} | lgpl-2.1 |
liujed/polyglot-eclipse | examples/coffer/compiler/src/coffer/types/CofferSubstClassType_c.java | 1787 | /*
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2006 Polyglot project group, Cornell University
*
*/
package coffer.types;
import java.util.ArrayList;
import java.util.List;
import polyglot.ext.param.types.PClass;
import polyglot.ext.param.types.SubstClassType_c;
import polyglot.types.ClassType;
import polyglot.util.Position;
import polyglot.util.SerialVersionUID;
public class CofferSubstClassType_c extends SubstClassType_c<Key, Key>
implements CofferSubstType {
private static final long serialVersionUID = SerialVersionUID.generate();
public CofferSubstClassType_c(CofferTypeSystem ts, Position pos,
ClassType base, CofferSubst subst) {
super(ts, pos, base, subst);
}
////////////////////////////////////////////////////////////////
// Implement methods of CofferSubstType
@Override
public PClass<Key, Key> instantiatedFrom() {
return ((CofferParsedClassType) base).instantiatedFrom();
}
@Override
public List<Key> actuals() {
PClass<Key, Key> pc = instantiatedFrom();
CofferSubst subst = (CofferSubst) this.subst;
List<Key> actuals = new ArrayList<Key>(pc.formals().size());
for (Key key : pc.formals()) {
actuals.add(subst.substKey(key));
}
return actuals;
}
////////////////////////////////////////////////////////////////
// Implement methods of CofferClassType
@Override
public Key key() {
CofferClassType base = (CofferClassType) this.base;
CofferSubst subst = (CofferSubst) this.subst;
return subst.substKey(base.key());
}
@Override
public String toString() {
return "tracked(" + subst + ") " + base;
}
}
| lgpl-2.1 |
trejkaz/swingx | swingx-core/src/main/java/org/jdesktop/swingx/treetable/SimpleFileSystemModel.java | 6862 | /*
* $Id$
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.treetable;
import java.io.File;
import java.util.Date;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreePath;
/**
* A tree table model to simulate a file system.
* <p>
* This tree table model implementation does not extends
* {@code AbstractTreeTableModel}. The file system metaphor demonstrates that
* it is often easier to directly implement tree structures directly instead of
* using intermediaries, such as {@code TreeNode}.
* <p>
* It would be possible to create this same class by extending
* {@code AbstractTreeTableModel}, however the number of methods that you would
* need to override almost precludes that means of implementation.
* <p>
* A "full" version of this model might allow editing of file names, the
* deletion of files, and the movement of files. This simple implementation does
* not intend to tackle such problems, but this implementation may be extended
* to handle such details.
*
* @author Ramesh Gupta
* @author Karl Schaefer
*/
public class SimpleFileSystemModel implements TreeTableModel {
protected EventListenerList listenerList;
// the returned file length for directories
private static final Long ZERO = Long.valueOf(0);
private File root;
/**
* Creates a file system model, using the root directory as the model root.
*/
public SimpleFileSystemModel() {
this(new File(File.separator));
}
/**
* Creates a file system model, using the specified {@code root} as the
* model root.
*/
public SimpleFileSystemModel(File root) {
this.root = root;
this.listenerList = new EventListenerList();
}
/**
* {@inheritDoc}
*/
@Override
public File getChild(Object parent, int index) {
if (parent instanceof File) {
File parentFile = (File) parent;
File[] files = parentFile.listFiles();
if (files != null) {
return files[index];
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int getChildCount(Object parent) {
if (parent instanceof File) {
String[] children = ((File) parent).list();
if (children != null) {
return children.length;
}
}
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getColumnClass(int column) {
switch(column) {
case 0:
return String.class;
case 1:
return Long.class;
case 2:
return Boolean.class;
case 3:
return Date.class;
default:
return Object.class;
}
}
/**
* {@inheritDoc}
*/
@Override
public int getColumnCount() {
return 4;
}
/**
* {@inheritDoc}
*/
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "Name";
case 1:
return "Size";
case 2:
return "Directory";
case 3:
return "Modification Date";
default:
return "Column " + column;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getValueAt(Object node, int column) {
if (node instanceof File) {
File file = (File) node;
switch (column) {
case 0:
return file.getName();
case 1:
return file.isFile() ? file.length() : ZERO;
case 2:
return file.isDirectory();
case 3:
return new Date(file.lastModified());
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int getHierarchicalColumn() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCellEditable(Object node, int column) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void setValueAt(Object value, Object node, int column) {
//does nothing
}
/**
* {@inheritDoc}
*/
@Override
public void addTreeModelListener(TreeModelListener l) {
listenerList.add(TreeModelListener.class, l);
}
/**
* {@inheritDoc}
*/
@Override
public int getIndexOfChild(Object parent, Object child) {
if (parent instanceof File && child instanceof File) {
File parentFile = (File) parent;
File[] files = parentFile.listFiles();
for (int i = 0, len = files.length; i < len; i++) {
if (files[i].equals(child)) {
return i;
}
}
}
return -1;
}
/**
* {@inheritDoc}
*/
@Override
public File getRoot() {
return root;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLeaf(Object node) {
if (node instanceof File) {
//do not use isFile(); some system files return false
return ((File) node).list() == null;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void removeTreeModelListener(TreeModelListener l) {
listenerList.remove(TreeModelListener.class, l);
}
/**
* {@inheritDoc}
*/
@Override
public void valueForPathChanged(TreePath path, Object newValue) {
//does nothing
}
/**
* Gets a an array of all the listeners attached to this model.
*
* @return an array of listeners; this array is guaranteed to be
* non-{@code null}
*/
public TreeModelListener[] getTreeModelListeners() {
return listenerList.getListeners(TreeModelListener.class);
}
}
| lgpl-2.1 |
jayway/powermock | powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java | 4415 | /*
* Copyright 2016 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.powermock.api.mockito.mockpolicies;
import org.mockito.Mockito;
import org.powermock.core.spi.PowerMockPolicy;
import org.powermock.mockpolicies.MockPolicyClassLoadingSettings;
import org.powermock.mockpolicies.MockPolicyInterceptionSettings;
import org.powermock.mockpolicies.support.LogPolicySupport;
import java.lang.reflect.Method;
/**
* Sfl4j mock policy that injects a Mockito-created mock to be returned on calls to getLogger factory methods.
* The implementation returns a single mock instance per thread but it doesn't return a different mock instance based
* on the actual value passed to getLogger. This limitation is acceptable in most real uses cases.
* <p/>
* Tests that want to do verifications on the mocked logger can do so by getting the mocked instance as production code
* does: {@code org.slf4j.LoggerFactory.getLogger(Class)}. However, it is critical that the mocked logger is
* reset after each test in order to avoid crosstalk between test cases.
* <p/>
*
* @author Alexandre Normand <alexandre.normand@gmail.com>
*/
public class Slf4jMockPolicy implements PowerMockPolicy {
private static final String LOGGER_FACTORY_CLASS_NAME = "org.slf4j.LoggerFactory";
private static final String LOGGER_FACTORY_METHOD_NAME = "getLogger";
private static final String FRAMEWORK_NAME = "sfl4j";
private static final String LOGGER_CLASS_NAME = "org.slf4j.Logger";
private static ThreadLocal<Object> threadLogger = new ThreadLocal<Object>();
@Override
public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings mockPolicyClassLoadingSettings) {
mockPolicyClassLoadingSettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(
LOGGER_FACTORY_CLASS_NAME,
"org.apache.log4j.Appender",
"org.apache.log4j.xml.DOMConfigurator");
}
@Override
public void applyInterceptionPolicy(MockPolicyInterceptionSettings mockPolicyInterceptionSettings) {
LogPolicySupport logPolicySupport = new LogPolicySupport();
Method[] loggerFactoryMethods = logPolicySupport.getLoggerMethods(LOGGER_FACTORY_CLASS_NAME,
LOGGER_FACTORY_METHOD_NAME, FRAMEWORK_NAME);
initializeMockForThread(logPolicySupport);
for (Method loggerFactoryMethod : loggerFactoryMethods) {
mockPolicyInterceptionSettings.stubMethod(loggerFactoryMethod, threadLogger.get());
}
}
private void initializeMockForThread(LogPolicySupport logPolicySupport) {
Class<?> loggerClass = getLoggerClass(logPolicySupport);
if (threadLogger.get() == null) {
/*
* When mocking with Mockito we need to change the context CL to the same CL that is loading Mockito
* otherwise the Mockito plugin mechanism will load the PowerMockMaker from the wrong classloader.
*/
final ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
final ClassLoader classLoader = Mockito.class.getClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
final Object mock;
try {
mock = Mockito.mock(loggerClass);
} finally {
Thread.currentThread().setContextClassLoader(originalCl);
}
threadLogger.set(mock);
}
}
private Class<?> getLoggerClass(LogPolicySupport logPolicySupport) {
Class<?> loggerType;
try {
loggerType = logPolicySupport.getType(LOGGER_CLASS_NAME, FRAMEWORK_NAME);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
return loggerType;
}
} | apache-2.0 |
niv0/isis | core/metamodel/src/main/java/org/apache/isis/core/commons/exceptions/UnknownTypeException.java | 1199 | /*
* 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.isis.core.commons.exceptions;
public class UnknownTypeException extends IsisException {
private static final long serialVersionUID = 1L;
public UnknownTypeException(final String message) {
super(message);
}
public UnknownTypeException(final Object object) {
this(object == null ? "null" : object.toString());
}
}
| apache-2.0 |
DariusX/camel | core/camel-core/src/test/java/org/apache/camel/language/simple/SimpleRouteExpressionAsPredicateTest.java | 2119 | /*
* 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.language.simple;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class SimpleRouteExpressionAsPredicateTest extends ContextTestSupport {
@Test
public void testSimpleRouteExpressionAsPredicateTest() throws Exception {
getMockEndpoint("mock:foo").expectedBodiesReceived(true);
getMockEndpoint("mock:bar").expectedBodiesReceived("ABC == ABC");
template.sendBodyAndHeader("direct:foo", "Hello World", "foo", "ABC");
template.sendBodyAndHeader("direct:bar", "Hello World", "bar", "ABC");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:foo")
// evaluate as predicate because the result type is boolean
.setBody().simple("${header.foo} == ${header.foo}", boolean.class).to("mock:foo");
from("direct:bar")
// evaluate as expression as no boolean as result type
.setBody().simple("${header.bar} == ${header.bar}").to("mock:bar");
}
};
}
}
| apache-2.0 |
andysiahaan90/Atlas-Android | layer-atlas/src/main/java/com/layer/atlas/AtlasMessageComposer.java | 9657 | /*
* Copyright (c) 2015 Layer. 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 com.layer.atlas;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.layer.sdk.LayerClient;
import com.layer.sdk.exceptions.LayerException;
import com.layer.sdk.listeners.LayerTypingIndicatorListener;
import com.layer.sdk.messaging.Conversation;
import com.layer.sdk.messaging.Message;
import com.layer.sdk.messaging.MessagePart;
/**
* @author Oleg Orlov
* @since 12 May 2015
*/
public class AtlasMessageComposer extends FrameLayout {
private static final String TAG = AtlasMessageComposer.class.getSimpleName();
private static final boolean debug = false;
private EditText messageText;
private View btnSend;
private View btnUpload;
private Listener listener;
private Conversation conv;
private LayerClient layerClient;
private ArrayList<MenuItem> menuItems = new ArrayList<MenuItem>();
// styles
private int textColor;
private float textSize;
private Typeface typeFace;
private int textStyle;
//
public AtlasMessageComposer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
parseStyle(context, attrs, defStyle);
}
public AtlasMessageComposer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AtlasMessageComposer(Context context) {
super(context);
}
public void parseStyle(Context context, AttributeSet attrs, int defStyle) {
TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AtlasMessageComposer, R.attr.AtlasMessageComposer, defStyle);
this.textColor = ta.getColor(R.styleable.AtlasMessageComposer_composerTextColor, context.getResources().getColor(R.color.atlas_text_black));
//this.textSize = ta.getDimension(R.styleable.AtlasMessageComposer_composerTextSize, context.getResources().getDimension(R.dimen.atlas_text_size_general));
this.textStyle = ta.getInt(R.styleable.AtlasMessageComposer_composerTextStyle, Typeface.NORMAL);
String typeFaceName = ta.getString(R.styleable.AtlasMessageComposer_composerTextTypeface);
this.typeFace = typeFaceName != null ? Typeface.create(typeFaceName, textStyle) : null;
ta.recycle();
}
/**
* Initialization is required to engage MessageComposer with LayerClient and Conversation
* to send messages.
* <p>
* If Conversation is not defined, "Send" action will not be able to send messages
*
* @param client - must be not null
* @param conversation - could be null. Conversation could be provided later using {@link #setConversation(Conversation)}
*/
public void init(LayerClient client, Conversation conversation) {
if (client == null) throw new IllegalArgumentException("LayerClient cannot be null");
if (messageText != null) throw new IllegalStateException("AtlasMessageComposer is already initialized!");
this.layerClient = client;
this.conv = conversation;
LayoutInflater.from(getContext()).inflate(R.layout.atlas_message_composer, this);
btnUpload = findViewById(R.id.atlas_message_composer_upload);
btnUpload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final PopupWindow popupWindow = new PopupWindow(v.getContext());
popupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LayoutInflater inflater = LayoutInflater.from(v.getContext());
LinearLayout menu = (LinearLayout) inflater.inflate(R.layout.atlas_view_message_composer_menu, null);
popupWindow.setContentView(menu);
for (MenuItem item : menuItems) {
View itemConvert = inflater.inflate(R.layout.atlas_view_message_composer_menu_convert, menu, false);
TextView titleText = ((TextView) itemConvert.findViewById(R.id.altas_view_message_composer_convert_text));
titleText.setText(item.title);
itemConvert.setTag(item);
itemConvert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
popupWindow.dismiss();
MenuItem item = (MenuItem) v.getTag();
if (item.clickListener != null) {
item.clickListener.onClick(v);
}
}
});
menu.addView(itemConvert);
}
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setOutsideTouchable(true);
int[] viewXYWindow = new int[2];
v.getLocationInWindow(viewXYWindow);
menu.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int menuHeight = menu.getMeasuredHeight();
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, viewXYWindow[0], viewXYWindow[1] - menuHeight);
}
});
messageText = (EditText) findViewById(R.id.atlas_message_composer_text);
messageText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (conv == null) return;
try {
if (s.length() > 0) {
conv.send(LayerTypingIndicatorListener.TypingIndicator.STARTED);
} else {
conv.send(LayerTypingIndicatorListener.TypingIndicator.FINISHED);
}
} catch (LayerException e) {
// `e.getType() == LayerException.Type.CONVERSATION_DELETED`
}
}
});
btnSend = findViewById(R.id.atlas_message_composer_send);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String text = messageText.getText().toString();
if (text.trim().length() > 0) {
ArrayList<MessagePart> parts = new ArrayList<MessagePart>();
String[] lines = text.split("\n+");
for (String line : lines) {
parts.add(layerClient.newMessagePart(line));
}
Message msg = layerClient.newMessage(parts);
if (listener != null) {
boolean proceed = listener.beforeSend(msg);
if (!proceed) return;
} else if (conv == null) {
Log.e(TAG, "Cannot send message. Conversation is not set");
}
if (conv == null) return;
conv.send(msg);
messageText.setText("");
}
}
});
applyStyle();
}
private void applyStyle() {
//messageText.setTextSize(textSize);
messageText.setTypeface(typeFace, textStyle);
messageText.setTextColor(textColor);
}
public void registerMenuItem(String title, OnClickListener clickListener) {
if (title == null) throw new NullPointerException("Item title must not be null");
MenuItem item = new MenuItem();
item.title = title;
item.clickListener = clickListener;
menuItems.add(item);
btnUpload.setVisibility(View.VISIBLE);
}
public void setListener(Listener listener) {
this.listener = listener;
}
public Conversation getConversation() {
return conv;
}
public void setConversation(Conversation conv) {
this.conv = conv;
}
public interface Listener {
boolean beforeSend(Message message);
}
private static class MenuItem {
String title;
OnClickListener clickListener;
}
}
| apache-2.0 |
laki88/carbon-apimgt | dependencies/synapse/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/connections/HostConnections.java | 4732 | /**
* Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) 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.apache.synapse.transport.passthru.connections;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* This stores connections for a particular host + port.
*/
public class HostConnections {
private static final Log log = LogFactory.getLog(HostConnections.class);
// route
private final HttpRoute route;
// maximum number of connections allowed for this host + port
private final int maxSize;
// number of awaiting connections
private int pendingConnections;
// list of free connections available
private List<NHttpClientConnection> freeConnections = new ArrayList<NHttpClientConnection>();
// list of connections in use
private List<NHttpClientConnection> busyConnections = new ArrayList<NHttpClientConnection>();
private Lock lock = new ReentrantLock();
public HostConnections(HttpRoute route, int maxSize) {
if (log.isDebugEnabled()) {
log.debug("Creating new connection pool: " + route);
}
this.route = route;
this.maxSize = maxSize;
}
/**
* Get a connection for the host:port
*
* @return a connection
*/
public NHttpClientConnection getConnection() {
lock.lock();
try {
if (freeConnections.size() > 0) {
if (log.isDebugEnabled()) {
log.debug("Returning an existing free connection " + route);
}
NHttpClientConnection conn = freeConnections.get(0);
freeConnections.remove(conn);
busyConnections.add(conn);
return conn;
}
} finally {
lock.unlock();
}
return null;
}
public void release(NHttpClientConnection conn) {
conn.getMetrics().reset();
HttpContext ctx = conn.getContext();
ctx.removeAttribute(ExecutionContext.HTTP_REQUEST);
ctx.removeAttribute(ExecutionContext.HTTP_RESPONSE);
lock.lock();
try {
if (busyConnections.remove(conn)) {
freeConnections.add(conn);
} else {
log.error("Attempted to releaseConnection connection not in the busy list");
}
} finally {
lock.unlock();
}
}
public void forget(NHttpClientConnection conn) {
lock.lock();
try {
if (!freeConnections.remove(conn)) {
busyConnections.remove(conn);
}
} finally {
lock.unlock();
}
}
public void addConnection(NHttpClientConnection conn) {
if (log.isDebugEnabled()) {
log.debug("New connection " + route + " is added to the free list");
}
lock.lock();
try {
busyConnections.add(conn);
} finally {
lock.unlock();
}
}
/**
* Indicates that a connection has been successfully established with a remote server
* as notified by the session request call back.
*/
public synchronized void pendingConnectionSucceeded() {
lock.lock();
try {
pendingConnections--;
} finally {
lock.unlock();
}
}
/**
* Keep track of the number of times connections to this host:port has failed
* consecutively
*/
public void pendingConnectionFailed() {
lock.lock();
try {
pendingConnections--;
} finally {
lock.unlock();
}
}
public HttpRoute getRoute() {
return route;
}
public boolean canHaveMoreConnections() {
return busyConnections.size() + pendingConnections < maxSize;
}
}
| apache-2.0 |
mirkosertic/Bytecoder | classlib/java.base/src/main/resources/META-INF/modules/java.base/classes/jdk/internal/org/objectweb/asm/util/CheckMethodAdapter.java | 61495 | /*
* 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 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.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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.
*/
package jdk.internal.org.objectweb.asm.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jdk.internal.org.objectweb.asm.AnnotationVisitor;
import jdk.internal.org.objectweb.asm.Attribute;
import jdk.internal.org.objectweb.asm.ConstantDynamic;
import jdk.internal.org.objectweb.asm.Handle;
import jdk.internal.org.objectweb.asm.Label;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.TypePath;
import jdk.internal.org.objectweb.asm.TypeReference;
import jdk.internal.org.objectweb.asm.tree.MethodNode;
import jdk.internal.org.objectweb.asm.tree.analysis.Analyzer;
import jdk.internal.org.objectweb.asm.tree.analysis.AnalyzerException;
import jdk.internal.org.objectweb.asm.tree.analysis.BasicValue;
import jdk.internal.org.objectweb.asm.tree.analysis.BasicVerifier;
/**
* A {@link MethodVisitor} that checks that its methods are properly used. More precisely this
* method adapter checks each instruction individually, i.e., each visit method checks some
* preconditions based <i>only</i> on its arguments - such as the fact that the given opcode is
* correct for a given visit method. This adapter can also perform some basic data flow checks (more
* precisely those that can be performed without the full class hierarchy - see {@link
* jdk.internal.org.objectweb.asm.tree.analysis.BasicVerifier}). For instance in a method whose signature is
* {@code void m ()}, the invalid instruction IRETURN, or the invalid sequence IADD L2I will be
* detected if the data flow checks are enabled. These checks are enabled by using the {@link
* #CheckMethodAdapter(int,String,String,MethodVisitor,Map)} constructor. They are not performed if
* any other constructor is used.
*
* @author Eric Bruneton
*/
public class CheckMethodAdapter extends MethodVisitor {
/** The 'generic' instruction visit methods (i.e. those that take an opcode argument). */
private enum Method {
VISIT_INSN,
VISIT_INT_INSN,
VISIT_VAR_INSN,
VISIT_TYPE_INSN,
VISIT_FIELD_INSN,
VISIT_METHOD_INSN,
VISIT_JUMP_INSN
}
/** The method to use to visit each instruction. Only generic methods are represented here. */
private static final Method[] OPCODE_METHODS = {
Method.VISIT_INSN, // NOP
Method.VISIT_INSN, // ACONST_NULL
Method.VISIT_INSN, // ICONST_M1
Method.VISIT_INSN, // ICONST_0
Method.VISIT_INSN, // ICONST_1
Method.VISIT_INSN, // ICONST_2
Method.VISIT_INSN, // ICONST_3
Method.VISIT_INSN, // ICONST_4
Method.VISIT_INSN, // ICONST_5
Method.VISIT_INSN, // LCONST_0
Method.VISIT_INSN, // LCONST_1
Method.VISIT_INSN, // FCONST_0
Method.VISIT_INSN, // FCONST_1
Method.VISIT_INSN, // FCONST_2
Method.VISIT_INSN, // DCONST_0
Method.VISIT_INSN, // DCONST_1
Method.VISIT_INT_INSN, // BIPUSH
Method.VISIT_INT_INSN, // SIPUSH
null, // LDC
null, // LDC_W
null, // LDC2_W
Method.VISIT_VAR_INSN, // ILOAD
Method.VISIT_VAR_INSN, // LLOAD
Method.VISIT_VAR_INSN, // FLOAD
Method.VISIT_VAR_INSN, // DLOAD
Method.VISIT_VAR_INSN, // ALOAD
null, // ILOAD_0
null, // ILOAD_1
null, // ILOAD_2
null, // ILOAD_3
null, // LLOAD_0
null, // LLOAD_1
null, // LLOAD_2
null, // LLOAD_3
null, // FLOAD_0
null, // FLOAD_1
null, // FLOAD_2
null, // FLOAD_3
null, // DLOAD_0
null, // DLOAD_1
null, // DLOAD_2
null, // DLOAD_3
null, // ALOAD_0
null, // ALOAD_1
null, // ALOAD_2
null, // ALOAD_3
Method.VISIT_INSN, // IALOAD
Method.VISIT_INSN, // LALOAD
Method.VISIT_INSN, // FALOAD
Method.VISIT_INSN, // DALOAD
Method.VISIT_INSN, // AALOAD
Method.VISIT_INSN, // BALOAD
Method.VISIT_INSN, // CALOAD
Method.VISIT_INSN, // SALOAD
Method.VISIT_VAR_INSN, // ISTORE
Method.VISIT_VAR_INSN, // LSTORE
Method.VISIT_VAR_INSN, // FSTORE
Method.VISIT_VAR_INSN, // DSTORE
Method.VISIT_VAR_INSN, // ASTORE
null, // ISTORE_0
null, // ISTORE_1
null, // ISTORE_2
null, // ISTORE_3
null, // LSTORE_0
null, // LSTORE_1
null, // LSTORE_2
null, // LSTORE_3
null, // FSTORE_0
null, // FSTORE_1
null, // FSTORE_2
null, // FSTORE_3
null, // DSTORE_0
null, // DSTORE_1
null, // DSTORE_2
null, // DSTORE_3
null, // ASTORE_0
null, // ASTORE_1
null, // ASTORE_2
null, // ASTORE_3
Method.VISIT_INSN, // IASTORE
Method.VISIT_INSN, // LASTORE
Method.VISIT_INSN, // FASTORE
Method.VISIT_INSN, // DASTORE
Method.VISIT_INSN, // AASTORE
Method.VISIT_INSN, // BASTORE
Method.VISIT_INSN, // CASTORE
Method.VISIT_INSN, // SASTORE
Method.VISIT_INSN, // POP
Method.VISIT_INSN, // POP2
Method.VISIT_INSN, // DUP
Method.VISIT_INSN, // DUP_X1
Method.VISIT_INSN, // DUP_X2
Method.VISIT_INSN, // DUP2
Method.VISIT_INSN, // DUP2_X1
Method.VISIT_INSN, // DUP2_X2
Method.VISIT_INSN, // SWAP
Method.VISIT_INSN, // IADD
Method.VISIT_INSN, // LADD
Method.VISIT_INSN, // FADD
Method.VISIT_INSN, // DADD
Method.VISIT_INSN, // ISUB
Method.VISIT_INSN, // LSUB
Method.VISIT_INSN, // FSUB
Method.VISIT_INSN, // DSUB
Method.VISIT_INSN, // IMUL
Method.VISIT_INSN, // LMUL
Method.VISIT_INSN, // FMUL
Method.VISIT_INSN, // DMUL
Method.VISIT_INSN, // IDIV
Method.VISIT_INSN, // LDIV
Method.VISIT_INSN, // FDIV
Method.VISIT_INSN, // DDIV
Method.VISIT_INSN, // IREM
Method.VISIT_INSN, // LREM
Method.VISIT_INSN, // FREM
Method.VISIT_INSN, // DREM
Method.VISIT_INSN, // INEG
Method.VISIT_INSN, // LNEG
Method.VISIT_INSN, // FNEG
Method.VISIT_INSN, // DNEG
Method.VISIT_INSN, // ISHL
Method.VISIT_INSN, // LSHL
Method.VISIT_INSN, // ISHR
Method.VISIT_INSN, // LSHR
Method.VISIT_INSN, // IUSHR
Method.VISIT_INSN, // LUSHR
Method.VISIT_INSN, // IAND
Method.VISIT_INSN, // LAND
Method.VISIT_INSN, // IOR
Method.VISIT_INSN, // LOR
Method.VISIT_INSN, // IXOR
Method.VISIT_INSN, // LXOR
null, // IINC
Method.VISIT_INSN, // I2L
Method.VISIT_INSN, // I2F
Method.VISIT_INSN, // I2D
Method.VISIT_INSN, // L2I
Method.VISIT_INSN, // L2F
Method.VISIT_INSN, // L2D
Method.VISIT_INSN, // F2I
Method.VISIT_INSN, // F2L
Method.VISIT_INSN, // F2D
Method.VISIT_INSN, // D2I
Method.VISIT_INSN, // D2L
Method.VISIT_INSN, // D2F
Method.VISIT_INSN, // I2B
Method.VISIT_INSN, // I2C
Method.VISIT_INSN, // I2S
Method.VISIT_INSN, // LCMP
Method.VISIT_INSN, // FCMPL
Method.VISIT_INSN, // FCMPG
Method.VISIT_INSN, // DCMPL
Method.VISIT_INSN, // DCMPG
Method.VISIT_JUMP_INSN, // IFEQ
Method.VISIT_JUMP_INSN, // IFNE
Method.VISIT_JUMP_INSN, // IFLT
Method.VISIT_JUMP_INSN, // IFGE
Method.VISIT_JUMP_INSN, // IFGT
Method.VISIT_JUMP_INSN, // IFLE
Method.VISIT_JUMP_INSN, // IF_ICMPEQ
Method.VISIT_JUMP_INSN, // IF_ICMPNE
Method.VISIT_JUMP_INSN, // IF_ICMPLT
Method.VISIT_JUMP_INSN, // IF_ICMPGE
Method.VISIT_JUMP_INSN, // IF_ICMPGT
Method.VISIT_JUMP_INSN, // IF_ICMPLE
Method.VISIT_JUMP_INSN, // IF_ACMPEQ
Method.VISIT_JUMP_INSN, // IF_ACMPNE
Method.VISIT_JUMP_INSN, // GOTO
Method.VISIT_JUMP_INSN, // JSR
Method.VISIT_VAR_INSN, // RET
null, // TABLESWITCH
null, // LOOKUPSWITCH
Method.VISIT_INSN, // IRETURN
Method.VISIT_INSN, // LRETURN
Method.VISIT_INSN, // FRETURN
Method.VISIT_INSN, // DRETURN
Method.VISIT_INSN, // ARETURN
Method.VISIT_INSN, // RETURN
Method.VISIT_FIELD_INSN, // GETSTATIC
Method.VISIT_FIELD_INSN, // PUTSTATIC
Method.VISIT_FIELD_INSN, // GETFIELD
Method.VISIT_FIELD_INSN, // PUTFIELD
Method.VISIT_METHOD_INSN, // INVOKEVIRTUAL
Method.VISIT_METHOD_INSN, // INVOKESPECIAL
Method.VISIT_METHOD_INSN, // INVOKESTATIC
Method.VISIT_METHOD_INSN, // INVOKEINTERFACE
null, // INVOKEDYNAMIC
Method.VISIT_TYPE_INSN, // NEW
Method.VISIT_INT_INSN, // NEWARRAY
Method.VISIT_TYPE_INSN, // ANEWARRAY
Method.VISIT_INSN, // ARRAYLENGTH
Method.VISIT_INSN, // ATHROW
Method.VISIT_TYPE_INSN, // CHECKCAST
Method.VISIT_TYPE_INSN, // INSTANCEOF
Method.VISIT_INSN, // MONITORENTER
Method.VISIT_INSN, // MONITOREXIT
null, // WIDE
null, // MULTIANEWARRAY
Method.VISIT_JUMP_INSN, // IFNULL
Method.VISIT_JUMP_INSN // IFNONNULL
};
private static final String INVALID = "Invalid ";
private static final String INVALID_DESCRIPTOR = "Invalid descriptor: ";
private static final String INVALID_TYPE_REFERENCE = "Invalid type reference sort 0x";
private static final String INVALID_LOCAL_VARIABLE_INDEX = "Invalid local variable index";
private static final String MUST_NOT_BE_NULL_OR_EMPTY = " (must not be null or empty)";
private static final String START_LABEL = "start label";
private static final String END_LABEL = "end label";
/** The class version number. */
public int version;
/** The access flags of the visited method. */
private int access;
/**
* The number of method parameters that can have runtime visible annotations. 0 means that all the
* parameters from the method descriptor can have annotations.
*/
private int visibleAnnotableParameterCount;
/**
* The number of method parameters that can have runtime invisible annotations. 0 means that all
* the parameters from the method descriptor can have annotations.
*/
private int invisibleAnnotableParameterCount;
/** Whether the {@link #visitCode} method has been called. */
private boolean visitCodeCalled;
/** Whether the {@link #visitMaxs} method has been called. */
private boolean visitMaxCalled;
/** Whether the {@link #visitEnd} method has been called. */
private boolean visitEndCalled;
/** The number of visited instructions so far. */
private int insnCount;
/** The index of the instruction designated by each visited label. */
private final Map<Label, Integer> labelInsnIndices;
/** The labels referenced by the visited method. */
private Set<Label> referencedLabels;
/** The index of the instruction corresponding to the last visited stack map frame. */
private int lastFrameInsnIndex = -1;
/** The number of visited frames in expanded form. */
private int numExpandedFrames;
/** The number of visited frames in compressed form. */
private int numCompressedFrames;
/**
* The exception handler ranges. Each pair of list element contains the start and end labels of an
* exception handler block.
*/
private List<Label> handlers;
/**
* Constructs a new {@link CheckMethodAdapter} object. This method adapter will not perform any
* data flow check (see {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)}).
* <i>Subclasses must not use this constructor</i>. Instead, they must use the {@link
* #CheckMethodAdapter(int, MethodVisitor, Map)} version.
*
* @param methodvisitor the method visitor to which this adapter must delegate calls.
*/
public CheckMethodAdapter(final MethodVisitor methodvisitor) {
this(methodvisitor, new HashMap<Label, Integer>());
}
/**
* Constructs a new {@link CheckMethodAdapter} object. This method adapter will not perform any
* data flow check (see {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)}).
* <i>Subclasses must not use this constructor</i>. Instead, they must use the {@link
* #CheckMethodAdapter(int, MethodVisitor, Map)} version.
*
* @param methodVisitor the method visitor to which this adapter must delegate calls.
* @param labelInsnIndices the index of the instruction designated by each visited label so far
* (in other methods). This map is updated with the labels from the visited method.
* @throws IllegalStateException If a subclass calls this constructor.
*/
public CheckMethodAdapter(
final MethodVisitor methodVisitor, final Map<Label, Integer> labelInsnIndices) {
this(/* latest api = */ Opcodes.ASM8, methodVisitor, labelInsnIndices);
if (getClass() != CheckMethodAdapter.class) {
throw new IllegalStateException();
}
}
/**
* Constructs a new {@link CheckMethodAdapter} object. This method adapter will not perform any
* data flow check (see {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)}).
*
* @param api the ASM API version implemented by this CheckMethodAdapter. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6}, {@link Opcodes#ASM7} or {@link
* Opcodes#ASM8}.
* @param methodVisitor the method visitor to which this adapter must delegate calls.
* @param labelInsnIndices the index of the instruction designated by each visited label so far
* (in other methods). This map is updated with the labels from the visited method.
*/
protected CheckMethodAdapter(
final int api,
final MethodVisitor methodVisitor,
final Map<Label, Integer> labelInsnIndices) {
super(api, methodVisitor);
this.labelInsnIndices = labelInsnIndices;
this.referencedLabels = new HashSet<>();
this.handlers = new ArrayList<>();
}
/**
* Constructs a new {@link CheckMethodAdapter} object. This method adapter will perform basic data
* flow checks. For instance in a method whose signature is {@code void m ()}, the invalid
* instruction IRETURN, or the invalid sequence IADD L2I will be detected. <i>Subclasses must not
* use this constructor</i>. Instead, they must use the {@link
* #CheckMethodAdapter(int,int,String,String,MethodVisitor,Map)} version.
*
* @param access the method's access flags.
* @param name the method's name.
* @param descriptor the method's descriptor (see {@link Type}).
* @param methodVisitor the method visitor to which this adapter must delegate calls.
* @param labelInsnIndices the index of the instruction designated by each visited label so far
* (in other methods). This map is updated with the labels from the visited method.
*/
public CheckMethodAdapter(
final int access,
final String name,
final String descriptor,
final MethodVisitor methodVisitor,
final Map<Label, Integer> labelInsnIndices) {
this(
/* latest api = */ Opcodes.ASM8, access, name, descriptor, methodVisitor, labelInsnIndices);
if (getClass() != CheckMethodAdapter.class) {
throw new IllegalStateException();
}
}
/**
* Constructs a new {@link CheckMethodAdapter} object. This method adapter will perform basic data
* flow checks. For instance in a method whose signature is {@code void m ()}, the invalid
* instruction IRETURN, or the invalid sequence IADD L2I will be detected.
*
* @param api the ASM API version implemented by this CheckMethodAdapter. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6}, {@link Opcodes#ASM7} or {@link
* Opcodes#ASM8}.
* @param access the method's access flags.
* @param name the method's name.
* @param descriptor the method's descriptor (see {@link Type}).
* @param methodVisitor the method visitor to which this adapter must delegate calls.
* @param labelInsnIndices the index of the instruction designated by each visited label so far
* (in other methods). This map is updated with the labels from the visited method.
*/
protected CheckMethodAdapter(
final int api,
final int access,
final String name,
final String descriptor,
final MethodVisitor methodVisitor,
final Map<Label, Integer> labelInsnIndices) {
this(
api,
new MethodNode(api, access, name, descriptor, null, null) {
@Override
public void visitEnd() {
Analyzer<BasicValue> analyzer = new Analyzer<>(new BasicVerifier());
try {
analyzer.analyze("dummy", this);
} catch (IndexOutOfBoundsException e) {
if (maxLocals == 0 && maxStack == 0) {
throw new IllegalArgumentException(
"Data flow checking option requires valid, non zero maxLocals and maxStack.",
e);
}
throwError(analyzer, e);
} catch (AnalyzerException e) {
throwError(analyzer, e);
}
if (methodVisitor != null) {
accept(methodVisitor);
}
}
private void throwError(final Analyzer<BasicValue> analyzer, final Exception e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter, true);
CheckClassAdapter.printAnalyzerResult(this, analyzer, printWriter);
printWriter.close();
throw new IllegalArgumentException(e.getMessage() + ' ' + stringWriter.toString(), e);
}
},
labelInsnIndices);
this.access = access;
}
@Override
public void visitParameter(final String name, final int access) {
if (name != null) {
checkUnqualifiedName(version, name, "name");
}
CheckClassAdapter.checkAccess(
access, Opcodes.ACC_FINAL + Opcodes.ACC_MANDATED + Opcodes.ACC_SYNTHETIC);
super.visitParameter(name, access);
}
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
checkVisitEndNotCalled();
checkDescriptor(version, descriptor, false);
return new CheckAnnotationAdapter(super.visitAnnotation(descriptor, visible));
}
@Override
public AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
checkVisitEndNotCalled();
int sort = new TypeReference(typeRef).getSort();
if (sort != TypeReference.METHOD_TYPE_PARAMETER
&& sort != TypeReference.METHOD_TYPE_PARAMETER_BOUND
&& sort != TypeReference.METHOD_RETURN
&& sort != TypeReference.METHOD_RECEIVER
&& sort != TypeReference.METHOD_FORMAL_PARAMETER
&& sort != TypeReference.THROWS) {
throw new IllegalArgumentException(INVALID_TYPE_REFERENCE + Integer.toHexString(sort));
}
CheckClassAdapter.checkTypeRef(typeRef);
CheckMethodAdapter.checkDescriptor(version, descriptor, false);
return new CheckAnnotationAdapter(
super.visitTypeAnnotation(typeRef, typePath, descriptor, visible));
}
@Override
public AnnotationVisitor visitAnnotationDefault() {
checkVisitEndNotCalled();
return new CheckAnnotationAdapter(super.visitAnnotationDefault(), false);
}
@Override
public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) {
checkVisitEndNotCalled();
if (visible) {
visibleAnnotableParameterCount = parameterCount;
} else {
invisibleAnnotableParameterCount = parameterCount;
}
super.visitAnnotableParameterCount(parameterCount, visible);
}
@Override
public AnnotationVisitor visitParameterAnnotation(
final int parameter, final String descriptor, final boolean visible) {
checkVisitEndNotCalled();
if ((visible
&& visibleAnnotableParameterCount > 0
&& parameter >= visibleAnnotableParameterCount)
|| (!visible
&& invisibleAnnotableParameterCount > 0
&& parameter >= invisibleAnnotableParameterCount)) {
throw new IllegalArgumentException("Invalid parameter index");
}
checkDescriptor(version, descriptor, false);
return new CheckAnnotationAdapter(
super.visitParameterAnnotation(parameter, descriptor, visible));
}
@Override
public void visitAttribute(final Attribute attribute) {
checkVisitEndNotCalled();
if (attribute == null) {
throw new IllegalArgumentException("Invalid attribute (must not be null)");
}
super.visitAttribute(attribute);
}
@Override
public void visitCode() {
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
throw new UnsupportedOperationException("Abstract methods cannot have code");
}
visitCodeCalled = true;
super.visitCode();
}
@Override
public void visitFrame(
final int type,
final int numLocal,
final Object[] local,
final int numStack,
final Object[] stack) {
if (insnCount == lastFrameInsnIndex) {
throw new IllegalStateException("At most one frame can be visited at a given code location.");
}
lastFrameInsnIndex = insnCount;
int maxNumLocal;
int maxNumStack;
switch (type) {
case Opcodes.F_NEW:
case Opcodes.F_FULL:
maxNumLocal = Integer.MAX_VALUE;
maxNumStack = Integer.MAX_VALUE;
break;
case Opcodes.F_SAME:
maxNumLocal = 0;
maxNumStack = 0;
break;
case Opcodes.F_SAME1:
maxNumLocal = 0;
maxNumStack = 1;
break;
case Opcodes.F_APPEND:
case Opcodes.F_CHOP:
maxNumLocal = 3;
maxNumStack = 0;
break;
default:
throw new IllegalArgumentException("Invalid frame type " + type);
}
if (numLocal > maxNumLocal) {
throw new IllegalArgumentException(
"Invalid numLocal=" + numLocal + " for frame type " + type);
}
if (numStack > maxNumStack) {
throw new IllegalArgumentException(
"Invalid numStack=" + numStack + " for frame type " + type);
}
if (type != Opcodes.F_CHOP) {
if (numLocal > 0 && (local == null || local.length < numLocal)) {
throw new IllegalArgumentException("Array local[] is shorter than numLocal");
}
for (int i = 0; i < numLocal; ++i) {
checkFrameValue(local[i]);
}
}
if (numStack > 0 && (stack == null || stack.length < numStack)) {
throw new IllegalArgumentException("Array stack[] is shorter than numStack");
}
for (int i = 0; i < numStack; ++i) {
checkFrameValue(stack[i]);
}
if (type == Opcodes.F_NEW) {
++numExpandedFrames;
} else {
++numCompressedFrames;
}
if (numExpandedFrames > 0 && numCompressedFrames > 0) {
throw new IllegalArgumentException("Expanded and compressed frames must not be mixed.");
}
super.visitFrame(type, numLocal, local, numStack, stack);
}
@Override
public void visitInsn(final int opcode) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_INSN);
super.visitInsn(opcode);
++insnCount;
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_INT_INSN);
switch (opcode) {
case Opcodes.BIPUSH:
checkSignedByte(operand, "Invalid operand");
break;
case Opcodes.SIPUSH:
checkSignedShort(operand, "Invalid operand");
break;
case Opcodes.NEWARRAY:
if (operand < Opcodes.T_BOOLEAN || operand > Opcodes.T_LONG) {
throw new IllegalArgumentException(
"Invalid operand (must be an array type code T_...): " + operand);
}
break;
default:
throw new AssertionError();
}
super.visitIntInsn(opcode, operand);
++insnCount;
}
@Override
public void visitVarInsn(final int opcode, final int var) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_VAR_INSN);
checkUnsignedShort(var, INVALID_LOCAL_VARIABLE_INDEX);
super.visitVarInsn(opcode, var);
++insnCount;
}
@Override
public void visitTypeInsn(final int opcode, final String type) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_TYPE_INSN);
checkInternalName(version, type, "type");
if (opcode == Opcodes.NEW && type.charAt(0) == '[') {
throw new IllegalArgumentException("NEW cannot be used to create arrays: " + type);
}
super.visitTypeInsn(opcode, type);
++insnCount;
}
@Override
public void visitFieldInsn(
final int opcode, final String owner, final String name, final String descriptor) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_FIELD_INSN);
checkInternalName(version, owner, "owner");
checkUnqualifiedName(version, name, "name");
checkDescriptor(version, descriptor, false);
super.visitFieldInsn(opcode, owner, name, descriptor);
++insnCount;
}
@Override
public void visitMethodInsn(
final int opcodeAndSource,
final String owner,
final String name,
final String descriptor,
final boolean isInterface) {
if (api < Opcodes.ASM5 && (opcodeAndSource & Opcodes.SOURCE_DEPRECATED) == 0) {
// Redirect the call to the deprecated version of this method.
super.visitMethodInsn(opcodeAndSource, owner, name, descriptor, isInterface);
return;
}
int opcode = opcodeAndSource & ~Opcodes.SOURCE_MASK;
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_METHOD_INSN);
if (opcode != Opcodes.INVOKESPECIAL || !"<init>".equals(name)) {
checkMethodIdentifier(version, name, "name");
}
checkInternalName(version, owner, "owner");
checkMethodDescriptor(version, descriptor);
if (opcode == Opcodes.INVOKEVIRTUAL && isInterface) {
throw new IllegalArgumentException("INVOKEVIRTUAL can't be used with interfaces");
}
if (opcode == Opcodes.INVOKEINTERFACE && !isInterface) {
throw new IllegalArgumentException("INVOKEINTERFACE can't be used with classes");
}
if (opcode == Opcodes.INVOKESPECIAL && isInterface && (version & 0xFFFF) < Opcodes.V1_8) {
throw new IllegalArgumentException(
"INVOKESPECIAL can't be used with interfaces prior to Java 8");
}
super.visitMethodInsn(opcodeAndSource, owner, name, descriptor, isInterface);
++insnCount;
}
@Override
public void visitInvokeDynamicInsn(
final String name,
final String descriptor,
final Handle bootstrapMethodHandle,
final Object... bootstrapMethodArguments) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkMethodIdentifier(version, name, "name");
checkMethodDescriptor(version, descriptor);
if (bootstrapMethodHandle.getTag() != Opcodes.H_INVOKESTATIC
&& bootstrapMethodHandle.getTag() != Opcodes.H_NEWINVOKESPECIAL) {
throw new IllegalArgumentException("invalid handle tag " + bootstrapMethodHandle.getTag());
}
for (Object bootstrapMethodArgument : bootstrapMethodArguments) {
checkLdcConstant(bootstrapMethodArgument);
}
super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
++insnCount;
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkOpcodeMethod(opcode, Method.VISIT_JUMP_INSN);
checkLabel(label, false, "label");
super.visitJumpInsn(opcode, label);
referencedLabels.add(label);
++insnCount;
}
@Override
public void visitLabel(final Label label) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkLabel(label, false, "label");
if (labelInsnIndices.get(label) != null) {
throw new IllegalArgumentException("Already visited label");
}
labelInsnIndices.put(label, insnCount);
super.visitLabel(label);
}
@Override
public void visitLdcInsn(final Object value) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkLdcConstant(value);
super.visitLdcInsn(value);
++insnCount;
}
@Override
public void visitIincInsn(final int var, final int increment) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkUnsignedShort(var, INVALID_LOCAL_VARIABLE_INDEX);
checkSignedShort(increment, "Invalid increment");
super.visitIincInsn(var, increment);
++insnCount;
}
@Override
public void visitTableSwitchInsn(
final int min, final int max, final Label dflt, final Label... labels) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
if (max < min) {
throw new IllegalArgumentException(
"Max = " + max + " must be greater than or equal to min = " + min);
}
checkLabel(dflt, false, "default label");
if (labels == null || labels.length != max - min + 1) {
throw new IllegalArgumentException("There must be max - min + 1 labels");
}
for (int i = 0; i < labels.length; ++i) {
checkLabel(labels[i], false, "label at index " + i);
}
super.visitTableSwitchInsn(min, max, dflt, labels);
Collections.addAll(referencedLabels, labels);
++insnCount;
}
@Override
public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
checkVisitMaxsNotCalled();
checkVisitCodeCalled();
checkLabel(dflt, false, "default label");
if (keys == null || labels == null || keys.length != labels.length) {
throw new IllegalArgumentException("There must be the same number of keys and labels");
}
for (int i = 0; i < labels.length; ++i) {
checkLabel(labels[i], false, "label at index " + i);
}
super.visitLookupSwitchInsn(dflt, keys, labels);
referencedLabels.add(dflt);
Collections.addAll(referencedLabels, labels);
++insnCount;
}
@Override
public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkDescriptor(version, descriptor, false);
if (descriptor.charAt(0) != '[') {
throw new IllegalArgumentException(
"Invalid descriptor (must be an array type descriptor): " + descriptor);
}
if (numDimensions < 1) {
throw new IllegalArgumentException(
"Invalid dimensions (must be greater than 0): " + numDimensions);
}
if (numDimensions > descriptor.lastIndexOf('[') + 1) {
throw new IllegalArgumentException(
"Invalid dimensions (must not be greater than numDimensions(descriptor)): "
+ numDimensions);
}
super.visitMultiANewArrayInsn(descriptor, numDimensions);
++insnCount;
}
@Override
public AnnotationVisitor visitInsnAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
int sort = new TypeReference(typeRef).getSort();
if (sort != TypeReference.INSTANCEOF
&& sort != TypeReference.NEW
&& sort != TypeReference.CONSTRUCTOR_REFERENCE
&& sort != TypeReference.METHOD_REFERENCE
&& sort != TypeReference.CAST
&& sort != TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT
&& sort != TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT
&& sort != TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT
&& sort != TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT) {
throw new IllegalArgumentException(INVALID_TYPE_REFERENCE + Integer.toHexString(sort));
}
CheckClassAdapter.checkTypeRef(typeRef);
CheckMethodAdapter.checkDescriptor(version, descriptor, false);
return new CheckAnnotationAdapter(
super.visitInsnAnnotation(typeRef, typePath, descriptor, visible));
}
@Override
public void visitTryCatchBlock(
final Label start, final Label end, final Label handler, final String type) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkLabel(start, false, START_LABEL);
checkLabel(end, false, END_LABEL);
checkLabel(handler, false, "handler label");
if (labelInsnIndices.get(start) != null
|| labelInsnIndices.get(end) != null
|| labelInsnIndices.get(handler) != null) {
throw new IllegalStateException("Try catch blocks must be visited before their labels");
}
if (type != null) {
checkInternalName(version, type, "type");
}
super.visitTryCatchBlock(start, end, handler, type);
handlers.add(start);
handlers.add(end);
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
int sort = new TypeReference(typeRef).getSort();
if (sort != TypeReference.EXCEPTION_PARAMETER) {
throw new IllegalArgumentException(INVALID_TYPE_REFERENCE + Integer.toHexString(sort));
}
CheckClassAdapter.checkTypeRef(typeRef);
CheckMethodAdapter.checkDescriptor(version, descriptor, false);
return new CheckAnnotationAdapter(
super.visitTryCatchAnnotation(typeRef, typePath, descriptor, visible));
}
@Override
public void visitLocalVariable(
final String name,
final String descriptor,
final String signature,
final Label start,
final Label end,
final int index) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkUnqualifiedName(version, name, "name");
checkDescriptor(version, descriptor, false);
if (signature != null) {
CheckClassAdapter.checkFieldSignature(signature);
}
checkLabel(start, true, START_LABEL);
checkLabel(end, true, END_LABEL);
checkUnsignedShort(index, INVALID_LOCAL_VARIABLE_INDEX);
int startInsnIndex = labelInsnIndices.get(start).intValue();
int endInsnIndex = labelInsnIndices.get(end).intValue();
if (endInsnIndex < startInsnIndex) {
throw new IllegalArgumentException(
"Invalid start and end labels (end must be greater than start)");
}
super.visitLocalVariable(name, descriptor, signature, start, end, index);
}
@Override
public AnnotationVisitor visitLocalVariableAnnotation(
final int typeRef,
final TypePath typePath,
final Label[] start,
final Label[] end,
final int[] index,
final String descriptor,
final boolean visible) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
int sort = new TypeReference(typeRef).getSort();
if (sort != TypeReference.LOCAL_VARIABLE && sort != TypeReference.RESOURCE_VARIABLE) {
throw new IllegalArgumentException(INVALID_TYPE_REFERENCE + Integer.toHexString(sort));
}
CheckClassAdapter.checkTypeRef(typeRef);
checkDescriptor(version, descriptor, false);
if (start == null
|| end == null
|| index == null
|| end.length != start.length
|| index.length != start.length) {
throw new IllegalArgumentException(
"Invalid start, end and index arrays (must be non null and of identical length");
}
for (int i = 0; i < start.length; ++i) {
checkLabel(start[i], true, START_LABEL);
checkLabel(end[i], true, END_LABEL);
checkUnsignedShort(index[i], INVALID_LOCAL_VARIABLE_INDEX);
int startInsnIndex = labelInsnIndices.get(start[i]).intValue();
int endInsnIndex = labelInsnIndices.get(end[i]).intValue();
if (endInsnIndex < startInsnIndex) {
throw new IllegalArgumentException(
"Invalid start and end labels (end must be greater than start)");
}
}
return super.visitLocalVariableAnnotation(
typeRef, typePath, start, end, index, descriptor, visible);
}
@Override
public void visitLineNumber(final int line, final Label start) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
checkUnsignedShort(line, "Invalid line number");
checkLabel(start, true, START_LABEL);
super.visitLineNumber(line, start);
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
checkVisitCodeCalled();
checkVisitMaxsNotCalled();
visitMaxCalled = true;
for (Label l : referencedLabels) {
if (labelInsnIndices.get(l) == null) {
throw new IllegalStateException("Undefined label used");
}
}
for (int i = 0; i < handlers.size(); i += 2) {
Integer startInsnIndex = labelInsnIndices.get(handlers.get(i));
Integer endInsnIndex = labelInsnIndices.get(handlers.get(i + 1));
if (startInsnIndex == null || endInsnIndex == null) {
throw new IllegalStateException("Undefined try catch block labels");
}
if (endInsnIndex.intValue() <= startInsnIndex.intValue()) {
throw new IllegalStateException("Emty try catch block handler range");
}
}
checkUnsignedShort(maxStack, "Invalid max stack");
checkUnsignedShort(maxLocals, "Invalid max locals");
super.visitMaxs(maxStack, maxLocals);
}
@Override
public void visitEnd() {
checkVisitEndNotCalled();
visitEndCalled = true;
super.visitEnd();
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/** Checks that the {@link #visitCode} method has been called. */
private void checkVisitCodeCalled() {
if (!visitCodeCalled) {
throw new IllegalStateException(
"Cannot visit instructions before visitCode has been called.");
}
}
/** Checks that the {@link #visitMaxs} method has not been called. */
private void checkVisitMaxsNotCalled() {
if (visitMaxCalled) {
throw new IllegalStateException("Cannot visit instructions after visitMaxs has been called.");
}
}
/** Checks that the {@link #visitEnd} method has not been called. */
private void checkVisitEndNotCalled() {
if (visitEndCalled) {
throw new IllegalStateException("Cannot visit elements after visitEnd has been called.");
}
}
/**
* Checks a stack frame value.
*
* @param value the value to be checked.
*/
private void checkFrameValue(final Object value) {
if (value == Opcodes.TOP
|| value == Opcodes.INTEGER
|| value == Opcodes.FLOAT
|| value == Opcodes.LONG
|| value == Opcodes.DOUBLE
|| value == Opcodes.NULL
|| value == Opcodes.UNINITIALIZED_THIS) {
return;
}
if (value instanceof String) {
checkInternalName(version, (String) value, "Invalid stack frame value");
} else if (value instanceof Label) {
referencedLabels.add((Label) value);
} else {
throw new IllegalArgumentException("Invalid stack frame value: " + value);
}
}
/**
* Checks that the method to visit the given opcode is equal to the given method.
*
* @param opcode the opcode to be checked.
* @param method the expected visit method.
*/
private static void checkOpcodeMethod(final int opcode, final Method method) {
if (opcode < Opcodes.NOP || opcode > Opcodes.IFNONNULL || OPCODE_METHODS[opcode] != method) {
throw new IllegalArgumentException("Invalid opcode: " + opcode);
}
}
/**
* Checks that the given value is a signed byte.
*
* @param value the value to be checked.
* @param message the message to use in case of error.
*/
private static void checkSignedByte(final int value, final String message) {
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
throw new IllegalArgumentException(message + " (must be a signed byte): " + value);
}
}
/**
* Checks that the given value is a signed short.
*
* @param value the value to be checked.
* @param message the message to use in case of error.
*/
private static void checkSignedShort(final int value, final String message) {
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
throw new IllegalArgumentException(message + " (must be a signed short): " + value);
}
}
/**
* Checks that the given value is an unsigned short.
*
* @param value the value to be checked.
* @param message the message to use in case of error.
*/
private static void checkUnsignedShort(final int value, final String message) {
if (value < 0 || value > 65535) {
throw new IllegalArgumentException(message + " (must be an unsigned short): " + value);
}
}
/**
* Checks that the given value is an {@link Integer}, {@link Float}, {@link Long}, {@link Double}
* or {@link String} value.
*
* @param value the value to be checked.
*/
static void checkConstant(final Object value) {
if (!(value instanceof Integer)
&& !(value instanceof Float)
&& !(value instanceof Long)
&& !(value instanceof Double)
&& !(value instanceof String)) {
throw new IllegalArgumentException("Invalid constant: " + value);
}
}
/**
* Checks that the given value is a valid operand for the LDC instruction.
*
* @param value the value to be checked.
*/
private void checkLdcConstant(final Object value) {
if (value instanceof Type) {
int sort = ((Type) value).getSort();
if (sort != Type.OBJECT && sort != Type.ARRAY && sort != Type.METHOD) {
throw new IllegalArgumentException("Illegal LDC constant value");
}
if (sort != Type.METHOD && (version & 0xFFFF) < Opcodes.V1_5) {
throw new IllegalArgumentException("ldc of a constant class requires at least version 1.5");
}
if (sort == Type.METHOD && (version & 0xFFFF) < Opcodes.V1_7) {
throw new IllegalArgumentException("ldc of a method type requires at least version 1.7");
}
} else if (value instanceof Handle) {
if ((version & 0xFFFF) < Opcodes.V1_7) {
throw new IllegalArgumentException("ldc of a Handle requires at least version 1.7");
}
Handle handle = (Handle) value;
int tag = handle.getTag();
if (tag < Opcodes.H_GETFIELD || tag > Opcodes.H_INVOKEINTERFACE) {
throw new IllegalArgumentException("invalid handle tag " + tag);
}
checkInternalName(this.version, handle.getOwner(), "handle owner");
if (tag <= Opcodes.H_PUTSTATIC) {
checkDescriptor(this.version, handle.getDesc(), false);
} else {
checkMethodDescriptor(this.version, handle.getDesc());
}
String handleName = handle.getName();
if (!("<init>".equals(handleName) && tag == Opcodes.H_NEWINVOKESPECIAL)) {
checkMethodIdentifier(this.version, handleName, "handle name");
}
} else if (value instanceof ConstantDynamic) {
if ((version & 0xFFFF) < Opcodes.V11) {
throw new IllegalArgumentException("ldc of a ConstantDynamic requires at least version 11");
}
ConstantDynamic constantDynamic = (ConstantDynamic) value;
checkMethodIdentifier(this.version, constantDynamic.getName(), "constant dynamic name");
checkDescriptor(this.version, constantDynamic.getDescriptor(), false);
checkLdcConstant(constantDynamic.getBootstrapMethod());
int bootstrapMethodArgumentCount = constantDynamic.getBootstrapMethodArgumentCount();
for (int i = 0; i < bootstrapMethodArgumentCount; ++i) {
checkLdcConstant(constantDynamic.getBootstrapMethodArgument(i));
}
} else {
checkConstant(value);
}
}
/**
* Checks that the given string is a valid unqualified name.
*
* @param version the class version.
* @param name the string to be checked.
* @param message the message to use in case of error.
*/
static void checkUnqualifiedName(final int version, final String name, final String message) {
checkIdentifier(version, name, 0, -1, message);
}
/**
* Checks that the given substring is a valid Java identifier.
*
* @param version the class version.
* @param name the string to be checked.
* @param startPos the index of the first character of the identifier (inclusive).
* @param endPos the index of the last character of the identifier (exclusive). -1 is equivalent
* to {@code name.length()} if name is not {@literal null}.
* @param message the message to use in case of error.
*/
static void checkIdentifier(
final int version,
final String name,
final int startPos,
final int endPos,
final String message) {
if (name == null || (endPos == -1 ? name.length() <= startPos : endPos <= startPos)) {
throw new IllegalArgumentException(INVALID + message + MUST_NOT_BE_NULL_OR_EMPTY);
}
int max = endPos == -1 ? name.length() : endPos;
if ((version & 0xFFFF) >= Opcodes.V1_5) {
for (int i = startPos; i < max; i = name.offsetByCodePoints(i, 1)) {
if (".;[/".indexOf(name.codePointAt(i)) != -1) {
throw new IllegalArgumentException(
INVALID + message + " (must not contain . ; [ or /): " + name);
}
}
return;
}
for (int i = startPos; i < max; i = name.offsetByCodePoints(i, 1)) {
if (i == startPos
? !Character.isJavaIdentifierStart(name.codePointAt(i))
: !Character.isJavaIdentifierPart(name.codePointAt(i))) {
throw new IllegalArgumentException(
INVALID + message + " (must be a valid Java identifier): " + name);
}
}
}
/**
* Checks that the given string is a valid Java identifier.
*
* @param version the class version.
* @param name the string to be checked.
* @param message the message to use in case of error.
*/
static void checkMethodIdentifier(final int version, final String name, final String message) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException(INVALID + message + MUST_NOT_BE_NULL_OR_EMPTY);
}
if ((version & 0xFFFF) >= Opcodes.V1_5) {
for (int i = 0; i < name.length(); i = name.offsetByCodePoints(i, 1)) {
if (".;[/<>".indexOf(name.codePointAt(i)) != -1) {
throw new IllegalArgumentException(
INVALID + message + " (must be a valid unqualified name): " + name);
}
}
return;
}
for (int i = 0; i < name.length(); i = name.offsetByCodePoints(i, 1)) {
if (i == 0
? !Character.isJavaIdentifierStart(name.codePointAt(i))
: !Character.isJavaIdentifierPart(name.codePointAt(i))) {
throw new IllegalArgumentException(
INVALID
+ message
+ " (must be a '<init>', '<clinit>' or a valid Java identifier): "
+ name);
}
}
}
/**
* Checks that the given string is a valid internal class name or array type descriptor.
*
* @param version the class version.
* @param name the string to be checked.
* @param message the message to use in case of error.
*/
static void checkInternalName(final int version, final String name, final String message) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException(INVALID + message + MUST_NOT_BE_NULL_OR_EMPTY);
}
if (name.charAt(0) == '[') {
checkDescriptor(version, name, false);
} else {
checkInternalClassName(version, name, message);
}
}
/**
* Checks that the given string is a valid internal class name.
*
* @param version the class version.
* @param name the string to be checked.
* @param message the message to use in case of error.
*/
private static void checkInternalClassName(
final int version, final String name, final String message) {
try {
int startIndex = 0;
int slashIndex;
while ((slashIndex = name.indexOf('/', startIndex + 1)) != -1) {
checkIdentifier(version, name, startIndex, slashIndex, null);
startIndex = slashIndex + 1;
}
checkIdentifier(version, name, startIndex, name.length(), null);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
INVALID + message + " (must be an internal class name): " + name, e);
}
}
/**
* Checks that the given string is a valid type descriptor.
*
* @param version the class version.
* @param descriptor the string to be checked.
* @param canBeVoid {@literal true} if {@code V} can be considered valid.
*/
static void checkDescriptor(final int version, final String descriptor, final boolean canBeVoid) {
int endPos = checkDescriptor(version, descriptor, 0, canBeVoid);
if (endPos != descriptor.length()) {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
}
/**
* Checks that a the given substring is a valid type descriptor.
*
* @param version the class version.
* @param descriptor the string to be checked.
* @param startPos the index of the first character of the type descriptor (inclusive).
* @param canBeVoid whether {@code V} can be considered valid.
* @return the index of the last character of the type descriptor, plus one.
*/
private static int checkDescriptor(
final int version, final String descriptor, final int startPos, final boolean canBeVoid) {
if (descriptor == null || startPos >= descriptor.length()) {
throw new IllegalArgumentException("Invalid type descriptor (must not be null or empty)");
}
switch (descriptor.charAt(startPos)) {
case 'V':
if (canBeVoid) {
return startPos + 1;
} else {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
case 'F':
case 'J':
case 'D':
return startPos + 1;
case '[':
int pos = startPos + 1;
while (pos < descriptor.length() && descriptor.charAt(pos) == '[') {
++pos;
}
if (pos < descriptor.length()) {
return checkDescriptor(version, descriptor, pos, false);
} else {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
case 'L':
int endPos = descriptor.indexOf(';', startPos);
if (startPos == -1 || endPos - startPos < 2) {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
try {
checkInternalClassName(version, descriptor.substring(startPos + 1, endPos), null);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor, e);
}
return endPos + 1;
default:
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
}
/**
* Checks that the given string is a valid method descriptor.
*
* @param version the class version.
* @param descriptor the string to be checked.
*/
static void checkMethodDescriptor(final int version, final String descriptor) {
if (descriptor == null || descriptor.length() == 0) {
throw new IllegalArgumentException("Invalid method descriptor (must not be null or empty)");
}
if (descriptor.charAt(0) != '(' || descriptor.length() < 3) {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
int pos = 1;
if (descriptor.charAt(pos) != ')') {
do {
if (descriptor.charAt(pos) == 'V') {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
pos = checkDescriptor(version, descriptor, pos, false);
} while (pos < descriptor.length() && descriptor.charAt(pos) != ')');
}
pos = checkDescriptor(version, descriptor, pos + 1, true);
if (pos != descriptor.length()) {
throw new IllegalArgumentException(INVALID_DESCRIPTOR + descriptor);
}
}
/**
* Checks that the given label is not null. This method can also check that the label has been
* visited.
*
* @param label the label to be checked.
* @param checkVisited whether to check that the label has been visited.
* @param message the message to use in case of error.
*/
private void checkLabel(final Label label, final boolean checkVisited, final String message) {
if (label == null) {
throw new IllegalArgumentException(INVALID + message + " (must not be null)");
}
if (checkVisited && labelInsnIndices.get(label) == null) {
throw new IllegalArgumentException(INVALID + message + " (must be visited first)");
}
}
}
| apache-2.0 |
etirelli/droolsjbpm-tools | drools-eclipse/org.jbpm.eclipse/src/main/java/org/jbpm/eclipse/action/GenerateForms.java | 11068 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.jbpm.eclipse.action;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.kie.api.definition.process.Node;
import org.kie.api.definition.process.NodeContainer;
import org.kie.api.definition.process.Process;
import org.drools.core.xml.SemanticModules;
import org.eclipse.core.internal.resources.File;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.jbpm.bpmn2.xml.BPMNDISemanticModule;
import org.jbpm.bpmn2.xml.BPMNExtensionsSemanticModule;
import org.jbpm.bpmn2.xml.BPMNSemanticModule;
import org.jbpm.compiler.xml.XmlProcessReader;
import org.jbpm.compiler.xml.processes.RuleFlowMigrator;
import org.jbpm.eclipse.JBPMEclipsePlugin;
import org.jbpm.process.core.context.variable.Variable;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.ruleflow.core.RuleFlowProcess;
import org.jbpm.workflow.core.node.HumanTaskNode;
public class GenerateForms implements IObjectActionDelegate {
private IFile file;
private IWorkbenchPart targetPart;
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
this.targetPart = targetPart;
}
public void run(IAction action) {
if (file != null && file.exists()) {
try {
generateForms();
} catch (Throwable t) {
JBPMEclipsePlugin.log(t);
}
}
}
public void selectionChanged(IAction action, ISelection selection) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection structured = (IStructuredSelection) selection;
if (structured.size() == 1) {
Object element = structured.getFirstElement();
if (element instanceof IFile) {
file = (IFile) element;
}
}
}
}
public void generateForms() {
try {
final IJavaProject javaProject = JavaCore.create(file.getProject());
if (javaProject == null || !javaProject.exists()) {
return;
}
InputStreamReader isr = new InputStreamReader(((File) file).getContents());
KnowledgeBuilderConfigurationImpl configuration = new KnowledgeBuilderConfigurationImpl();
SemanticModules modules = configuration.getSemanticModules();
modules.addSemanticModule(new BPMNSemanticModule());
modules.addSemanticModule(new BPMNDISemanticModule());
modules.addSemanticModule(new BPMNExtensionsSemanticModule());
XmlProcessReader xmlReader = new XmlProcessReader( modules, Thread.currentThread().getContextClassLoader() );
String xml = RuleFlowMigrator.convertReaderToString(isr);
Reader reader = new StringReader(xml);
List<Process> processes = xmlReader.read(reader);
if (processes != null && processes.size() == 1) {
final RuleFlowProcess process = (RuleFlowProcess) processes.get(0);
List<HumanTaskNode> result = new ArrayList<HumanTaskNode>();
processNodes(process.getNodes(), result);
final Map<String, TaskDef> tasks = new HashMap<String, TaskDef>();
for (HumanTaskNode node: result) {
String taskName = (String) node.getWork().getParameter("TaskName");
if (taskName == null) {
break;
}
TaskDef task = tasks.get(taskName);
if (task == null) {
task = new TaskDef(taskName);
tasks.put(taskName, task);
}
for (Map.Entry<String, String> entry: node.getInMappings().entrySet()) {
if (task.getInputParams().get(entry.getKey()) == null) {
VariableScope variableScope = (VariableScope) node.resolveContext(VariableScope.VARIABLE_SCOPE, entry.getValue());
if (variableScope != null) {
task.getInputParams().put(entry.getKey(), variableScope.findVariable(entry.getValue()).getType().getStringType());
}
}
}
for (Map.Entry<String, String> entry: node.getOutMappings().entrySet()) {
if (task.getOutputParams().get(entry.getKey()) == null) {
VariableScope variableScope = (VariableScope) node.resolveContext(VariableScope.VARIABLE_SCOPE, entry.getValue());
if (variableScope != null && !"outcome".equals(entry.getKey())) {
task.getOutputParams().put(entry.getKey(), variableScope.findVariable(entry.getValue()).getType().getStringType());
}
}
}
}
WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
public void execute(final IProgressMonitor monitor)
throws CoreException {
try {
IFolder folder = file.getProject().getFolder("src/main/resources");
for (TaskDef task: tasks.values()) {
String fileName = task.getTaskName() + ".ftl";
String output =
"<html>\n" +
"<body>\n" +
"<h2>" + task.getTaskName() + "</h2>\n" +
"<hr>\n" +
"<#if task.descriptions[0]??>\n" +
"Description: ${task.descriptions[0].text}<BR/>\n" +
"</#if>\n";
for (String input: task.getInputParams().keySet()) {
output += input + ": ${" + input + "}<BR/>\n";
}
output +=
"<form action=\"complete\" method=\"POST\" enctype=\"multipart/form-data\">\n";
for (String outputP: task.getOutputParams().keySet()) {
output += outputP + ": <input type=\"text\" name=\"" + outputP + "\" /><BR/>\n";
}
output +=
"<BR/>\n" +
"<input type=\"submit\" name=\"outcome\" value=\"Complete\"/>\n" +
"</form>\n" +
"</body>\n" +
"</html>";
IFile file = folder.getFile(fileName);
if (!file.exists()) {
file.create(new ByteArrayInputStream(output.getBytes()), true, monitor);
} else {
file.setContents(new ByteArrayInputStream(output.getBytes()), true, false, monitor);
}
}
String fileName = process.getId() + ".ftl";
String output =
"<html>\n" +
"<body>\n" +
"<h2>" + process.getName() + "</h2>\n" +
"<hr>\n" +
"<form action=\"complete\" method=\"POST\" enctype=\"multipart/form-data\">\n";
for (Variable variable: process.getVariableScope().getVariables()) {
if ("String".equals(variable.getType().getStringType())) {
output += variable.getName() + ": <input type=\"text\" name=\"" + variable.getName() + "\" /><BR/>\n";
}
}
output +=
"<input type=\"submit\" value=\"Complete\"/>\n" +
"</form>\n" +
"</body>\n" +
"</html>";
IFile file = folder.getFile(fileName);
if (!file.exists()) {
file.create(new ByteArrayInputStream(output.getBytes()), true, monitor);
} else {
file.setContents(new ByteArrayInputStream(output.getBytes()), true, false, monitor);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
try {
new ProgressMonitorDialog(targetPart.getSite().getShell()).run(false, true, op);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
private static void processNodes(Node[] nodes, List<HumanTaskNode> result) {
for (Node node: nodes) {
if (node instanceof HumanTaskNode) {
result.add((HumanTaskNode) node);
} else if (node instanceof NodeContainer) {
processNodes(((NodeContainer) node).getNodes(), result);
}
}
}
private class TaskDef {
private String taskName;
private Map<String, String> inputParams = new HashMap<String, String>();
private Map<String, String> outputParams = new HashMap<String, String>();
public TaskDef(String taskName) {
this.taskName = taskName;
}
public String getTaskName() {
return taskName;
}
public Map<String, String> getInputParams() {
return inputParams;
}
public Map<String, String> getOutputParams() {
return outputParams;
}
}
}
| apache-2.0 |
mt25367117/lforum | src/main/java/com/javaeye/lonlysky/lforum/entity/forum/Medals.java | 2314 | package com.javaeye.lonlysky.lforum.entity.forum;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
/**
* 勋章
*
* @author 黄磊
*
*/
@Entity
@Table(name = "medals")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Medals implements java.io.Serializable {
private static final long serialVersionUID = -6179820632546837134L;
private Integer medalid;
private String name;
private Integer available;
private String image;
private Set<Medalslog> medalslogs = new HashSet<Medalslog>(0);
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "increment")
@Column(name = "medalid", unique = true, nullable = false, insertable = true, updatable = true)
public Integer getMedalid() {
return medalid;
}
public void setMedalid(Integer medalid) {
this.medalid = medalid;
}
@Column(name = "name", unique = false, nullable = false, insertable = true, updatable = true, length = 50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "available", unique = false, nullable = false, insertable = true, updatable = true)
public Integer getAvailable() {
return available;
}
public void setAvailable(Integer available) {
this.available = available;
}
@Column(name = "image", unique = false, nullable = false, insertable = true, updatable = true, length = 30)
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "medals")
public Set<Medalslog> getMedalslogs() {
return medalslogs;
}
public void setMedalslogs(Set<Medalslog> medalslogs) {
this.medalslogs = medalslogs;
}
} | apache-2.0 |
rockmkd/datacollector | json-dto/src/main/java/com/streamsets/datacollector/event/dto/PipelineSaveEvent.java | 1931 | /*
* Copyright 2017 StreamSets 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.streamsets.datacollector.event.dto;
import com.streamsets.datacollector.config.dto.PipelineConfigAndRules;
import com.streamsets.lib.security.acl.dto.Acl;
public class PipelineSaveEvent extends PipelineBaseEvent {
private PipelineConfigAndRules pipelineConfigurationAndRules;
private String description;
private String offset;
private int offsetProtocolVersion;
private Acl acl;
public PipelineSaveEvent() {
}
public PipelineConfigAndRules getPipelineConfigurationAndRules() {
return pipelineConfigurationAndRules;
}
public void setPipelineConfigurationAndRules(PipelineConfigAndRules pipelineConfigurationAndRules) {
this.pipelineConfigurationAndRules = pipelineConfigurationAndRules;
}
public int getOffsetProtocolVersion() {
return offsetProtocolVersion;
}
public void setOffsetProtocolVersion(int offsetProtocolVersion) {
this.offsetProtocolVersion = offsetProtocolVersion;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public String getOffset() {
return offset;
}
public void setOffset(String offset) {
this.offset = offset;
}
public Acl getAcl() {
return acl;
}
public void setAcl(Acl acl) {
this.acl = acl;
}
}
| apache-2.0 |
facebook/buck | src/com/facebook/buck/jvm/java/plugin/PluginLoader.java | 4598 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.jvm.java.plugin;
import com.facebook.buck.jvm.java.plugin.api.PluginClassLoader;
import com.facebook.buck.jvm.java.plugin.api.PluginClassLoaderFactory;
import com.facebook.buck.util.ClassLoaderCache;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.annotation.Nullable;
import javax.tools.JavaCompiler;
/**
* Loads the Buck javac plugin JAR using the {@link ClassLoader} of a particular compiler instance.
*
* <p>{@link com.sun.source.tree} and {@link com.sun.source.util} packages are public APIs whose
* implementation is packaged with javac rather than in the Java runtime jar. Code that needs to
* work with these must be loaded using the same {@link ClassLoader} as the instance of javac with
* which it will be working.
*/
public final class PluginLoader implements PluginClassLoader {
private static final String JAVAC_PLUGIN_JAR_RESOURCE_PATH = "javac-plugin.jar";
private static final URL JAVAC_PLUGIN_JAR_URL = extractJavacPluginJar();
private final ClassLoader classLoader;
/**
* Extracts the jar containing the Buck javac plugin and returns a URL that can be given to a
* {@link java.net.URLClassLoader} to load it.
*/
private static URL extractJavacPluginJar() {
@Nullable URL resourceURL = PluginLoader.class.getResource(JAVAC_PLUGIN_JAR_RESOURCE_PATH);
if (resourceURL == null) {
throw new RuntimeException("Could not find javac plugin jar; Buck may be corrupted.");
} else if ("file".equals(resourceURL.getProtocol())) {
// When Buck is running from the repo, the jar is actually already on disk, so no extraction
// is necessary
return resourceURL;
} else {
// Running from a .pex file, extraction is required
try (InputStream resourceStream =
PluginLoader.class.getResourceAsStream(JAVAC_PLUGIN_JAR_RESOURCE_PATH)) {
File tempFile = File.createTempFile("javac-plugin", ".jar");
tempFile.deleteOnExit();
try (OutputStream tempFileStream = new FileOutputStream(tempFile)) {
ByteStreams.copy(resourceStream, tempFileStream);
return tempFile.toURI().toURL();
}
} catch (IOException e) {
throw new RuntimeException("Failed to extract javac plugin jar; cannot continue", e);
}
}
}
/** Returns a class loader that can be used to load classes from the compiler plugin jar. */
public static ClassLoader getPluginClassLoader(
ClassLoaderCache classLoaderCache, JavaCompiler.CompilationTask compiler) {
ClassLoader compilerClassLoader = compiler.getClass().getClassLoader();
return classLoaderCache.getClassLoaderForClassPath(
compilerClassLoader, ImmutableList.of(JAVAC_PLUGIN_JAR_URL));
}
public static PluginLoader newInstance(
ClassLoaderCache classLoaderCache, JavaCompiler.CompilationTask compiler) {
return new PluginLoader(getPluginClassLoader(classLoaderCache, compiler));
}
public static PluginClassLoaderFactory newFactory(ClassLoaderCache cache) {
return new PluginClassLoaderFactory() {
@Override
public PluginClassLoader getPluginClassLoader(JavaCompiler.CompilationTask task) {
return PluginLoader.newInstance(cache, task);
}
};
}
private PluginLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public <T> Class<? extends T> loadClass(String name, Class<T> superclass) {
if (classLoader == null) {
// No log here because we logged when the plugin itself failed to load
return null;
}
try {
return Class.forName(name, false, classLoader).asSubclass(superclass);
} catch (ClassNotFoundException e) {
throw new RuntimeException(String.format("Failed loading %s", name), e);
}
}
}
| apache-2.0 |
engagepoint/camel | camel-core/src/test/java/org/apache/camel/component/file/FileProduceGeneratedFileNameTest.java | 2112 | /**
* 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;
import java.io.File;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
/**
* Unit test that FileProducer can use message id as the filename.
*/
public class FileProduceGeneratedFileNameTest extends ContextTestSupport {
public void testGeneratedFileName() throws Exception {
Endpoint endpoint = context.getEndpoint("direct:a");
FileEndpoint fileEndpoint = resolveMandatoryEndpoint("file://target", FileEndpoint.class);
Exchange exchange = endpoint.createExchange();
exchange.getIn().setBody("Hello World");
String id = fileEndpoint.getGeneratedFileName(exchange.getIn());
template.send(endpoint, exchange);
File file = new File("target/" + id);
// use absolute file to let unittest pass on all platforms
file = file.getAbsoluteFile();
assertEquals("The generated file should exists: " + file, true, file.exists());
}
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("direct:a").to("file://target");
}
};
}
}
| apache-2.0 |
tananaev/traccar | src/main/java/org/traccar/protocol/SiwiProtocol.java | 1331 | /*
* Copyright 2017 - 2018 Anton Tananaev (anton@traccar.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.traccar.protocol;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.traccar.BaseProtocol;
import org.traccar.PipelineBuilder;
import org.traccar.TrackerServer;
public class SiwiProtocol extends BaseProtocol {
public SiwiProtocol() {
addServer(new TrackerServer(false, getName()) {
@Override
protected void addProtocolHandlers(PipelineBuilder pipeline) {
pipeline.addLast(new LineBasedFrameDecoder(1024));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new SiwiProtocolDecoder(SiwiProtocol.this));
}
});
}
}
| apache-2.0 |
mohanaraosv/commons-collections | src/test/java/org/apache/commons/collections4/bag/AbstractSortedBagTest.java | 4887 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections4.bag;
import java.util.Iterator;
import org.apache.commons.collections4.SortedBag;
/**
* Abstract test class for
* {@link org.apache.commons.collections4.SortedBag SortedBag}
* methods and contracts.
*
* @since 3.0
* @version $Id$
*/
public abstract class AbstractSortedBagTest<T> extends AbstractBagTest<T> {
public AbstractSortedBagTest(final String testName) {
super(testName);
}
//-----------------------------------------------------------------------
/**
* Verification extension, will check the order of elements,
* the sets should already be verified equal.
*/
@Override
public void verify() {
super.verify();
// Check that iterator returns elements in order and first() and last()
// are consistent
final Iterator<T> colliter = getCollection().iterator();
final Iterator<T> confiter = getConfirmed().iterator();
T first = null;
T last = null;
while (colliter.hasNext()) {
if (first == null) {
first = colliter.next();
last = first;
} else {
last = colliter.next();
}
assertEquals("Element appears to be out of order.", last, confiter.next());
}
if (getCollection().size() > 0) {
assertEquals("Incorrect element returned by first().", first,
getCollection().first());
assertEquals("Incorrect element returned by last().", last,
getCollection().last());
}
}
//-----------------------------------------------------------------------
/**
* Overridden because SortedBags don't allow null elements (normally).
* @return false
*/
@Override
public boolean isNullSupported() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public abstract SortedBag<T> makeObject();
/**
* {@inheritDoc}
*/
@Override
public SortedBag<T> makeFullCollection() {
return (SortedBag<T>) super.makeFullCollection();
}
/**
* Returns an empty {@link TreeBag} for use in modification testing.
*
* @return a confirmed empty collection
*/
@Override
public SortedBag<T> makeConfirmedCollection() {
return new TreeBag<T>();
}
//-----------------------------------------------------------------------
@Override
public void resetEmpty() {
this.setCollection(CollectionSortedBag.collectionSortedBag(makeObject()));
this.setConfirmed(makeConfirmedCollection());
}
@Override
public void resetFull() {
this.setCollection(CollectionSortedBag.collectionSortedBag(makeFullCollection()));
this.setConfirmed(makeConfirmedFullCollection());
}
//-----------------------------------------------------------------------
/**
* Override to return comparable objects.
*/
@Override
@SuppressWarnings("unchecked")
public T[] getFullNonNullElements() {
final Object[] elements = new Object[30];
for (int i = 0; i < 30; i++) {
elements[i] = Integer.valueOf(i + i + 1);
}
return (T[]) elements;
}
/**
* Override to return comparable objects.
*/
@Override
@SuppressWarnings("unchecked")
public T[] getOtherNonNullElements() {
final Object[] elements = new Object[30];
for (int i = 0; i < 30; i++) {
elements[i] = Integer.valueOf(i + i + 2);
}
return (T[]) elements;
}
//-----------------------------------------------------------------------
/**
* Returns the {@link #collection} field cast to a {@link SortedBag}.
*
* @return the collection field as a SortedBag
*/
@Override
public SortedBag<T> getCollection() {
return (SortedBag<T>) super.getCollection();
}
//-----------------------------------------------------------------------
// TODO: Add the SortedBag tests!
}
| apache-2.0 |
phantomjinx/modeshape | modeshape-jcr/src/test/java/org/modeshape/jcr/JcrObservationManagerTest.java | 96585 | /*
* ModeShape (http://www.modeshape.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.modeshape.jcr;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.modeshape.jcr.api.observation.Event.ALL_EVENTS;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import javax.jcr.NamespaceRegistry;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeType;
import javax.jcr.observation.Event;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventJournal;
import javax.jcr.observation.EventListener;
import javax.jcr.observation.ObservationManager;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.transaction.TransactionManager;
import org.apache.jackrabbit.test.api.observation.AddEventListenerTest;
import org.apache.jackrabbit.test.api.observation.EventIteratorTest;
import org.apache.jackrabbit.test.api.observation.EventTest;
import org.apache.jackrabbit.test.api.observation.GetRegisteredEventListenersTest;
import org.apache.jackrabbit.test.api.observation.NodeAddedTest;
import org.apache.jackrabbit.test.api.observation.NodeMovedTest;
import org.apache.jackrabbit.test.api.observation.NodeRemovedTest;
import org.apache.jackrabbit.test.api.observation.NodeReorderTest;
import org.apache.jackrabbit.test.api.observation.PropertyAddedTest;
import org.apache.jackrabbit.test.api.observation.PropertyChangedTest;
import org.apache.jackrabbit.test.api.observation.PropertyRemovedTest;
import org.apache.jackrabbit.test.api.observation.WorkspaceOperationTest;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.modeshape.common.FixFor;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.JcrObservationManager.JcrEventBundle;
import org.modeshape.jcr.api.observation.PropertyEvent;
import org.modeshape.jcr.api.value.DateTime;
import org.modeshape.jcr.value.Name;
/**
* The {@link JcrObservationManager} test class.
*/
public final class JcrObservationManagerTest extends SingleUseAbstractTest {
private static final String LOCK_MIXIN = "mix:lockable"; // extends referenceable
private static final String LOCK_OWNER = "jcr:lockOwner"; // property
private static final String LOCK_IS_DEEP = "jcr:lockIsDeep"; // property
// private static final String NT_BASE = "nt:base";
private static final String REF_MIXIN = "mix:referenceable";
private static final String UNSTRUCTURED = "nt:unstructured";
private static final String USER_ID = "superuser";
protected static final String WORKSPACE = "ws1";
protected static final String WORKSPACE2 = "ws2";
private Node testRootNode;
@BeforeClass
public static void beforeAll() {
// Initialize PicketBox ...
JaasTestUtil.initJaas("security/jaas.conf.xml");
}
@AfterClass
public static void afterAll() {
JaasTestUtil.releaseJaas();
}
@Override
protected boolean startRepositoryAutomatically() {
return false;
}
@Override
@Before
public void beforeEach() throws Exception {
super.beforeEach();
FileUtil.delete("target/journal");
startRepositoryWithConfiguration(resourceStream("config/repo-config-observation.json"));
session = login(WORKSPACE);
this.testRootNode = this.session.getRootNode().addNode("testroot", UNSTRUCTURED);
save();
}
SimpleListener addListener( int expectedEventsCount,
int eventTypes,
String absPath,
boolean isDeep,
String[] uuids,
String[] nodeTypeNames,
boolean noLocal ) throws Exception {
return addListener(expectedEventsCount, 1, eventTypes, absPath, isDeep, uuids, nodeTypeNames, noLocal);
}
SimpleListener addListener( int expectedEventsCount,
int numIterators,
int eventTypes,
String absPath,
boolean isDeep,
String[] uuids,
String[] nodeTypeNames,
boolean noLocal ) throws Exception {
return addListener(this.session,
expectedEventsCount,
numIterators,
eventTypes,
absPath,
isDeep,
uuids,
nodeTypeNames,
noLocal);
}
SimpleListener addListener( Session session,
int expectedEventsCount,
int eventTypes,
String absPath,
boolean isDeep,
String[] uuids,
String[] nodeTypeNames,
boolean noLocal ) throws Exception {
return addListener(session, expectedEventsCount, 1, eventTypes, absPath, isDeep, uuids, nodeTypeNames, noLocal);
}
SimpleListener addListener( Session session,
int expectedEventsCount,
int numIterators,
int eventTypes,
String absPath,
boolean isDeep,
String[] uuids,
String[] nodeTypeNames,
boolean noLocal ) throws Exception {
SimpleListener listener = new SimpleListener(expectedEventsCount, numIterators, eventTypes);
session.getWorkspace()
.getObservationManager()
.addEventListener(listener, eventTypes, absPath, isDeep, uuids, nodeTypeNames, noLocal);
return listener;
}
protected JcrSession login( String workspaceName ) throws RepositoryException {
Session session = repository.login(new SimpleCredentials(USER_ID, USER_ID.toCharArray()), workspaceName);
assertTrue(session != this.session);
return (JcrSession)session;
}
void checkResults( SimpleListener listener ) {
if (listener.getActualEventCount() != listener.getExpectedEventCount()) {
// Wrong number ...
StringBuilder sb = new StringBuilder(" Actual events were: ");
for (Event event : listener.getEvents()) {
sb.append('\n').append(event);
}
assertThat("Received incorrect number of events." + sb.toString(),
listener.getActualEventCount(),
is(listener.getExpectedEventCount()));
assertThat(listener.getErrorMessage(), listener.getErrorMessage(), is(nullValue()));
}
}
boolean containsPath( SimpleListener listener,
String path ) throws Exception {
for (Event event : listener.getEvents()) {
if (event.getPath().equals(path)) return true;
}
return false;
}
ObservationManager getObservationManager() throws RepositoryException {
return this.session.getWorkspace().getObservationManager();
}
Node getRoot() {
return testRootNode;
}
Workspace getWorkspace() {
return this.session.getWorkspace();
}
void removeListener( SimpleListener listener ) throws Exception {
this.session.getWorkspace().getObservationManager().removeEventListener(listener);
}
void save() throws RepositoryException {
this.session.save();
}
@Test
public void shouldNotReceiveEventIfUuidDoesNotMatch() throws Exception {
// setup
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
n1.addMixin(REF_MIXIN);
save();
// register listener
SimpleListener listener = addListener(0,
Event.PROPERTY_ADDED,
getRoot().getPath(),
true,
new String[] { UUID.randomUUID().toString() },
null,
false);
// create properties
n1.setProperty("prop1", "foo");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
}
@Test
public void shouldNotReceiveEventIfNodeTypeDoesNotMatch() throws Exception {
// setup
Node node1 = getRoot().addNode("node1", UNSTRUCTURED);
save();
// register listener
SimpleListener listener = addListener(0, ALL_EVENTS, null, false, null, new String[] {REF_MIXIN}, false);
// create event triggers
node1.setProperty("newProperty", "newValue"); // node1 is NOT referenceable
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
}
@Test
public void shouldReceiveNodeAddedEventWhenRegisteredToReceiveAllEvents() throws Exception {
// register listener (add + primary type property)
SimpleListener listener = addListener(4, ALL_EVENTS, null, false, null, null, false)
.withExpectedNodePrimaryType(UNSTRUCTURED).withExpectedNodeMixinTypes(REF_MIXIN);
// add node
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
addedNode.addMixin(REF_MIXIN);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
}
@Test
public void shouldReceiveNodeRemovedEventWhenRegisteredToReceiveAllEvents() throws Exception {
// add the node that will be removed
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
save();
// register listener (add + 3 property events)
SimpleListener listener = addListener(1, ALL_EVENTS, null, false, null, null, false).withExpectedNodePrimaryType(UNSTRUCTURED);
// remove node
String path = addedNode.getPath();
addedNode.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for removed node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected=" + path,
containsPath(listener, path));
}
@Test
public void shouldReceivePropertyAddedEventWhenRegisteredToReceiveAllEvents() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
node.addMixin(REF_MIXIN);
save();
// register listener
SimpleListener listener = addListener(1, ALL_EVENTS, null, false, null, null, false)
.withExpectedNodePrimaryType(UNSTRUCTURED).withExpectedNodeMixinTypes(REF_MIXIN);
// add the property
Property prop1 = node.setProperty("prop1", "prop1 content");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
Event propertyAddedEvent = listener.getEvents().get(0);
assertTrue("Path for added property is wrong: actual=" + propertyAddedEvent.getPath() + ", expected="
+ prop1.getPath(),
containsPath(listener, prop1.getPath()));
assertTrue(propertyAddedEvent instanceof PropertyEvent);
PropertyEvent propertyEvent = (PropertyEvent) propertyAddedEvent;
assertEquals("prop1 content", propertyEvent.getCurrentValue());
assertEquals(1, propertyEvent.getCurrentValues().size());
assertEquals("prop1 content", propertyEvent.getCurrentValues().get(0));
assertFalse(propertyEvent.isMultiValue());
assertFalse(propertyEvent.wasMultiValue());
assertNull(propertyEvent.getPreviousValue());
assertNull(propertyEvent.getPreviousValues());
}
@Test
public void shouldReceivePropertyChangedEventWhenRegisteredToReceiveAllEvents() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop1 = node.setProperty("prop1", "prop1 content");
save();
// register listener
SimpleListener listener = addListener(1, ALL_EVENTS, null, false, null, null, false).withExpectedNodePrimaryType(UNSTRUCTURED);
// change the property
prop1.setValue("prop1 modified content");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
Event propertyChangedEvent = listener.getEvents().get(0);
assertTrue("Path for changed property is wrong: actual=" + propertyChangedEvent.getPath() + ", expected="
+ prop1.getPath(),
containsPath(listener, prop1.getPath()));
assertTrue(propertyChangedEvent instanceof PropertyEvent);
PropertyEvent propertyEvent = (PropertyEvent) propertyChangedEvent;
assertEquals("prop1 modified content", propertyEvent.getCurrentValue());
assertEquals(1, propertyEvent.getCurrentValues().size());
assertEquals("prop1 modified content", propertyEvent.getCurrentValues().get(0));
assertFalse(propertyEvent.isMultiValue());
assertFalse(propertyEvent.wasMultiValue());
assertEquals("prop1 content", propertyEvent.getPreviousValue());
assertEquals(1, propertyEvent.getPreviousValues().size());
assertEquals("prop1 content", propertyEvent.getPreviousValues().get(0));
}
@Test
public void shouldReceivePropertyRemovedEventWhenRegisteredToReceiveAllEvents() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop = node.setProperty("prop1", "prop1 content");
String propPath = prop.getPath();
save();
// register listener
SimpleListener listener = addListener(1, ALL_EVENTS, null, false, null, null, false).withExpectedNodePrimaryType(UNSTRUCTURED);
// remove the property
prop.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
Event propertyRemovedEvent = listener.getEvents().get(0);
assertTrue("Path for removed property is wrong: actual=" + propertyRemovedEvent.getPath() + ", expected="
+ propPath, containsPath(listener, propPath));
assertTrue(propertyRemovedEvent instanceof PropertyEvent);
PropertyEvent propertyEvent = (PropertyEvent) propertyRemovedEvent;
assertEquals("prop1 content", propertyEvent.getCurrentValue());
assertEquals(1, propertyEvent.getCurrentValues().size());
assertEquals("prop1 content", propertyEvent.getCurrentValues().get(0));
assertFalse(propertyEvent.isMultiValue());
assertFalse(propertyEvent.wasMultiValue());
assertNull(propertyEvent.getPreviousValue());
assertNull(propertyEvent.getPreviousValues());
}
@Test
public void shouldReceivePropertyAddedEventWhenRegisteredToReceiveEventsBasedUponNodeTypeName() throws Exception {
// register listener
String[] nodeTypeNames = {"mode:root"};
SimpleListener listener = addListener(1, ALL_EVENTS, null, true, null, nodeTypeNames, false)
.withExpectedNodePrimaryType("mode:root");
// add the property
this.session.getRootNode().setProperty("fooProp", new String[]{"foo", "bar"});
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
String propPath = "/fooProp";
Event propertyAddedEvent = listener.getEvents().get(0);
assertTrue("Path for added property is wrong: actual=" + propertyAddedEvent.getPath() + ", expected=" + propPath,
containsPath(listener, propPath));
assertTrue(propertyAddedEvent instanceof PropertyEvent);
PropertyEvent propertyEvent = (PropertyEvent) propertyAddedEvent;
assertEquals("foo", propertyEvent.getCurrentValue());
assertEquals(2, propertyEvent.getCurrentValues().size());
assertEquals(Arrays.asList("foo", "bar"), propertyEvent.getCurrentValues());
assertTrue(propertyEvent.isMultiValue());
assertFalse(propertyEvent.wasMultiValue());
assertNull(propertyEvent.getPreviousValue());
assertNull(propertyEvent.getPreviousValues());
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.EventIteratorTest
// ===========================================================================================================================
/**
* @see EventIteratorTest#testGetPosition()
* @throws Exception
*/
@Test
public void shouldTestEventIteratorTest_testGetPosition() throws Exception {
// register listener
SimpleListener listener = addListener(3, Event.NODE_ADDED, null, false, null, null, false);
// add nodes to generate events
getRoot().addNode("node1", UNSTRUCTURED);
getRoot().addNode("node2", UNSTRUCTURED);
getRoot().addNode("node3", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
}
/**
* @see EventIteratorTest#testGetSize()
* @throws Exception
*/
@Test
public void shouldTestEventIteratorTest_testGetSize() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add node to generate event
getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
}
@Test
public void shouldTestEventIteratorTest_testSkip() throws Exception {
// create events
List<Event> events = new ArrayList<Event>();
DateTime now = session.dateFactory().create();
JcrEventBundle bundle = new JcrEventBundle(now, "userId", null);
String id1 = UUID.randomUUID().toString();
String id2 = UUID.randomUUID().toString();
String id3 = UUID.randomUUID().toString();
events.add(new JcrObservationManager.JcrEvent(bundle, Event.NODE_ADDED, "/testroot/node1",
id1, nodeType(JcrNtLexicon.UNSTRUCTURED), null));
events.add(new JcrObservationManager.JcrEvent(bundle, Event.NODE_ADDED, "/testroot/node2", id2,
nodeType(JcrNtLexicon.UNSTRUCTURED), null));
events.add(new JcrObservationManager.JcrEvent(bundle, Event.NODE_ADDED, "/testroot/node3", id3,
nodeType(JcrNtLexicon.UNSTRUCTURED), null));
// create iterator
EventIterator itr = new JcrObservationManager.JcrEventIterator(events);
// tests
itr.skip(0); // skip zero elements
assertThat("getPosition() for first element should return 0.", itr.getPosition(), is(0L));
itr.skip(2); // skip one element
assertThat("Wrong value when skipping ", itr.getPosition(), is(2L));
try {
itr.skip(2); // skip past end
fail("EventIterator must throw NoSuchElementException when skipping past the end");
} catch (NoSuchElementException e) {
// success
}
}
private NodeType nodeType(Name name) {
return session.repository().nodeTypeManager().getNodeTypes().getNodeType(name);
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.EventTest
// ===========================================================================================================================
/**
* @see EventTest#testGetNodePath()
* @throws Exception
*/
@Test
public void shouldTestEventTest_testGetNodePath() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add node to generate event
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
}
/**
* @see EventTest#testGetType()
* @throws Exception
*/
@Test
public void shouldTestEventTest_testGetType() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add node to generate event
getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertThat("Event did not return correct event type", listener.getEvents().get(0).getType(), is(Event.NODE_ADDED));
}
/**
* @see EventTest#testGetUserId()
* @throws Exception
*/
@Test
public void shouldTestEventTest_testGetUserId() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add a node to generate event
getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertThat("UserId of event is not equal to userId of session", listener.getEvents().get(0).getUserID(), is(USER_ID));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.GetRegisteredEventListenersTest
// ===========================================================================================================================
/**
* @see GetRegisteredEventListenersTest#testGetSize()
* @throws Exception
*/
@Test
public void shouldTestGetRegisteredEventListenersTest_testGetSize() throws Exception {
assertThat("A new session must not have any event listeners registered.",
getObservationManager().getRegisteredEventListeners().getSize(),
is(0L));
// register listener
SimpleListener listener = addListener(0, ALL_EVENTS, null, false, null, null, false);
addListener(0, ALL_EVENTS, null, false, null, null, false);
assertThat("Wrong number of event listeners.", getObservationManager().getRegisteredEventListeners().getSize(), is(2L));
// make sure same listener isn't added again
getObservationManager().addEventListener(listener, ALL_EVENTS, null, false, null, null, false);
assertThat("The same listener should not be added more than once.", getObservationManager().getRegisteredEventListeners()
.getSize(), is(2L));
}
/**
* @see GetRegisteredEventListenersTest#testRemoveEventListener()
* @throws Exception
*/
@Test
public void shouldTestGetRegisteredEventListenersTest_testRemoveEventListener() throws Exception {
SimpleListener listener1 = addListener(0, ALL_EVENTS, null, false, null, null, false);
EventListener listener2 = addListener(0, ALL_EVENTS, null, false, null, null, false);
assertThat("Wrong number of event listeners.", getObservationManager().getRegisteredEventListeners().getSize(), is(2L));
// now remove
removeListener(listener1);
assertThat("Wrong number of event listeners after removing a listener.",
getObservationManager().getRegisteredEventListeners().getSize(),
is(1L));
assertThat("Wrong number of event listeners after removing a listener.",
getObservationManager().getRegisteredEventListeners().nextEventListener(),
is(listener2));
}
@Test
@FixFor( "MODE-1407" )
public void shouldTestLockingTest_testAddLockToNode() throws Exception {
// setup
String node1 = "node1";
Node lockable = getRoot().addNode(node1, UNSTRUCTURED);
lockable.addMixin(LOCK_MIXIN);
save();
// register listener
SimpleListener listener = addListener(2, 2, Event.PROPERTY_ADDED, getRoot().getPath(), true, null, null, false);
// lock node (no save needed)
session.getWorkspace().getLockManager().lock(lockable.getPath(), false, true, 1L, "me");
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("No event created for " + LOCK_OWNER, containsPath(listener, lockable.getPath() + '/' + LOCK_OWNER));
assertTrue("No event created for " + LOCK_IS_DEEP, containsPath(listener, lockable.getPath() + '/' + LOCK_IS_DEEP));
}
@Test
@FixFor( "MODE-1407" )
public void shouldTestLockingTest_testRemoveLockFromNode() throws Exception {
// setup
String node1 = "node1";
Node lockable = getRoot().addNode(node1, UNSTRUCTURED);
lockable.addMixin(LOCK_MIXIN);
save();
session.getWorkspace().getLockManager().lock(lockable.getPath(), false, true, 1L, "me");
// register listener
SimpleListener listener = addListener(2, Event.PROPERTY_REMOVED, null, false, null, null, false);
// lock node (no save needed)
session.getWorkspace().getLockManager().unlock(lockable.getPath());
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("No event created for " + LOCK_OWNER, containsPath(listener, lockable.getPath() + '/' + LOCK_OWNER));
assertTrue("No event created for " + LOCK_IS_DEEP, containsPath(listener, lockable.getPath() + '/' + LOCK_IS_DEEP));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.NodeAddedTest
// ===========================================================================================================================
/**
* @see NodeAddedTest#testMultipleNodeAdded1()
* @throws Exception
*/
@Test
public void shouldTestNodeAddedTest_testMultipleNodeAdded1() throws Exception {
// register listener
SimpleListener listener = addListener(2, Event.NODE_ADDED, null, false, null, null, false);
// add a couple sibling nodes
Node addedNode1 = getRoot().addNode("node1", UNSTRUCTURED);
Node addedNode2 = getRoot().addNode("node2", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for first added node is wrong", containsPath(listener, addedNode1.getPath()));
assertTrue("Path for second added node is wrong", containsPath(listener, addedNode2.getPath()));
}
/**
* @see NodeAddedTest#testMultipleNodeAdded2()
* @throws Exception
*/
@Test
public void shouldTestNodeAddedTest_testMultipleNodeAdded2() throws Exception {
// register listener
SimpleListener listener = addListener(2, Event.NODE_ADDED, null, false, null, null, false);
// add node and child node
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
Node addedChildNode = addedNode.addNode("node2", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong", containsPath(listener, addedNode.getPath()));
assertTrue("Path for added child node is wrong", containsPath(listener, addedChildNode.getPath()));
}
/**
* @see NodeAddedTest#testSingleNodeAdded()
* @throws Exception
*/
@Test
public void shouldTestNodeAddedTest_testSingleNodeAdded() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add node
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
}
/**
* @see NodeAddedTest#testTransientNodeAddedRemoved()
* @throws Exception
*/
@Test
public void shouldTestNodeAddedTest_testTransientNodeAddedRemoved() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add a child node and immediately remove it
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
Node transientNode = addedNode.addNode("node2", UNSTRUCTURED); // should not get this event because of the following
// remove
transientNode.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.NodeRemovedTest
// ===========================================================================================================================
/**
* @see NodeRemovedTest#testMultiNodesRemoved()
* @throws Exception
*/
@Test
public void shouldTestNodeRemovedTest_testMultiNodesRemoved() throws Exception {
// register listener
SimpleListener listener = addListener(2, Event.NODE_REMOVED, null, false, null, null, false);
// add nodes to be removed
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
Node childNode = addedNode.addNode("node2", UNSTRUCTURED);
save();
// remove parent node which removes child node
String parentPath = addedNode.getPath();
String childPath = childNode.getPath();
addedNode.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for removed node is wrong", containsPath(listener, parentPath));
assertTrue("Path for removed child node is wrong", containsPath(listener, childPath));
}
/**
* @see NodeRemovedTest#testSingleNodeRemoved()
* @throws Exception
*/
@Test
public void shouldTestNodeRemovedTest_testSingleNodeRemoved() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// add the node that will be removed
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
save();
// remove node
String path = addedNode.getPath();
addedNode.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for removed node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected=" + path,
containsPath(listener, path));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.NodeMovedTest
// ===========================================================================================================================
/**
* @see NodeMovedTest#testMoveNode()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
public void shouldTestNodeMovedTest_testMoveNode() throws Exception {
// setup
String node1 = "node1";
String node2 = "node2";
Node n1 = getRoot().addNode(node1, UNSTRUCTURED);
Node n2 = n1.addNode(node2, UNSTRUCTURED);
String oldPath = n2.getPath();
save();
// register listeners
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// move node
String newPath = getRoot().getPath() + '/' + node2;
getWorkspace().move(oldPath, newPath);
save();
// event handling
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(oldPath));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(newPath));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(nullValue()));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + newPath, containsPath(moveNodeListener, newPath));
assertTrue("Path for new location of added node is wrong: actual=" + addNodeListener.getEvents().get(0).getPath()
+ ", expected=" + newPath, containsPath(addNodeListener, newPath));
assertTrue("Path for new location of removed node is wrong: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + oldPath, containsPath(removeNodeListener, oldPath));
}
/**
* @see NodeMovedTest#testMoveTree()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
@FixFor( "MODE-1410" )
public void shouldTestNodeMovedTest_testMoveTree() throws Exception {
// setup
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
String oldPath = n1.getPath();
n1.addNode("node2", UNSTRUCTURED);
save();
// register listeners
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// move node
String newPath = getRoot().getPath() + "/node3";
getWorkspace().move(oldPath, newPath);
save();
// event handling
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(oldPath));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(newPath));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(nullValue()));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + newPath, containsPath(moveNodeListener, newPath));
assertTrue("Path for new location of added node is wrong: actual=" + addNodeListener.getEvents().get(0).getPath()
+ ", expected=" + newPath, containsPath(addNodeListener, newPath));
assertTrue("Path for new location of removed node is wrong: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + oldPath, containsPath(removeNodeListener, oldPath));
}
/**
* @see NodeMovedTest#testMoveWithRemove()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
public void shouldTestNodeMovedTest_testMoveWithRemove() throws Exception {
// setup
String node2 = "node2";
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
Node n2 = n1.addNode(node2, UNSTRUCTURED);
Node n3 = getRoot().addNode("node3", UNSTRUCTURED);
save();
// register listeners
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(2, 2, Event.NODE_REMOVED, null, false, null, null, false);
// move node
String oldPath = n2.getPath();
String newPath = n3.getPath() + '/' + node2;
getWorkspace().move(oldPath, newPath);
// remove node
String removedNodePath = n1.getPath();
n1.remove();
save();
// event handling
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(oldPath));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(newPath));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + newPath, containsPath(moveNodeListener, newPath));
assertTrue("Path for new location of added node is wrong: actual=" + addNodeListener.getEvents().get(0).getPath()
+ ", expected=" + newPath, containsPath(addNodeListener, newPath));
assertTrue("Path for new location of removed node is wrong: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + oldPath, containsPath(removeNodeListener, oldPath));
assertTrue("Path for removed node is wrong", containsPath(removeNodeListener, removedNodePath));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.NodeReorderTest
// ===========================================================================================================================
/**
* @see NodeReorderTest#testNodeReorderSameName()
* @see NodeReorderTest#testNodeReorderSameNameWithRemove()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
public void shouldTestNodeReorderTest_testNodeReorder() throws Exception {
// setup
getRoot().addNode("node1", UNSTRUCTURED);
Node n2 = getRoot().addNode("node2", UNSTRUCTURED);
Node n3 = getRoot().addNode("node3", UNSTRUCTURED);
save();
// register listeners
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// reorder to trigger events
getRoot().orderBefore(n3.getName(), n2.getName());
save();
// handle events
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is("node3"));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is("node2"));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + n3.getPath(), containsPath(moveNodeListener, n3.getPath()));
assertTrue("Added reordered node has wrong path: actual=" + addNodeListener.getEvents().get(0).getPath() + ", expected="
+ n3.getPath(), containsPath(addNodeListener, n3.getPath()));
assertTrue("Removed reordered node has wrong path: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + n3.getPath(), containsPath(removeNodeListener, n3.getPath()));
}
/**
* @see NodeReorderTest#testNodeReorderSameName()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
@FixFor( "MODE-1409" )
public void shouldTestNodeReorderTest_testNodeReorderSameName() throws Exception {
// setup
String node1 = "node1";
Node n1 = getRoot().addNode(node1, UNSTRUCTURED);
getRoot().addNode(node1, UNSTRUCTURED);
getRoot().addNode(node1, UNSTRUCTURED);
save();
// register listeners + "[2]"
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// reorder to trigger events
getRoot().orderBefore(node1 + "[3]", node1 + "[2]");
save();
// handle events
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(node1 + "[3]"));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(node1 + "[2]"));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + getRoot().getPath() + "/" + node1 + "[2]",
containsPath(moveNodeListener, getRoot().getPath() + "/" + node1 + "[2]"));
assertTrue("Added reordered node has wrong path: actual=" + addNodeListener.getEvents().get(0).getPath() + ", expected="
+ n1.getPath() + "[2]", containsPath(addNodeListener, n1.getPath() + "[2]"));
assertTrue("Removed reordered node has wrong path: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + n1.getPath() + "[3]", containsPath(removeNodeListener, n1.getPath() + "[3]"));
}
/**
* @see NodeReorderTest#testNodeReorderSameNameWithRemove()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
@FixFor( "MODE-1409" )
public void shouldTestNodeReorderTest_testNodeReorderSameNameWithRemove() throws Exception {
// setup
String node1 = "node1";
Node n1 = getRoot().addNode(node1, UNSTRUCTURED);
getRoot().addNode("node2", UNSTRUCTURED);
getRoot().addNode(node1, UNSTRUCTURED);
getRoot().addNode(node1, UNSTRUCTURED);
Node n3 = getRoot().addNode("node3", UNSTRUCTURED);
save();
// register listeners + "[2]"
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(2, Event.NODE_REMOVED, null, false, null, null, false);
// trigger events
getRoot().orderBefore(node1 + "[2]", null);
String removedPath = n3.getPath();
n3.remove();
save();
// handle events
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
List<Event> moveNodeListenerEvents = moveNodeListener.getEvents();
assertFalse(moveNodeListenerEvents.isEmpty());
Map<String, String> info = moveNodeListenerEvents.get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(node1 + "[2]"));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(nullValue()));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListenerEvents.get(0).getPath()
+ ", expected=" + getRoot().getPath() + "/" + node1 + "[3]",
containsPath(moveNodeListener, getRoot().getPath() + "/" + node1 + "[3]"));
assertTrue("Added reordered node has wrong path: actual=" + addNodeListener.getEvents().get(0).getPath() + ", expected="
+ n1.getPath() + "[3]", containsPath(addNodeListener, n1.getPath() + "[3]"));
assertTrue("Removed reordered node path not found: " + n1.getPath() + "[2]",
containsPath(removeNodeListener, n1.getPath() + "[2]"));
assertTrue("Removed node path not found: " + removedPath, containsPath(removeNodeListener, removedPath));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.PropertyAddedTest
// ===========================================================================================================================
/**
* @see PropertyAddedTest#testMultiPropertyAdded()
* @throws Exception
*/
@Test
public void shouldTestPropertyAddedTest_testMultiPropertyAdded() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
save();
// register listener
SimpleListener listener = addListener(2, Event.PROPERTY_ADDED, null, false, null, null, false);
// add multiple properties
Property prop1 = node.setProperty("prop1", "prop1 content");
Property prop2 = node.setProperty("prop2", "prop2 content");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for first added property not found: " + prop1.getPath(), containsPath(listener, prop1.getPath()));
assertTrue("Path for second added property not found: " + prop2.getPath(), containsPath(listener, prop2.getPath()));
}
/**
* @see PropertyAddedTest#testSinglePropertyAdded()
* @throws Exception
*/
@Test
public void shouldTestPropertyAddedTest_testSinglePropertyAdded() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
save();
// register listener
SimpleListener listener = addListener(1, Event.PROPERTY_ADDED, null, false, null, null, false);
// add the property
Property prop1 = node.setProperty("prop1", "prop1 content");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added property is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ prop1.getPath(),
containsPath(listener, prop1.getPath()));
}
/**
* @see PropertyAddedTest#testSystemGenerated()
* @throws Exception
*/
@Test
public void shouldTestPropertyAddedTest_testSystemGenerated() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.PROPERTY_ADDED, null, false, null, null, false);
// create node (which adds 1 property)
Node node = getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for jrc:primaryType property was not found.",
containsPath(listener, node.getProperty("jcr:primaryType").getPath()));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.PropertyChangedTests
// ===========================================================================================================================
/**
* @see PropertyChangedTest#testMultiPropertyChanged()
* @throws Exception
*/
@Test
public void shouldTestPropertyChangedTests_testMultiPropertyChanged() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop1 = node.setProperty("prop1", "prop1 content");
Property prop2 = node.setProperty("prop2", "prop2 content");
save();
// register listener
SimpleListener listener = addListener(2, Event.PROPERTY_CHANGED, null, false, null, null, false);
// add multiple properties
prop1.setValue("prop1 modified content");
prop2.setValue("prop2 modified content");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for first changed property not found: " + prop1.getPath(), containsPath(listener, prop1.getPath()));
assertTrue("Path for second changed property not found: " + prop2.getPath(), containsPath(listener, prop2.getPath()));
}
/**
* @see PropertyChangedTest#testPropertyRemoveCreate()
* @throws Exception
*/
@Test
public void shouldTestPropertyChangedTests_testPropertyRemoveCreate() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
String propName = "prop1";
Property prop = node.setProperty(propName, propName + " content");
String propPath = prop.getPath();
save();
// register listeners
SimpleListener listener1 = addListener(1, Event.PROPERTY_CHANGED, null, false, null, null, false);
SimpleListener listener2 = addListener(2, Event.PROPERTY_ADDED | Event.PROPERTY_REMOVED, null, false, null, null, false);
// trigger events
prop.remove();
node.setProperty(propName, true);
save();
// event handling
listener1.waitForEvents();
removeListener(listener1);
listener2.waitForEvents();
removeListener(listener2);
// tests
if (listener1.getEvents().size() == 1) {
checkResults(listener1);
assertTrue("Path for removed then added property is wrong: actual=" + listener1.getEvents().get(0).getPath()
+ ", expected=" + propPath, containsPath(listener1, propPath));
} else {
checkResults(listener2);
assertTrue("Path for removed then added property is wrong: actual=" + listener2.getEvents().get(0).getPath()
+ ", expected=" + propPath, containsPath(listener2, propPath));
assertTrue("Path for removed then added property is wrong: actual=" + listener2.getEvents().get(1).getPath()
+ ", expected=" + propPath, containsPath(listener2, propPath));
}
}
/**
* @see PropertyChangedTest#testSinglePropertyChanged()
* @throws Exception
*/
@Test
public void shouldTestPropertyChangedTests_testSinglePropertyChanged() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop1 = node.setProperty("prop1", "prop1 content");
save();
// register listener
SimpleListener listener = addListener(1, Event.PROPERTY_CHANGED, null, false, null, null, false);
// change the property
prop1.setValue("prop1 modified content");
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for changed property is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ prop1.getPath(),
containsPath(listener, prop1.getPath()));
}
/**
* @see PropertyChangedTest#testSinglePropertyChangedWithAdded()
* @throws Exception
*/
@Test
public void shouldTestPropertyChangedTests_testSinglePropertyChangedWithAdded() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop1 = node.setProperty("prop1", "prop1 content");
save();
// register listener
SimpleListener listener = addListener(1, Event.PROPERTY_CHANGED, null, false, null, null, false);
// change the property
prop1.setValue("prop1 modified content");
node.setProperty("prop2", "prop2 content"); // property added event should not be received
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for changed property is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ prop1.getPath(),
containsPath(listener, prop1.getPath()));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.PropertyRemovedTest
// ===========================================================================================================================
/**
* @see PropertyRemovedTest#testMultiPropertyRemoved()
* @throws Exception
*/
@Test
public void shouldTestPropertyRemovedTest_testMultiPropertyRemoved() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop1 = node.setProperty("prop1", "prop1 content");
Property prop2 = node.setProperty("prop2", "prop2 content");
save();
// register listener
SimpleListener listener = addListener(2, Event.PROPERTY_REMOVED, null, false, null, null, false);
// remove the property
String prop1Path = prop1.getPath();
prop1.remove();
String prop2Path = prop2.getPath();
prop2.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for first removed property not found: " + prop1Path, containsPath(listener, prop1Path));
assertTrue("Path for second removed property not found: " + prop2Path, containsPath(listener, prop2Path));
}
/**
* @see PropertyRemovedTest#testSinglePropertyRemoved()
* @throws Exception
*/
@Test
public void shouldTestPropertyRemovedTest_testSinglePropertyRemoved() throws Exception {
// setup
Node node = getRoot().addNode("node1", UNSTRUCTURED);
Property prop = node.setProperty("prop1", "prop1 content");
String propPath = prop.getPath();
save();
// register listener
SimpleListener listener = addListener(1, Event.PROPERTY_REMOVED, null, false, null, null, false);
// remove the property
prop.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for removed property is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ propPath, containsPath(listener, propPath));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.AddEventListenerTest
// ===========================================================================================================================
/**
* @see AddEventListenerTest#testIsDeepFalseNodeAdded()
* @throws Exception
*/
@Test
public void shouldTestAddEventListenerTest_testIsDeepFalseNodeAdded() throws Exception {
// setup
String node1 = "node1";
String path = getRoot().getPath() + '/' + node1;
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, path, false, null, null, false);
// add child node under the path we care about
Node n1 = getRoot().addNode(node1, UNSTRUCTURED);
Node childNode = n1.addNode("node2", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
checkResults(listener);
assertTrue("Child node path is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ childNode.getPath(),
containsPath(listener, childNode.getPath()));
}
/**
* @see AddEventListenerTest#testIsDeepFalsePropertyAdded()
* @throws Exception
*/
@Test
public void shouldTestAddEventListenerTest_testIsDeepFalsePropertyAdded() throws Exception {
// setup
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
Node n2 = getRoot().addNode("node2", UNSTRUCTURED);
save();
// register listener
SimpleListener listener = addListener(1, Event.PROPERTY_ADDED, n1.getPath(), false, null, null, false);
// add property
String prop = "prop";
Property n1Prop = n1.setProperty(prop, "foo");
n2.setProperty(prop, "foo"); // should not receive event for this
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added property is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ n1Prop.getPath(),
containsPath(listener, n1Prop.getPath()));
}
/**
* @see AddEventListenerTest#testNodeType()
* @throws Exception
*/
@Test
public void shouldTestAddEventListenerTest_testNodeType() throws Exception {
// setup
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
n1.addMixin(LOCK_MIXIN);
Node n2 = getRoot().addNode("node2", UNSTRUCTURED);
save();
// register listener
SimpleListener listener = addListener(1,
Event.NODE_ADDED,
getRoot().getPath(),
true,
null,
new String[] {LOCK_MIXIN},
false);
// trigger events
String node3 = "node3";
Node n3 = n1.addNode(node3, UNSTRUCTURED);
n2.addNode(node3, UNSTRUCTURED);
save();
// handle events
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Wrong path: actual=" + listener.getEvents().get(0).getPath() + ", expected=" + n3.getPath(),
containsPath(listener, n3.getPath()));
}
/**
* @see AddEventListenerTest#testNoLocalTrue()
* @throws Exception
*/
@Test
public void shouldTestAddEventListenerTest_testNoLocalTrue() throws Exception {
// register listener
SimpleListener listener = addListener(0, Event.NODE_ADDED, getRoot().getPath(), true, null, null, true);
// trigger events
getRoot().addNode("node1", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
}
/**
* @see AddEventListenerTest#testPath()
* @throws Exception
*/
@Test
public void shouldTestAddEventListenerTest_testPath() throws Exception {
// setup
String node1 = "node1";
String path = getRoot().getPath() + '/' + node1;
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, path, true, null, null, false);
// add child node under the path we care about
Node n1 = getRoot().addNode(node1, UNSTRUCTURED);
Node childNode = n1.addNode("node2", UNSTRUCTURED);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Child node path is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ childNode.getPath(),
containsPath(listener, childNode.getPath()));
}
/**
* @see AddEventListenerTest#testUUID()
* @throws Exception
*/
@Test
public void shouldTestAddEventListenerTest_testUUID() throws Exception {
// setup
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
n1.addMixin(REF_MIXIN);
Node n2 = getRoot().addNode("node2", UNSTRUCTURED);
n2.addMixin(REF_MIXIN);
save();
// register listener
SimpleListener listener = addListener(1,
Event.PROPERTY_ADDED,
getRoot().getPath(),
true,
new String[] {n1.getIdentifier()},
null,
false);
// create properties
String prop1 = "prop1";
Property n1Prop = n1.setProperty(prop1, "foo");
n2.setProperty(prop1, "foo"); // should not get an event for this
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Wrong path: actual=" + listener.getEvents().get(0).getPath() + ", expected=" + n1Prop.getPath(),
containsPath(listener, n1Prop.getPath()));
}
// ===========================================================================================================================
// @see org.apache.jackrabbit.test.api.observation.WorkspaceOperationTest
// ===========================================================================================================================
/**
* @see WorkspaceOperationTest#testCopy()
* @throws Exception
*/
@FixFor( "MODE-1312" )
@Test
public void shouldTestWorkspaceOperationTest_testCopy() throws Exception {
// setup
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
String node2 = "node2";
addedNode.addNode(node2, UNSTRUCTURED);
save();
// register listener
SimpleListener listener = addListener(2, Event.NODE_ADDED, null, false, null, null, false);
// perform copy
String targetPath = getRoot().getPath() + "/node3";
getWorkspace().copy(addedNode.getPath(), targetPath);
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for copied node not found: " + targetPath, containsPath(listener, targetPath));
assertTrue("Path for copied child node not found: " + (targetPath + '/' + node2),
containsPath(listener, (targetPath + '/' + node2)));
}
/**
* @see WorkspaceOperationTest#testMove()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
public void shouldTestWorkspaceOperationTest_testMove() throws Exception {
// setup
String node2 = "node2";
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
n1.addNode(node2, UNSTRUCTURED);
Node n3 = getRoot().addNode("node3", UNSTRUCTURED);
save();
// register listeners
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// perform move
String oldPath = n1.getPath();
String targetPath = n3.getPath() + "/node4";
getWorkspace().move(oldPath, targetPath);
save();
// event handling
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(oldPath));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(targetPath));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(nullValue()));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + targetPath, containsPath(moveNodeListener, targetPath));
assertTrue("Path for new location of moved node is wrong: actual=" + addNodeListener.getEvents().get(0).getPath()
+ ", expected=" + targetPath, containsPath(addNodeListener, targetPath));
assertTrue("Path for old location of moved node is wrong: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + oldPath, containsPath(removeNodeListener, oldPath));
}
/**
* @see WorkspaceOperationTest#testRename()
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
@Test
@FixFor( "MODE-1410" )
public void shouldTestWorkspaceOperationTest_testRename() throws Exception {
// setup
Node n1 = getRoot().addNode("node1", UNSTRUCTURED);
n1.addNode("node2", UNSTRUCTURED);
save();
// register listeners
SimpleListener moveNodeListener = addListener(1, Event.NODE_MOVED, null, false, null, null, false);
SimpleListener addNodeListener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
SimpleListener removeNodeListener = addListener(1, Event.NODE_REMOVED, null, false, null, null, false);
// rename node
String oldPath = n1.getPath();
String renamedPath = getRoot().getPath() + "/node3";
getWorkspace().move(oldPath, renamedPath);
// event handling
moveNodeListener.waitForEvents();
removeListener(moveNodeListener);
addNodeListener.waitForEvents();
removeListener(addNodeListener);
removeNodeListener.waitForEvents();
removeListener(removeNodeListener);
// tests
checkResults(moveNodeListener);
checkResults(addNodeListener);
checkResults(removeNodeListener);
Map<String, String> info = moveNodeListener.getEvents().get(0).getInfo();
assertThat(info.get(JcrObservationManager.MOVE_FROM_KEY), is(oldPath));
assertThat(info.get(JcrObservationManager.MOVE_TO_KEY), is(renamedPath));
assertThat(info.get(JcrObservationManager.ORDER_SRC_KEY), is(nullValue()));
assertThat(info.get(JcrObservationManager.ORDER_DEST_KEY), is(nullValue()));
assertTrue("Path for new location of moved node is wrong: actual=" + moveNodeListener.getEvents().get(0).getPath()
+ ", expected=" + renamedPath, containsPath(moveNodeListener, renamedPath));
assertTrue("Path for renamed node is wrong: actual=" + addNodeListener.getEvents().get(0).getPath() + ", expected="
+ renamedPath, containsPath(addNodeListener, renamedPath));
assertTrue("Path for old name of renamed node is wrong: actual=" + removeNodeListener.getEvents().get(0).getPath()
+ ", expected=" + oldPath, containsPath(removeNodeListener, oldPath));
}
@Test
public void shouldNotReceiveEventsFromOtherWorkspaces() throws Exception {
// Log into a second workspace ...
Session session2 = login(WORKSPACE2);
// Register 2 listeners in the first session ...
SimpleListener listener1 = addListener(session, 2, ALL_EVENTS, "/", true, null, null, false);
SimpleListener addListener1 = addListener(session, 1, Event.NODE_ADDED, "/", true, null, null, false);
// Register 2 listeners in the second session ...
SimpleListener listener2 = addListener(session2, 0, ALL_EVENTS, "/", true, null, null, false);
SimpleListener addListener2 = addListener(session2, 0, Event.NODE_ADDED, "/", true, null, null, false);
// Add a node to the first session ...
session.getRootNode().addNode("nodeA", "nt:unstructured");
session.save();
// Wait for the events on the first session's listeners (that should get the events) ...
listener1.waitForEvents();
addListener1.waitForEvents();
removeListener(listener1);
removeListener(addListener1);
// Wait for the events on the second session's listeners (that should NOT get the events) ...
listener2.waitForEvents();
// addListener2.waitForEvents();
removeListener(listener2);
removeListener(addListener2);
// Verify the expected events were received ...
checkResults(listener1);
checkResults(addListener1);
checkResults(listener2);
checkResults(addListener2);
}
@FixFor( "MODE-786" )
@Test
public void shouldReceiveEventsForChangesToSessionNamespacesInSystemContent() throws Exception {
String uri = "http://acme.com/example/foobar/";
String prefix = "foobar";
assertNoSessionNamespace(uri, prefix);
SimpleListener listener = addListener(session, 0, ALL_EVENTS, "/jcr:system", true, null, null, false);
session.setNamespacePrefix(prefix, uri);
// Wait for the events on the session's listeners (that should NOT get the events) ...
listener.waitForEvents();
removeListener(listener);
// Verify the expected events were received ...
checkResults(listener);
}
@FixFor( "MODE-1408" )
@Test
public void shouldReceiveEventsForChangesToRepositoryNamespacesInSystemContent() throws Exception {
String uri = "http://acme.com/example/foobar/";
String prefix = "foobar";
assertNoRepositoryNamespace(uri, prefix);
Session session2 = login(WORKSPACE2);
SimpleListener listener = addListener(session, 4, ALL_EVENTS, "/jcr:system", true, null, null, false);
SimpleListener listener2 = addListener(session2, 4, ALL_EVENTS, "/jcr:system", true, null, null, false);
session.getWorkspace().getNamespaceRegistry().registerNamespace(prefix, uri);
// Wait for the events on the session's listeners (that should get the events) ...
listener.waitForEvents();
listener2.waitForEvents();
removeListener(listener);
removeListener(listener2);
assertThat(session.getWorkspace().getNamespaceRegistry().getPrefix(uri), is(prefix));
assertThat(session.getWorkspace().getNamespaceRegistry().getURI(prefix), is(uri));
// Verify the expected events were received ...
checkResults(listener);
checkResults(listener2);
}
@Test
public void shouldReceiveEventsForChangesToLocksInSystemContent() throws Exception {
Node root = session.getRootNode();
Node parentNode = root.addNode("lockedPropParent");
parentNode.addMixin("mix:lockable");
Node targetNode = parentNode.addNode("lockedTarget");
targetNode.setProperty("foo", "bar");
session.save();
// no event should be fired from the system path for the lock (excluded explicitly because the TCK does not expect events
// from this)
SimpleListener systemListener = addListener(session, 1, 2, ALL_EVENTS, "/jcr:system", true, null, null, false);
// 2 events (property added for isDeep and lock owner) should be fired for the lock in the regular path (as per TCK)
SimpleListener nodeListener = addListener(session, 2, 2, ALL_EVENTS, parentNode.getPath(), true, null, null, false);
lock(parentNode, true, true);
// Wait for the events on the session's listeners (that should get the events) ...
systemListener.waitForEvents();
removeListener(systemListener);
// Verify the expected events were received ...
checkResults(systemListener);
nodeListener.waitForEvents();
removeListener(nodeListener);
checkResults(nodeListener);
}
@FixFor( "MODE-786" )
@Test
public void shouldReceiveEventsForChangesToVersionsInSystemContent() throws Exception {
int numEvents = 22;
SimpleListener listener = addListener(session, numEvents, ALL_EVENTS, "/jcr:system", true, null, null, false);
Node node = session.getRootNode().addNode("/test", "nt:unstructured");
node.addMixin("mix:versionable");
session.save(); // SHOULD GENERATE AN EVENT TO CREATE VERSION HISTORY FOR THE NODE
// Wait for the events on the session's listeners (that should get the events) ...
listener.waitForEvents();
removeListener(listener);
Node history = node.getProperty("jcr:versionHistory").getNode();
assertThat(history, is(notNullValue()));
assertThat(node.hasProperty("jcr:baseVersion"), is(true));
Node version = node.getProperty("jcr:baseVersion").getNode();
assertThat(version, is(notNullValue()));
assertThat(version.getParent(), is(history));
assertThat(node.hasProperty("jcr:uuid"), is(true));
assertThat(node.getProperty("jcr:uuid").getString(), is(history.getProperty("jcr:versionableUuid").getString()));
assertThat(versionHistory(node).getIdentifier(), is(history.getIdentifier()));
assertThat(versionHistory(node).getPath(), is(history.getPath()));
assertThat(baseVersion(node).getIdentifier(), is(version.getIdentifier()));
assertThat(baseVersion(node).getPath(), is(version.getPath()));
// Verify the expected events were received ...
checkResults(listener);
}
@FixFor( " MODE-1315 " )
@Test
public void shouldReceiveEventWhenPropertyDeletedOnCustomNode() throws Exception {
session.getWorkspace()
.getNodeTypeManager()
.registerNodeTypes(getClass().getClassLoader().getResourceAsStream("cars.cnd"), true);
Node car = getRoot().addNode("car", "car:Car");
car.setProperty("car:maker", "Audi");
session.save();
SimpleListener listener = addListener(1, Event.PROPERTY_REMOVED, null, true, null, new String[] {"car:Car"}, false);
Property carMakerProperty = car.getProperty("car:maker");
String propertyPath = carMakerProperty.getPath();
carMakerProperty.remove();
session.save();
listener.waitForEvents();
checkResults(listener);
Event receivedEvent = listener.getEvents().get(0);
assertEquals(Event.PROPERTY_REMOVED, receivedEvent.getType());
assertEquals(propertyPath, receivedEvent.getPath());
}
@FixFor( "MODE-1370" )
@Test
public void shouldReceiveUserDataWithEventWhenObservationSessionIsSameThatMadeChange() throws Exception {
// register listener
SimpleListener listener = addListener(1, Event.NODE_ADDED, null, false, null, null, false);
// add node
Node addedNode = getRoot().addNode("node1", UNSTRUCTURED);
// Add user-data to the observation manager ...
String userData = "my user data";
getRoot().getSession().getWorkspace().getObservationManager().setUserData(userData);
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
// Now check the userdata in the events ...
for (Event event : listener.events) {
String eventUserData = event.getUserData();
assertThat(eventUserData, is(userData));
}
// Now check the userdata ...
assertThat(listener.userData.size(), is(not(0)));
for (String receivedUserData : listener.userData) {
assertThat(receivedUserData, is(userData));
}
}
@FixFor( "MODE-1370" )
@Test
public void shouldReceiveUserDataWithEventWhenUserDataSetOnSessionThatMadeChange() throws Exception {
// Now register a listener
SimpleListener listener = new SimpleListener(1, 1, Event.NODE_ADDED);
session.getWorkspace()
.getObservationManager()
.addEventListener(listener, Event.NODE_ADDED, null, true, null, null, false);
// Create a new session ...
Session session2 = login(WORKSPACE);
// Add user-data to the observation manager for our session ...
String userData = "my user data";
session2.getWorkspace().getObservationManager().setUserData(userData);
// add node and save
Node addedNode = session2.getRootNode().addNode("node1", UNSTRUCTURED);
session2.save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
// Now check the userdata in the events ...
for (Event event : listener.events) {
String eventUserData = event.getUserData();
assertThat(eventUserData, is(userData));
}
// Now check the userdata ...
assertThat(listener.userData.size(), is(not(0)));
for (String receivedUserData : listener.userData) {
assertThat(receivedUserData, is(userData));
}
}
@FixFor( "MODE-1370" )
@Test
public void shouldNotReceiveUserDataWithEventIfUserDataSetOnObservationSession() throws Exception {
// Add user-data to the observation manager using the observation session ...
String userData = "my user data";
ObservationManager om = session.getWorkspace().getObservationManager();
om.setUserData(userData);
// Now register a listener
SimpleListener listener = new SimpleListener(1, 1, Event.NODE_ADDED);
session.getWorkspace()
.getObservationManager()
.addEventListener(listener, Event.NODE_ADDED, null, true, null, null, false);
// Create a new session and do NOT set the user data ...
Session session2 = login(WORKSPACE);
// but add node and save ...
Node addedNode = session2.getRootNode().addNode("node1", UNSTRUCTURED);
session2.save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
// Now check the userdata in the events ...
for (Event event : listener.events) {
String eventUserData = event.getUserData();
assertThat(eventUserData, is(nullValue()));
}
// Now check the userdata ...
assertThat(listener.userData.size(), is(1));
for (String receivedUserData : listener.userData) {
assertThat(receivedUserData, is(nullValue()));
}
}
@Test
@FixFor( "MODE-2268" )
public void shouldReceiveNonLocalEvents() throws Exception {
// register a non-local listener with the 1st session
SimpleListener listener = new SimpleListener(1, 1, Event.NODE_ADDED);
session.getWorkspace()
.getObservationManager()
.addEventListener(listener, Event.NODE_ADDED, null, true, null, null, true);
//create a node in the 1st session - the listener should not get this event
session.getRootNode().addNode("session1Node");
session.save();
// Create a new session ...
Session session2 = login(WORKSPACE);
// add node and save
Node addedNode = session2.getRootNode().addNode("session2Node");
session2.save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for added node is wrong: actual=" + listener.getEvents().get(0).getPath() + ", expected="
+ addedNode.getPath(),
containsPath(listener, addedNode.getPath()));
}
@Test
@FixFor( "MODE-2019" )
public void shouldProvideFullEventJournal() throws Exception {
// add node
Node node1 = getRoot().addNode("node1");
node1.setProperty("prop1", "value");
node1.setProperty("prop2", "value2");
Node node2 = getRoot().addNode("node2");
session.save();
Thread.sleep(100);
node1.setProperty("prop2", "edited value");
node1.setProperty("prop1", (String) null);
node2.remove();
session.save();
Thread.sleep(100);
EventJournal eventJournal = getObservationManager().getEventJournal();
assertPathsInJournal(eventJournal, false,
"/testroot/node1", "/testroot/node1/jcr:primaryType", "/testroot/node1/prop1",
"/testroot/node1/prop2", "/testroot/node2/jcr:primaryType", "/testroot/node2/jcr:primaryType",
"/testroot/node1/prop2", "/testroot/node1/prop1", "/testroot/node1/prop2");
}
@Test
@FixFor( "MODE-2019" )
public void shouldProvideFilteredEventJournal() throws Exception {
// add node
Node node1 = getRoot().addNode("node1");
getRoot().addNode("node2");
Node node3 = getRoot().addNode("node3");
session.save();
Thread.sleep(200);
EventJournal eventJournal = getObservationManager().getEventJournal(org.modeshape.jcr.api.observation.Event.ALL_EVENTS,
null, true, new String[]{node1.getIdentifier(),
node3.getIdentifier()},
null);
assertPathsInJournal(eventJournal, true,
"/testroot/node1", "/testroot/node1/jcr:primaryType",
"/testroot/node3", "/testroot/node3/jcr:primaryType");
}
@Test
@FixFor( "MODE-2019" )
public void shouldSkipToEventsInJournal() throws Exception {
long startingDate = System.currentTimeMillis();
getRoot().addNode("node1");
session.save();
Thread.sleep(100);
long afterNode1 = System.currentTimeMillis();
getRoot().addNode("node2");
session.save();
Thread.sleep(100);
long afterNode2 = System.currentTimeMillis();
getRoot().addNode("node3");
session.save();
Thread.sleep(100);
long afterNode3 = System.currentTimeMillis();
EventJournal journal = getObservationManager().getEventJournal();
journal.skipTo(startingDate);
assertPathsInJournal(journal, true,
"/testroot/node1", "/testroot/node1/jcr:primaryType",
"/testroot/node2", "/testroot/node2/jcr:primaryType",
"/testroot/node3", "/testroot/node3/jcr:primaryType");
journal = getObservationManager().getEventJournal();
journal.skipTo(afterNode1);
assertPathsInJournal(journal, true,
"/testroot/node2", "/testroot/node2/jcr:primaryType",
"/testroot/node3", "/testroot/node3/jcr:primaryType");
journal = getObservationManager().getEventJournal();
journal.skipTo(afterNode2);
assertPathsInJournal(journal, true,
"/testroot/node3", "/testroot/node3/jcr:primaryType");
journal = getObservationManager().getEventJournal();
journal.skipTo(afterNode3);
assertFalse(journal.hasNext());
}
@Test
@FixFor( "MODE-2336" )
public void shouldReceiveNodeTypeFilteredEventsWithUserTransactions() throws Exception {
stopRepository();
startRepositoryWithConfiguration(resourceStream("config/repo-config-inmemory-jbosstxn.json"));
session = repository.login();
// initialize workspace
session.getRootNode().addNode("folder1");
session.save();
// register listener for PropertyEvent with nodeType restriction
Session listenerSession = newSession();
EventListener listener = new EventListener() {
@Override
public void onEvent(EventIterator events) {
while (events.hasNext()) {
events.nextEvent();
}
}
};
listenerSession
.getWorkspace()
.getObservationManager()
.addEventListener(listener, ALL_EVENTS, "/folder1", true, null, new String[] { "nt:unstructured" }, false);
// try to add nodes within transactions
TransactionManager txMgr = repository.transactionManager();
for (int i = 0; i < 1000; i++) {
txMgr.begin();
Session writerSession = repository().login();
String nodeName = "node" + i;
writerSession.getNode("/folder1").addNode(nodeName);
writerSession.save();
writerSession.logout();
txMgr.commit();
}
// wait for listener thread
Thread.sleep(1000);
// clean
listenerSession.getWorkspace().getObservationManager().removeEventListener(listener);
listenerSession.logout();
}
@Test
@FixFor( "MODE-2379" )
public void shouldReceiveEventsWhenFilteringBasedOnNodeTypeAndParentsRemoved() throws Exception {
// register listener
SimpleListener listener = addListener(2, Event.NODE_REMOVED, null, false, null, new String[]{UNSTRUCTURED}, false);
// add nodes to be removed
Node parent = getRoot().addNode("parent", UNSTRUCTURED);
Node child = parent.addNode("child", UNSTRUCTURED);
save();
// remove parent node which removes child node
String parentPath = parent.getPath();
String childPath = child.getPath();
parent.remove();
save();
// event handling
listener.waitForEvents();
removeListener(listener);
// tests
checkResults(listener);
assertTrue("Path for removed node is wrong", containsPath(listener, parentPath));
assertTrue("Path for removed child node is wrong", containsPath(listener, childPath));
}
protected void assertPathsInJournal(EventJournal journal, boolean assertSize, String...expectedPaths) throws RepositoryException {
assertNotNull("Event journal not configured", journal);
assertEquals("Event journal size not known upfront", -1, journal.getSize());
List<String> eventPaths = new ArrayList<>();
while (journal.hasNext()) {
Event event = journal.nextEvent();
eventPaths.add(event.getPath());
}
if (assertSize) {
assertEquals("Incorrect number of events in journal", eventPaths.size(), expectedPaths.length);
}
assertTrue(eventPaths.containsAll(Arrays.asList(expectedPaths)));
}
protected void assertNoRepositoryNamespace( String uri,
String prefix ) throws RepositoryException {
NamespaceRegistry registry = session.getWorkspace().getNamespaceRegistry();
for (String existingPrefix : registry.getPrefixes()) {
assertThat(existingPrefix.equals(prefix), is(false));
}
for (String existingUri : registry.getURIs()) {
assertThat(existingUri.equals(uri), is(false));
}
}
protected void assertNoSessionNamespace( String uri,
String prefix ) throws RepositoryException {
for (String existingPrefix : session.getNamespacePrefixes()) {
assertThat(existingPrefix.equals(prefix), is(false));
String existingUri = session.getNamespaceURI(existingPrefix);
assertThat(existingUri.equals(uri), is(false));
}
}
protected VersionHistory versionHistory( Node node ) throws RepositoryException {
return session.getWorkspace().getVersionManager().getVersionHistory(node.getPath());
}
protected Version baseVersion( Node node ) throws RepositoryException {
return session.getWorkspace().getVersionManager().getBaseVersion(node.getPath());
}
protected void lock( Node node,
boolean isDeep,
boolean isSessionScoped ) throws RepositoryException {
session.getWorkspace().getLockManager().lock(node.getPath(), isDeep, isSessionScoped, 1L, "owner");
}
}
| apache-2.0 |
smmribeiro/intellij-community | java/debugger/impl/src/com/intellij/debugger/memory/utils/InstanceJavaValue.java | 902 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.memory.utils;
import com.intellij.debugger.engine.JavaValue;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
import org.jetbrains.annotations.NotNull;
public class InstanceJavaValue extends JavaValue {
public InstanceJavaValue(@NotNull ValueDescriptorImpl valueDescriptor,
@NotNull EvaluationContextImpl evaluationContext,
NodeManagerImpl nodeManager) {
super(null, valueDescriptor, evaluationContext, nodeManager, false);
}
@Override
public boolean canNavigateToSource() {
return false;
}
}
| apache-2.0 |
mxm/incubator-beam | sdks/java/io/common/src/test/java/org/apache/beam/sdk/io/common/IOTestPipelineOptions.java | 1327 | /*
* 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.beam.sdk.io.common;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.testing.TestPipelineOptions;
/** Pipeline options common for IO integration tests. */
public interface IOTestPipelineOptions extends TestPipelineOptions {
/* Used by most IOIT */
@Description("Number records that will be written and read by the test")
@Default.Integer(100000)
Integer getNumberOfRecords();
void setNumberOfRecords(Integer count);
}
| apache-2.0 |
akiellor/selenium | java/client/src/org/openqa/selenium/iphone/IPhoneSimulatorDriver.java | 934 | package org.openqa.selenium.iphone;
import java.net.URL;
/**
* @author jmleyba@gmail.com (Jason Leyba)
*/
public class IPhoneSimulatorDriver extends IPhoneDriver {
public IPhoneSimulatorDriver(URL iWebDriverUrl, IPhoneSimulatorBinary iphoneSimulator)
throws Exception {
super(new IPhoneSimulatorCommandExecutor(iWebDriverUrl, iphoneSimulator));
}
public IPhoneSimulatorDriver(String iWebDriverUrl, IPhoneSimulatorBinary iphoneSimulator)
throws Exception {
this(new URL(iWebDriverUrl), iphoneSimulator);
}
public IPhoneSimulatorDriver(IPhoneSimulatorBinary iphoneSimulator) throws Exception {
this(DEFAULT_IWEBDRIVER_URL, iphoneSimulator);
}
@Override
protected void startClient() {
((IPhoneSimulatorCommandExecutor) getCommandExecutor()).startClient();
}
@Override
protected void stopClient() {
((IPhoneSimulatorCommandExecutor) getCommandExecutor()).stopClient();
}
}
| apache-2.0 |
marcusholl/xcode-maven-plugin | modules/xcode-maven-plugin/src/main/java/com/sap/prd/mobile/ios/mios/XCodeDefaultConfigurationMojo.java | 7621 | /*
* #%L
* xcode-maven-plugin
* %%
* Copyright (C) 2012 SAP AG
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.sap.prd.mobile.ios.mios;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.LogManager;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
/**
* Sets default values needed during Xcode build.
*
* @goal set-default-configuration
*/
public class XCodeDefaultConfigurationMojo extends AbstractMojo
{
private static final String DEFAULT_MAVEN_SOURCE_DIRECTORY = "src/main/java";
static final String DEFAULT_XCODE_SOURCE_DIRECTORY = "src/xcode";
private static final String DEFAULT_FOLDER_NAME_CHECKOUT_DIRECTORY = "checkout";
private static final String XCODE_CHECKOUT_DIR = "xcode.checkoutDirectory";
private static final String XCODE_COMPILE_DIR = "xcode.compileDirectory";
static final String XCODE_SOURCE_DIRECTORY = "xcode.sourceDirectory";
/**
* @parameter expression="${project}"
* @required
*/
protected MavenProject project;
private static XCodePluginLogger logger = new XCodePluginLogger();
static {
if(null == LogManager.getLogManager().getLogger(XCodePluginLogger.getLoggerName())) {
LogManager.getLogManager().addLogger(logger);
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
final Properties projectProperties = project.getProperties();
if (!projectProperties.containsKey(XCODE_SOURCE_DIRECTORY)) {
projectProperties.setProperty(XCODE_SOURCE_DIRECTORY, DEFAULT_XCODE_SOURCE_DIRECTORY);
getLog().info(
"Property ${" + XCODE_SOURCE_DIRECTORY + "} was not set. ${" + XCODE_SOURCE_DIRECTORY + "} set to '"
+ projectProperties.getProperty(XCODE_SOURCE_DIRECTORY) + "'.");
}
else {
getLog().info(
"Property ${" + XCODE_SOURCE_DIRECTORY + "} found with value '"
+ projectProperties.getProperty(XCODE_SOURCE_DIRECTORY) + "' This value will no be modified");
project.getBuild().setSourceDirectory(
FileUtils.getCanonicalPath(new File(project.getBasedir(), projectProperties.getProperty(XCODE_SOURCE_DIRECTORY))));
}
if (project.getBuild().getSourceDirectory().contains("${" + XCODE_SOURCE_DIRECTORY + "}")) {
project.getBuild().setSourceDirectory(
project.getBuild().getSourceDirectory()
.replace("${" + XCODE_SOURCE_DIRECTORY + "}", projectProperties.getProperty(XCODE_SOURCE_DIRECTORY)));
getLog().info(
"Project Build directory detected with unresolved property ${" + XCODE_SOURCE_DIRECTORY
+ "}. This property is resolved to '"
+ projectProperties.getProperty(XCODE_SOURCE_DIRECTORY) + "'.");
}
String sourceDirectory = getCurrentSourceDirectory(FileUtils.getCanonicalFile(project.getBasedir()),
FileUtils.getCanonicalFile(new File(project.getBuild().getSourceDirectory())));
if (sourceDirectory.equals(DEFAULT_MAVEN_SOURCE_DIRECTORY)) {
project.getBuild().setSourceDirectory(
FileUtils.getCanonicalPath(new File(project.getBasedir(), DEFAULT_XCODE_SOURCE_DIRECTORY)));
getLog().info(
"Build source directory was found to bet '" + DEFAULT_MAVEN_SOURCE_DIRECTORY
+ "' which is the maven default. Set to xcode default '" + DEFAULT_XCODE_SOURCE_DIRECTORY + "'.");
sourceDirectory = DEFAULT_XCODE_SOURCE_DIRECTORY;
}
else {
getLog().info(
"Build source directory was found to be '" + sourceDirectory
+ "' which is not the default value in maven. This value is not modified.");
}
File checkoutDirectory = FileUtils.getCanonicalFile(new File(new File(project.getBuild().getDirectory()),
DEFAULT_FOLDER_NAME_CHECKOUT_DIRECTORY));
if (!projectProperties.containsKey(XCODE_CHECKOUT_DIR)) {
projectProperties.setProperty(XCODE_CHECKOUT_DIR, FileUtils.getCanonicalPath(checkoutDirectory));
getLog().info(
"Property ${" + XCODE_CHECKOUT_DIR + "} was not set. ${" + XCODE_CHECKOUT_DIR + "} set to '"
+ FileUtils.getCanonicalPath(checkoutDirectory) + "'.");
}
else {
getLog().info(
"Property ${" + XCODE_CHECKOUT_DIR + "} found with value '"
+ projectProperties.getProperty(XCODE_CHECKOUT_DIR) + "'. This value will not be modified.");
checkoutDirectory = FileUtils.getCanonicalFile(new File(new File(project.getBuild().getDirectory()),
projectProperties.getProperty(XCODE_CHECKOUT_DIR)));
projectProperties.setProperty(XCODE_CHECKOUT_DIR, FileUtils.getCanonicalPath(checkoutDirectory));
}
final File compileDirectory = FileUtils.getCanonicalFile(new File(checkoutDirectory, sourceDirectory));
if (!projectProperties.containsKey(XCODE_COMPILE_DIR)) {
projectProperties.setProperty(XCODE_COMPILE_DIR, FileUtils.getCanonicalPath(compileDirectory));
getLog().info(
"Property ${" + XCODE_COMPILE_DIR + "} was not set. ${" + XCODE_COMPILE_DIR + "} set to "
+ FileUtils.getCanonicalPath(compileDirectory));
}
else if (!compileDirectory.equals(FileUtils.getCanonicalFile(new File(projectProperties.getProperty(XCODE_COMPILE_DIR))))) {
getLog()
.warn("Property ${"
+ XCODE_COMPILE_DIR
+ "} was found to be '"
+ projectProperties.getProperty(XCODE_COMPILE_DIR)
+ "' but should be '"
+ compileDirectory
+ "'. That property will be updated accordingly. Fix this issue in your pom file e.g by removing property ${"
+ XCODE_COMPILE_DIR + "}.");
projectProperties.setProperty(XCODE_COMPILE_DIR, FileUtils.getCanonicalPath(compileDirectory));
}
else {
getLog().info(
"Property ${" + XCODE_COMPILE_DIR + "} was found with value '" + compileDirectory
+ "' which is the expended value. This value is not modified.");
}
getLog().info("Summary:");
getLog().info("${project.build.sourceDirectory}: " + project.getBuild().getSourceDirectory());
getLog().info("${" + XCODE_CHECKOUT_DIR + "} : " + project.getProperties().getProperty(XCODE_CHECKOUT_DIR));
getLog().info("${" + XCODE_COMPILE_DIR + "} : " + project.getProperties().getProperty(XCODE_COMPILE_DIR));
getLog().info("${" + XCODE_SOURCE_DIRECTORY + "}: " + project.getProperties().getProperty(XCODE_SOURCE_DIRECTORY));
}
/**
*
* @return The part of the path that is under $project.basedir that represents the
* sourceDirectory. Assumption is: sourceDirectory is located under the project base
* directory.
*/
private String getCurrentSourceDirectory(final File baseDir, final File sourceDir)
{
return FileUtils.getDelta(baseDir, sourceDir);
}
}
| apache-2.0 |
mikeweisskopf/RxNetty | rxnetty-http/src/test/java/io/reactivex/netty/protocol/http/client/HttpClientPoolTest.java | 7035 | /*
* Copyright 2015 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 io.reactivex.netty.protocol.http.client;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.client.pool.FIFOIdleConnectionsHolder;
import io.reactivex.netty.client.pool.PoolConfig;
import io.reactivex.netty.client.pool.PooledConnection;
import io.reactivex.netty.protocol.http.client.internal.HttpClientResponseImpl;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import rx.observers.TestSubscriber;
import java.nio.channels.ClosedChannelException;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class HttpClientPoolTest {
@Rule
public final PooledHttpClientRule clientRule = new PooledHttpClientRule();
@Test(timeout = 60000)
public void testBasicAcquireRelease() throws Exception {
clientRule.assertIdleConnections(0);
final HttpClientRequest<ByteBuf, ByteBuf> request1 = clientRule.getHttpClient().createGet("/");
TestSubscriber<Void> subscriber = clientRule.sendRequestAndDiscardResponseContent(request1);
clientRule.assertIdleConnections(0); // No idle connections post connect
clientRule.assertRequestHeadersWritten(HttpMethod.GET, "/");
clientRule.feedResponseAndComplete();
subscriber.assertTerminalEvent();
subscriber.assertNoErrors();
clientRule.getLastCreatedChannel().runPendingTasks();
clientRule.assertIdleConnections(1);
}
@Test(timeout = 60000)
public void testBasicAcquireReleaseWithServerClose() throws Exception {
clientRule.assertIdleConnections(0);
final HttpClientRequest<ByteBuf, ByteBuf> request1 = clientRule.getHttpClient().createGet("/");
TestSubscriber<Void> subscriber = clientRule.sendRequestAndDiscardResponseContent(request1);
clientRule.assertIdleConnections(0); // No idle connections post connect
clientRule.assertRequestHeadersWritten(HttpMethod.GET, "/");
clientRule.getLastCreatedChannel().close().await();
subscriber.assertTerminalEvent();
assertThat("On complete sent instead of onError", subscriber.getOnCompletedEvents(), is(empty()));
assertThat("Unexpected error notifications count.", subscriber.getOnErrorEvents(), hasSize(1));
assertThat("Unexpected error notification.", subscriber.getOnErrorEvents().get(0),
is(instanceOf(ClosedChannelException.class)));
clientRule.getLastCreatedChannel().runPendingTasks();
clientRule.assertIdleConnections(0); // Since, channel is closed, it should be discarded.
}
@Test(timeout = 60000)
public void testCloseOnKeepAliveTimeout() throws Exception {
clientRule.assertIdleConnections(0);
final HttpClientRequest<ByteBuf, ByteBuf> request1 = clientRule.getHttpClient().createGet("/");
TestSubscriber<HttpClientResponse<ByteBuf>> responseSub = clientRule.sendRequest(request1);
clientRule.assertIdleConnections(0); // No idle connections post connect
clientRule.assertRequestHeadersWritten(HttpMethod.GET, "/");
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpClientResponseImpl.KEEP_ALIVE_HEADER_NAME,
HttpClientResponseImpl.KEEP_ALIVE_TIMEOUT_HEADER_ATTR + "=0");
clientRule.feedResponseAndComplete(response);
HttpClientResponse<ByteBuf> resp = clientRule.discardResponseContent(responseSub);
Channel nettyChannel = resp.unsafeNettyChannel();
clientRule.getLastCreatedChannel().runPendingTasks();
// Close is while release, so this should be post running pending tasks
assertThat("Channel not closed.", nettyChannel.isOpen(), is(false));
clientRule.assertIdleConnections(0); // Since, the channel is closed
}
@Test(timeout = 60000)
public void testReuse() throws Exception {
clientRule.assertIdleConnections(0);
Channel channel1 = clientRule.sendRequestAndGetChannel();
clientRule.getLastCreatedChannel().runPendingTasks();
clientRule.assertIdleConnections(1);
Channel channel2 = clientRule.sendRequestAndGetChannel();
assertThat("Connection was not reused.", channel2, is(channel1));
}
public static class PooledHttpClientRule extends HttpClientRule {
private FIFOIdleConnectionsHolder<ByteBuf, ByteBuf> idleConnHolder;
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
idleConnHolder = new FIFOIdleConnectionsHolder<>();
PoolConfig<ByteBuf, ByteBuf> pConfig = new PoolConfig<>();
pConfig.idleConnectionsHolder(idleConnHolder);
setupPooledConnectionFactroy(pConfig); // sets the client et al.
base.evaluate();
}
};
}
public void assertIdleConnections(int expectedCount) {
TestSubscriber<PooledConnection<ByteBuf, ByteBuf>> testSub = new TestSubscriber<>();
idleConnHolder.peek().subscribe(testSub);
testSub.assertTerminalEvent();
testSub.assertNoErrors();
assertThat("Unexpected number of connections in the holder.", testSub.getOnNextEvents(),
hasSize(expectedCount));
}
protected Channel sendRequestAndGetChannel() {
final HttpClientRequest<ByteBuf, ByteBuf> request1 = getHttpClient().createGet("/");
TestSubscriber<HttpClientResponse<ByteBuf>> respSub = sendRequest(request1);
assertIdleConnections(0); // No idle connections post connect
assertRequestHeadersWritten(HttpMethod.GET, "/");
feedResponseAndComplete();
final HttpClientResponse<ByteBuf> response = discardResponseContent(respSub);
return response.unsafeNettyChannel();
}
}
}
| apache-2.0 |
jjeb/kettle-trunk | ui/src/org/pentaho/di/ui/trans/steps/setvaluefield/SetValueFieldDialog.java | 10539 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.setvaluefield;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.setvaluefield.SetValueFieldMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class SetValueFieldDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = SetValueFieldMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private Label wlStepname;
private Text wStepname;
private FormData fdlStepname, fdStepname;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private SetValueFieldMeta input;
private Map<String, Integer> inputFields;
private ColumnInfo[] colinf;
public SetValueFieldDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(SetValueFieldMeta)in;
inputFields =new HashMap<String, Integer>();
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "SetValueFieldDialog.Shell.Label")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "SetValueFieldDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wlFields=new Label(shell, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "SetValueFieldDialog.Fields.Label")); //$NON-NLS-1$
props.setLook(wlFields);
fdlFields=new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wStepname, margin);
wlFields.setLayoutData(fdlFields);
final int FieldsCols=2;
final int FieldsRows=input.getFieldName().length;
colinf=new ColumnInfo[FieldsCols];
colinf[0]=new ColumnInfo(BaseMessages.getString(PKG, "SetValueFieldDialog.ColumnInfo.Name"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false); //$NON-NLS-1$
colinf[1]=new ColumnInfo(BaseMessages.getString(PKG, "SetValueFieldDialog.ColumnInfo.ValueFromField"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false); //$NON-NLS-1$
wFields=new TableView(transMeta,shell,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(100, -50);
wFields.setLayoutData(fdFields);
//
// Search the fields in the background
final Runnable runnable = new Runnable()
{
public void run()
{
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
try
{
RowMetaInterface row = transMeta.getPrevStepFields(stepMeta);
// Remember these fields...
for (int i=0;i<row.size();i++)
{
inputFields.put(row.getValueMeta(i).getName(), Integer.valueOf(i));
}
setComboBoxes();
}
catch(KettleException e)
{
logError("It was not possible to get the list of input fields from previous steps", e);
}
}
}
};
new Thread(runnable).start();
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$
wGet=new Button(shell, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "System.Button.GetFields")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wGet, wCancel }, margin, wFields);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
wCancel.addListener(SWT.Selection, lsCancel);
wGet.addListener (SWT.Selection, lsGet );
wOK.addListener (SWT.Selection, lsOK );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
protected void setComboBoxes()
{
// Something was changed in the row.
//
final Map<String, Integer> fields = new HashMap<String, Integer>();
// Add the currentMeta fields...
fields.putAll(inputFields);
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<String>(keySet);
String[] fieldNames = (String[]) entries.toArray(new String[entries.size()]);
Const.sortStrings(fieldNames);
colinf[0].setComboValues(fieldNames);
colinf[1].setComboValues(fieldNames);
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wStepname.setText(stepname);
for (int i=0;i<input.getFieldName().length;i++)
{
TableItem item = wFields.table.getItem(i);
String name = input.getFieldName()[i];
String type = input.getReplaceByFieldValue()[i];
if (name!=null) item.setText(1, name);
if (type!=null) item.setText(2, type);
}
wFields.setRowNums();
wFields.optWidth(true);
wStepname.selectAll();
}
private void cancel()
{
stepname=null;
input.setChanged(changed);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
int count = wFields.nrNonEmpty();
input.allocate(count);
for (int i=0;i<count;i++)
{
TableItem item = wFields.getNonEmpty(i);
input.getFieldName()[i] = item.getText(1);
input.getReplaceByFieldValue()[i] = item.getText(2);
}
dispose();
}
private void get()
{
try
{
RowMetaInterface r = transMeta.getPrevStepFields(stepMeta);
if (r!=null)
{
BaseStepDialog.getFieldsFromPrevious(r, wFields, 1, new int[] { 1 }, null, -1, -1, null);
}
}
catch(KettleException ke)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Title"), BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
| apache-2.0 |
zhangzhonglai/heron | heron/spi/src/java/com/twitter/heron/spi/common/Context.java | 10993 | // Copyright 2016 Twitter. 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 com.twitter.heron.spi.common;
public class Context {
protected Context() {
}
public static String cluster(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("CLUSTER"));
}
public static String role(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("ROLE"));
}
public static String environ(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("ENVIRON"));
}
public static Boolean verbose(Config cfg) {
return cfg.getBooleanValue(ConfigKeys.get("VERBOSE"), true);
}
public static String configPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("CONFIG_PATH"));
}
public static String buildVersion(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("BUILD_VERSION"));
}
public static String buildTime(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("BUILD_TIME"));
}
public static Long buildTimeStamp(Config cfg) {
return cfg.getLongValue(ConfigKeys.get("BUILD_TIMESTAMP"));
}
public static String buildHost(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("BUILD_HOST"));
}
public static String buildUser(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("BUILD_USER"));
}
public static String topologyName(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("TOPOLOGY_NAME"));
}
public static int topologyContainerId(Config cfg) {
return cfg.getIntegerValue(ConfigKeys.get("TOPOLOGY_CONTAINER_ID"));
}
public static String uploaderClass(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("UPLOADER_CLASS"));
}
public static String launcherClass(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("LAUNCHER_CLASS"));
}
public static String schedulerClass(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SCHEDULER_CLASS"));
}
public static String packingClass(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("PACKING_CLASS"));
}
public static String repackingClass(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("REPACKING_CLASS"));
}
public static String stateManagerClass(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("STATE_MANAGER_CLASS"));
}
public static Boolean schedulerService(Config cfg) {
return cfg.getBooleanValue(ConfigKeys.get("SCHEDULER_IS_SERVICE"), true);
}
public static String clusterFile(Config cfg) {
return cfg.getStringValue(Keys.clusterFile());
}
public static String clientFile(Config cfg) {
return cfg.getStringValue(Keys.clientFile());
}
public static String defaultsFile(Config cfg) {
return cfg.getStringValue(Keys.defaultsFile());
}
public static String metricsSinksFile(Config cfg) {
return cfg.getStringValue(Keys.metricsSinksFile());
}
public static String packingFile(Config cfg) {
return cfg.getStringValue(Keys.packingFile());
}
public static String schedulerFile(Config cfg) {
return cfg.getStringValue(Keys.schedulerFile());
}
public static String stateManagerFile(Config cfg) {
return cfg.getStringValue(Keys.stateManagerFile());
}
public static String systemFile(Config cfg) {
return cfg.getStringValue(Keys.systemFile());
}
public static String uploaderFile(Config cfg) {
return cfg.getStringValue(Keys.uploaderFile());
}
public static String schedulerJar(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SCHEDULER_JAR"));
}
public static String schedulerProxyConnectionString(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SCHEDULER_PROXY_CONNECTION_STRING"));
}
public static String schedulerProxyConnectionType(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SCHEDULER_PROXY_CONNECTION_TYPE"));
}
public static String stateManagerConnectionString(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("STATEMGR_CONNECTION_STRING"));
}
public static String stateManagerRootPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("STATEMGR_ROOT_PATH"));
}
public static String corePackageUri(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("CORE_PACKAGE_URI"));
}
public static String systemConfigFile(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SYSTEM_YAML"));
}
public static String topologyDefinitionFile(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("TOPOLOGY_DEFINITION_FILE"));
}
public static String topologyBinaryFile(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("TOPOLOGY_BINARY_FILE"));
}
public static String topologyPackageFile(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("TOPOLOGY_PACKAGE_FILE"));
}
public static String topologyPackageType(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("TOPOLOGY_PACKAGE_TYPE"));
}
public static Long stmgrRam(Config cfg) {
return cfg.getLongValue(ConfigKeys.get("STMGR_RAM"));
}
public static Long instanceRam(Config cfg) {
return cfg.getLongValue(ConfigKeys.get("INSTANCE_RAM"));
}
public static Double instanceCpu(Config cfg) {
return cfg.getDoubleValue(ConfigKeys.get("INSTANCE_CPU"));
}
public static Long instanceDisk(Config cfg) {
return cfg.getLongValue(ConfigKeys.get("INSTANCE_DISK"));
}
public static String heronHome(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_HOME"));
}
public static String heronBin(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_BIN"));
}
public static String heronConf(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_CONF"));
}
public static final String heronLib(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_LIB"));
}
public static final String heronDist(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_DIST"));
}
public static final String heronEtc(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_ETC"));
}
public static final String instanceClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("INSTANCE_CLASSPATH"));
}
public static final String metricsManagerClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("METRICSMGR_CLASSPATH"));
}
public static final String packingClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("PACKING_CLASSPATH"));
}
public static final String schedulerClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SCHEDULER_CLASSPATH"));
}
public static final String stateManagerClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("STATEMGR_CLASSPATH"));
}
public static final String uploaderClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("UPLOADER_CLASSPATH"));
}
public static final String javaHome(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("JAVA_HOME"));
}
public static String heronSandboxHome(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_SANDBOX_HOME"));
}
public static String heronSandboxBin(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_SANDBOX_BIN"));
}
public static String heronSandboxConf(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_SANDBOX_CONF"));
}
public static final String heronSandboxLib(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_SANDBOX_LIB"));
}
public static final String javaSandboxHome(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("HERON_SANDBOX_JAVA_HOME"));
}
public static String clusterSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.clusterSandboxFile());
}
public static String defaultsSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.defaultsSandboxFile());
}
public static String metricsSinksSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.metricsSinksSandboxFile());
}
public static String packingSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.packingSandboxFile());
}
public static String overrideSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.overrideSandboxFile());
}
public static String schedulerSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.schedulerSandboxFile());
}
public static String stateManagerSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.stateManagerSandboxFile());
}
public static String systemConfigSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.systemSandboxFile());
}
public static String uploaderSandboxFile(Config cfg) {
return cfg.getStringValue(Keys.uploaderSandboxFile());
}
public static String executorSandboxBinary(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_EXECUTOR_BINARY"));
}
public static String stmgrSandboxBinary(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_STMGR_BINARY"));
}
public static String tmasterSandboxBinary(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_TMASTER_BINARY"));
}
public static String shellSandboxBinary(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_SHELL_BINARY"));
}
public static final String pythonInstanceSandboxBinary(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_PYTHON_INSTANCE_BINARY"));
}
public static String schedulerSandboxJar(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_SCHEDULER_JAR"));
}
public static final String instanceSandboxClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_INSTANCE_CLASSPATH"));
}
public static final String metricsManagerSandboxClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_METRICSMGR_CLASSPATH"));
}
public static final String packingSandboxClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_PACKING_CLASSPATH"));
}
public static final String schedulerSandboxClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_SCHEDULER_CLASSPATH"));
}
public static final String stateManagerSandboxClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_STATEMGR_CLASSPATH"));
}
public static final String uploaderSandboxClassPath(Config cfg) {
return cfg.getStringValue(ConfigKeys.get("SANDBOX_UPLOADER_CLASSPATH"));
}
}
| apache-2.0 |
sflyphotobooks/crp-batik | sources/org/apache/batik/gvt/flow/RegionInfo.java | 2535 | /*
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.batik.gvt.flow;
import java.awt.Shape;
/**
* This class holds the neccessary information to render a
* <batik:flowRegion> that is defined within the <batik:flowRoot>
* element. Namely it holds the bounds of the region and the desired
* vertical alignment.
*
* @author <a href="mailto:thomas.deweese@kodak.com">Thomas DeWeese</a>
* @version $Id: RegionInfo.java 475477 2006-11-15 22:44:28Z cam $
*/
public class RegionInfo {
/**
* The shape that defines the region.
*/
private Shape shape;
/**
* The alignment proportion.
*/
private float verticalAlignment;
/**
* Creates a new RegionInfo with the given shape and alignment.
*/
public RegionInfo(Shape s, float verticalAlignment) {
this.shape = s;
this.verticalAlignment = verticalAlignment;
}
/**
* Returns the flow region shape.
*/
public Shape getShape() {
return shape;
}
/**
* Sets the flow region shape.
*/
public void setShape(Shape s) {
this.shape = s;
}
/**
* Gets the vertical alignment for this flow region.
* @return the vertical alignment for this flow region.
* It will be 0.0 for top, 0.5 for middle and 1.0 for bottom.
*/
public float getVerticalAlignment() {
return verticalAlignment;
}
/**
* Sets the alignment position of the text within this flow region.
* The value must be 0.0 for top, 0.5 for middle and 1.0 for bottom.
* @param verticalAlignment the vertical alignment of the text.
*/
public void setVerticalAlignment(float verticalAlignment) {
this.verticalAlignment = verticalAlignment;
}
}
| apache-2.0 |
b-slim/druid | server/src/main/java/io/druid/segment/realtime/plumber/PlumberSchool.java | 1623 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.segment.realtime.plumber;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.druid.segment.indexing.DataSchema;
import io.druid.segment.indexing.RealtimeTuningConfig;
import io.druid.segment.realtime.FireDepartmentMetrics;
/**
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RealtimePlumberSchool.class)
@JsonSubTypes(value = {
@JsonSubTypes.Type(name = "realtime", value = RealtimePlumberSchool.class),
@JsonSubTypes.Type(name = "flushing", value = FlushingPlumberSchool.class)
})
public interface PlumberSchool
{
/**
* Creates a Plumber
*
* @return returns a plumber
*/
Plumber findPlumber(DataSchema schema, RealtimeTuningConfig config, FireDepartmentMetrics metrics);
}
| apache-2.0 |
walteryang47/ovirt-engine | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/GuideModel.java | 9126 | package org.ovirt.engine.ui.uicommonweb.models;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.action.ChangeVDSClusterParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.ErrorPopupManager;
import org.ovirt.engine.ui.uicommonweb.TypeResolver;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.hosts.MoveHost;
import org.ovirt.engine.ui.uicommonweb.models.hosts.MoveHostData;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.ObservableCollection;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
import com.google.gwt.user.client.Timer;
@SuppressWarnings("unused")
public class GuideModel extends EntityModel {
private ErrorPopupManager errorPopupManager;
private void setConsoleHelpers() {
this.errorPopupManager = (ErrorPopupManager) TypeResolver.getInstance().resolve(ErrorPopupManager.class);
}
private List<UICommand> compulsoryActions;
public List<UICommand> getCompulsoryActions() {
return compulsoryActions;
}
public void setCompulsoryActions(List<UICommand> value) {
if (compulsoryActions != value) {
compulsoryActions = value;
onPropertyChanged(new PropertyChangedEventArgs("CompulsoryActions")); //$NON-NLS-1$
}
}
private List<UICommand> optionalActions;
public List<UICommand> getOptionalActions() {
return optionalActions;
}
public void setOptionalActions(List<UICommand> value) {
if (optionalActions != value) {
optionalActions = value;
onPropertyChanged(new PropertyChangedEventArgs("OptionalActions")); //$NON-NLS-1$
}
}
private EntityModel<String> note;
public EntityModel<String> getNote() {
return note;
}
public void setNote(EntityModel<String> value) {
note = value;
}
public GuideModel() {
setCompulsoryActions(new ObservableCollection<UICommand>());
setOptionalActions(new ObservableCollection<UICommand>());
setNote(new EntityModel<String>());
getNote().setIsAvailable(false);
setConsoleHelpers();
}
protected void cancel() {}
protected void postAction() {}
protected String getVdsSearchString(final MoveHost moveHost) {
StringBuilder buf = new StringBuilder("Host: "); //$NON-NLS-1$
for (MoveHostData hostData : moveHost.getSelectedHosts()) {
if ((buf.length()) > 6) {
buf.append(" or "); //$NON-NLS-1$
}
buf.append("name = "); //$NON-NLS-1$
buf.append(hostData.getEntity().getName());
}
return buf.toString();
}
protected void checkVdsClusterChangeSucceeded(final GuideModel guideModel,
final String searchStr,
final List<VdcActionParametersBase> changeVdsParameterList,
final List<VdcActionParametersBase> activateVdsParameterList) {
final Map<Guid, Guid> hostClusterIdMap = new HashMap<>();
for (VdcActionParametersBase param : changeVdsParameterList) {
hostClusterIdMap.put(((ChangeVDSClusterParameters) param).getVdsId(),
((ChangeVDSClusterParameters) param).getClusterId());
}
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters(searchStr, SearchType.VDS),
new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
List<VDS> hosts = ((VdcQueryReturnValue) returnValue).getReturnValue();
boolean succeeded = true;
for (VDS host : hosts) {
if (!host.getVdsGroupId().equals(hostClusterIdMap.get(host.getId()))) {
succeeded = false;
}
}
if (!succeeded) {
guideModel.getWindow().stopProgress();
guideModel.cancel();
errorPopupManager.show(ConstantsManager.getInstance().getConstants().hostChangeClusterTimeOut());
} else {
activateHostsAfterClusterChange(guideModel, searchStr, activateVdsParameterList);
}
}
}));
}
protected void activateHostsAfterClusterChange(
final GuideModel guideModel,
final String searchStr,
final List<VdcActionParametersBase> activateVdsParameterList) {
Frontend.getInstance().runMultipleAction(VdcActionType.ActivateVds, activateVdsParameterList,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
Timer timer = new Timer() {
public void run() {
checkVdsActivateSucceeded(guideModel, searchStr);
}
};
// Execute the timer to expire 5 seconds in the future
timer.schedule(5000);
}
},
this);
}
protected void checkVdsActivateSucceeded(final GuideModel guideModel, final String searchStr) {
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters(searchStr, SearchType.VDS),
new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
List<VDS> hosts = ((VdcQueryReturnValue) returnValue).getReturnValue();
boolean succeeded = true;
for (VDS host : hosts) {
if (host.getStatus() != VDSStatus.Up) {
succeeded = false;
}
}
guideModel.getWindow().stopProgress();
guideModel.cancel();
if (succeeded) {
guideModel.postAction();
} else {
ConfirmationModel confirmModel = new ConfirmationModel();
setConfirmWindow(confirmModel);
confirmModel.setTitle(ConstantsManager.getInstance()
.getConstants().operating());
confirmModel.setHelpTag(HelpTag.select_host);
confirmModel.setHashName("guide_model"); //$NON-NLS-1$
confirmModel.setMessage(ConstantsManager.getInstance().getConstants().hostActivationTimeOut());
confirmModel.getCommands().add(new UICommand("CancelConfirm", GuideModel.this)//$NON-NLS-1$
.setTitle(ConstantsManager.getInstance().getConstants().close())
.setIsDefault(true)
.setIsCancel(true));
}
}
}));
}
@Override
public void executeCommand(UICommand command) {
super.executeCommand(command);
if("CancelConfirm".equals(command.getName())){//$NON-NLS-1$
cancelConfirm();
}
}
protected void cancelConfirm() {
setConfirmWindow(null);
}
}
| apache-2.0 |
hekonsek/fabric8 | sandbox/fabric/fabric-client/src/main/java/io/fabric8/jolokia/facade/dto/FabricServiceStatusDTO.java | 1307 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.jolokia.facade.dto;
/**
* Author: lhein
*/
public class FabricServiceStatusDTO {
public boolean managed;
public Object clientConnectionError;
public boolean clientValid;
public boolean clientConnected;
public boolean provisionComplete;
@Override
public String toString() {
return String.format("FabricServiceStatus (clientConnected: %s, clientConnectionError: %s, clientValid: %s, managed: %s, provisionComplete: %s",
clientConnected,
clientConnectionError,
clientValid,
managed,
provisionComplete);
}
}
| apache-2.0 |
sfcoding-school/party-manager | libs/facebook/src/com/facebook/android/Facebook.java | 55504 | /**
* Copyright 2010-present Facebook
*
* 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.android;
import android.Manifest;
import android.app.Activity;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.*;
import com.facebook.*;
import com.facebook.Session.StatusCallback;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link Session} to manage session state,
* {@link Request} to make API requests, and
* {@link com.facebook.widget.WebDialog} to make dialog requests.
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public class Facebook {
// Strings used in the authorization flow
@Deprecated
public static final String REDIRECT_URI = "fbconnect://success";
@Deprecated
public static final String CANCEL_URI = "fbconnect://cancel";
@Deprecated
public static final String TOKEN = "access_token";
@Deprecated
public static final String EXPIRES = "expires_in";
@Deprecated
public static final String SINGLE_SIGN_ON_DISABLED = "service_disabled";
@Deprecated
public static final Uri ATTRIBUTION_ID_CONTENT_URI =
Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider");
@Deprecated
public static final String ATTRIBUTION_ID_COLUMN_NAME = "aid";
@Deprecated
public static final int FORCE_DIALOG_AUTH = -1;
private static final String LOGIN = "oauth";
// Used as default activityCode by authorize(). See authorize() below.
private static final int DEFAULT_AUTH_ACTIVITY_CODE = 32665;
// Facebook server endpoints: may be modified in a subclass for testing
@Deprecated
protected static String DIALOG_BASE_URL = "https://m.facebook.com/dialog/";
@Deprecated
protected static String GRAPH_BASE_URL = "https://graph.facebook.com/";
@Deprecated
protected static String RESTSERVER_URL = "https://api.facebook.com/restserver.php";
private final Object lock = new Object();
private String accessToken = null;
private long accessExpiresMillisecondsAfterEpoch = 0;
private long lastAccessUpdateMillisecondsAfterEpoch = 0;
private String mAppId;
private Activity pendingAuthorizationActivity;
private String[] pendingAuthorizationPermissions;
private Session pendingOpeningSession;
private volatile Session session; // must synchronize this.sync to write
private boolean sessionInvalidated; // must synchronize this.sync to access
private SetterTokenCachingStrategy tokenCache;
private volatile Session userSetSession;
// If the last time we extended the access token was more than 24 hours ago
// we try to refresh the access token again.
final private static long REFRESH_TOKEN_BARRIER = 24L * 60L * 60L * 1000L;
/**
* Constructor for Facebook object.
*
* @param appId
* Your Facebook application ID. Found at
* www.facebook.com/developers/apps.php.
*/
@Deprecated
public Facebook(String appId) {
if (appId == null) {
throw new IllegalArgumentException("You must specify your application ID when instantiating "
+ "a Facebook object. See README for details.");
}
mAppId = appId;
}
/**
* Default authorize method. Grants only basic permissions.
* <p/>
* See authorize() below for @params.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*/
@Deprecated
public void authorize(Activity activity, final DialogListener listener) {
authorize(activity, new String[]{}, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK,
listener);
}
/**
* Authorize method that grants custom permissions.
* <p/>
* See authorize() below for @params.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*/
@Deprecated
public void authorize(Activity activity, String[] permissions, final DialogListener listener) {
authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK, listener);
}
/**
* Full authorize method.
* <p/>
* Starts either an Activity or a dialog which prompts the user to log in to
* Facebook and grant the requested permissions to the given application.
* <p/>
* This method will, when possible, use Facebook's single sign-on for
* Android to obtain an access token. This involves proxying a call through
* the Facebook for Android stand-alone application, which will handle the
* authentication flow, and return an OAuth access token for making API
* calls.
* <p/>
* Because this process will not be available for all users, if single
* sign-on is not possible, this method will automatically fall back to the
* OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
* by Facebook in an embedded WebView, not by the client application. As
* such, the dialog makes a network request and renders HTML content rather
* than a native UI. The access token is retrieved from a redirect to a
* special URL that the WebView handles.
* <p/>
* Note that User credentials could be handled natively using the OAuth 2.0
* Username and Password Flow, but this is not supported by this SDK.
* <p/>
* See http://developers.facebook.com/docs/authentication/ and
* http://wiki.oauth.net/OAuth-2 for more details.
* <p/>
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
* <p/>
* Also note that requests may be made to the API without calling authorize
* first, in which case only public information is returned.
* <p/>
* IMPORTANT: Note that single sign-on authentication will not function
* correctly if you do not include a call to the authorizeCallback() method
* in your onActivityResult() function! Please see below for more
* information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
* as the activityCode parameter in your call to authorize().
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param activity
* The Android activity in which we want to display the
* authorization dialog.
* @param permissions
* A list of permissions required for this application: e.g.
* "read_stream", "publish_stream", "offline_access", etc. see
* http://developers.facebook.com/docs/authentication/permissions
* This parameter should not be null -- if you do not require any
* permissions, then pass in an empty String array.
* @param activityCode
* Single sign-on requires an activity result to be called back
* to the client application -- if you are waiting on other
* activities to return data, pass a custom activity code here to
* avoid collisions. If you would like to force the use of legacy
* dialog-based authorization, pass FORCE_DIALOG_AUTH for this
* parameter. Otherwise just omit this parameter and Facebook
* will use a suitable default. See
* http://developer.android.com/reference/android/
* app/Activity.html for more information.
* @param listener
* Callback interface for notifying the calling application when
* the authentication dialog has completed, failed, or been
* canceled.
*/
@Deprecated
public void authorize(Activity activity, String[] permissions, int activityCode, final DialogListener listener) {
SessionLoginBehavior behavior = (activityCode >= 0) ? SessionLoginBehavior.SSO_WITH_FALLBACK
: SessionLoginBehavior.SUPPRESS_SSO;
authorize(activity, permissions, activityCode, behavior, listener);
}
/**
* Full authorize method.
*
* Starts either an Activity or a dialog which prompts the user to log in to
* Facebook and grant the requested permissions to the given application.
*
* This method will, when possible, use Facebook's single sign-on for
* Android to obtain an access token. This involves proxying a call through
* the Facebook for Android stand-alone application, which will handle the
* authentication flow, and return an OAuth access token for making API
* calls.
*
* Because this process will not be available for all users, if single
* sign-on is not possible, this method will automatically fall back to the
* OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
* by Facebook in an embedded WebView, not by the client application. As
* such, the dialog makes a network request and renders HTML content rather
* than a native UI. The access token is retrieved from a redirect to a
* special URL that the WebView handles.
*
* Note that User credentials could be handled natively using the OAuth 2.0
* Username and Password Flow, but this is not supported by this SDK.
*
* See http://developers.facebook.com/docs/authentication/ and
* http://wiki.oauth.net/OAuth-2 for more details.
*
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
*
* Also note that requests may be made to the API without calling authorize
* first, in which case only public information is returned.
*
* IMPORTANT: Note that single sign-on authentication will not function
* correctly if you do not include a call to the authorizeCallback() method
* in your onActivityResult() function! Please see below for more
* information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
* as the activityCode parameter in your call to authorize().
*
* @param activity
* The Android activity in which we want to display the
* authorization dialog.
* @param permissions
* A list of permissions required for this application: e.g.
* "read_stream", "publish_stream", "offline_access", etc. see
* http://developers.facebook.com/docs/authentication/permissions
* This parameter should not be null -- if you do not require any
* permissions, then pass in an empty String array.
* @param activityCode
* Single sign-on requires an activity result to be called back
* to the client application -- if you are waiting on other
* activities to return data, pass a custom activity code here to
* avoid collisions. If you would like to force the use of legacy
* dialog-based authorization, pass FORCE_DIALOG_AUTH for this
* parameter. Otherwise just omit this parameter and Facebook
* will use a suitable default. See
* http://developer.android.com/reference/android/
* app/Activity.html for more information.
* @param behavior
* The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
* @param listener
* Callback interface for notifying the calling application when
* the authentication dialog has completed, failed, or been
* canceled.
*/
private void authorize(Activity activity, String[] permissions, int activityCode,
SessionLoginBehavior behavior, final DialogListener listener) {
checkUserSession("authorize");
pendingOpeningSession = new Session.Builder(activity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
pendingAuthorizationActivity = activity;
pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0];
StatusCallback callback = new StatusCallback() {
@Override
public void call(Session callbackSession, SessionState state, Exception exception) {
// Invoke user-callback.
onSessionCallback(callbackSession, state, exception, listener);
}
};
Session.OpenRequest openRequest = new Session.OpenRequest(activity).
setCallback(callback).
setLoginBehavior(behavior).
setRequestCode(activityCode).
setPermissions(Arrays.asList(pendingAuthorizationPermissions));
openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0);
}
private void openSession(Session session, Session.OpenRequest openRequest, boolean isPublish) {
openRequest.setIsLegacy(true);
if (isPublish) {
session.openForPublish(openRequest);
} else {
session.openForRead(openRequest);
}
}
@SuppressWarnings("deprecation")
private void onSessionCallback(Session callbackSession, SessionState state, Exception exception,
DialogListener listener) {
Bundle extras = callbackSession.getAuthorizationBundle();
if (state == SessionState.OPENED) {
Session sessionToClose = null;
synchronized (Facebook.this.lock) {
if (callbackSession != Facebook.this.session) {
sessionToClose = Facebook.this.session;
Facebook.this.session = callbackSession;
Facebook.this.sessionInvalidated = false;
}
}
if (sessionToClose != null) {
sessionToClose.close();
}
listener.onComplete(extras);
} else if (exception != null) {
if (exception instanceof FacebookOperationCanceledException) {
listener.onCancel();
} else if ((exception instanceof FacebookAuthorizationException) && (extras != null)
&& extras.containsKey(Session.WEB_VIEW_ERROR_CODE_KEY)
&& extras.containsKey(Session.WEB_VIEW_FAILING_URL_KEY)) {
DialogError error = new DialogError(exception.getMessage(),
extras.getInt(Session.WEB_VIEW_ERROR_CODE_KEY),
extras.getString(Session.WEB_VIEW_FAILING_URL_KEY));
listener.onError(error);
} else {
FacebookError error = new FacebookError(exception.getMessage());
listener.onFacebookError(error);
}
}
}
/**
* Helper to validate a service intent by resolving and checking the
* provider's package signature.
*
* @param context
* @param intent
* @return true if the service intent resolution happens successfully and
* the signatures match.
*/
private boolean validateServiceIntent(Context context, Intent intent) {
ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
if (resolveInfo == null) {
return false;
}
return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName);
}
/**
* Query the signature for the application that would be invoked by the
* given intent and verify that it matches the FB application's signature.
*
* @param context
* @param packageName
* @return true if the app's signature matches the expected signature.
*/
private boolean validateAppSignatureForPackage(Context context, String packageName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
} catch (NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
return true;
}
}
return false;
}
/**
* IMPORTANT: If you are using the deprecated authorize() method,
* this method must be invoked at the top of the calling
* activity's onActivityResult() function or Facebook authentication will
* not function properly!
* <p/>
* If your calling activity does not currently implement onActivityResult(),
* you must implement it and include a call to this method if you intend to
* use the authorize() method in this SDK.
* <p/>
* For more information, see
* http://developer.android.com/reference/android/app/
* Activity.html#onActivityResult(int, int, android.content.Intent)
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*/
@Deprecated
public void authorizeCallback(int requestCode, int resultCode, Intent data) {
checkUserSession("authorizeCallback");
Session pending = this.pendingOpeningSession;
if (pending != null) {
if (pending.onActivityResult(this.pendingAuthorizationActivity, requestCode, resultCode, data)) {
this.pendingOpeningSession = null;
this.pendingAuthorizationActivity = null;
this.pendingAuthorizationPermissions = null;
}
}
}
/**
* Refresh OAuth access token method. Binds to Facebook for Android
* stand-alone application application to refresh the access token. This
* method tries to connect to the Facebook App which will handle the
* authentication flow, and return a new OAuth access token. This method
* will automatically replace the old token with a new one. Note that this
* method is asynchronous and the callback will be invoked in the original
* calling thread (not in a background thread).
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param context
* The Android Context that will be used to bind to the Facebook
* RefreshToken Service
* @param serviceListener
* Callback interface for notifying the calling application when
* the refresh request has completed or failed (can be null). In
* case of a success a new token can be found inside the result
* Bundle under Facebook.ACCESS_TOKEN key.
* @return true if the binding to the RefreshToken Service was created
*/
@Deprecated
public boolean extendAccessToken(Context context, ServiceListener serviceListener) {
checkUserSession("extendAccessToken");
Intent intent = new Intent();
intent.setClassName("com.facebook.katana", "com.facebook.katana.platform.TokenRefreshService");
// Verify that the application whose package name is
// com.facebook.katana
// has the expected FB app signature.
if (!validateServiceIntent(context, intent)) {
return false;
}
return context.bindService(intent, new TokenRefreshServiceConnection(context, serviceListener),
Context.BIND_AUTO_CREATE);
}
/**
* Calls extendAccessToken if shouldExtendAccessToken returns true.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @return the same value as extendAccessToken if the the token requires
* refreshing, true otherwise
*/
@Deprecated
public boolean extendAccessTokenIfNeeded(Context context, ServiceListener serviceListener) {
checkUserSession("extendAccessTokenIfNeeded");
if (shouldExtendAccessToken()) {
return extendAccessToken(context, serviceListener);
}
return true;
}
/**
* Check if the access token requires refreshing.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @return true if the last time a new token was obtained was over 24 hours
* ago.
*/
@Deprecated
public boolean shouldExtendAccessToken() {
checkUserSession("shouldExtendAccessToken");
return isSessionValid()
&& (System.currentTimeMillis() - lastAccessUpdateMillisecondsAfterEpoch >= REFRESH_TOKEN_BARRIER);
}
/**
* Handles connection to the token refresh service (this service is a part
* of Facebook App).
*/
private class TokenRefreshServiceConnection implements ServiceConnection {
final Messenger messageReceiver = new Messenger(
new TokenRefreshConnectionHandler(Facebook.this, this));
final ServiceListener serviceListener;
final Context applicationsContext;
Messenger messageSender = null;
public TokenRefreshServiceConnection(Context applicationsContext, ServiceListener serviceListener) {
this.applicationsContext = applicationsContext;
this.serviceListener = serviceListener;
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
messageSender = new Messenger(service);
refreshToken();
}
@Override
public void onServiceDisconnected(ComponentName arg) {
serviceListener.onError(new Error("Service disconnected"));
// We returned an error so there's no point in
// keeping the binding open.
applicationsContext.unbindService(TokenRefreshServiceConnection.this);
}
private void refreshToken() {
Bundle requestData = new Bundle();
requestData.putString(TOKEN, accessToken);
Message request = Message.obtain();
request.setData(requestData);
request.replyTo = messageReceiver;
try {
messageSender.send(request);
} catch (RemoteException e) {
serviceListener.onError(new Error("Service connection error"));
}
}
}
// Creating a static Handler class to reduce the possibility of a memory leak.
// Handler objects for the same thread all share a common Looper object, which they post messages
// to and read from. As messages contain target Handler, as long as there are messages with target
// handler in the message queue, the handler cannot be garbage collected. If handler is not static,
// the instance of the containing class also cannot be garbage collected even if it is destroyed.
private static class TokenRefreshConnectionHandler extends Handler {
WeakReference<Facebook> facebookWeakReference;
WeakReference<TokenRefreshServiceConnection> connectionWeakReference;
TokenRefreshConnectionHandler(Facebook facebook, TokenRefreshServiceConnection connection) {
super();
facebookWeakReference = new WeakReference<Facebook>(facebook);
connectionWeakReference = new WeakReference<TokenRefreshServiceConnection>(connection);
}
@Override
@SuppressWarnings("deprecation")
public void handleMessage(Message msg) {
Facebook facebook = facebookWeakReference.get();
TokenRefreshServiceConnection connection = connectionWeakReference.get();
if (facebook == null || connection == null) {
return;
}
String token = msg.getData().getString(TOKEN);
// Legacy functions in Facebook class (and ServiceListener implementors) expect expires_in in
// milliseconds from epoch
long expiresAtMsecFromEpoch = msg.getData().getLong(EXPIRES) * 1000L;
if (token != null) {
facebook.setAccessToken(token);
facebook.setAccessExpires(expiresAtMsecFromEpoch);
Session refreshSession = facebook.session;
if (refreshSession != null) {
// Session.internalRefreshToken expects the original bundle with expires_in in seconds from
// epoch.
LegacyHelper.extendTokenCompleted(refreshSession, msg.getData());
}
if (connection.serviceListener != null) {
// To avoid confusion we should return the expiration time in
// the same format as the getAccessExpires() function - that
// is in milliseconds.
Bundle resultBundle = (Bundle) msg.getData().clone();
resultBundle.putLong(EXPIRES, expiresAtMsecFromEpoch);
connection.serviceListener.onComplete(resultBundle);
}
} else if (connection.serviceListener != null) { // extract errors only if
// client wants them
String error = msg.getData().getString("error");
if (msg.getData().containsKey("error_code")) {
int errorCode = msg.getData().getInt("error_code");
connection.serviceListener.onFacebookError(new FacebookError(error, null, errorCode));
} else {
connection.serviceListener.onError(new Error(error != null ? error : "Unknown service error"));
}
}
// The refreshToken function should be called rarely,
// so there is no point in keeping the binding open.
connection.applicationsContext.unbindService(connection);
}
}
/**
* Invalidate the current user session by removing the access token in
* memory, clearing the browser cookie, and calling auth.expireSession
* through the API.
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param context
* The Android context in which the logout should be called: it
* should be the same context in which the login occurred in
* order to clear any stored cookies
* @throws java.io.IOException
* @throws java.net.MalformedURLException
* @return JSON string representation of the auth.expireSession response
* ("true" if successful)
*/
@Deprecated
public String logout(Context context) throws MalformedURLException, IOException {
return logoutImpl(context);
}
String logoutImpl(Context context) throws MalformedURLException, IOException {
checkUserSession("logout");
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
String response = request(b);
long currentTimeMillis = System.currentTimeMillis();
Session sessionToClose = null;
synchronized (this.lock) {
sessionToClose = session;
session = null;
accessToken = null;
accessExpiresMillisecondsAfterEpoch = 0;
lastAccessUpdateMillisecondsAfterEpoch = currentTimeMillis;
sessionInvalidated = false;
}
if (sessionToClose != null) {
sessionToClose.closeAndClearTokenInformation();
}
return response;
}
/**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
* <p/>
* See http://developers.facebook.com/docs/reference/rest/
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* Example: <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* String response = request(parameters);
* </code>
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Request} for more info.
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @throws java.io.IOException
* if a network error occurs
* @throws java.net.MalformedURLException
* if accessing an invalid endpoint
* @throws IllegalArgumentException
* if one of the parameters is not "method"
* @return JSON string representation of the response
*/
@Deprecated
public String request(Bundle parameters) throws MalformedURLException, IOException {
if (!parameters.containsKey("method")) {
throw new IllegalArgumentException("API method must be specified. "
+ "(parameters must contain key \"method\" and value). See"
+ " http://developers.facebook.com/docs/reference/rest/");
}
return requestImpl(null, parameters, "GET");
}
/**
* Make a request to the Facebook Graph API without any parameters.
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @throws java.io.IOException
* @throws java.net.MalformedURLException
* @return JSON string representation of the response
*/
@Deprecated
public String request(String graphPath) throws MalformedURLException, IOException {
return requestImpl(graphPath, new Bundle(), "GET");
}
/**
* Make a request to the Facebook Graph API with the given string parameters
* using an HTTP GET (default method).
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters "q" : "facebook" would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @throws java.io.IOException
* @throws java.net.MalformedURLException
* @return JSON string representation of the response
*/
@Deprecated
public String request(String graphPath, Bundle parameters) throws MalformedURLException, IOException {
return requestImpl(graphPath, parameters, "GET");
}
/**
* Synchronously make a request to the Facebook Graph API with the given
* HTTP method and string parameters. Note that binary data parameters (e.g.
* pictures) are not yet supported by this helper function.
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param params
* Key-value string parameters, e.g. the path "search" with
* parameters {"q" : "facebook"} would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param httpMethod
* http verb, e.g. "GET", "POST", "DELETE"
* @throws java.io.IOException
* @throws java.net.MalformedURLException
* @return JSON string representation of the response
*/
@Deprecated
public String request(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
return requestImpl(graphPath, params, httpMethod);
}
// Internal call to avoid deprecated warnings.
@SuppressWarnings("deprecation")
String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
}
/**
* Generate a UI dialog for the request action in the given Android context.
* <p/>
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
*
* This method is deprecated. See {@link com.facebook.widget.WebDialog}.
*
* @param context
* The Android context in which we will generate this dialog.
* @param action
* String representation of the desired method: e.g. "login",
* "stream.publish", ...
* @param listener
* Callback interface to notify the application when the dialog
* has completed.
*/
@Deprecated
public void dialog(Context context, String action, DialogListener listener) {
dialog(context, action, new Bundle(), listener);
}
/**
* Generate a UI dialog for the request action in the given Android context
* with the provided parameters.
* <p/>
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
*
* This method is deprecated. See {@link com.facebook.widget.WebDialog}.
*
* @param context
* The Android context in which we will generate this dialog.
* @param action
* String representation of the desired method: e.g. "feed" ...
* @param parameters
* String key-value pairs to be passed as URL parameters.
* @param listener
* Callback interface to notify the application when the dialog
* has completed.
*/
@Deprecated
public void dialog(Context context, String action, Bundle parameters, final DialogListener listener) {
parameters.putString("display", "touch");
parameters.putString("redirect_uri", REDIRECT_URI);
if (action.equals(LOGIN)) {
parameters.putString("type", "user_agent");
parameters.putString("client_id", mAppId);
} else {
parameters.putString("app_id", mAppId);
// We do not want to add an access token when displaying the auth dialog.
if (isSessionValid()) {
parameters.putString(TOKEN, getAccessToken());
}
}
if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
Util.showAlert(context, "Error", "Application requires permission to access the Internet");
} else {
new FbDialog(context, action, parameters, listener).show();
}
}
/**
* Returns whether the current access token is valid
*
* @return boolean - whether this object has an non-expired session token
*/
@Deprecated
public boolean isSessionValid() {
return (getAccessToken() != null)
&& ((getAccessExpires() == 0) || (System.currentTimeMillis() < getAccessExpires()));
}
/**
* Allows the user to set a Session for the Facebook class to use.
* If a Session is set here, then one should not use the authorize, logout,
* or extendAccessToken methods which alter the Session object since that may
* result in undefined behavior. Using those methods after setting the
* session here will result in exceptions being thrown.
*
* @param session the Session object to use, cannot be null
*/
@Deprecated
public void setSession(Session session) {
if (session == null) {
throw new IllegalArgumentException("session cannot be null");
}
synchronized (this.lock) {
this.userSetSession = session;
}
}
private void checkUserSession(String methodName) {
if (userSetSession != null) {
throw new UnsupportedOperationException(
String.format("Cannot call %s after setSession has been called.", methodName));
}
}
/**
* Get the underlying Session object to use with 3.0 api.
*
* @return Session - underlying session
*/
@Deprecated
public final Session getSession() {
while (true) {
String cachedToken = null;
Session oldSession = null;
synchronized (this.lock) {
if (userSetSession != null) {
return userSetSession;
}
if ((session != null) || !sessionInvalidated) {
return session;
}
cachedToken = accessToken;
oldSession = session;
}
if (cachedToken == null) {
return null;
}
// At this point we do not have a valid session, but mAccessToken is
// non-null.
// So we can try building a session based on that.
List<String> permissions;
if (oldSession != null) {
permissions = oldSession.getPermissions();
} else if (pendingAuthorizationPermissions != null) {
permissions = Arrays.asList(pendingAuthorizationPermissions);
} else {
permissions = Collections.<String>emptyList();
}
Session newSession = new Session.Builder(pendingAuthorizationActivity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) {
return null;
}
Session.OpenRequest openRequest =
new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions);
openSession(newSession, openRequest, !permissions.isEmpty());
Session invalidatedSession = null;
Session returnSession = null;
synchronized (this.lock) {
if (sessionInvalidated || (session == null)) {
invalidatedSession = session;
returnSession = session = newSession;
sessionInvalidated = false;
}
}
if (invalidatedSession != null) {
invalidatedSession.close();
}
if (returnSession != null) {
return returnSession;
}
// Else token state changed between the synchronized blocks, so
// retry..
}
}
/**
* Retrieve the OAuth 2.0 access token for API access: treat with care.
* Returns null if no session exists.
*
* @return String - access token
*/
@Deprecated
public String getAccessToken() {
Session s = getSession();
if (s != null) {
return s.getAccessToken();
} else {
return null;
}
}
/**
* Retrieve the current session's expiration time (in milliseconds since
* Unix epoch), or 0 if the session doesn't expire or doesn't exist.
*
* @return long - session expiration time
*/
@Deprecated
public long getAccessExpires() {
Session s = getSession();
if (s != null) {
return s.getExpirationDate().getTime();
} else {
return accessExpiresMillisecondsAfterEpoch;
}
}
/**
* Retrieve the last time the token was updated (in milliseconds since
* the Unix epoch), or 0 if the token has not been set.
*
* @return long - timestamp of the last token update.
*/
@Deprecated
public long getLastAccessUpdate() {
return lastAccessUpdateMillisecondsAfterEpoch;
}
/**
* Restore the token, expiration time, and last update time from cached values.
* These should be values obtained from getAccessToken(), getAccessExpires, and
* getLastAccessUpdate() respectively.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param accessToken - access token
* @param accessExpires - access token expiration time
* @param lastAccessUpdate - timestamp of the last token update
*/
@Deprecated
public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) {
checkUserSession("setTokenFromCache");
synchronized (this.lock) {
this.accessToken = accessToken;
accessExpiresMillisecondsAfterEpoch = accessExpires;
lastAccessUpdateMillisecondsAfterEpoch = lastAccessUpdate;
}
}
/**
* Set the OAuth 2.0 access token for API access.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param token
* - access token
*/
@Deprecated
public void setAccessToken(String token) {
checkUserSession("setAccessToken");
synchronized (this.lock) {
accessToken = token;
lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis();
sessionInvalidated = true;
}
}
/**
* Set the current session's expiration time (in milliseconds since Unix
* epoch), or 0 if the session doesn't expire.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param timestampInMsec
* - timestamp in milliseconds
*/
@Deprecated
public void setAccessExpires(long timestampInMsec) {
checkUserSession("setAccessExpires");
synchronized (this.lock) {
accessExpiresMillisecondsAfterEpoch = timestampInMsec;
lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis();
sessionInvalidated = true;
}
}
/**
* Set the current session's duration (in seconds since Unix epoch), or "0"
* if session doesn't expire.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param expiresInSecsFromNow
* - duration in seconds (or 0 if the session doesn't expire)
*/
@Deprecated
public void setAccessExpiresIn(String expiresInSecsFromNow) {
checkUserSession("setAccessExpiresIn");
if (expiresInSecsFromNow != null) {
long expires = expiresInSecsFromNow.equals("0") ? 0 : System.currentTimeMillis()
+ Long.parseLong(expiresInSecsFromNow) * 1000L;
setAccessExpires(expires);
}
}
/**
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @return the String representing application ID
*/
@Deprecated
public String getAppId() {
return mAppId;
}
/**
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Session} for more info.
*
* @param appId the String representing the application ID
*/
@Deprecated
public void setAppId(String appId) {
checkUserSession("setAppId");
synchronized (this.lock) {
mAppId = appId;
sessionInvalidated = true;
}
}
private TokenCachingStrategy getTokenCache() {
// Intentionally not volatile/synchronized--it is okay if we race to
// create more than one of these.
if (tokenCache == null) {
tokenCache = new SetterTokenCachingStrategy();
}
return tokenCache;
}
private static String[] stringArray(List<String> list) {
int size = (list != null) ? list.size() : 0;
String[] array = new String[size];
if (list != null) {
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}
}
return array;
}
private static List<String> stringList(String[] array) {
if (array != null) {
return Arrays.asList(array);
} else {
return Collections.emptyList();
}
}
private class SetterTokenCachingStrategy extends TokenCachingStrategy {
@Override
public Bundle load() {
Bundle bundle = new Bundle();
if (accessToken != null) {
TokenCachingStrategy.putToken(bundle, accessToken);
TokenCachingStrategy.putExpirationMilliseconds(bundle, accessExpiresMillisecondsAfterEpoch);
TokenCachingStrategy.putPermissions(bundle, stringList(pendingAuthorizationPermissions));
TokenCachingStrategy.putSource(bundle, AccessTokenSource.WEB_VIEW);
TokenCachingStrategy.putLastRefreshMilliseconds(bundle, lastAccessUpdateMillisecondsAfterEpoch);
}
return bundle;
}
@Override
public void save(Bundle bundle) {
accessToken = TokenCachingStrategy.getToken(bundle);
accessExpiresMillisecondsAfterEpoch = TokenCachingStrategy.getExpirationMilliseconds(bundle);
pendingAuthorizationPermissions = stringArray(TokenCachingStrategy.getPermissions(bundle));
lastAccessUpdateMillisecondsAfterEpoch = TokenCachingStrategy.getLastRefreshMilliseconds(bundle);
}
@Override
public void clear() {
accessToken = null;
}
}
/**
* Get Attribution ID for app install conversion tracking.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Settings} for more info.
*
* @param contentResolver
* @return Attribution ID that will be used for conversion tracking. It will be null only if
* the user has not installed or logged in to the Facebook app.
*/
@Deprecated
public static String getAttributionId(ContentResolver contentResolver) {
return Settings.getAttributionId(contentResolver);
}
/**
* Get the auto install publish setting. If true, an install event will be published during authorize(), unless
* it has occurred previously or the app does not have install attribution enabled on the application's developer
* config page.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Settings} for more info.
*
* @return a Boolean indicating whether installation of the app should be auto-published.
*/
@Deprecated
public boolean getShouldAutoPublishInstall() {
return Settings.getShouldAutoPublishInstall();
}
/**
* Sets whether auto publishing of installs will occur.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Settings} for more info.
*
* @param value a Boolean indicating whether installation of the app should be auto-published.
*/
@Deprecated
public void setShouldAutoPublishInstall(boolean value) {
Settings.setShouldAutoPublishInstall(value);
}
/**
* Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent
* multiple installs being published to the graph.
* <p/>
* This method is deprecated. See {@link com.facebook.android.Facebook} and {@link Settings} for more info.
*
* @param context the current Android context
* @return Always false. Earlier versions of the API returned true if it was no longer necessary to call.
* Apps should ignore this value, but for compatibility we will return false to ensure repeat calls (and the
* underlying code will prevent duplicate network traffic).
*/
@Deprecated
public boolean publishInstall(final Context context) {
Settings.publishInstallAsync(context, mAppId);
return false;
}
/**
* Callback interface for dialog requests.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link com.facebook.widget.WebDialog}
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public static interface DialogListener {
/**
* Called when a dialog completes.
*
* Executed by the thread that initiated the dialog.
*
* @param values
* Key-value string pairs extracted from the response.
*/
public void onComplete(Bundle values);
/**
* Called when a Facebook responds to a dialog with an error.
*
* Executed by the thread that initiated the dialog.
*
*/
public void onFacebookError(FacebookError e);
/**
* Called when a dialog has an error.
*
* Executed by the thread that initiated the dialog.
*
*/
public void onError(DialogError e);
/**
* Called when a dialog is canceled by the user.
*
* Executed by the thread that initiated the dialog.
*
*/
public void onCancel();
}
/**
* Callback interface for service requests.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link Session} to manage session state.
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public static interface ServiceListener {
/**
* Called when a service request completes.
*
* @param values
* Key-value string pairs extracted from the response.
*/
public void onComplete(Bundle values);
/**
* Called when a Facebook server responds to the request with an error.
*/
public void onFacebookError(FacebookError e);
/**
* Called when a Facebook Service responds to the request with an error.
*/
public void onError(Error e);
}
@Deprecated
public static final String FB_APP_SIGNATURE =
"30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310"
+ "b3009060355040613025553310b30090603550408130243413112301006035504"
+ "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204"
+ "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504"
+ "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333"
+ "13231353231365a180f32303530303932353231353231365a307a310b30090603"
+ "55040613025553310b30090603550408130243413112301006035504071309506"
+ "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c"
+ "653111300f060355040b130846616365626f6f6b311d301b06035504031314466"
+ "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01"
+ "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa"
+ "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7"
+ "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc"
+ "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603"
+ "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050"
+ "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c"
+ "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6"
+ "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2"
+ "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd"
+ "928a2";
}
| apache-2.0 |
atul-bhouraskar/closure-templates | java/src/com/google/template/soy/pysrc/internal/IsComputableAsPyExprVisitor.java | 6405 | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.pysrc.internal;
import com.google.template.soy.shared.internal.ApiCallScope;
import com.google.template.soy.soytree.AbstractReturningSoyNodeVisitor;
import com.google.template.soy.soytree.CallNode;
import com.google.template.soy.soytree.CallParamContentNode;
import com.google.template.soy.soytree.CallParamValueNode;
import com.google.template.soy.soytree.CssNode;
import com.google.template.soy.soytree.DebuggerNode;
import com.google.template.soy.soytree.ForNode;
import com.google.template.soy.soytree.ForeachNode;
import com.google.template.soy.soytree.IfCondNode;
import com.google.template.soy.soytree.IfElseNode;
import com.google.template.soy.soytree.IfNode;
import com.google.template.soy.soytree.LetNode;
import com.google.template.soy.soytree.LogNode;
import com.google.template.soy.soytree.MsgFallbackGroupNode;
import com.google.template.soy.soytree.MsgNode;
import com.google.template.soy.soytree.PrintNode;
import com.google.template.soy.soytree.RawTextNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import com.google.template.soy.soytree.SwitchNode;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
/**
* Visitor to determine whether the output string for the subtree rooted at a given node is
* computable as the concatenation of one or more Python expressions. If this is false, it means the
* generated code for computing the node's output must include one or more full Python statements.
*
* <p> Important: This class is in {@link ApiCallScope} because it memoizes results that are
* reusable for the same parse tree. If we change the parse tree between uses of the scoped
* instance, then the results may not be correct. (In that case, we would need to take this class
* out of {@code ApiCallScope} and rewrite the code somehow to still take advantage of the
* memoized results to the extent that they remain correct.)
*
*/
@ApiCallScope
class IsComputableAsPyExprVisitor extends AbstractReturningSoyNodeVisitor<Boolean> {
/** The memoized results of past visits to nodes. */
private final Map<SoyNode, Boolean> memoizedResults;
@Inject
IsComputableAsPyExprVisitor() {
memoizedResults = new HashMap<>();
}
/**
* Executes this visitor on the children of the given node, and returns true if all children are
* computable as PyExprs. Ignores whether the given node itself is computable as PyExprs or not.
*/
public Boolean execOnChildren(ParentSoyNode<?> node) {
return areChildrenComputableAsPyExprs(node);
}
@Override protected Boolean visit(SoyNode node) {
if (memoizedResults.containsKey(node)) {
return memoizedResults.get(node);
} else {
Boolean result = super.visit(node);
memoizedResults.put(node, result);
return result;
}
}
// -----------------------------------------------------------------------------------------------
// Implementations for specific nodes.
@Override protected Boolean visitRawTextNode(RawTextNode node) {
return true;
}
@Override protected Boolean visitPrintNode(PrintNode node) {
return true;
}
@Override protected Boolean visitMsgFallbackGroupNode(MsgFallbackGroupNode node) {
return true;
}
@Override protected Boolean visitMsgNode(MsgNode node) {
return true;
}
@Override protected Boolean visitLetNode(LetNode node) {
return false;
}
@Override protected Boolean visitCssNode(CssNode node) {
return true;
}
@Override protected Boolean visitIfNode(IfNode node) {
// If all children are computable as Python expressions, then this 'if' statement can be written
// as an expression as well, using the ternary conditional operator ("'a' if x else 'b'").
return areChildrenComputableAsPyExprs(node);
}
@Override protected Boolean visitIfCondNode(IfCondNode node) {
return areChildrenComputableAsPyExprs(node);
}
@Override protected Boolean visitIfElseNode(IfElseNode node) {
return areChildrenComputableAsPyExprs(node);
}
@Override protected Boolean visitSwitchNode(SwitchNode node) {
return false;
}
@Override protected Boolean visitForeachNode(ForeachNode node) {
// TODO(dcphillips): Consider using list comprehensions to generate the output of a foreach.
return false;
}
@Override protected Boolean visitForNode(ForNode node) {
return false;
}
@Override protected Boolean visitCallNode(CallNode node) {
return areChildrenComputableAsPyExprs(node);
}
@Override protected Boolean visitCallParamValueNode(CallParamValueNode node) {
return true;
}
@Override protected Boolean visitCallParamContentNode(CallParamContentNode node) {
return areChildrenComputableAsPyExprs(node);
}
@Override protected Boolean visitLogNode(LogNode node) {
return false;
}
@Override protected Boolean visitDebuggerNode(DebuggerNode node) {
return false;
}
// -----------------------------------------------------------------------------------------------
// Private helpers.
/**
* Private helper to check whether all SoyNode children of a given parent node satisfy
* IsComputableAsPyExprVisitor. ExprNode children are assumed to be computable as PyExprs.
*
* @param node The parent node whose children to check.
* @return True if all children satisfy IsComputableAsPyExprVisitor.
*/
private boolean areChildrenComputableAsPyExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
// Note: Save time by not visiting RawTextNode and PrintNode children.
if (!(child instanceof RawTextNode) && !(child instanceof PrintNode)) {
if (!visit(child)) {
return false;
}
}
}
return true;
}
}
| apache-2.0 |
JingchengDu/hadoop | hadoop-tools/hadoop-sls/src/test/java/org/apache/hadoop/yarn/sls/TestSynthJobGeneration.java | 8685 | /**
* 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.yarn.sls;
import org.apache.commons.math3.random.JDKRandomGenerator;
import org.apache.hadoop.yarn.api.records.ExecutionType;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.sls.synthetic.SynthJob;
import org.apache.hadoop.yarn.sls.synthetic.SynthTraceJobProducer;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonFactoryBuilder;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Simple test class driving the {@code SynthTraceJobProducer}, and validating
* jobs produce are within expected range.
*/
public class TestSynthJobGeneration {
public final static Logger LOG =
LoggerFactory.getLogger(TestSynthJobGeneration.class);
@Test
public void testWorkloadGenerateTime()
throws IllegalArgumentException, IOException {
String workloadJson = "{\"job_classes\": [], \"time_distribution\":["
+ "{\"time\": 0, \"weight\": 1}, " + "{\"time\": 30, \"weight\": 0},"
+ "{\"time\": 60, \"weight\": 2}," + "{\"time\": 90, \"weight\": 1}"
+ "]}";
JsonFactoryBuilder jsonFactoryBuilder = new JsonFactoryBuilder();
jsonFactoryBuilder.configure(JsonFactory.Feature.INTERN_FIELD_NAMES, true);
ObjectMapper mapper = new ObjectMapper(jsonFactoryBuilder.build());
mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
SynthTraceJobProducer.Workload wl =
mapper.readValue(workloadJson, SynthTraceJobProducer.Workload.class);
JDKRandomGenerator rand = new JDKRandomGenerator();
rand.setSeed(0);
wl.init(rand);
int bucket0 = 0;
int bucket1 = 0;
int bucket2 = 0;
int bucket3 = 0;
for (int i = 0; i < 1000; ++i) {
long time = wl.generateSubmissionTime();
LOG.info("Generated time " + time);
if (time < 30) {
bucket0++;
} else if (time < 60) {
bucket1++;
} else if (time < 90) {
bucket2++;
} else {
bucket3++;
}
}
Assert.assertTrue(bucket0 > 0);
Assert.assertTrue(bucket1 == 0);
Assert.assertTrue(bucket2 > 0);
Assert.assertTrue(bucket3 > 0);
Assert.assertTrue(bucket2 > bucket0);
Assert.assertTrue(bucket2 > bucket3);
LOG.info("bucket0 {}, bucket1 {}, bucket2 {}, bucket3 {}", bucket0, bucket1,
bucket2, bucket3);
}
@Test
public void testMapReduce() throws IllegalArgumentException, IOException {
Configuration conf = new Configuration();
conf.set(SynthTraceJobProducer.SLS_SYNTHETIC_TRACE_FILE,
"src/test/resources/syn.json");
SynthTraceJobProducer stjp = new SynthTraceJobProducer(conf);
LOG.info(stjp.toString());
SynthJob js = (SynthJob) stjp.getNextJob();
int jobCount = 0;
while (js != null) {
LOG.info(js.toString());
validateJob(js);
js = (SynthJob) stjp.getNextJob();
jobCount++;
}
Assert.assertEquals(stjp.getNumJobs(), jobCount);
}
@Test
public void testGeneric() throws IllegalArgumentException, IOException {
Configuration conf = new Configuration();
conf.set(SynthTraceJobProducer.SLS_SYNTHETIC_TRACE_FILE,
"src/test/resources/syn_generic.json");
SynthTraceJobProducer stjp = new SynthTraceJobProducer(conf);
LOG.info(stjp.toString());
SynthJob js = (SynthJob) stjp.getNextJob();
int jobCount = 0;
while (js != null) {
LOG.info(js.toString());
validateJob(js);
js = (SynthJob) stjp.getNextJob();
jobCount++;
}
Assert.assertEquals(stjp.getNumJobs(), jobCount);
}
@Test
public void testStream() throws IllegalArgumentException, IOException {
Configuration conf = new Configuration();
conf.set(SynthTraceJobProducer.SLS_SYNTHETIC_TRACE_FILE,
"src/test/resources/syn_stream.json");
SynthTraceJobProducer stjp = new SynthTraceJobProducer(conf);
LOG.info(stjp.toString());
SynthJob js = (SynthJob) stjp.getNextJob();
int jobCount = 0;
while (js != null) {
LOG.info(js.toString());
validateJob(js);
js = (SynthJob) stjp.getNextJob();
jobCount++;
}
Assert.assertEquals(stjp.getNumJobs(), jobCount);
}
@Test
public void testSample() throws IOException {
JsonFactoryBuilder jsonFactoryBuilder = new JsonFactoryBuilder();
jsonFactoryBuilder.configure(JsonFactory.Feature.INTERN_FIELD_NAMES, true);
ObjectMapper mapper = new ObjectMapper(jsonFactoryBuilder.build());
mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
JDKRandomGenerator rand = new JDKRandomGenerator();
rand.setSeed(0);
String valJson = "{\"val\" : 5 }";
SynthTraceJobProducer.Sample valSample =
mapper.readValue(valJson, SynthTraceJobProducer.Sample.class);
valSample.init(rand);
int val = valSample.getInt();
Assert.assertEquals(5, val);
String distJson = "{\"val\" : 5, \"std\" : 1 }";
SynthTraceJobProducer.Sample distSample =
mapper.readValue(distJson, SynthTraceJobProducer.Sample.class);
distSample.init(rand);
double dist = distSample.getDouble();
Assert.assertTrue(dist > 2 && dist < 8);
String normdistJson = "{\"val\" : 5, \"std\" : 1, \"dist\": \"NORM\" }";
SynthTraceJobProducer.Sample normdistSample =
mapper.readValue(normdistJson, SynthTraceJobProducer.Sample.class);
normdistSample.init(rand);
double normdist = normdistSample.getDouble();
Assert.assertTrue(normdist > 2 && normdist < 8);
String discreteJson = "{\"discrete\" : [2, 4, 6, 8]}";
SynthTraceJobProducer.Sample discreteSample =
mapper.readValue(discreteJson, SynthTraceJobProducer.Sample.class);
discreteSample.init(rand);
int discrete = discreteSample.getInt();
Assert.assertTrue(
Arrays.asList(new Integer[] {2, 4, 6, 8}).contains(discrete));
String discreteWeightsJson =
"{\"discrete\" : [2, 4, 6, 8], " + "\"weights\": [0, 0, 0, 1]}";
SynthTraceJobProducer.Sample discreteWeightsSample = mapper
.readValue(discreteWeightsJson, SynthTraceJobProducer.Sample.class);
discreteWeightsSample.init(rand);
int discreteWeights = discreteWeightsSample.getInt();
Assert.assertEquals(8, discreteWeights);
String invalidJson = "{\"val\" : 5, \"discrete\" : [2, 4, 6, 8], "
+ "\"weights\": [0, 0, 0, 1]}";
try {
mapper.readValue(invalidJson, SynthTraceJobProducer.Sample.class);
Assert.fail();
} catch (JsonMappingException e) {
Assert.assertTrue(e.getMessage().startsWith("Instantiation of"));
}
String invalidDistJson =
"{\"val\" : 5, \"std\" : 1, " + "\"dist\": \"INVALID\" }";
try {
mapper.readValue(invalidDistJson, SynthTraceJobProducer.Sample.class);
Assert.fail();
} catch (JsonMappingException e) {
Assert.assertTrue(e.getMessage().startsWith("Cannot construct instance of"));
}
}
private void validateJob(SynthJob js) {
assertTrue(js.getSubmissionTime() > 0);
assertTrue(js.getDuration() > 0);
assertTrue(js.getTotalSlotTime() >= 0);
if (js.hasDeadline()) {
assertTrue(js.getDeadline() > js.getSubmissionTime() + js.getDuration());
}
assertTrue(js.getTasks().size() > 0);
for (SynthJob.SynthTask t : js.getTasks()) {
assertTrue(t.getType() != null);
assertTrue(t.getTime() > 0);
assertTrue(t.getMemory() > 0);
assertTrue(t.getVcores() > 0);
assertEquals(ExecutionType.GUARANTEED, t.getExecutionType());
}
}
}
| apache-2.0 |
KevinHorvatin/apiman | gateway/engine/vertx-eb-inmemory/src/main/java/io/apiman/gateway/engine/vertxebinmemory/services/EBRegistryProxyHandler.java | 3298 | /*
* Copyright 2015 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 io.apiman.gateway.engine.vertxebinmemory.services;
import io.apiman.gateway.engine.beans.Application;
import io.apiman.gateway.engine.beans.Service;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
/**
* Listens for registry events on the event bus. Ignores self-generated events. These arrive as a simple JSON
* payload, with a header containing the operation type, action and then a marshalled object containing the
* corresponding object (e.g. Application, Service, etc).
*
* Requests are then routed to the appropriate registry method.
*
* @author Marc Savy {@literal <msavy@redhat.com>}
*/
public interface EBRegistryProxyHandler {
@SuppressWarnings("nls")
default void listenProxyHandler() {
System.out.println("Setting up a listener on " + address());
vertx().eventBus().consumer(address(), (Message<JsonObject> message) -> {
String uuid = message.body().getString("uuid");
System.out.println("UUID == " + uuid + " vs " + uuid());
if (shouldIgnore(uuid))
return;
String type = message.body().getString("type");
String action = message.body().getString("action");
String body = message.body().getString("body");
switch (type) {
case "application":
Application app = Json.decodeValue(body, Application.class);
if (action == "register") {
registerApplication(app);
} else if (action == "unregister") {
unregisterApplication(app);
}
break;
case "service":
Service svc = Json.decodeValue(body, Service.class);
if (action == "publish") { //$NON-NLS-1$
publishService(svc);
} else if (action == "retire") {
retireService(svc);
}
break;
default:
throw new IllegalStateException("Unknown type: " + type);
}
});
}
// Address to subscribe on
String address();
// UUID of registry
String uuid();
Vertx vertx();
void publishService(Service svc);
void retireService(Service svc);
void registerApplication(Application app);
void unregisterApplication(Application app);
// If *we* sent the message, we shouldn't also digest it, else we'll end in a cycle.
default boolean shouldIgnore(String uuid) {
return uuid() == uuid;
}
} | apache-2.0 |
ashward/buddycloud-server-java | src/main/java/org/buddycloud/channelserver/queue/InQueueConsumer.java | 2945 | package org.buddycloud.channelserver.queue;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import org.buddycloud.channelserver.Configuration;
import org.buddycloud.channelserver.channel.ChannelManager;
import org.buddycloud.channelserver.channel.ChannelManagerFactory;
import org.buddycloud.channelserver.db.exception.NodeStoreException;
import org.buddycloud.channelserver.packetprocessor.iq.IQProcessor;
import org.buddycloud.channelserver.packetprocessor.message.MessageProcessor;
import org.buddycloud.channelserver.packetprocessor.presence.PresenceProcessor;
import org.buddycloud.channelserver.utils.users.OnlineResourceManager;
import org.xmpp.packet.IQ;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.Presence;
public class InQueueConsumer extends QueueConsumer {
private static final Logger logger = Logger.getLogger(InQueueConsumer.class);
private final BlockingQueue<Packet> outQueue;
private final Configuration conf;
private final ChannelManagerFactory channelManagerFactory;
private final FederatedQueueManager federatedQueueManager;
private OnlineResourceManager onlineUsers;
public InQueueConsumer(BlockingQueue<Packet> outQueue, Configuration conf, BlockingQueue<Packet> inQueue, ChannelManagerFactory channelManagerFactory,
FederatedQueueManager federatedQueueManager, OnlineResourceManager onlineUsers) {
super(inQueue);
this.outQueue = outQueue;
this.conf = conf;
this.channelManagerFactory = channelManagerFactory;
this.federatedQueueManager = federatedQueueManager;
this.onlineUsers = onlineUsers;
}
@Override
protected void consume(Packet p) {
ChannelManager channelManager = null;
try {
Long start = System.currentTimeMillis();
String xml = p.toXML();
logger.debug("Received payload: '" + xml + "'.");
channelManager = channelManagerFactory.create();
if (p instanceof IQ) {
new IQProcessor(outQueue, conf, channelManager, federatedQueueManager).process((IQ) p);
} else if (p instanceof Message) {
new MessageProcessor(outQueue, conf, channelManager).process((Message) p);
} else if (p instanceof Presence) {
new PresenceProcessor(conf, onlineUsers).process((Presence) p);
} else {
logger.info("Not handling following stanzas yet: '" + xml + "'.");
}
logger.debug("Payload handled in '" + Long.toString((System.currentTimeMillis() - start)) + "' milliseconds.");
} catch (Exception e) {
logger.error("Exception: " + e.getMessage(), e);
} finally {
try {
channelManager.close();
} catch (NodeStoreException e) {
logger.error(e);
}
}
}
}
| apache-2.0 |
bxf12315/jbpm | jbpm-flow/src/main/java/org/jbpm/workflow/core/impl/WorkflowProcessImpl.java | 2501 | /**
* Copyright 2005 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.workflow.core.impl;
import org.kie.api.definition.process.Node;
import org.kie.api.definition.process.NodeContainer;
import org.jbpm.process.core.impl.ProcessImpl;
import org.jbpm.workflow.core.WorkflowProcess;
/**
* Default implementation of a RuleFlow process.
*
*/
public class WorkflowProcessImpl extends ProcessImpl implements WorkflowProcess, org.jbpm.workflow.core.NodeContainer {
private static final long serialVersionUID = 510l;
private boolean autoComplete = false;
private boolean dynamic = false;
private org.jbpm.workflow.core.NodeContainer nodeContainer;
public WorkflowProcessImpl() {
nodeContainer = (org.jbpm.workflow.core.NodeContainer) createNodeContainer();
}
protected NodeContainer createNodeContainer() {
return new NodeContainerImpl();
}
public Node[] getNodes() {
return nodeContainer.getNodes();
}
public Node getNode(final long id) {
return nodeContainer.getNode(id);
}
public Node internalGetNode(long id) {
try {
return getNode(id);
} catch (IllegalArgumentException e) {
if (dynamic) {
return null;
} else {
throw e;
}
}
}
public void removeNode(final Node node) {
nodeContainer.removeNode(node);
((org.jbpm.workflow.core.Node) node).setNodeContainer(null);
}
public void addNode(final Node node) {
nodeContainer.addNode(node);
((org.jbpm.workflow.core.Node) node).setNodeContainer(this);
}
public boolean isAutoComplete() {
return autoComplete;
}
public void setAutoComplete(boolean autoComplete) {
this.autoComplete = autoComplete;
}
public boolean isDynamic() {
return dynamic;
}
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic;
}
}
| apache-2.0 |
rmetzger/flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/NetworkBufferAllocator.java | 3024 | /*
* 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.io.network.netty;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.runtime.io.network.NetworkClientHandler;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.io.network.buffer.FreeingBufferRecycler;
import org.apache.flink.runtime.io.network.buffer.NetworkBuffer;
import org.apache.flink.runtime.io.network.partition.consumer.InputChannelID;
import org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel;
import javax.annotation.Nullable;
import static org.apache.flink.util.Preconditions.checkNotNull;
/** An allocator used for requesting buffers in the client side netty handlers. */
class NetworkBufferAllocator {
private final NetworkClientHandler networkClientHandler;
NetworkBufferAllocator(NetworkClientHandler networkClientHandler) {
this.networkClientHandler = checkNotNull(networkClientHandler);
}
/**
* Allocates a pooled network buffer for the specific input channel.
*
* @param receiverId The id of the requested input channel.
* @return The pooled network buffer.
*/
@Nullable
Buffer allocatePooledNetworkBuffer(InputChannelID receiverId) {
Buffer buffer = null;
RemoteInputChannel inputChannel = networkClientHandler.getInputChannel(receiverId);
// If the input channel has been released, we cannot allocate buffer and the received
// message
// will be discarded.
if (inputChannel != null) {
buffer = inputChannel.requestBuffer();
}
return buffer;
}
/**
* Allocates an un-pooled network buffer with the specific size.
*
* @param size The requested buffer size.
* @param dataType The data type this buffer represents.
* @return The un-pooled network buffer.
*/
Buffer allocateUnPooledNetworkBuffer(int size, Buffer.DataType dataType) {
byte[] byteArray = new byte[size];
MemorySegment memSeg = MemorySegmentFactory.wrap(byteArray);
return new NetworkBuffer(memSeg, FreeingBufferRecycler.INSTANCE, dataType);
}
}
| apache-2.0 |
googlearchive/caja | tests/com/google/caja/render/JsPrettyPrinterTest.java | 14818 | // Copyright (C) 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.render;
import com.google.caja.SomethingWidgyHappenedError;
import com.google.caja.lexer.FilePosition;
import com.google.caja.lexer.JsLexer;
import com.google.caja.lexer.JsTokenQueue;
import com.google.caja.lexer.JsTokenType;
import com.google.caja.lexer.Keyword;
import com.google.caja.lexer.ParseException;
import com.google.caja.lexer.Token;
import com.google.caja.lexer.escaping.Escaping;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.js.IntegerLiteral;
import com.google.caja.parser.js.Operation;
import com.google.caja.parser.js.Operator;
import com.google.caja.parser.js.Parser;
import com.google.caja.parser.js.StringLiteral;
import com.google.caja.reporting.RenderContext;
import com.google.caja.util.CajaTestCase;
import com.google.caja.util.MoreAsserts;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@SuppressWarnings("static-method")
public class JsPrettyPrinterTest extends CajaTestCase {
public final void testEmptyBlock() throws Exception {
assertRendered("{ {} }", "{}");
}
public final void testAdjacentBlocks() throws Exception {
assertRendered("{ {}\n {} }", "{}{}");
}
public final void testSimpleStatement() throws Exception {
assertRendered("{ foo(); }", "foo();");
}
public final void testLongLines() throws Exception {
assertRendered(
""
+ "{\n cdefgh10abcdefgh20abcdefgh30abcdefgh40"
+ "abcdefgh50abcdefgh60abcdefgh70abcd();\n}",
""
+ " cdefgh10abcdefgh20abcdefgh30abcdefgh40"
+ "abcdefgh50abcdefgh60abcdefgh70abcd();"
);
assertRendered(
""
+ "{\n cdefgh10abcdefgh20abcdefgh30abcdefgh40"
+ "abcdefgh50abcdefgh60abcdefgh70abcde();\n"
+ "}",
""
+ " cdefgh10abcdefgh20abcdefgh30abcdefgh40"
+ "abcdefgh50abcdefgh60abcdefgh70abcde();"
);
assertRendered(
""
+ "{\n"
+ " cdefgh10abcdefgh20abcdefgh30abcdefgh40"
+ "abcdefgh50abcdefgh60abcdefgh70abcdefgh()\n"
+ " ;"
+ "\n}",
""
+ " cdefgh10abcdefgh20abcdefgh30abcdefgh40"
+ "abcdefgh50abcdefgh60abcdefgh70abcdefgh();"
);
}
public final void testSemisInsideParents() throws Exception {
assertRendered(
"{\n for (var i = 0, n = a.length; i < n; ++i) {\n"
+ " bar(a[ i ]);\n }\n}",
"for (var i = 0, n = a.length; i < n; ++i) {"
+ " bar(a[ i ]);"
+ "}");
}
public final void testObjectConstructor() throws Exception {
assertRendered(
"{\n"
+ " foo({\n"
+ " 'x': 1,\n"
+ " 'y': bar({ 'w': 4 }),\n"
+ " 'z': 3\n"
+ " });\n"
+ "}",
"foo({ x: 1, y: bar({ w: 4 }), z: 3 });");
}
public final void testMultipleStatements() throws Exception {
assertRendered(
"{\n"
+ " (function (a, b, c) {\n"
+ " foo(a);\n"
+ " bar(b);\n"
+ " return c;\n"
+ " })(1, 2, 3);\n"
+ "}",
"(function (a, b, c) { foo(a); bar(b); return (c); })(1, 2, 3);");
}
public final void testBreakBeforeWhile() throws Exception {
assertRendered(
"{\n"
+ " do {\n"
+ " foo(bar());\n"
+ " } while (1);\n"
+ "}",
"do { foo(bar()); } while(1);");
assertRendered(
"{\n"
+ " {\n"
+ " foo(bar());\n"
+ " }\n"
+ " while (1);\n"
+ "}",
"{ foo(bar()); } while(1);");
}
public final void testMarkupEndStructures() throws Exception {
// Make sure -->, </script, and ]]> don't show up in rendered output.
// Preventing these in strings is handled separately.
assertRendered(
"{\n (i--) > j, k < /script\\x3e/, [ [ 0 ] ] > 0;\n}",
"i-->j, k</script>/, [[0]]>0;");
}
public final void testJSON() throws Exception {
assertRendered(
"{\n"
+ " ({\n"
+ " 'a': [ 1, 2, 3 ],\n"
+ " 'b': {\n"
+ " 'c': [{}],\n"
+ " 'd': [{\n"
+ " 'e': null,\n"
+ " 'f': 'foo'\n"
+ " }, null ]\n"
+ " }\n"
+ " });\n"
+ "}",
"({ a: [1,2,3], b: { c: [{}], d: [{ e: null, f: 'foo' }, null] } });");
}
public final void testConditional() throws Exception {
assertRendered(
"{\n"
+ " if (c1) { foo(); } else if (c2) bar();\n"
+ " else baz();\n"
+ "}",
"if (c1) { foo(); } else if (c2) bar(); else baz();");
}
public final void testNumberPropertyAccess() throws Exception {
assertRendered("{\n (3).toString();\n}", "(3).toString();");
}
public final void testComments() throws Exception {
assertLexed(
"var x = foo; /* end of line */\n"
+ "/** Own line */\n"
+ "function Bar() {}\n"
+ "/* Beginning */\n"
+ "var baz;\n"
+ "a+// Line comment\n"
+ " b;",
""
+ "var x = foo; /* end of line */\n"
+ "/** Own line */\n"
+ "function Bar() {}\n"
+ "/* Beginning */ var baz;\n"
+ "a + // Line comment\n"
+ "b;");
}
public final void testDivisionByRegex() throws Exception {
assertLexed("3/ /foo/;", "3 / /foo/;");
}
public final void testNegatedNegativeNumericConstants() {
assertRendered(
"- (-3)", // not --3
Operation.create(
FilePosition.UNKNOWN, Operator.NEGATION,
new IntegerLiteral(FilePosition.UNKNOWN,-3)));
}
public final void testRetokenization() throws Exception {
long seed = Long.parseLong(
System.getProperty("junit.seed", "" + System.currentTimeMillis()));
Random rnd = new Random(seed);
try {
for (int i = 1000; --i >= 0;) {
List<String> randomTokens = generateRandomTokens(rnd);
StringBuilder sb = new StringBuilder();
JsPrettyPrinter pp = new JsPrettyPrinter(sb);
for (String token : randomTokens) {
pp.consume(token);
}
pp.noMoreTokens();
List<String> actualTokens = new ArrayList<String>();
try {
JsLexer lex = new JsLexer(fromString(sb.toString()));
while (lex.hasNext()) {
actualTokens.add(simplifyComments(lex.next().text));
}
} catch (ParseException ex) {
for (String tok : randomTokens) {
System.err.println(StringLiteral.toQuotedValue(tok));
}
System.err.println("<<<" + sb + ">>>");
throw ex;
}
List<String> simplifiedRandomTokens = new ArrayList<String>();
for (String randomToken : randomTokens) {
simplifiedRandomTokens.add(simplifyComments(randomToken));
}
MoreAsserts.assertListsEqual(simplifiedRandomTokens, actualTokens);
}
} catch (Exception e) {
System.err.println("Using seed " + seed);
throw e;
}
}
/**
* The renderer is allowed to muck with comment internals to fix problems
* with line-breaks in restricted productions.
*/
private static String simplifyComments(String token) {
if (token.startsWith("//")) {
token = "/*" + token.substring(2) + "*/";
}
if (!token.startsWith("/*")) { return token; }
StringBuilder sb = new StringBuilder(token);
for (int i = sb.length() - 2; --i >= 2;) {
if (JsLexer.isJsLineSeparator(sb.charAt(i))) {
sb.setCharAt(i, ' ');
}
}
for (int close = -1; (close = sb.indexOf("*/", close + 1)) >= 0;) {
sb.setCharAt(close + 1, ' ');
}
return sb.toString();
}
public final void testIndentationAfterParens1() {
assertTokens("longObjectInstance.reallyLongMethodName(a, b, c, d);",
"longObjectInstance", ".", "reallyLongMethodName", "(",
"a", ",", "b", ",", "c", ",", "d", ")", ";");
}
public final void testIndentationAfterParens2() {
assertTokens("longObjectInstance.reallyLongMethodName(a, b, c,\n" +
" d);",
"longObjectInstance", ".", "reallyLongMethodName", "(",
"a", ",", "b", ",", "c", ",", "\n", "d", ")", ";");
}
public final void testIndentationAfterParens3() {
assertTokens("longObjectInstance.reallyLongMethodName(\n" +
" a, b, c, d);",
"longObjectInstance", ".", "reallyLongMethodName", "(",
"\n", "a", ",", "b", ",", "c", ",", "d", ")", ";");
}
public final void testIndentationAfterParens4() {
assertTokens("var x = ({\n" +
" 'fooBar': [\n" +
" 0, 1, 2, ]\n" +
" });",
"var", "x", "=", "(", "{", "'fooBar'", ":", "[",
"\n", "0", ",", "1", ",", "2", ",", "]", "}", ")", ";");
}
public final void testCommentsInRestrictedProductions1() {
assertTokens("return /* */ 4;", "return", "/*\n*/", "4", ";");
}
public final void testCommentsInRestrictedProductions2() {
assertTokens("return /**/ 4;", "return", "//", "4", ";");
}
private static final JsTokenType[] TYPES = JsTokenType.values();
private static final Operator[] OPERATORS = Operator.values();
private static final Keyword[] KEYWORDS = Keyword.values();
private static List<String> generateRandomTokens(Random rnd) {
List<String> tokens = new ArrayList<String>();
for (int i = 10; --i >= 0;) {
final String tok;
switch (TYPES[rnd.nextInt(TYPES.length)]) {
case COMMENT:
if (rnd.nextBoolean()) {
String s = "//" + randomString(rnd).replace('\r', '\ufffd')
.replace('\n', '\ufffd').replace('\u2028', '\ufffd')
.replace('\u2029', '\ufffd');
if (s.endsWith("\\")) { // This is blocked in CStyleTokenClass
s = s + " ";
}
tok = s;
} else {
tok = "/*" + randomString(rnd).replace('*', '.') + "*/";
}
break;
case STRING:
tok = StringLiteral.toQuotedValue(randomString(rnd));
break;
case REGEXP:
// Since regexps are context sensitive, make sure we're in the right
// context.
tokens.add("=");
StringBuilder out = new StringBuilder();
out.append('/');
Escaping.normalizeRegex(randomString(rnd), out);
out.append('/');
if (rnd.nextBoolean()) { out.append('g'); }
if (rnd.nextBoolean()) { out.append('m'); }
if (rnd.nextBoolean()) { out.append('i'); }
tok = out.toString();
break;
case PUNCTUATION:
Operator op = OPERATORS[rnd.nextInt(OPERATORS.length)];
if (op.getClosingSymbol() != null) {
tok = rnd.nextBoolean()
? op.getOpeningSymbol()
: op.getClosingSymbol();
} else {
tok = op.getSymbol();
}
if (tok.startsWith("/")) {
// Make sure / operators follow numbers so they're not interpreted
// as regular expressions.
tokens.add("3");
}
break;
case WORD:
tok = randomWord(rnd);
break;
case KEYWORD:
tok = KEYWORDS[rnd.nextInt(KEYWORDS.length)].toString();
break;
case INTEGER:
int j = rnd.nextInt(Integer.MAX_VALUE);
switch (rnd.nextInt(3)) {
case 0: tok = Integer.toString(j, 10); break;
case 1: tok = "0" + Integer.toString(Math.abs(j), 8); break;
default: tok = "0x" + Long.toString(Math.abs((long) j), 16); break;
}
break;
case FLOAT:
tok = "" + Math.abs(rnd.nextFloat());
break;
case LINE_CONTINUATION:
continue;
default:
throw new SomethingWidgyHappenedError();
}
tokens.add(tok);
}
return tokens;
}
private static final String WORD_CHARS
= "_$ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static String randomWord(Random rnd) {
int len = rnd.nextInt(100) + 1;
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
sb.append(WORD_CHARS.charAt(rnd.nextInt(WORD_CHARS.length())));
}
if (Character.isDigit(sb.charAt(0))) {
sb.insert(0, '_');
}
return sb.toString();
}
private static String randomString(Random rnd) {
int minCp = 0, maxCp = 0;
if (rnd.nextBoolean()) {
minCp = 0x20;
maxCp = 0x7f;
} else {
minCp = 0x0;
maxCp = 0xd000;
}
int len = rnd.nextInt(100) + 1;
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
sb.appendCodePoint(rnd.nextInt(maxCp - minCp) + minCp);
}
return sb.toString();
}
private void assertRendered(String golden, String input) throws Exception {
JsLexer lex = new JsLexer(fromString(input));
JsTokenQueue tq = new JsTokenQueue(lex, is);
ParseTreeNode node = new Parser(tq, mq).parse();
tq.expectEmpty();
assertRendered(golden, node);
}
private static void assertRendered(String golden, ParseTreeNode node) {
StringBuilder out = new StringBuilder();
JsPrettyPrinter pp = new JsPrettyPrinter(out);
node.render(new RenderContext(pp));
pp.noMoreTokens();
assertEquals(golden, out.toString());
}
private void assertLexed(String golden, String input) throws Exception {
StringBuilder out = new StringBuilder();
JsPrettyPrinter pp = new JsPrettyPrinter(out);
JsLexer lex = new JsLexer(fromString(input));
while (lex.hasNext()) {
Token<JsTokenType> t = lex.next();
pp.mark(t.pos);
pp.consume(t.text);
}
pp.noMoreTokens();
assertEquals(golden, out.toString());
}
private static void assertTokens(String golden, String... input) {
StringBuilder out = new StringBuilder();
JsPrettyPrinter pp = new JsPrettyPrinter(out);
for (String token : input) {
pp.consume(token);
}
pp.noMoreTokens();
assertEquals(golden, out.toString());
}
}
| apache-2.0 |
datametica/calcite | core/src/main/java/org/apache/calcite/rel/rules/UnionToDistinctRule.java | 3294 | /*
* 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.calcite.rel.rules;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.rel.core.RelFactories;
import org.apache.calcite.rel.core.Union;
import org.apache.calcite.rel.logical.LogicalUnion;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.tools.RelBuilderFactory;
/**
* Planner rule that translates a distinct
* {@link org.apache.calcite.rel.core.Union}
* (<code>all</code> = <code>false</code>)
* into an {@link org.apache.calcite.rel.core.Aggregate}
* on top of a non-distinct {@link org.apache.calcite.rel.core.Union}
* (<code>all</code> = <code>true</code>).
*
* @see CoreRules#UNION_TO_DISTINCT
*/
public class UnionToDistinctRule
extends RelRule<UnionToDistinctRule.Config>
implements TransformationRule {
/** Creates a UnionToDistinctRule. */
protected UnionToDistinctRule(Config config) {
super(config);
}
@Deprecated // to be removed before 2.0
public UnionToDistinctRule(Class<? extends Union> unionClass,
RelBuilderFactory relBuilderFactory) {
this(Config.DEFAULT.withOperandFor(unionClass)
.withRelBuilderFactory(relBuilderFactory)
.as(Config.class));
}
@Deprecated // to be removed before 2.0
public UnionToDistinctRule(Class<? extends Union> unionClazz,
RelFactories.SetOpFactory setOpFactory) {
this(Config.DEFAULT.withOperandFor(unionClazz)
.withRelBuilderFactory(RelBuilder.proto(setOpFactory))
.as(Config.class));
}
//~ Methods ----------------------------------------------------------------
@Override public void onMatch(RelOptRuleCall call) {
final Union union = call.rel(0);
final RelBuilder relBuilder = call.builder();
relBuilder.pushAll(union.getInputs());
relBuilder.union(true, union.getInputs().size());
relBuilder.distinct();
call.transformTo(relBuilder.build());
}
/** Rule configuration. */
public interface Config extends RelRule.Config {
Config DEFAULT = EMPTY.as(Config.class)
.withOperandFor(LogicalUnion.class);
@Override default UnionToDistinctRule toRule() {
return new UnionToDistinctRule(this);
}
/** Defines an operand tree for the given classes. */
default Config withOperandFor(Class<? extends Union> unionClass) {
return withOperandSupplier(b ->
b.operand(unionClass)
.predicate(union -> !union.all).anyInputs())
.as(Config.class);
}
}
}
| apache-2.0 |